: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
chore(deletion): remove legacy Celery deletion path and rollout flag (#67435)
Yasen4d981aac4dbd
diff --git a/ee/api/test/test_organization.py b/ee/api/test/test_organization.pyindex 030c9b54585c..59f480093c5f 100644--- a/ee/api/test/test_organization.py+++ b/ee/api/test/test_organization.py@@ -60,7 +60,7 @@ class TestOrganizationEnterpriseAPI(APILicensedTest):response.json().items(),)- @patch("posthog.api.organization.delete_organization_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_organization_workflow")@patch("posthoganalytics.capture")def test_delete_second_managed_organization(self, mock_capture, mock_delete_task):organization, _, team = Organization.objects.bootstrap(self.user, name="X")@@ -84,7 +84,7 @@ class TestOrganizationEnterpriseAPI(APILicensedTest):properties=organization_props,groups={"instance": ANY, "organization": str(organization.id)},)- mock_delete_task.delay.assert_called_once_with(+ mock_delete_task.assert_called_once_with(team_ids=[team.id],organization_id=str(organization.id),user_id=self.user.id,@@ -92,7 +92,7 @@ class TestOrganizationEnterpriseAPI(APILicensedTest):project_names=[team.name],)- @patch("posthog.api.organization.delete_organization_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_organization_workflow")@patch("posthoganalytics.capture")def test_delete_last_organization(self, mock_capture, mock_delete_task):org_id = self.organization.id@@ -159,7 +159,7 @@ class TestOrganizationEnterpriseAPI(APILicensedTest):self.assertEqual(response.status_code, 403, potential_err_message)self.assertTrue(self.organization.name, self.CONFIG_ORGANIZATION_NAME)- @patch("posthog.api.organization.delete_organization_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_organization_workflow")def test_delete_organization_owning(self, mock_delete_task):self.organization_membership.level = OrganizationMembership.Level.OWNERself.organization_membership.save()diff --git a/ee/api/test/test_team.py b/ee/api/test/test_team.pyindex 56324345acb3..7b80aaec253a 100644--- a/ee/api/test/test_team.py+++ b/ee/api/test/test_team.py@@ -3,6 +3,7 @@ from typing import Optionalfrom freezegun import freeze_timefrom posthog.test.base import FuzzyInt+from unittest.mock import patchfrom rest_framework.status import HTTP_200_OK, HTTP_204_NO_CONTENT, HTTP_403_FORBIDDEN, HTTP_404_NOT_FOUND@@ -45,12 +46,13 @@ def team_enterprise_api_test_factory():# Deleting projects- def test_delete_team_as_org_admin_allowed(self):+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow")+ def test_delete_team_as_org_admin_allowed(self, mock_start_deletion):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()response = self.client.delete(f"/api/environments/{self.team.id}")self.assertEqual(response.status_code, HTTP_204_NO_CONTENT)- self.assertEqual(Team.objects.filter(organization=self.organization).count(), 0)+ mock_start_deletion.assert_called_once()def test_delete_team_as_org_member_forbidden(self):self.organization_membership.level = OrganizationMembership.Level.MEMBER@@ -65,13 +67,14 @@ def team_enterprise_api_test_factory():self.assertEqual(response.status_code, HTTP_403_FORBIDDEN)self.assertEqual(Team.objects.filter(organization=self.organization).count(), 1)- def test_delete_second_team_as_org_admin_allowed(self):+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow")+ def test_delete_second_team_as_org_admin_allowed(self, mock_start_deletion):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()team = Team.objects.create(organization=self.organization)response = self.client.delete(f"/api/environments/{team.id}")self.assertEqual(response.status_code, HTTP_204_NO_CONTENT)- self.assertEqual(Team.objects.filter(organization=self.organization).count(), 1)+ mock_start_deletion.assert_called_once()def test_no_delete_team_not_administrating_organization(self):self.organization_membership.level = OrganizationMembership.Level.MEMBERdiff --git a/posthog/api/organization.py b/posthog/api/organization.pyindex cb58f22bc3d8..484fc229e250 100644--- a/posthog/api/organization.py+++ b/posthog/api/organization.py@@ -49,7 +49,6 @@ from posthog.rbac.migrations.rbac_feature_flag_migration import rbac_feature_flafrom posthog.rbac.migrations.rbac_team_migration import rbac_team_access_control_migrationfrom posthog.rbac.user_access_control import UserAccessControlSerializerMixinfrom posthog.tasks.email import send_posthog_ai_access_request-from posthog.tasks.tasks import delete_organization_data_and_notify_taskfrom posthog.user_permissions import UserPermissions, UserPermissionsSerializerMixinfrom posthog.utils import get_safe_cache, safe_cache_set@@ -481,30 +480,17 @@ class OrganizationViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):organization.save(update_fields=["is_pending_deletion"])# 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,+ # ClickHouse, email) to the durable Temporal workflow.+ from posthog.temporal.delete_teams.dispatch import start_delete_organization_workflow++ 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,)- 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 6d2d9c6bae58..c509281a55d2 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -97,7 +97,6 @@ from posthog.session_recordings.data_retention import (retention_violates_entitlement,validate_retention_period,)-from posthog.tasks.tasks import delete_project_data_and_notify_taskfrom posthog.user_permissions import UserPermissions, UserPermissionsSerializerMixinfrom posthog.utils import get_instance_realm, get_ip_address, get_week_start_for_country_code@@ -1471,28 +1470,16 @@ class ProjectViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsetsproject.save(update_fields=["is_pending_deletion"])# 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,+ # ClickHouse, email) to the durable Temporal workflow.+ from posthog.temporal.delete_teams.dispatch import start_delete_project_data_workflow++ start_delete_project_data_workflow(+ team_ids=team_ids,+ project_id=project_id,+ user_id=user.id,+ project_name=project_name,)- 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 fc17a19cdbda..a52c42a24c46 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -1926,8 +1926,6 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Moreturn self.get_object()def perform_destroy(self, team: Team):- from posthog.tasks.tasks import delete_project_data_and_notify_task-# Check if bulk deletion operations are disabled via environment variableif settings.DISABLE_BULK_DELETES:raise exceptions.ValidationError(@@ -1941,28 +1939,16 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mouser = cast(User, self.request.user)# 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,+ # ClickHouse, email) to the durable Temporal workflow.+ from posthog.temporal.delete_teams.dispatch import start_delete_project_data_workflow++ 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,)- 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/api/test/test_bulk_deletion_disabled.py b/posthog/api/test/test_bulk_deletion_disabled.pyindex 222d8d227363..652971817831 100644--- a/posthog/api/test/test_bulk_deletion_disabled.py+++ b/posthog/api/test/test_bulk_deletion_disabled.py@@ -27,17 +27,17 @@ class TestBulkDeletionDisabled(APIBaseTest):self.assertTrue(Team.objects.filter(id=self.additional_team.id).exists())+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow")@patch("posthog.api.team.settings.DISABLE_BULK_DELETES", False)- def test_team_deletion_enabled(self):- """Test that team deletion works when DISABLE_BULK_DELETES is False."""+ def test_team_deletion_enabled(self, mock_start_deletion):+ """Test that team deletion is allowed (hands off to Temporal) when DISABLE_BULK_DELETES is False."""self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()response = self.client.delete(f"/api/environments/{self.additional_team.id}/")self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)-- self.assertFalse(Team.objects.filter(id=self.additional_team.id).exists())+ mock_start_deletion.assert_called_once()@patch("posthog.api.project.settings.DISABLE_BULK_DELETES", True)def test_project_deletion_disabled(self):diff --git a/posthog/api/test/test_organization.py b/posthog/api/test/test_organization.pyindex 80f93ba33958..9cd4ba5e11b4 100644--- a/posthog/api/test/test_organization.py+++ b/posthog/api/test/test_organization.py@@ -430,7 +430,7 @@ class TestOrganizationAPI(APIBaseTest):self.organization.refresh_from_db()self.assertTrue(getattr(self.organization, field))- @patch("posthog.api.organization.delete_organization_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_organization_workflow")def test_delete_organizations_and_verify_list(self, mock_delete_task):self.organization_membership.level = OrganizationMembership.Level.OWNERself.organization_membership.save()@@ -486,9 +486,12 @@ class TestOrganizationAPI(APIBaseTest):self.assertIn("active subscription", response.json()["detail"])self.assertTrue(Organization.objects.filter(id=self.organization.id).exists())+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_organization_workflow")@patch("ee.billing.billing_manager.BillingManager.get_billing")@patch("posthog.api.organization.get_cached_instance_license")- def test_can_delete_organization_without_active_subscription(self, mock_get_license, mock_get_billing):+ def test_can_delete_organization_without_active_subscription(+ self, mock_get_license, mock_get_billing, mock_start_deletion+ ):mock_get_license.return_value = Truemock_get_billing.return_value = {"has_active_subscription": False}@@ -500,9 +503,11 @@ class TestOrganizationAPI(APIBaseTest):response = self.client.delete(f"/api/organizations/{org_id}")self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)- self.assertFalse(Organization.objects.filter(id=org_id).exists())+ # Deletion runs asynchronously on Temporal, so the org is marked pending, not removed synchronously+ self.assertTrue(Organization.objects.get(id=org_id).is_pending_deletion)+ mock_start_deletion.assert_called_once()- @patch("posthog.api.organization.delete_organization_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_organization_workflow")def test_delete_organization_sets_pending_deletion_flag(self, mock_delete_task):self.organization_membership.level = OrganizationMembership.Level.OWNERself.organization_membership.save()@@ -512,9 +517,9 @@ class TestOrganizationAPI(APIBaseTest):self.organization.refresh_from_db()self.assertTrue(self.organization.is_pending_deletion)- mock_delete_task.delay.assert_called_once()+ mock_delete_task.assert_called_once()- @patch("posthog.api.organization.delete_organization_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_organization_workflow")def test_delete_organization_preserves_memberships(self, mock_delete_task):self.organization_membership.level = OrganizationMembership.Level.OWNERself.organization_membership.save()@@ -524,7 +529,7 @@ class TestOrganizationAPI(APIBaseTest):self.assertTrue(OrganizationMembership.objects.filter(organization=self.organization, user=self.user).exists())- @patch("posthog.api.organization.delete_organization_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_organization_workflow")def test_delete_organization_returns_pending_deletion_in_api(self, mock_delete_task):self.organization_membership.level = OrganizationMembership.Level.OWNERself.organization_membership.save()@@ -535,7 +540,7 @@ class TestOrganizationAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertTrue(response.json()["is_pending_deletion"])- @patch("posthog.api.organization.delete_organization_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_organization_workflow")def test_delete_organization_already_pending_deletion_returns_400(self, mock_delete_task):self.organization_membership.level = OrganizationMembership.Level.OWNERself.organization_membership.save()@@ -546,9 +551,9 @@ class TestOrganizationAPI(APIBaseTest):response = self.client.delete(f"/api/organizations/{self.organization.id}")self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertIn("already being deleted", response.json()["detail"])- mock_delete_task.delay.assert_not_called()+ mock_delete_task.assert_not_called()- @patch("posthog.api.organization.delete_organization_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_organization_workflow")@patch("posthog.event_usage.posthoganalytics.capture")def test_delete_organization_fires_initiated_event(self, mock_capture, mock_delete_task):self.organization_membership.level = OrganizationMembership.Level.OWNERdiff --git a/posthog/api/test/test_project.py b/posthog/api/test/test_project.pyindex 48d7107b2c57..a6145cba7498 100644--- a/posthog/api/test/test_project.py+++ b/posthog/api/test/test_project.py@@ -342,7 +342,7 @@ class TestProjectAPI(team_api_test_factory()): # type: ignoreself.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.json()["name"], "Updated Name")- @patch("posthog.api.project.delete_project_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow")def test_project_deletion_queues_async_task(self, mock_delete_task):"""Verify that project deletion queues async task for full deletion."""viewset = ProjectViewSet()@@ -357,9 +357,9 @@ class TestProjectAPI(team_api_test_factory()): # type: ignoreviewset.perform_destroy(self.project)- # Project deletion happens async in Celery task+ # Project deletion happens async in the Temporal workflow- mock_delete_task.delay.assert_called_once_with(+ mock_delete_task.assert_called_once_with(team_ids=[team_id],project_id=project_id,user_id=self.user.id,@@ -375,7 +375,7 @@ class TestProjectAPI(team_api_test_factory()): # type: ignore("cloud_no_license", True, 1, True, None, status.HTTP_204_NO_CONTENT),])- @patch("posthog.api.project.delete_project_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow")@patch("ee.billing.billing_manager.BillingManager.get_billing")@patch("posthog.api.project.get_cached_instance_license")def test_delete_last_project_subscription_guard(@@ -409,7 +409,7 @@ class TestProjectAPI(team_api_test_factory()): # type: ignoreself.assertIn("active subscription", response.json()["detail"])self.assertTrue(Project.objects.filter(id=self.project.id).exists())- @patch("posthog.api.project.delete_project_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow")def test_project_deletion_sets_pending_deletion_flag(self, mock_delete_task):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()@@ -419,9 +419,9 @@ class TestProjectAPI(team_api_test_factory()): # type: ignoreself.project.refresh_from_db()self.assertTrue(self.project.is_pending_deletion)- mock_delete_task.delay.assert_called_once()+ mock_delete_task.assert_called_once()- @patch("posthog.api.project.delete_project_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow")def test_project_deletion_returns_pending_deletion_in_api(self, mock_delete_task):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()@@ -432,7 +432,7 @@ class TestProjectAPI(team_api_test_factory()): # type: ignoreself.assertEqual(response.status_code, status.HTTP_200_OK)self.assertTrue(response.json()["is_pending_deletion"])- @patch("posthog.api.project.delete_project_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow")def test_delete_project_already_pending_deletion_returns_400(self, mock_delete_task):self.organization_membership.level = OrganizationMembership.Level.ADMINself.organization_membership.save()@@ -443,7 +443,7 @@ class TestProjectAPI(team_api_test_factory()): # type: ignoreresponse = self.client.delete(f"/api/projects/{self.project.id}")self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)self.assertIn("already being deleted", response.json()["detail"])- mock_delete_task.delay.assert_not_called()+ mock_delete_task.assert_not_called()def test_team_deletion_does_not_cascade_to_persons(self):"""Verify that deleting Team directly doesn't CASCADE delete Persons (on_delete=DO_NOTHING)."""diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex 1fd19dbe8690..99db5c29ce59 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -1,13 +1,11 @@-import jsonfrom datetime import UTC, datetime, timedeltafrom typing import Anyfrom freezegun import freeze_time-from posthog.test.base import APIBaseTest, QueryMatchingTest, snapshot_postgres_queries_context+from posthog.test.base import APIBaseTest, QueryMatchingTestfrom unittest import mockfrom unittest.mock import ANY, MagicMock, call, patch-from django.conf import settingsfrom django.core.cache import cachefrom django.db import OperationalErrorfrom django.http import HttpResponse@@ -16,7 +14,6 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status, test-from temporalio.service import RPCErrorfrom posthog.api.team import (TEAM_CONFIG_FIELDS_SET,@@ -26,7 +23,6 @@ from posthog.api.team import (_reset_default_data_color_theme_id_cache,)from posthog.constants import AvailableFeature-from posthog.models import ActivityLogfrom posthog.models.group_type_mapping import (GROUP_TYPES_CACHE_KEY_PREFIX,GROUP_TYPES_STALE_CACHE_KEY_PREFIX,@@ -41,15 +37,10 @@ from posthog.models.project import Projectfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.models.utils import generate_random_token_personal, hash_key_value-from posthog.temporal.common.client import sync_connect-from posthog.temporal.common.schedule import describe_schedule-from posthog.temporal.common.test_utils import start_test_workerfrom posthog.test.test_utils import create_group_type_mapping_without_created_atfrom posthog.utils import get_instance_realm-from products.batch_exports.backend.temporal import ACTIVITIES, WORKFLOWSfrom products.dashboards.backend.models.dashboard import Dashboard-from products.early_access_features.backend.models import EarlyAccessFeaturefrom ee.models.rbac.access_control import AccessControl@@ -400,110 +391,12 @@ def team_api_test_factory():[{"key": "$current_url", "value": "test"}],)- @freeze_time("2022-02-08")- def test_delete_team_activity_log(self):- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization_membership.save()-- team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)-- response = self.client.delete(f"/api/environments/{team.id}")- assert response.status_code == 204-- # activity log is queried in the context of the team- # and the team was deleted, so we can't (for now) view a deleted team activity via the API- # even though the activity log is recorded-- deleted_team_activity_response = self.client.get(f"/api/environments/{team.id}/activity")- assert deleted_team_activity_response.status_code == status.HTTP_404_NOT_FOUND-- # we can't query by API but can prove the log was recorded- activity = [a.__dict__ for a in ActivityLog.objects.filter(team_id=team.pk).order_by("scope").all()]- expected_activity = [- {- "_state": ANY,- "id": ANY,- "team_id": team.pk,- "organization_id": ANY,- "user_id": None,- "was_impersonated": False,- "is_system": True,- "activity": "created",- "item_id": ANY,- "scope": "Dashboard",- "detail": {- "name": "Your starter dashboard",- "type": "dashboard",- "changes": [],- "context": None,- "short_id": None,- "trigger": None,- },- "client": None,- "created_at": ANY,- "ip_address": None,- },- {- "_state": ANY,- "activity": "deleted",- "created_at": ANY,- "detail": {- "changes": None,- "context": None,- "name": "Default project",- "short_id": None,- "trigger": None,- "type": None,- },- "id": ANY,- "is_system": False,- "organization_id": ANY,- "team_id": team.pk,- "item_id": str(team.pk),- "scope": "Team",- "user_id": self.user.pk,- "was_impersonated": False,- "client": None,- "ip_address": "127.0.0.1",- },- ]- if self.client_class is EnvironmentToProjectRewriteClient:- expected_activity.insert(- 1,- {- "_state": ANY,- "activity": "deleted",- "created_at": ANY,- "detail": {- "changes": None,- "context": None,- "name": "Default project",- "short_id": None,- "trigger": None,- "type": None,- },- "id": ANY,- "is_system": False,- "organization_id": ANY,- "team_id": team.pk,- "item_id": str(team.project_id),- "scope": "Project",- "user_id": self.user.pk,- "was_impersonated": False,- "client": None,- "ip_address": "127.0.0.1",- },- )- assert activity == expected_activity-- @patch("posthog.api.project.delete_project_data_and_notify_task")- @patch("posthog.tasks.tasks.delete_project_data_and_notify_task")+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow")@patch("posthoganalytics.capture")def test_delete_team_own_second(self,mock_capture: MagicMock,- mock_delete_task_team: MagicMock,- mock_delete_task_project: MagicMock,+ mock_start_workflow: MagicMock,):# NOTE: the factory-level setUp already bumps to ADMIN (without firing the# "membership level changed" event because it uses .update() to bypass signals),@@ -520,8 +413,8 @@ def team_api_test_factory():response = self.client.delete(f"/api/environments/{team.id}")self.assertEqual(response.status_code, 204)- # Team deletion happens async in the (mocked) Celery task, so team still exists- # We only verify the task was queued correctly+ # Team deletion happens async in the (mocked) Temporal workflow, so team still exists+ # We only verify the workflow was started correctlyexpected_capture_calls = [call(distinct_id=self.user.distinct_id,@@ -541,14 +434,14 @@ def team_api_test_factory():send_feature_flags=False,))- mock_delete_task_project.delay.assert_called_once_with(+ mock_start_workflow.assert_called_once_with(team_ids=[team_pk],project_id=team_pk,user_id=self.user.id,project_name="Default project",)else:- mock_delete_task_team.delay.assert_called_once_with(+ mock_start_workflow.assert_called_once_with(team_ids=[team_pk],project_id=None,user_id=self.user.id,@@ -556,216 +449,6 @@ def team_api_test_factory():)assert mock_capture.call_args_list == expected_capture_calls- def test_delete_bulky_postgres_data(self):- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization_membership.save()-- team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)-- self.assertEqual(Team.objects.filter(organization=self.organization).count(), 2)- from posthog.personhog_client.fake_client import get_active_fake- from posthog.test.persons import add_cohort_members, add_distinct_id, create_person-- from products.cohorts.backend.models.cohort import Cohort- from products.feature_flags.backend.models.feature_flag import FeatureFlag-- cohort = Cohort.objects.create(team=team, created_by=self.user, name="test")- person = create_person(- team=team,- distinct_ids=["example_id"],- properties={"email": "[email protected]", "team": "posthog"},- )- add_distinct_id(person=person, distinct_id="test")- flag = FeatureFlag.objects.create(- team=team,- name="test",- key="test",- created_by=self.user,- )- add_cohort_members(cohort, [person])- EarlyAccessFeature.objects.create(- team=team,- name="Test flag",- description="A fancy new flag.",- stage="beta",- feature_flag=flag,- )-- # if something is missing then teardown fails- with snapshot_postgres_queries_context(- self, custom_query_matcher=lambda query: "DELETE" in query and "posthog_person" in query- ):- response = self.client.delete(f"/api/environments/{team.id}")- self.assertEqual(response.status_code, 204)-- # Verify personhog RPCs were called for persons-DB cleanup- 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",- ]:- fake.assert_called(rpc)-- def test_delete_batch_exports(self):- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization_membership.save()- self.organization.save()- team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)-- destination_data = {- "type": "AwsS3",- "config": {- "bucket_name": "my-production-s3-bucket",- "region": "us-east-1",- "prefix": "posthog-events/",- "aws_access_key_id": "abc123",- "aws_secret_access_key": "secret",- },- }-- batch_export_data = {- "name": "my-production-s3-bucket-destination",- "destination": destination_data,- "interval": "hour",- }-- temporal = sync_connect()-- with start_test_worker(- temporal,- task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,- workflows=WORKFLOWS,- activities=ACTIVITIES,- ):- response = self.client.post(- f"/api/environments/{team.id}/batch_exports",- json.dumps(batch_export_data),- content_type="application/json",- )- assert response.status_code == 201, response.json()-- batch_export = response.json()- batch_export_id = batch_export["id"]-- response = self.client.delete(f"/api/environments/{team.id}")- assert response.status_code == 204, response.json()-- response = self.client.get(f"/api/environments/{team.id}/batch_exports/{batch_export_id}")- assert response.status_code == 404, response.json()-- with self.assertRaises(RPCError):- describe_schedule(temporal, batch_export_id)-- def test_delete_team_with_already_deleted_batch_export(self):- """Team deletion should succeed even if batch exports were already soft-deleted."""- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization_membership.save()- self.organization.save()- team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)-- destination_data = {- "type": "AwsS3",- "config": {- "bucket_name": "my-production-s3-bucket",- "region": "us-east-1",- "prefix": "posthog-events/",- "aws_access_key_id": "abc123",- "aws_secret_access_key": "secret",- },- }-- batch_export_data = {- "name": "my-production-s3-bucket-destination",- "destination": destination_data,- "interval": "hour",- }-- temporal = sync_connect()-- with start_test_worker(- temporal,- task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,- workflows=WORKFLOWS,- activities=ACTIVITIES,- ):- response = self.client.post(- f"/api/environments/{team.id}/batch_exports",- json.dumps(batch_export_data),- content_type="application/json",- )- assert response.status_code == 201, response.json()-- batch_export = response.json()- batch_export_id = batch_export["id"]-- # Delete the batch export first (this soft-deletes it and removes the Temporal schedule)- response = self.client.delete(f"/api/environments/{team.id}/batch_exports/{batch_export_id}")- assert response.status_code == 204-- # Verify the schedule is gone- with self.assertRaises(RPCError):- describe_schedule(temporal, batch_export_id)-- # Now delete the team - this should succeed- response = self.client.delete(f"/api/environments/{team.id}")- assert response.status_code == 204-- @patch("posthog.temporal.common.schedule.delete_schedule")- @patch("posthog.models.team.util.sync_connect")- def test_delete_data_modeling_schedules(self, mock_sync_connect, mock_delete_schedule):- from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery-- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization_membership.save()-- team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)-- saved_query = DataWarehouseSavedQuery.objects.create(- team=team,- name="test_scheduled_query",- query={"kind": "HogQLQuery", "query": "SELECT 1"},- sync_frequency_interval=timedelta(hours=1),- )-- mock_temporal = MagicMock()- mock_sync_connect.return_value = mock_temporal-- response = self.client.delete(f"/api/environments/{team.id}")- assert response.status_code == 204-- mock_delete_schedule.assert_called_once_with(mock_temporal, schedule_id=str(saved_query.id))-- @patch("posthog.temporal.common.schedule.delete_schedule")- @patch("posthog.models.team.util.sync_connect")- def test_delete_data_modeling_schedules_handles_not_found(self, mock_sync_connect, mock_delete_schedule):- import temporalio.service-- from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery-- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization_membership.save()-- team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)-- DataWarehouseSavedQuery.objects.create(- team=team,- name="test_missing_schedule",- query={"kind": "HogQLQuery", "query": "SELECT 1"},- sync_frequency_interval=timedelta(hours=1),- )-- mock_temporal = MagicMock()- mock_sync_connect.return_value = mock_temporal-- rpc_error = temporalio.service.RPCError("not found", temporalio.service.RPCStatusCode.NOT_FOUND, b"")- mock_delete_schedule.side_effect = rpc_error-- response = self.client.delete(f"/api/environments/{team.id}")- assert response.status_code == 204-@freeze_time("2022-02-08")def test_reset_token(self):self.organization_membership.level = OrganizationMembership.Level.ADMINdiff --git a/posthog/api/test/test_team_deletion.py b/posthog/api/test/test_team_deletion.pynew file mode 100644index 000000000000..960b0271d3eb--- /dev/null+++ b/posthog/api/test/test_team_deletion.py@@ -0,0 +1,282 @@+import json+from datetime import timedelta++from freezegun import freeze_time+from posthog.test.base import NonAtomicBaseTest+from unittest.mock import ANY, MagicMock, patch++from django.conf import settings++from temporalio.service import RPCError++from posthog.models import OrganizationMembership, Team+from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.temporal.common.client import sync_connect+from posthog.temporal.common.schedule import describe_schedule+from posthog.temporal.common.test_utils import start_test_worker+from posthog.temporal.tests.delete_teams.inline import execute_deletion_workflows_inline++from products.batch_exports.backend.temporal import ACTIVITIES, WORKFLOWS+from products.early_access_features.backend.models import EarlyAccessFeature+++class TestTeamDeletionSideEffects(NonAtomicBaseTest):+ """Deletion side-effect coverage, exercised by running the Temporal deletion workflow inline.++ These tests assert on the actual effects of team deletion (records removed, batch exports and+ schedules torn down, persons cleaned up). They run the durable Temporal workflow to completion+ via ``execute_deletion_workflows_inline`` and therefore require a non-atomic test case so the+ workflow's activities (which run on their own connections) can see committed test data.+ """++ # Recreate org/team/user per test: TransactionTestCase flushes the DB between tests, which would+ # otherwise leave class-level fixture data dangling.+ CLASS_DATA_LEVEL_SETUP = False++ def setUp(self):+ super().setUp()+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()+ self.client.force_login(self.user)++ @freeze_time("2022-02-08")+ def test_delete_team_activity_log(self):+ team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)++ with execute_deletion_workflows_inline():+ response = self.client.delete(f"/api/environments/{team.id}")+ assert response.status_code == 204++ # The team was deleted, so its activity can no longer be viewed via the API even though it was recorded+ deleted_team_activity_response = self.client.get(f"/api/environments/{team.id}/activity")+ assert deleted_team_activity_response.status_code == 404++ # We can't query by API but can prove the deletion was recorded in the activity log+ activity = [a.__dict__ for a in ActivityLog.objects.filter(team_id=team.pk).order_by("scope").all()]+ assert activity == [+ {+ "_state": ANY,+ "id": ANY,+ "team_id": team.pk,+ "organization_id": ANY,+ "user_id": None,+ "was_impersonated": False,+ "is_system": True,+ "activity": "created",+ "item_id": ANY,+ "scope": "Dashboard",+ "detail": {+ "name": "Your starter dashboard",+ "type": "dashboard",+ "changes": [],+ "context": None,+ "short_id": None,+ "trigger": None,+ },+ "client": None,+ "created_at": ANY,+ "ip_address": None,+ },+ {+ "_state": ANY,+ "activity": "deleted",+ "created_at": ANY,+ "detail": {+ "changes": None,+ "context": None,+ "name": "Default project",+ "short_id": None,+ "trigger": None,+ "type": None,+ },+ "id": ANY,+ "is_system": False,+ "organization_id": ANY,+ "team_id": team.pk,+ "item_id": str(team.pk),+ "scope": "Team",+ "user_id": self.user.pk,+ "was_impersonated": False,+ "client": None,+ "ip_address": "127.0.0.1",+ },+ ]++ def test_delete_bulky_postgres_data(self):+ from posthog.personhog_client.fake_client import get_active_fake+ from posthog.test.persons import add_cohort_members, add_distinct_id, create_person++ from products.cohorts.backend.models.cohort import Cohort+ from products.feature_flags.backend.models.feature_flag import FeatureFlag++ team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)+ self.assertEqual(Team.objects.filter(organization=self.organization).count(), 2)++ cohort = Cohort.objects.create(team=team, created_by=self.user, name="test")+ person = create_person(+ team=team,+ distinct_ids=["example_id"],+ properties={"email": "[email protected]", "team": "posthog"},+ )+ add_distinct_id(person=person, distinct_id="test")+ flag = FeatureFlag.objects.create(team=team, name="test", key="test", created_by=self.user)+ add_cohort_members(cohort, [person])+ EarlyAccessFeature.objects.create(+ team=team, name="Test flag", description="A fancy new flag.", stage="beta", feature_flag=flag+ )++ with execute_deletion_workflows_inline():+ response = self.client.delete(f"/api/environments/{team.id}")+ self.assertEqual(response.status_code, 204)+ self.assertFalse(Team.objects.filter(id=team.id).exists())++ # Verify personhog RPCs were called for persons-DB cleanup+ 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",+ ]:+ fake.assert_called(rpc)++ def test_delete_batch_exports(self):+ team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)++ batch_export_data = {+ "name": "my-production-s3-bucket-destination",+ "destination": {+ "type": "AwsS3",+ "config": {+ "bucket_name": "my-production-s3-bucket",+ "region": "us-east-1",+ "prefix": "posthog-events/",+ "aws_access_key_id": "abc123",+ "aws_secret_access_key": "secret",+ },+ },+ "interval": "hour",+ }++ temporal = sync_connect()++ with start_test_worker(+ temporal,+ task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,+ workflows=WORKFLOWS,+ activities=ACTIVITIES,+ ):+ response = self.client.post(+ f"/api/environments/{team.id}/batch_exports",+ json.dumps(batch_export_data),+ content_type="application/json",+ )+ assert response.status_code == 201, response.json()+ batch_export_id = response.json()["id"]++ with execute_deletion_workflows_inline():+ response = self.client.delete(f"/api/environments/{team.id}")+ assert response.status_code == 204, response.json()++ response = self.client.get(f"/api/environments/{team.id}/batch_exports/{batch_export_id}")+ assert response.status_code == 404, response.json()++ with self.assertRaises(RPCError):+ describe_schedule(temporal, batch_export_id)++ def test_delete_team_with_already_deleted_batch_export(self):+ """Team deletion should succeed even if batch exports were already soft-deleted."""+ team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)++ batch_export_data = {+ "name": "my-production-s3-bucket-destination",+ "destination": {+ "type": "AwsS3",+ "config": {+ "bucket_name": "my-production-s3-bucket",+ "region": "us-east-1",+ "prefix": "posthog-events/",+ "aws_access_key_id": "abc123",+ "aws_secret_access_key": "secret",+ },+ },+ "interval": "hour",+ }++ temporal = sync_connect()++ with start_test_worker(+ temporal,+ task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,+ workflows=WORKFLOWS,+ activities=ACTIVITIES,+ ):+ response = self.client.post(+ f"/api/environments/{team.id}/batch_exports",+ json.dumps(batch_export_data),+ content_type="application/json",+ )+ assert response.status_code == 201, response.json()+ batch_export_id = response.json()["id"]++ # Delete the batch export first (this soft-deletes it and removes the Temporal schedule)+ response = self.client.delete(f"/api/environments/{team.id}/batch_exports/{batch_export_id}")+ assert response.status_code == 204++ with self.assertRaises(RPCError):+ describe_schedule(temporal, batch_export_id)++ # Now delete the team - this should succeed+ with execute_deletion_workflows_inline():+ response = self.client.delete(f"/api/environments/{team.id}")+ assert response.status_code == 204++ @patch("posthog.temporal.common.schedule.delete_schedule")+ @patch("posthog.models.team.util.sync_connect")+ def test_delete_data_modeling_schedules(self, mock_sync_connect, mock_delete_schedule):+ from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery++ team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)++ saved_query = DataWarehouseSavedQuery.objects.create(+ team=team,+ name="test_scheduled_query",+ query={"kind": "HogQLQuery", "query": "SELECT 1"},+ sync_frequency_interval=timedelta(hours=1),+ )++ mock_temporal = MagicMock()+ mock_sync_connect.return_value = mock_temporal++ with execute_deletion_workflows_inline():+ response = self.client.delete(f"/api/environments/{team.id}")+ assert response.status_code == 204++ mock_delete_schedule.assert_called_once_with(mock_temporal, schedule_id=str(saved_query.id))++ @patch("posthog.temporal.common.schedule.delete_schedule")+ @patch("posthog.models.team.util.sync_connect")+ def test_delete_data_modeling_schedules_handles_not_found(self, mock_sync_connect, mock_delete_schedule):+ import temporalio.service++ from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery++ team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)++ DataWarehouseSavedQuery.objects.create(+ team=team,+ name="test_missing_schedule",+ query={"kind": "HogQLQuery", "query": "SELECT 1"},+ sync_frequency_interval=timedelta(hours=1),+ )++ mock_temporal = MagicMock()+ mock_sync_connect.return_value = mock_temporal+ mock_delete_schedule.side_effect = temporalio.service.RPCError(+ "not found", temporalio.service.RPCStatusCode.NOT_FOUND, b""+ )++ with execute_deletion_workflows_inline():+ response = self.client.delete(f"/api/environments/{team.id}")+ assert response.status_code == 204diff --git a/posthog/api/test/test_team_project_differential.py b/posthog/api/test/test_team_project_differential.pyindex e36f385568f8..4b6bae27bde3 100644--- a/posthog/api/test/test_team_project_differential.py+++ b/posthog/api/test/test_team_project_differential.py@@ -458,9 +458,8 @@ class TestLifecycleMethodDivergences(DifferentialParityBase):self.assertEqual(env.status_code, status.HTTP_400_BAD_REQUEST, env.json())self.assertEqual(proj.status_code, status.HTTP_201_CREATED, proj.json())- @patch("posthog.api.project.delete_project_data_and_notify_task")- @patch("posthog.tasks.tasks.delete_project_data_and_notify_task")- def test_delete_common_case_parity_but_project_is_a_superset(self, mock_team_task, mock_project_task):+ @patch("posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow")+ def test_delete_common_case_parity_but_project_is_a_superset(self, mock_start_workflow):project_a, team_a = self._make_twin()project_b, team_b = self._make_twin()@@ -475,8 +474,10 @@ class TestLifecycleMethodDivergences(DifferentialParityBase):# whole project (project_id set + all child team_ids) AND additionally enforces a last-project active-# subscription guard. In the 1:1 world the data actually removed is equivalent, but post-redirect an# env DELETE would inherit the project guard/cascade. This requires explicit product sign-off.- env_kwargs = mock_team_task.delay.call_args.kwargs- proj_kwargs = mock_project_task.delay.call_args.kwargs+ # Both routes now start the same Temporal workflow; the env delete runs first, the project delete second.+ self.assertEqual(mock_start_workflow.call_count, 2)+ env_kwargs = mock_start_workflow.call_args_list[0].kwargs+ proj_kwargs = mock_start_workflow.call_args_list[1].kwargsself.assertIsNone(env_kwargs["project_id"])self.assertEqual(proj_kwargs["project_id"], project_b.id)self.assertEqual(env_kwargs["team_ids"], [team_a.id])diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex 843457236a0f..7c267ce83bae 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -5,7 +5,7 @@ from typing import castfrom urllib.parse import quote, unquotefrom freezegun.api import freeze_time-from posthog.test.base import APIBaseTest+from posthog.test.base import APIBaseTest, NonAtomicBaseTestfrom unittest import mockfrom unittest.mock import ANY, patch@@ -32,6 +32,7 @@ from posthog.models.organization_domain import OrganizationDomainfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_valuefrom posthog.models.webauthn_credential import WebauthnCredential+from posthog.temporal.tests.delete_teams.inline import execute_deletion_workflows_inlinefrom products.dashboards.backend.models.dashboard import Dashboard@@ -1534,42 +1535,6 @@ class TestUserAPI(APIBaseTest):properties=mock.ANY,)- @patch("posthoganalytics.capture")- def test_can_delete_account_after_deleting_only_organization(self, mock_capture):- org = Organization.objects.create(name="Solo Org")- user = User.objects.create(email="[email protected]", password="testpassword")- OrganizationMembership.objects.create(- user=user,- organization=org,- level=OrganizationMembership.Level.OWNER,- )- self.client.force_login(user)-- # User belongs to exactly one organization- response = self.client.get("/api/users/@me/")- assert response.status_code == status.HTTP_200_OK- assert len(response.json()["organizations"]) == 1-- # Cannot delete account while still a member of an organization- response = self.client.delete("/api/users/@me/")- assert response.status_code == status.HTTP_409_CONFLICT-- # Delete the organization- response = self.client.delete(f"/api/organizations/{org.id}")- assert response.status_code == status.HTTP_204_NO_CONTENT-- # Membership is removed synchronously so the user immediately- # sees zero organizations, even before the async Celery task runs- assert not OrganizationMembership.objects.filter(user=user).exists()- response = self.client.get("/api/users/@me/")- assert response.status_code == status.HTTP_200_OK- assert len(response.json()["organizations"]) == 0-- # Now the user can delete their account- response = self.client.delete("/api/users/@me/")- assert response.status_code == status.HTTP_204_NO_CONTENT- assert not User.objects.filter(pk=user.pk).exists()-def test_cannot_delete_another_user_with_no_org_memberships(self):user = self._create_user("[email protected]", password="test")@@ -2960,3 +2925,49 @@ class TestUserTwoFactor(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)response_data = response.json()self.assertEqual(response_data["uuid"], str(self.user.uuid))+++class TestUserDeletionAfterOrgDeletion(NonAtomicBaseTest):+ """Deleting a user's only organization (which runs on Temporal) must let them delete their account.++ The org-deletion workflow runs inline so the membership cascade actually completes; that requires a+ non-atomic test case, since the workflow's activities run on their own database connections.+ """++ CLASS_DATA_LEVEL_SETUP = False++ @patch("posthoganalytics.capture")+ def test_can_delete_account_after_deleting_only_organization(self, mock_capture):+ org = Organization.objects.create(name="Solo Org")+ user = User.objects.create(email="[email protected]", password="testpassword")+ OrganizationMembership.objects.create(+ user=user,+ organization=org,+ level=OrganizationMembership.Level.OWNER,+ )+ self.client.force_login(user)++ # User belongs to exactly one organization+ response = self.client.get("/api/users/@me/")+ assert response.status_code == status.HTTP_200_OK+ assert len(response.json()["organizations"]) == 1++ # Cannot delete account while still a member of an organization+ response = self.client.delete("/api/users/@me/")+ assert response.status_code == status.HTTP_409_CONFLICT++ # Delete the organization (runs the deletion workflow to completion)+ with execute_deletion_workflows_inline():+ response = self.client.delete(f"/api/organizations/{org.id}")+ assert response.status_code == status.HTTP_204_NO_CONTENT++ # The membership cascade removed the user's memberships, so they now see zero organizations+ assert not OrganizationMembership.objects.filter(user=user).exists()+ response = self.client.get("/api/users/@me/")+ assert response.status_code == status.HTTP_200_OK+ assert len(response.json()["organizations"]) == 0++ # Now the user can delete their account+ response = self.client.delete("/api/users/@me/")+ assert response.status_code == status.HTTP_204_NO_CONTENT+ assert not User.objects.filter(pk=user.pk).exists()diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex 212194a8ebf4..c17a30d6a36f 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -7,7 +7,7 @@ if TYPE_CHECKING:from uuid import UUIDfrom django.conf import settings-from django.db import ProgrammingError, connection, transaction+from django.db import ProgrammingError, connectionfrom django.utils import timezoneimport requests@@ -1155,185 +1155,6 @@ def _queue_delete_team_recordings(team_ids: list[int], deleted_by: str) -> None:asyncio.run(start_all())-def _delete_teams_and_data(team_ids: list[int], user_id: int, project_id: int | None = None) -> None:- """- Shared logic for deleting teams and all associated data (Postgres, batch exports, ClickHouse).- """- from posthog.models.async_deletion import AsyncDeletion, DeletionType- from posthog.models.project import Project- from posthog.models.team import Team- from posthog.models.team.util import (- delete_batch_exports,- delete_bulky_postgres_data,- delete_data_modeling_schedules,- )- from posthog.models.user import User-- # User may have already deleted their account after requesting org deletion,- # so we must not block the cleanup on user existence.- user = User.objects.filter(id=user_id).first()-- try:- deleted_by = user.email if user else f"deleted_user_id:{user_id}"- _queue_delete_team_recordings(team_ids, deleted_by=deleted_by)- except Exception:- logger.exception("Failed to queue recording deletion workflows", team_ids=team_ids)- capture_exception()-- logger.info("Deleting bulky postgres data", team_ids=team_ids)- delete_bulky_postgres_data(team_ids=team_ids)-- logger.info("Deleting batch exports", team_ids=team_ids)- delete_batch_exports(team_ids=team_ids)-- logger.info("Deleting data modeling schedules", team_ids=team_ids)- delete_data_modeling_schedules(team_ids=team_ids)-- logger.info("Deleting team records", team_ids=team_ids)- # FOR UPDATE on teams blocks concurrent FK-inserts to any child table during cascade.- with transaction.atomic():- list(Team.objects.select_for_update().filter(id__in=team_ids))- if project_id:- Project.objects.filter(id=project_id).delete()- else:- Team.objects.filter(id__in=team_ids).delete()-- logger.info("Queueing ClickHouse deletion", team_ids=team_ids)- 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,- )---@shared_task(- ignore_result=True,- queue=CeleryQueue.LONG_RUNNING.value,- autoretry_for=(Exception,),- max_retries=3,- retry_backoff=60,- retry_backoff_max=300,-)-def delete_project_data_and_notify_task(- team_ids: list[int],- project_id: int | None,- user_id: int,- project_name: str,-) -> None:- """- Task to delete project/team and all associated data, then notify user.-- Args:- team_ids: List of team IDs whose data should be deleted- project_id: Project ID to delete (None if deleting just a team/environment)- user_id: User who initiated the deletion (for email notification)- project_name: Name of the deleted project/team (for email notification)- """- from posthog.email import is_email_available- from posthog.tasks.email import send_project_deleted_email-- logger.info("Starting project data deletion", team_ids=team_ids, project_name=project_name, project_id=project_id)-- try:- _delete_teams_and_data(team_ids, user_id, project_id)- logger.info("Project data deletion completed", team_ids=team_ids, project_name=project_name)- if is_email_available():- send_project_deleted_email.delay(user_id=user_id, project_name=project_name)- except Exception as e:- logger.error(- "Project data deletion failed", team_ids=team_ids, project_name=project_name, error=str(e), exc_info=True- )- capture_exception(- e,- additional_properties={- "task": "delete_project_data_and_notify",- "team_ids": team_ids,- "project_name": project_name,- },- )- raise---@shared_task(- ignore_result=True,- queue=CeleryQueue.LONG_RUNNING.value,- autoretry_for=(Exception,),- max_retries=3,- retry_backoff=60,- retry_backoff_max=300,-)-@skip_team_scope_audit-def delete_organization_data_and_notify_task(- team_ids: list[int],- organization_id: str,- user_id: int,- organization_name: str,- project_names: list[str],-) -> None:- """- Task to delete organization and all associated data, then notify user.-- Args:- team_ids: List of team IDs whose data should be deleted- organization_id: UUID of the organization to delete- user_id: User who initiated the deletion (for email notification)- organization_name: Name of the deleted organization (for email notification)- project_names: Names of all projects in the organization (for email notification)- """- from posthog.email import is_email_available- from posthog.event_usage import report_organization_deletion_completed- from posthog.models.organization import Organization- from posthog.tasks.email import send_organization_deleted_email-- logger.info(- "Starting organization data deletion",- team_ids=team_ids,- organization_name=organization_name,- organization_id=organization_id,- )-- try:- # Delete teams and their data first- if team_ids:- _delete_teams_and_data(team_ids, user_id)-- # Delete the organization record- if organization_id:- logger.info("Deleting organization record", organization_id=organization_id)- Organization.objects.filter(id=organization_id).delete()-- logger.info("Organization data deletion completed", team_ids=team_ids, organization_name=organization_name)- report_organization_deletion_completed(user_id=user_id, organization_id=organization_id)- if is_email_available():- send_organization_deleted_email.delay(- user_id=user_id, organization_name=organization_name, project_names=project_names- )- except Exception as e:- logger.error(- "Organization data deletion failed",- team_ids=team_ids,- organization_name=organization_name,- error=str(e),- exc_info=True,- )- capture_exception(- e,- additional_properties={- "task": "delete_organization_data_and_notify",- "team_ids": team_ids,- "organization_name": organization_name,- },- )- raise--@shared_task(bind=True,base=PushGatewayTask,diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex fe35e33822f5..a6ca0a287fe5 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -107,8 +107,6 @@'posthog.tasks.tasks.clickhouse_send_license_usage','posthog.tasks.tasks.delete_expired_delegation_invites','posthog.tasks.tasks.delete_expired_exported_assets',- 'posthog.tasks.tasks.delete_organization_data_and_notify_task',- 'posthog.tasks.tasks.delete_project_data_and_notify_task','posthog.tasks.tasks.demo_reset_master_team','posthog.tasks.tasks.find_flags_with_enriched_analytics','posthog.tasks.tasks.ingestion_lag',diff --git a/posthog/tasks/test/test_deletion_tasks.py b/posthog/tasks/test/test_deletion_tasks.pydeleted file mode 100644index bb1fcfbd2167..000000000000--- a/posthog/tasks/test/test_deletion_tasks.py+++ /dev/null@@ -1,230 +0,0 @@-from typing import Any--from posthog.test.base import BaseTest-from unittest.mock import patch--from posthog.models.organization import Organization-from posthog.models.project import Project-from posthog.models.team import Team-from posthog.personhog_client.fake_client import fake_personhog_client-from posthog.tasks.tasks import delete_organization_data_and_notify_task, delete_project_data_and_notify_task-from posthog.test.persons import create_person---class TestDeleteProjectDataAndNotifyTask(BaseTest):- @patch("posthog.email.is_email_available", return_value=False)- def test_deletes_team_and_data(self, mock_email: Any) -> None:- team = Team.objects.create(organization=self.organization, name="Team to delete")- team_id = team.id-- delete_project_data_and_notify_task(- team_ids=[team_id],- project_id=None,- user_id=self.user.id,- project_name="Team to delete",- )-- self.assertFalse(Team.objects.filter(id=team_id).exists())-- @patch("posthog.email.is_email_available", return_value=False)- def test_deletes_project_and_teams(self, mock_email: Any) -> None:- project, team = Project.objects.create_with_team(- organization=self.organization,- initiating_user=self.user,- name="Project to delete",- )- project_id = project.id- team_id = team.id-- delete_project_data_and_notify_task(- team_ids=[team_id],- project_id=project_id,- user_id=self.user.id,- project_name="Project to delete",- )-- self.assertFalse(Project.objects.filter(id=project_id).exists())- self.assertFalse(Team.objects.filter(id=team_id).exists())-- @patch("posthog.tasks.email.send_project_deleted_email")- @patch("posthog.email.is_email_available", return_value=True)- def test_sends_email_when_available(self, mock_email_available: Any, mock_send_email: Any) -> None:- team = Team.objects.create(organization=self.organization, name="Team to delete")- team_id = team.id-- delete_project_data_and_notify_task(- team_ids=[team_id],- project_id=None,- user_id=self.user.id,- project_name="Team to delete",- )-- mock_send_email.delay.assert_called_once_with(- user_id=self.user.id,- project_name="Team to delete",- )---class TestDeleteProjectPersonsEndToEnd(BaseTest):- @patch("posthog.email.is_email_available", return_value=False)- def test_deletes_persons_and_distinct_ids_for_team(self, mock_email: Any) -> None:- team = Team.objects.create(organization=self.organization, name="Team to delete")- other_team = Team.objects.create(organization=self.organization, name="Other team")-- p1 = create_person(team=team, distinct_ids=["a", "b"])- p2 = create_person(team=team, distinct_ids=["c"])- p_other = create_person(team=other_team, distinct_ids=["d"])-- with fake_personhog_client() as fake:- fake.add_person(team_id=team.id, person_id=p1.pk, uuid=str(p1.uuid), distinct_ids=["a", "b"])- fake.add_person(team_id=team.id, person_id=p2.pk, uuid=str(p2.uuid), distinct_ids=["c"])- fake.add_person(team_id=other_team.id, person_id=p_other.pk, uuid=str(p_other.uuid), distinct_ids=["d"])-- delete_project_data_and_notify_task(- team_ids=[team.id],- project_id=None,- user_id=self.user.id,- project_name="Team to delete",- )-- self.assertFalse(Team.objects.filter(id=team.id).exists())-- # Fake client doesn't touch Django DB — verify the RPC was called correctly- calls = fake.assert_called("delete_persons_batch_for_team")- team_ids_called = {c.request.team_id for c in calls}- self.assertIn(team.id, team_ids_called)- self.assertNotIn(other_team.id, team_ids_called)---class TestDeleteOrganizationDataAndNotifyTask(BaseTest):- @patch("posthog.email.is_email_available", return_value=False)- def test_deletes_organization_and_teams(self, mock_email: Any) -> None:- org = Organization.objects.create(name="Org to delete")- org.members.add(self.user)- team = Team.objects.create(organization=org, name="Team in org")- org_id = str(org.id)- team_id = team.id-- delete_organization_data_and_notify_task(- team_ids=[team_id],- organization_id=org_id,- user_id=self.user.id,- organization_name="Org to delete",- project_names=["Team in org"],- )-- self.assertFalse(Organization.objects.filter(id=org_id).exists())- self.assertFalse(Team.objects.filter(id=team_id).exists())-- @patch("posthog.ph_client.is_cloud", return_value=True)- @patch("posthog.ph_client.get_client")- @patch("posthog.email.is_email_available", return_value=False)- def test_fires_deletion_completed_event(self, mock_email: Any, mock_get_client: Any, mock_is_cloud: Any) -> None:- org = Organization.objects.create(name="Org to delete")- org.members.add(self.user)- team = Team.objects.create(organization=org, name="Team in org")- org_id = str(org.id)-- delete_organization_data_and_notify_task(- team_ids=[team.id],- organization_id=org_id,- user_id=self.user.id,- organization_name="Org to delete",- project_names=["Team in org"],- )-- ph_client = mock_get_client.return_value- event_names = [call.kwargs.get("event") for call in ph_client.capture.call_args_list]- self.assertIn("organization deletion completed", event_names)- ph_client.shutdown.assert_called()-- @patch("posthog.email.is_email_available", return_value=False)- def test_deletes_organization_with_data_warehouse_saved_query_and_node(self, mock_email: Any) -> None:- """- Verify that Node.saved_query doesn't block organization and team deletion.- """- from products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Node-- org = Organization.objects.create(name="Org to delete")- org.members.add(self.user)- team = Team.objects.create(organization=org, name="Team in org")- org_id = str(org.id)- team_id = team.id-- # Create a DataWarehouseSavedQuery (view definition)- saved_query = DataWarehouseSavedQuery.objects.create(- team=team,- name="test_view",- query={"kind": "HogQLQuery", "query": "SELECT 1"},- )-- dag = DAG.objects.create(team=team, name=f"posthog_{team.id}")-- # Create a Node referencing the saved query (this has PROTECT on saved_query)- node = Node.objects.create(- team=team,- saved_query=saved_query,- dag=dag,- type="view",- )-- delete_organization_data_and_notify_task(- team_ids=[team_id],- organization_id=org_id,- user_id=self.user.id,- organization_name="Org to delete",- project_names=["Team in org"],- )-- self.assertFalse(Organization.objects.filter(id=org_id).exists())- self.assertFalse(Team.objects.filter(id=team_id).exists())- self.assertFalse(DataWarehouseSavedQuery.objects.filter(id=saved_query.id).exists())- self.assertFalse(Node.objects.filter(id=node.id).exists())-- @patch("posthog.email.is_email_available", return_value=False)- def test_deletes_organization_when_user_already_deleted(self, mock_email: Any) -> None:- org = Organization.objects.create(name="Org to delete")- org.members.add(self.user)- team = Team.objects.create(organization=org, name="Team in org")- org_id = str(org.id)- team_id = team.id- project_id = team.project_id- user_id = self.user.id-- # Simulate the user deleting their account before the async task runs- self.user.delete()-- delete_organization_data_and_notify_task(- team_ids=[team_id],- organization_id=org_id,- user_id=user_id,- organization_name="Org to delete",- project_names=["Team in org"],- )-- self.assertFalse(Organization.objects.filter(id=org_id).exists())- self.assertFalse(Team.objects.filter(id=team_id).exists())- self.assertFalse(Project.objects.filter(id=project_id).exists())-- @patch("posthog.tasks.email.send_organization_deleted_email")- @patch("posthog.email.is_email_available", return_value=True)- def test_sends_email_when_available(self, mock_email_available: Any, mock_send_email: Any) -> None:- org = Organization.objects.create(name="Org to delete")- org.members.add(self.user)- team = Team.objects.create(organization=org, name="Team in org")- org_id = str(org.id)- team_id = team.id-- delete_organization_data_and_notify_task(- team_ids=[team_id],- organization_id=org_id,- user_id=self.user.id,- organization_name="Org to delete",- project_names=["Team in org"],- )-- mock_send_email.delay.assert_called_once_with(- user_id=self.user.id,- organization_name="Org to delete",- project_names=["Team in org"],- )diff --git a/posthog/temporal/delete_teams/dispatch.py b/posthog/temporal/delete_teams/dispatch.pyindex 82d86e7aee72..427412e4ff19 100644--- a/posthog/temporal/delete_teams/dispatch.py+++ b/posthog/temporal/delete_teams/dispatch.py@@ -2,29 +2,9 @@ import asynciofrom django.conf import settings-import posthoganalytics-from posthog.temporal.common.client import async_connectfrom 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: strdiff --git a/posthog/temporal/delete_teams/workflows.py b/posthog/temporal/delete_teams/workflows.pyindex 17b1d22edea7..0cc4f1289482 100644--- a/posthog/temporal/delete_teams/workflows.py+++ b/posthog/temporal/delete_teams/workflows.py@@ -72,9 +72,8 @@ 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.+ and ``DeleteOrganizationWorkflow``. Each deletion phase runs as an independently+ retryable, heartbeating activity."""inputs_cls = DeleteTeamsDataWorkflowInputs@@ -156,7 +155,7 @@ async def _delete_teams_data_child(inputs: DeleteTeamsDataWorkflowInputs, workfl@temporalio.workflow.defn(name="delete-project-data")class DeleteProjectDataWorkflow(PostHogWorkflow):- """Replaces ``delete_project_data_and_notify_task`` — project or environment-only deletion."""+ """Durable project or environment-only deletion."""inputs_cls = DeleteProjectDataWorkflowInputs@@ -189,7 +188,7 @@ class DeleteProjectDataWorkflow(PostHogWorkflow):@temporalio.workflow.defn(name="delete-organization")class DeleteOrganizationWorkflow(PostHogWorkflow):- """Replaces ``delete_organization_data_and_notify_task``."""+ """Durable organization deletion."""inputs_cls = DeleteOrganizationWorkflowInputsdiff --git a/posthog/temporal/tests/delete_teams/inline.py b/posthog/temporal/tests/delete_teams/inline.pynew file mode 100644index 000000000000..fa9640168f07--- /dev/null+++ b/posthog/temporal/tests/delete_teams/inline.py@@ -0,0 +1,101 @@+"""Run the team/org deletion Temporal workflows inline for tests that need real side effects.++The API deletion endpoints hand off to Temporal via ``start_delete_project_data_workflow`` /+``start_delete_organization_workflow``. Tests that assert on the *effects* of deletion (batch+exports removed, schedules deleted, persons cleaned up, records gone) need those workflows to run+to completion synchronously. ``execute_deletion_workflows_inline`` patches both dispatch helpers to+execute the corresponding workflow on an in-process time-skipping ``WorkflowEnvironment`` with the+real activities, so the side effects land in the test's (committed) database.++Only ``queue_recording_deletions_activity`` is stubbed — it starts a separate recording-deletion+workflow on the external cluster, which is out of scope for these tests and covered elsewhere.++Callers MUST run in a non-atomic test case (``NonAtomicBaseTest`` / ``transaction=True``); the+activities run on a worker thread pool with their own connections and cannot see data held open in+an uncommitted transaction.+"""++import uuid+import asyncio+from collections.abc import Iterator+from contextlib import contextmanager++from unittest.mock import patch++import temporalio.worker+from temporalio import activity+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import Worker++from posthog.temporal.delete_teams import ACTIVITIES as REAL_ACTIVITIES+from posthog.temporal.delete_teams.activities import (+ queue_recording_deletions_activity as real_queue_recording_deletions_activity,+)+from posthog.temporal.delete_teams.types import (+ DeleteOrganizationWorkflowInputs,+ DeleteProjectDataWorkflowInputs,+ TeamDataActivityInputs,+)+from posthog.temporal.delete_teams.workflows import (+ DeleteOrganizationWorkflow,+ DeleteProjectDataWorkflow,+ DeleteTeamsDataWorkflow,+)++WORKFLOWS = [DeleteTeamsDataWorkflow, DeleteProjectDataWorkflow, DeleteOrganizationWorkflow]++# Activities swapped for no-op stubs in the inline worker, matched by object identity so the swap+# stays correct regardless of how the Temporal SDK derives the registered activity name.+_STUBBED_ACTIVITIES = {real_queue_recording_deletions_activity}+++def _inline_activities() -> list:+ @activity.defn(name="queue_recording_deletions_activity")+ async def queue_recording_deletions_activity(inputs: TeamDataActivityInputs) -> None:+ pass++ real = [fn for fn in REAL_ACTIVITIES if fn not in _STUBBED_ACTIVITIES]+ return [*real, queue_recording_deletions_activity]+++async def _execute(workflow_run, 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=_inline_activities(),+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ await env.client.execute_workflow(workflow_run, inputs, id=str(uuid.uuid4()), task_queue=task_queue)+++def _run_delete_project_data(*, 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+ )+ asyncio.run(_execute(DeleteProjectDataWorkflow.run, inputs))+++def _run_delete_organization(+ *, 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,+ )+ asyncio.run(_execute(DeleteOrganizationWorkflow.run, inputs))+++@contextmanager+def execute_deletion_workflows_inline() -> Iterator[None]:+ """Patch the deletion dispatch helpers to run their workflows to completion synchronously."""+ with (+ patch("posthog.temporal.delete_teams.dispatch.start_delete_project_data_workflow", _run_delete_project_data),+ patch("posthog.temporal.delete_teams.dispatch.start_delete_organization_workflow", _run_delete_organization),+ ):+ yield