: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(deletion): run org/project/team deletion on Temporal (#62708)
Yasenc903e02d1300
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.ymlindex 5bdc378a3820..231a9fd14f98 100644--- a/.github/workflows/container-images-cd.yml+++ b/.github/workflows/container-images-cd.yml@@ -358,7 +358,7 @@ jobs:- name: Check for changes that affect general purpose temporal workerid: check_changes_general_purpose_temporal_workerrun: |- if git diff --name-only HEAD^ HEAD | grep -qE '^products/exports/backend/temporal/subscriptions|^products/experiments/backend/temporal/|^posthog/temporal/common|^posthog/temporal/session_recordings|^posthog/temporal/proxy_service|^posthog/temporal/(ai_observability|llm_analytics)|^posthog/temporal/product_analytics|^posthog/temporal/delete_persons|^posthog/temporal/ingestion_acceptance_test|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then+ if git diff --name-only HEAD^ HEAD | grep -qE '^products/exports/backend/temporal/subscriptions|^products/experiments/backend/temporal/|^posthog/temporal/common|^posthog/temporal/session_recordings|^posthog/temporal/proxy_service|^posthog/temporal/(ai_observability|llm_analytics)|^posthog/temporal/product_analytics|^posthog/temporal/delete_persons|^posthog/temporal/delete_teams|^posthog/temporal/ingestion_acceptance_test|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; thenecho "changed=true" >> $GITHUB_OUTPUTelseecho "changed=false" >> $GITHUB_OUTPUTdiff --git a/posthog/api/organization.py b/posthog/api/organization.pyindex 9f0949871743..936f51bdfa11 100644--- a/posthog/api/organization.py+++ b/posthog/api/organization.py@@ -464,16 +464,31 @@ class OrganizationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):organization.is_pending_deletion = Trueorganization.save(update_fields=["is_pending_deletion"])- # Queue background task to handle all deletion- # bulky postgres, batch exports, org/team records, ClickHouse, email- delete_organization_data_and_notify_task.delay(- team_ids=team_ids,- organization_id=str(organization_id),- user_id=user.id,- organization_name=organization_name,- project_names=project_names,+ # Hand off all deletion work (bulky postgres, batch exports, org/team records,+ # ClickHouse, email). Route to the durable Temporal workflow when the rollout flag+ # is enabled for this org; otherwise keep the legacy Celery task.+ from posthog.temporal.delete_teams.dispatch import (+ delete_via_temporal_enabled,+ start_delete_organization_workflow,)+ if delete_via_temporal_enabled(str(organization_id)):+ start_delete_organization_workflow(+ team_ids=team_ids,+ organization_id=str(organization_id),+ user_id=user.id,+ organization_name=organization_name,+ project_names=project_names,+ )+ else:+ delete_organization_data_and_notify_task.delay(+ team_ids=team_ids,+ organization_id=str(organization_id),+ user_id=user.id,+ organization_name=organization_name,+ project_names=project_names,+ )+def get_serializer_context(self) -> dict[str, Any]:return {**super().get_serializer_context(),diff --git a/posthog/api/project.py b/posthog/api/project.pyindex e8331cc71604..d61a78ddf161 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -1383,15 +1383,29 @@ class ProjectViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsetsproject.is_pending_deletion = Trueproject.save(update_fields=["is_pending_deletion"])- # Queue background task to handle all deletion- # bulky postgres, batch exports, project/team records, ClickHouse, email- delete_project_data_and_notify_task.delay(- team_ids=team_ids,- project_id=project_id,- user_id=user.id,- project_name=project_name,+ # Hand off all deletion work (bulky postgres, batch exports, project/team records,+ # ClickHouse, email). Route to the durable Temporal workflow when the rollout flag+ # is enabled for this org; otherwise keep the legacy Celery task.+ from posthog.temporal.delete_teams.dispatch import (+ delete_via_temporal_enabled,+ start_delete_project_data_workflow,)+ if delete_via_temporal_enabled(str(organization_id)):+ start_delete_project_data_workflow(+ team_ids=team_ids,+ project_id=project_id,+ user_id=user.id,+ project_name=project_name,+ )+ else:+ delete_project_data_and_notify_task.delay(+ team_ids=team_ids,+ project_id=project_id,+ user_id=user.id,+ project_name=project_name,+ )+for team in teams:log_activity(organization_id=cast(UUIDT, organization_id),diff --git a/posthog/api/team.py b/posthog/api/team.pyindex 851f0bd55d3f..51d35f282a8b 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -1703,15 +1703,29 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mouser = cast(User, self.request.user)- # Queue background task to handle all deletion- # bulky postgres, batch exports, team record, ClickHouse, email- delete_project_data_and_notify_task.delay(- team_ids=[team_id],- project_id=None, # Only deleting a team, not the whole project- user_id=user.id,- project_name=team_name,+ # Hand off all deletion work (bulky postgres, batch exports, team record,+ # ClickHouse, email). Route to the durable Temporal workflow when the rollout flag+ # is enabled for this org; otherwise keep the legacy Celery task.+ from posthog.temporal.delete_teams.dispatch import (+ delete_via_temporal_enabled,+ start_delete_project_data_workflow,)+ if delete_via_temporal_enabled(str(organization_id)):+ start_delete_project_data_workflow(+ team_ids=[team_id],+ project_id=None, # Only deleting a team, not the whole project+ user_id=user.id,+ project_name=team_name,+ )+ else:+ delete_project_data_and_notify_task.delay(+ team_ids=[team_id],+ project_id=None, # Only deleting a team, not the whole project+ user_id=user.id,+ project_name=team_name,+ )+log_activity(organization_id=cast(UUIDT, organization_id),team_id=team_id,diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 125849ad4ab8..dead21436dbc 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -58,6 +58,10 @@ from posthog.temporal.delete_persons import (ACTIVITIES as DELETE_PERSONS_ACTIVITIES,WORKFLOWS as DELETE_PERSONS_WORKFLOWS,)+from posthog.temporal.delete_teams import (+ ACTIVITIES as DELETE_TEAMS_ACTIVITIES,+ WORKFLOWS as DELETE_TEAMS_WORKFLOWS,+)from posthog.temporal.dlq_replay import (ACTIVITIES as DLQ_REPLAY_ACTIVITIES,WORKFLOWS as DLQ_REPLAY_WORKFLOWS,@@ -236,6 +240,7 @@ _task_queue_specs = [settings.GENERAL_PURPOSE_TASK_QUEUE,PROXY_SERVICE_WORKFLOWS+ DELETE_PERSONS_WORKFLOWS+ + DELETE_TEAMS_WORKFLOWS+ SALESFORCE_ENRICHMENT_WORKFLOWS+ PRODUCT_ANALYTICS_WORKFLOWS+ LLM_ANALYTICS_WORKFLOWS@@ -248,6 +253,7 @@ _task_queue_specs = [+ WAREHOUSE_SOURCES_QUEUE_PARTITION_WORKFLOWS,PROXY_SERVICE_ACTIVITIES+ DELETE_PERSONS_ACTIVITIES+ + DELETE_TEAMS_ACTIVITIES+ QUOTA_LIMITING_ACTIVITIES+ SALESFORCE_ENRICHMENT_ACTIVITIES+ PRODUCT_ANALYTICS_ACTIVITIESdiff --git a/posthog/models/team/util.py b/posthog/models/team/util.pyindex 4e35075a3c78..ecd221f87bcb 100644--- a/posthog/models/team/util.py+++ b/posthog/models/team/util.py@@ -25,43 +25,62 @@ actions_that_require_current_team = [def delete_bulky_postgres_data(team_ids: list[int]):"Efficiently delete large tables for teams from postgres. Using normal CASCADE delete here can time out"+ # 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)++ # Delete Person + PersonDistinctId via personhog RPC (handles both tables).+ # Falls back to ORM batch deletion when personhog is not available.+ _delete_persons_for_teams(team_ids)+++def _delete_misc_small_tables_for_teams(team_ids: list[int]) -> None:+ """Batch-delete the per-team tables that have no dedicated bulk path.++ These previously used a single unbatched DELETE each, which could hit a statement+ timeout or hold a long lock on very large teams. _raw_delete_batch keeps every+ statement bounded.+ """from posthog.models.file_system.file_system_view_log import FileSystemViewLog- from products.cohorts.backend.models.cohort import Cohortfrom products.data_modeling.backend.models import Edge, Nodefrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.error_tracking.backend.models import ErrorTrackingIssueFingerprintV2from products.feature_flags.backend.models.feature_flag import FeatureFlagHashKeyOverridefrom products.product_analytics.backend.models.insight_caching_state import InsightCachingState- # Delete data modeling nodes and edges first to not block Team deletion.- # Team cascades to DataWarehouseSavedQuery, but it has PROTECT on delete.- _raw_delete(Edge.objects.filter(team_id__in=team_ids))- _raw_delete(Node.objects.filter(team_id__in=team_ids))+ # Data modeling Edge/Node must be deleted before the Team row: Team cascades to+ # DataWarehouseSavedQuery, which has PROTECT on delete.+ _raw_delete_batch(Edge.objects.filter(team_id__in=team_ids))+ _raw_delete_batch(Node.objects.filter(team_id__in=team_ids))+ _raw_delete_batch(FileSystemViewLog.objects.filter(team_id__in=team_ids))+ _raw_delete_batch(EarlyAccessFeature.objects.filter(team_id__in=team_ids))+ _raw_delete_batch(ErrorTrackingIssueFingerprintV2.objects.filter(team_id__in=team_ids))+ # FeatureFlagHashKeyOverride references Person, so it must go before persons are deleted.+ _raw_delete_batch(+ FeatureFlagHashKeyOverride.objects.filter(team_id__in=team_ids) # nosemgrep: no-direct-persons-db-orm+ )+ _raw_delete_batch(InsightCachingState.objects.filter(team_id__in=team_ids))- _raw_delete(FileSystemViewLog.objects.filter(team_id__in=team_ids))- _raw_delete(EarlyAccessFeature.objects.filter(team_id__in=team_ids))+def _delete_personless_distinct_ids_for_teams(team_ids: list[int]) -> None:for team_id in team_ids:_raw_delete_personless_distinct_ids_for_team(team_id)- _raw_delete(ErrorTrackingIssueFingerprintV2.objects.filter(team_id__in=team_ids))- # Get cohort_ids from the default database first to avoid cross-database join- # CohortPeople is in persons_db, Cohort is in default db++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.+ from products.cohorts.backend.models.cohort import Cohort+cohort_ids = list(Cohort.objects.filter(team_id__in=team_ids).values_list("id", flat=True))if cohort_ids:_delete_cohort_members_for_teams(team_ids, cohort_ids)- _raw_delete(FeatureFlagHashKeyOverride.objects.filter(team_id__in=team_ids)) # nosemgrep: no-direct-persons-db-orm- _delete_groups_for_teams(team_ids)- _delete_group_type_mappings_for_teams(team_ids)-- # Delete Person + PersonDistinctId via personhog RPC (handles both tables).- # Falls back to ORM batch deletion when personhog is not available.- _delete_persons_for_teams(team_ids)-- _raw_delete(InsightCachingState.objects.filter(team_id__in=team_ids))-def _raw_delete_personless_distinct_ids_for_team(team_id: int, batch_size: int = 10000) -> None:"""Delete posthog_personlessdistinctid rows for a single team in batches.@@ -343,6 +362,33 @@ def delete_data_modeling_schedules(team_ids: list[int]) -> None:capture_exception(e)+def delete_team_records(team_ids: list[int]) -> None:+ """Delete the Team rows once their bulky child data has been removed.++ FOR UPDATE on the teams blocks concurrent FK-inserts to any child table during the+ cascade delete.+ """+ from django.db import transaction++ from posthog.models.team import Team++ with transaction.atomic():+ list(Team.objects.select_for_update().filter(id__in=team_ids))+ Team.objects.filter(id__in=team_ids).delete()+++def delete_project_record(project_id: int) -> None:+ from posthog.models.project import Project++ Project.objects.filter(id=project_id).delete()+++def delete_organization_record(organization_id: str) -> None:+ from posthog.models.organization import Organization++ Organization.objects.filter(id=organization_id).delete()++can_enable_actor_on_events = Falsediff --git a/posthog/temporal/delete_teams/__init__.py b/posthog/temporal/delete_teams/__init__.pynew file mode 100644index 000000000000..d568a8fe60df--- /dev/null+++ b/posthog/temporal/delete_teams/__init__.py@@ -0,0 +1,44 @@+from posthog.temporal.delete_teams.activities import (+ delete_batch_exports_activity,+ delete_cohort_members_activity,+ delete_data_modeling_schedules_activity,+ delete_groups_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,+ enqueue_clickhouse_deletion_activity,+ queue_recording_deletions_activity,+ send_organization_deleted_email_activity,+ send_project_deleted_email_activity,+)+from posthog.temporal.delete_teams.workflows import (+ DeleteOrganizationWorkflow,+ DeleteProjectDataWorkflow,+ DeleteTeamsDataWorkflow,+)++WORKFLOWS = [+ DeleteTeamsDataWorkflow,+ DeleteProjectDataWorkflow,+ DeleteOrganizationWorkflow,+]++ACTIVITIES = [+ 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,+ delete_batch_exports_activity,+ delete_data_modeling_schedules_activity,+ delete_team_records_activity,+ enqueue_clickhouse_deletion_activity,+ delete_project_record_activity,+ delete_organization_record_activity,+ send_project_deleted_email_activity,+ send_organization_deleted_email_activity,+]diff --git a/posthog/temporal/delete_teams/activities.py b/posthog/temporal/delete_teams/activities.pynew file mode 100644index 000000000000..09517b569741--- /dev/null+++ b/posthog/temporal/delete_teams/activities.py@@ -0,0 +1,172 @@+import temporalio.activity++from posthog.sync import database_sync_to_async_pool+from posthog.temporal.common.heartbeat import Heartbeater+from posthog.temporal.delete_teams.types import (+ OrganizationEmailInputs,+ OrganizationRecordInputs,+ ProjectEmailInputs,+ ProjectRecordInputs,+ TeamDataActivityInputs,+)+++def _resolve_deleted_by(user_id: int) -> str:+ from posthog.models.user import User++ user = User.objects.filter(id=user_id).first()+ return user.email if user else f"deleted_user_id:{user_id}"+++async def queue_recording_deletions_activity(inputs: TeamDataActivityInputs) -> None:+ """Start the autonomous session-replay recording-deletion workflows for each team."""+ async with Heartbeater():+ from posthog.tasks.tasks import _queue_delete_team_recordings++ deleted_by = await database_sync_to_async_pool(_resolve_deleted_by)(inputs.user_id)+ await database_sync_to_async_pool(_queue_delete_team_recordings)(inputs.team_ids, deleted_by)+++async def delete_misc_small_tables_activity(inputs: TeamDataActivityInputs) -> None:+ async with Heartbeater():+ from posthog.models.team.util import _delete_misc_small_tables_for_teams++ await 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)+++async def delete_cohort_members_activity(inputs: TeamDataActivityInputs) -> None:+ async with Heartbeater():+ from posthog.models.team.util import _delete_cohort_members_for_all_teams++ await database_sync_to_async_pool(_delete_cohort_members_for_all_teams)(inputs.team_ids)+++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)+++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)+++async def delete_batch_exports_activity(inputs: TeamDataActivityInputs) -> None:+ async with Heartbeater():+ from posthog.models.team.util import delete_batch_exports++ await database_sync_to_async_pool(delete_batch_exports)(inputs.team_ids)+++async def delete_data_modeling_schedules_activity(inputs: TeamDataActivityInputs) -> None:+ async with Heartbeater():+ from posthog.models.team.util import delete_data_modeling_schedules++ await database_sync_to_async_pool(delete_data_modeling_schedules)(inputs.team_ids)+++async def delete_team_records_activity(inputs: TeamDataActivityInputs) -> None:+ async with Heartbeater():+ from posthog.models.team.util import delete_team_records++ await database_sync_to_async_pool(delete_team_records)(inputs.team_ids)+++def _enqueue_clickhouse_deletion(team_ids: list[int], user_id: int) -> None:+ from posthog.models.async_deletion import AsyncDeletion, DeletionType+ from posthog.models.user import User++ user = User.objects.filter(id=user_id).first()+ AsyncDeletion.objects.bulk_create(+ [+ AsyncDeletion(+ deletion_type=DeletionType.Team,+ team_id=team_id,+ key=str(team_id),+ created_by=user,+ )+ for team_id in team_ids+ ],+ ignore_conflicts=True,+ )+++async def enqueue_clickhouse_deletion_activity(inputs: TeamDataActivityInputs) -> None:+ async with Heartbeater():+ await database_sync_to_async_pool(_enqueue_clickhouse_deletion)(inputs.team_ids, inputs.user_id)+++async def delete_project_record_activity(inputs: ProjectRecordInputs) -> None:+ async with Heartbeater():+ from posthog.models.team.util import delete_project_record++ await database_sync_to_async_pool(delete_project_record)(inputs.project_id)+++def _delete_organization_record(organization_id: str, user_id: int) -> None:+ from posthog.event_usage import report_organization_deletion_completed+ from posthog.models.team.util import delete_organization_record++ delete_organization_record(organization_id)+ report_organization_deletion_completed(user_id=user_id, organization_id=organization_id)+++async def delete_organization_record_activity(inputs: OrganizationRecordInputs) -> None:+ async with Heartbeater():+ await database_sync_to_async_pool(_delete_organization_record)(inputs.organization_id, inputs.user_id)+++def _send_project_deleted_email(user_id: int, project_name: str) -> None:+ from posthog.email import is_email_available+ from posthog.tasks.email import send_project_deleted_email++ if is_email_available():+ send_project_deleted_email.delay(user_id=user_id, project_name=project_name)+++async def send_project_deleted_email_activity(inputs: ProjectEmailInputs) -> None:+ async with Heartbeater():+ await database_sync_to_async_pool(_send_project_deleted_email)(inputs.user_id, inputs.project_name)+++def _send_organization_deleted_email(user_id: int, organization_name: str, project_names: list[str]) -> None:+ from posthog.email import is_email_available+ from posthog.tasks.email import send_organization_deleted_email++ if is_email_available():+ send_organization_deleted_email.delay(+ user_id=user_id, organization_name=organization_name, project_names=project_names+ )+++async def send_organization_deleted_email_activity(inputs: OrganizationEmailInputs) -> None:+ async with Heartbeater():+ await database_sync_to_async_pool(_send_organization_deleted_email)(+ inputs.user_id, inputs.organization_name, inputs.project_names+ )diff --git a/posthog/temporal/delete_teams/dispatch.py b/posthog/temporal/delete_teams/dispatch.pynew file mode 100644index 000000000000..82d86e7aee72--- /dev/null+++ b/posthog/temporal/delete_teams/dispatch.py@@ -0,0 +1,69 @@+import asyncio++from django.conf import settings++import posthoganalytics++from posthog.temporal.common.client import async_connect+from posthog.temporal.delete_teams.types import DeleteOrganizationWorkflowInputs, DeleteProjectDataWorkflowInputs++TEMPORAL_DELETION_ROLLOUT_FLAG = "temporal-deletion-rollout"+++def delete_via_temporal_enabled(organization_id: str) -> bool:+ """Whether org/project/team deletion for this organization should run on Temporal.++ Evaluated at the API dispatch site so the rollout can be ramped per organization.+ Returns False when flags are unavailable (e.g. self-hosted), keeping deletion on Celery.+ """+ return bool(+ posthoganalytics.feature_enabled(+ TEMPORAL_DELETION_ROLLOUT_FLAG,+ organization_id,+ groups={"organization": organization_id},+ group_properties={"organization": {"id": organization_id}},+ )+ )+++def start_delete_project_data_workflow(+ *, team_ids: list[int], project_id: int | None, user_id: int, project_name: str+) -> None:+ inputs = DeleteProjectDataWorkflowInputs(+ team_ids=team_ids, project_id=project_id, user_id=user_id, project_name=project_name+ )+ workflow_id = f"delete-project-{project_id}" if project_id is not None else f"delete-environment-{team_ids[0]}"++ async def _start() -> None:+ client = await async_connect()+ await client.start_workflow(+ "delete-project-data",+ inputs,+ id=workflow_id,+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,+ )++ asyncio.run(_start())+++def start_delete_organization_workflow(+ *, team_ids: list[int], organization_id: str, user_id: int, organization_name: str, project_names: list[str]+) -> None:+ inputs = DeleteOrganizationWorkflowInputs(+ team_ids=team_ids,+ organization_id=organization_id,+ user_id=user_id,+ organization_name=organization_name,+ project_names=project_names,+ )++ async def _start() -> None:+ client = await async_connect()+ await client.start_workflow(+ "delete-organization",+ inputs,+ id=f"delete-organization-{organization_id}",+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,+ )++ asyncio.run(_start())diff --git a/posthog/temporal/delete_teams/types.py b/posthog/temporal/delete_teams/types.pynew file mode 100644index 000000000000..62581d7a4a72--- /dev/null+++ b/posthog/temporal/delete_teams/types.py@@ -0,0 +1,95 @@+import typing+import dataclasses+++class TeamDataActivityInputs:+ """Inputs shared by the per-domain team-data deletion activities."""++ team_ids: list[int]+ user_id: int++ @property+ def properties_to_log(self) -> dict[str, typing.Any]:+ return {"team_ids": self.team_ids, "user_id": self.user_id}+++class ProjectRecordInputs:+ project_id: int++ @property+ def properties_to_log(self) -> dict[str, typing.Any]:+ return {"project_id": self.project_id}+++class OrganizationRecordInputs:+ organization_id: str+ user_id: int++ @property+ def properties_to_log(self) -> dict[str, typing.Any]:+ return {"organization_id": self.organization_id, "user_id": self.user_id}+++class ProjectEmailInputs:+ user_id: int+ project_name: str++ @property+ def properties_to_log(self) -> dict[str, typing.Any]:+ return {"user_id": self.user_id}+++class OrganizationEmailInputs:+ user_id: int+ organization_name: str+ project_names: list[str]++ @property+ def properties_to_log(self) -> dict[str, typing.Any]:+ return {"user_id": self.user_id}+++class DeleteTeamsDataWorkflowInputs:+ """Inputs for the reusable core ``DeleteTeamsDataWorkflow``."""++ team_ids: list[int]+ user_id: int++ @property+ def properties_to_log(self) -> dict[str, typing.Any]:+ return {"team_ids": self.team_ids, "user_id": self.user_id}+++class DeleteProjectDataWorkflowInputs:+ """Inputs for ``DeleteProjectDataWorkflow`` (project or environment-only deletion)."""++ team_ids: list[int]+ project_id: int | None+ user_id: int+ project_name: str++ @property+ def properties_to_log(self) -> dict[str, typing.Any]:+ return {"team_ids": self.team_ids, "project_id": self.project_id, "user_id": self.user_id}+++class DeleteOrganizationWorkflowInputs:+ """Inputs for ``DeleteOrganizationWorkflow``."""++ team_ids: list[int]+ organization_id: str+ user_id: int+ organization_name: str+ project_names: list[str]++ @property+ def properties_to_log(self) -> dict[str, typing.Any]:+ return {"team_ids": self.team_ids, "organization_id": self.organization_id, "user_id": self.user_id}diff --git a/posthog/temporal/delete_teams/workflows.py b/posthog/temporal/delete_teams/workflows.pynew file mode 100644index 000000000000..f86d8ee295aa--- /dev/null+++ b/posthog/temporal/delete_teams/workflows.py@@ -0,0 +1,213 @@+import datetime as dt++import temporalio.common+import temporalio.workflow++from posthog.temporal.common.base import PostHogWorkflow+from posthog.temporal.delete_teams.activities import (+ delete_batch_exports_activity,+ delete_cohort_members_activity,+ delete_data_modeling_schedules_activity,+ delete_groups_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,+ enqueue_clickhouse_deletion_activity,+ queue_recording_deletions_activity,+ send_organization_deleted_email_activity,+ send_project_deleted_email_activity,+)+from posthog.temporal.delete_teams.types import (+ DeleteOrganizationWorkflowInputs,+ DeleteProjectDataWorkflowInputs,+ DeleteTeamsDataWorkflowInputs,+ OrganizationEmailInputs,+ OrganizationRecordInputs,+ ProjectEmailInputs,+ ProjectRecordInputs,+ TeamDataActivityInputs,+)++# The bulky deletes are idempotent ("delete next N rows for this team until empty"), so they+# can retry indefinitely on transient DB errors — the data only ever shrinks, and a restarted+# activity just resumes. Deterministic failures (e.g. a ProtectedError from a PROTECT FK the+# phase ordering doesn't account for) are non-retryable so the workflow fails fast and surfaces+# instead of retrying forever unnoticed.+DELETE_RETRY_POLICY = temporalio.common.RetryPolicy(+ initial_interval=dt.timedelta(seconds=10),+ maximum_interval=dt.timedelta(seconds=360),+ maximum_attempts=0,+ non_retryable_error_types=["ProtectedError"],+)+# Bounded retries for the lighter orchestration / side-effect activities.+SIDE_EFFECT_RETRY_POLICY = temporalio.common.RetryPolicy(+ initial_interval=dt.timedelta(seconds=5),+ maximum_interval=dt.timedelta(seconds=60),+ maximum_attempts=5,+)++HEAVY_ACTIVITY_TIMEOUT = dt.timedelta(hours=2)+HEAVY_HEARTBEAT_TIMEOUT = dt.timedelta(seconds=60)+LIGHT_ACTIVITY_TIMEOUT = dt.timedelta(minutes=10)+LIGHT_HEARTBEAT_TIMEOUT = dt.timedelta(seconds=60)+EMAIL_ACTIVITY_TIMEOUT = dt.timedelta(minutes=2)+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,+)++[email protected](name="delete-teams-data")+class DeleteTeamsDataWorkflow(PostHogWorkflow):+ """Delete all child data and the team rows for a set of teams.++ The reusable core: composed as a child workflow by both ``DeleteProjectDataWorkflow``+ and ``DeleteOrganizationWorkflow``. Mirrors the phase order of the legacy+ ``_delete_teams_and_data`` Celery path, with each phase as an independently retryable,+ heartbeating activity.+ """++ inputs_cls = DeleteTeamsDataWorkflowInputs++ @temporalio.workflow.run+ async def run(self, inputs: DeleteTeamsDataWorkflowInputs) -> None:+ if not inputs.team_ids:+ return++ team_inputs = TeamDataActivityInputs(team_ids=inputs.team_ids, user_id=inputs.user_id)++ # Start the autonomous session-replay recording deletion (fire-and-forget).+ await temporalio.workflow.execute_activity(+ queue_recording_deletions_activity,+ team_inputs,+ start_to_close_timeout=LIGHT_ACTIVITY_TIMEOUT,+ heartbeat_timeout=LIGHT_HEARTBEAT_TIMEOUT,+ retry_policy=SIDE_EFFECT_RETRY_POLICY,+ )++ for activity in BULKY_POSTGRES_ACTIVITIES:+ await temporalio.workflow.execute_activity(+ 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,+ team_inputs,+ start_to_close_timeout=LIGHT_ACTIVITY_TIMEOUT,+ heartbeat_timeout=LIGHT_HEARTBEAT_TIMEOUT,+ retry_policy=SIDE_EFFECT_RETRY_POLICY,+ )+ await temporalio.workflow.execute_activity(+ delete_data_modeling_schedules_activity,+ team_inputs,+ start_to_close_timeout=LIGHT_ACTIVITY_TIMEOUT,+ heartbeat_timeout=LIGHT_HEARTBEAT_TIMEOUT,+ retry_policy=SIDE_EFFECT_RETRY_POLICY,+ )++ # The bulky children are gone, so the Team row delete is cheap, then hand off to ClickHouse.+ await temporalio.workflow.execute_activity(+ delete_team_records_activity,+ team_inputs,+ start_to_close_timeout=LIGHT_ACTIVITY_TIMEOUT,+ heartbeat_timeout=LIGHT_HEARTBEAT_TIMEOUT,+ retry_policy=DELETE_RETRY_POLICY,+ )+ await temporalio.workflow.execute_activity(+ enqueue_clickhouse_deletion_activity,+ team_inputs,+ start_to_close_timeout=LIGHT_ACTIVITY_TIMEOUT,+ heartbeat_timeout=LIGHT_HEARTBEAT_TIMEOUT,+ retry_policy=SIDE_EFFECT_RETRY_POLICY,+ )+++async def _delete_teams_data_child(inputs: DeleteTeamsDataWorkflowInputs, workflow_id: str) -> None:+ await temporalio.workflow.execute_child_workflow(+ DeleteTeamsDataWorkflow.run,+ inputs,+ id=workflow_id,+ )++[email protected](name="delete-project-data")+class DeleteProjectDataWorkflow(PostHogWorkflow):+ """Replaces ``delete_project_data_and_notify_task`` — project or environment-only deletion."""++ inputs_cls = DeleteProjectDataWorkflowInputs++ @temporalio.workflow.run+ async def run(self, inputs: DeleteProjectDataWorkflowInputs) -> None:+ if inputs.team_ids:+ await _delete_teams_data_child(+ DeleteTeamsDataWorkflowInputs(team_ids=inputs.team_ids, user_id=inputs.user_id),+ f"{temporalio.workflow.info().workflow_id}-teams-data",+ )++ # For environment-only deletion (project_id is None) the team rows are already gone.+ if inputs.project_id is not None:+ await temporalio.workflow.execute_activity(+ delete_project_record_activity,+ ProjectRecordInputs(project_id=inputs.project_id),+ start_to_close_timeout=LIGHT_ACTIVITY_TIMEOUT,+ heartbeat_timeout=LIGHT_HEARTBEAT_TIMEOUT,+ retry_policy=DELETE_RETRY_POLICY,+ )++ await temporalio.workflow.execute_activity(+ send_project_deleted_email_activity,+ ProjectEmailInputs(user_id=inputs.user_id, project_name=inputs.project_name),+ start_to_close_timeout=EMAIL_ACTIVITY_TIMEOUT,+ heartbeat_timeout=EMAIL_HEARTBEAT_TIMEOUT,+ retry_policy=SIDE_EFFECT_RETRY_POLICY,+ )++[email protected](name="delete-organization")+class DeleteOrganizationWorkflow(PostHogWorkflow):+ """Replaces ``delete_organization_data_and_notify_task``."""++ inputs_cls = DeleteOrganizationWorkflowInputs++ @temporalio.workflow.run+ async def run(self, inputs: DeleteOrganizationWorkflowInputs) -> None:+ if inputs.team_ids:+ await _delete_teams_data_child(+ DeleteTeamsDataWorkflowInputs(team_ids=inputs.team_ids, user_id=inputs.user_id),+ f"{temporalio.workflow.info().workflow_id}-teams-data",+ )++ # Deleting the org row cascades any remaining Projects; the teams are already gone.+ await temporalio.workflow.execute_activity(+ delete_organization_record_activity,+ OrganizationRecordInputs(organization_id=inputs.organization_id, user_id=inputs.user_id),+ start_to_close_timeout=LIGHT_ACTIVITY_TIMEOUT,+ heartbeat_timeout=LIGHT_HEARTBEAT_TIMEOUT,+ retry_policy=DELETE_RETRY_POLICY,+ )++ await temporalio.workflow.execute_activity(+ send_organization_deleted_email_activity,+ OrganizationEmailInputs(+ user_id=inputs.user_id,+ organization_name=inputs.organization_name,+ project_names=inputs.project_names,+ ),+ start_to_close_timeout=EMAIL_ACTIVITY_TIMEOUT,+ heartbeat_timeout=EMAIL_HEARTBEAT_TIMEOUT,+ retry_policy=SIDE_EFFECT_RETRY_POLICY,+ )diff --git a/posthog/temporal/tests/delete_teams/__init__.py b/posthog/temporal/tests/delete_teams/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/posthog/temporal/tests/delete_teams/test_integration.py b/posthog/temporal/tests/delete_teams/test_integration.pynew file mode 100644index 000000000000..2e0af92efde6--- /dev/null+++ b/posthog/temporal/tests/delete_teams/test_integration.py@@ -0,0 +1,122 @@+import uuid++import pytest++import temporalio.worker+from asgiref.sync import sync_to_async+from temporalio import activity+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import Worker++from posthog.models.async_deletion import AsyncDeletion, DeletionType+from posthog.models.organization import Organization+from posthog.models.team import Team+from posthog.temporal.delete_teams import ACTIVITIES as REAL_ACTIVITIES+from posthog.temporal.delete_teams.types import (+ DeleteOrganizationWorkflowInputs,+ OrganizationEmailInputs,+ ProjectEmailInputs,+ TeamDataActivityInputs,+)+from posthog.temporal.delete_teams.workflows import (+ DeleteOrganizationWorkflow,+ DeleteProjectDataWorkflow,+ DeleteTeamsDataWorkflow,+)++from products.early_access_features.backend.models import EarlyAccessFeature++pytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]++WORKFLOWS = [DeleteTeamsDataWorkflow, DeleteProjectDataWorkflow, DeleteOrganizationWorkflow]++# Activities that reach out to Temporal schedules / email are stubbed so the test stays+# hermetic; every Postgres-deletion activity runs for real against the test DB.+STUBBED_ACTIVITY_NAMES = {+ "queue_recording_deletions_activity",+ "delete_batch_exports_activity",+ "delete_data_modeling_schedules_activity",+ "send_organization_deleted_email_activity",+ "send_project_deleted_email_activity",+}+++def _activities_with_stubs() -> list:+ @activity.defn(name="queue_recording_deletions_activity")+ async def queue_recording_deletions_activity(inputs: TeamDataActivityInputs) -> None:+ pass++ @activity.defn(name="delete_batch_exports_activity")+ async def delete_batch_exports_activity(inputs: TeamDataActivityInputs) -> None:+ pass++ @activity.defn(name="delete_data_modeling_schedules_activity")+ async def delete_data_modeling_schedules_activity(inputs: TeamDataActivityInputs) -> None:+ pass++ @activity.defn(name="send_organization_deleted_email_activity")+ async def send_organization_deleted_email_activity(inputs: OrganizationEmailInputs) -> None:+ pass++ @activity.defn(name="send_project_deleted_email_activity")+ async def send_project_deleted_email_activity(inputs: ProjectEmailInputs) -> None:+ pass++ real = [fn for fn in REAL_ACTIVITIES if fn.__name__ not in STUBBED_ACTIVITY_NAMES]+ return [+ *real,+ queue_recording_deletions_activity,+ delete_batch_exports_activity,+ delete_data_modeling_schedules_activity,+ send_organization_deleted_email_activity,+ send_project_deleted_email_activity,+ ]+++def _bootstrap_tenant() -> tuple[str, int]:+ org, _, team = Organization.objects.bootstrap(None)+ EarlyAccessFeature.objects.create(team=team, name="to-be-deleted", stage="concept")+ return str(org.id), team.id+++def _tenant_state(org_id: str, team_id: int) -> dict[str, bool]:+ return {+ "org": Organization.objects.filter(id=org_id).exists(),+ "team": Team.objects.filter(id=team_id).exists(),+ "early_access_feature": EarlyAccessFeature.objects.filter(team_id=team_id).exists(),+ "async_deletion": AsyncDeletion.objects.filter(deletion_type=DeletionType.Team, team_id=team_id).exists(),+ }+++async def _execute(workflow, inputs) -> None:+ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=WORKFLOWS,+ activities=_activities_with_stubs(),+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ await env.client.execute_workflow(workflow, inputs, id=str(uuid.uuid4()), task_queue=task_queue)+++async def test_organization_workflow_deletes_real_rows():+ org_id, team_id = await sync_to_async(_bootstrap_tenant)()++ before = await sync_to_async(_tenant_state)(org_id, team_id)+ assert before == {"org": True, "team": True, "early_access_feature": True, "async_deletion": False}++ await _execute(+ DeleteOrganizationWorkflow.run,+ DeleteOrganizationWorkflowInputs(+ team_ids=[team_id],+ organization_id=org_id,+ user_id=999999, # no such user; report + email paths no-op safely+ organization_name="throwaway",+ project_names=[],+ ),+ )++ after = await sync_to_async(_tenant_state)(org_id, team_id)+ assert after == {"org": False, "team": False, "early_access_feature": False, "async_deletion": True}diff --git a/posthog/temporal/tests/delete_teams/test_workflows.py b/posthog/temporal/tests/delete_teams/test_workflows.pynew file mode 100644index 000000000000..44ff07b58e77--- /dev/null+++ b/posthog/temporal/tests/delete_teams/test_workflows.py@@ -0,0 +1,211 @@+import uuid++import pytest++import temporalio.worker+from temporalio import activity+from temporalio.client import WorkflowFailureError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import Worker++from posthog.temporal.delete_teams.types import (+ DeleteOrganizationWorkflowInputs,+ DeleteProjectDataWorkflowInputs,+ DeleteTeamsDataWorkflowInputs,+ OrganizationEmailInputs,+ OrganizationRecordInputs,+ ProjectEmailInputs,+ ProjectRecordInputs,+ TeamDataActivityInputs,+)+from posthog.temporal.delete_teams.workflows import (+ DeleteOrganizationWorkflow,+ DeleteProjectDataWorkflow,+ DeleteTeamsDataWorkflow,+)++pytestmark = pytest.mark.asyncio++WORKFLOWS = [DeleteTeamsDataWorkflow, DeleteProjectDataWorkflow, DeleteOrganizationWorkflow]++CORE_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",+ "delete_batch_exports_activity",+ "delete_data_modeling_schedules_activity",+ "delete_team_records_activity",+ "enqueue_clickhouse_deletion_activity",+]+++def _recording_activities(calls: list[str]) -> list:+ """Mock every delete_teams activity by name; each records its invocation order."""++ def _team_activity(name: str):+ @activity.defn(name=name)+ async def _fn(inputs: TeamDataActivityInputs) -> None:+ calls.append(name)++ return _fn++ @activity.defn(name="delete_project_record_activity")+ async def delete_project_record_activity(inputs: ProjectRecordInputs) -> None:+ calls.append("delete_project_record_activity")++ @activity.defn(name="delete_organization_record_activity")+ async def delete_organization_record_activity(inputs: OrganizationRecordInputs) -> None:+ calls.append("delete_organization_record_activity")++ @activity.defn(name="send_project_deleted_email_activity")+ async def send_project_deleted_email_activity(inputs: ProjectEmailInputs) -> None:+ calls.append("send_project_deleted_email_activity")++ @activity.defn(name="send_organization_deleted_email_activity")+ async def send_organization_deleted_email_activity(inputs: OrganizationEmailInputs) -> None:+ calls.append("send_organization_deleted_email_activity")++ return [+ *[_team_activity(name) for name in CORE_ACTIVITY_ORDER],+ delete_project_record_activity,+ delete_organization_record_activity,+ send_project_deleted_email_activity,+ send_organization_deleted_email_activity,+ ]+++async def _run(workflow, inputs, calls: list[str]) -> None:+ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=WORKFLOWS,+ activities=_recording_activities(calls),+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ await env.client.execute_workflow(+ workflow,+ inputs,+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )+++async def test_core_workflow_runs_every_phase_in_order():+ calls: list[str] = []+ await _run(DeleteTeamsDataWorkflow.run, DeleteTeamsDataWorkflowInputs(team_ids=[1, 2], user_id=7), calls)+ assert calls == CORE_ACTIVITY_ORDER+++async def test_core_workflow_noop_for_empty_team_ids():+ calls: list[str] = []+ await _run(DeleteTeamsDataWorkflow.run, DeleteTeamsDataWorkflowInputs(team_ids=[], user_id=7), calls)+ assert calls == []+++async def test_project_workflow_deletes_record_then_emails():+ calls: list[str] = []+ await _run(+ DeleteProjectDataWorkflow.run,+ DeleteProjectDataWorkflowInputs(team_ids=[1], project_id=42, user_id=7, project_name="proj"),+ calls,+ )+ assert calls == [*CORE_ACTIVITY_ORDER, "delete_project_record_activity", "send_project_deleted_email_activity"]+++async def test_environment_only_deletion_skips_project_record():+ calls: list[str] = []+ await _run(+ DeleteProjectDataWorkflow.run,+ DeleteProjectDataWorkflowInputs(team_ids=[1], project_id=None, user_id=7, project_name="env"),+ calls,+ )+ assert "delete_project_record_activity" not in calls+ assert calls == [*CORE_ACTIVITY_ORDER, "send_project_deleted_email_activity"]+++async def test_organization_workflow_deletes_record_then_emails():+ calls: list[str] = []+ await _run(+ DeleteOrganizationWorkflow.run,+ DeleteOrganizationWorkflowInputs(+ team_ids=[1, 2],+ organization_id="11111111-1111-1111-1111-111111111111",+ user_id=7,+ organization_name="org",+ project_names=["a", "b"],+ ),+ calls,+ )+ assert calls == [+ *CORE_ACTIVITY_ORDER,+ "delete_organization_record_activity",+ "send_organization_deleted_email_activity",+ ]+++def _core_activities_with(target_name: str, target_fn) -> list:+ """Core activity set where target_name uses target_fn and the rest are no-ops."""+ activities = [activity.defn(name=target_name)(target_fn)]+ for name in CORE_ACTIVITY_ORDER:+ if name == target_name:+ continue++ @activity.defn(name=name)+ async def _noop(inputs: TeamDataActivityInputs) -> None:+ pass++ activities.append(_noop)+ return activities+++async def _run_core_with(activities: list) -> None:+ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=WORKFLOWS,+ activities=activities,+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ await env.client.execute_workflow(+ DeleteTeamsDataWorkflow.run,+ DeleteTeamsDataWorkflowInputs(team_ids=[1], user_id=7),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )+++async def test_protected_error_fails_fast_without_retry():+ from django.db.models.deletion import ProtectedError++ attempts: list[str] = []++ async def raises_protected(inputs: TeamDataActivityInputs) -> None:+ attempts.append("attempt")+ raise ProtectedError("blocked by a PROTECT foreign key", set())++ activities = _core_activities_with("delete_misc_small_tables_activity", raises_protected)+ with pytest.raises(WorkflowFailureError):+ await _run_core_with(activities)++ assert len(attempts) == 1 # non-retryable: the workflow fails on the first attempt+++async def test_transient_error_is_retried():+ attempts: list[str] = []++ async def fails_once(inputs: TeamDataActivityInputs) -> None:+ attempts.append("attempt")+ if len(attempts) == 1:+ raise RuntimeError("transient database hiccup")++ activities = _core_activities_with("delete_misc_small_tables_activity", fails_once)+ await _run_core_with(activities) # completes despite the first failure++ assert len(attempts) == 2 # retried once, then succeeded