:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(team-deletion): delete retired session summaries before deleting the team (#83306)
Yasen3bbaa791c341
diff --git a/posthog/models/team/util.py b/posthog/models/team/util.pyindex 89eb327d2b21..215a31276bd6 100644--- a/posthog/models/team/util.py+++ b/posthog/models/team/util.py@@ -3,6 +3,7 @@ from datetime import timedeltafrom typing import Anyfrom django.apps import apps+from django.db import connectionsimport structlog@@ -36,6 +37,18 @@ TEAM_DELETE_BATCH_SIZE = 2000# activity bound.TEAM_DELETE_RPC_TIMEOUT_SECONDS = 30 * 60+# The retired session-summary tables. products/replay/backend/migrations/0002_remove_session_summary_models.py+# dropped their models from Django state only, so both the tables and their foreign keys on+# posthog_team still exist in Postgres. Django's cascade cannot see them any more, and the+# constraints are DEFERRABLE INITIALLY DEFERRED, so a leftover row fails the team delete at COMMIT+# with an IntegrityError instead of at the DELETE statement. All three tables are dead: no Django+# model reads or writes them. This list goes away with the migration that drops them.+RETIRED_SESSION_SUMMARY_TABLES = (+ "ee_group_session_summary",+ "ee_single_session_summary",+ "ee_teamsessionsummariesconfig",+)+actions_that_require_current_team = ["rotate_secret_token","delete_secret_token_backup",@@ -87,6 +100,7 @@ def _delete_misc_small_tables_for_teams(team_ids: list[int]) -> None:# FeatureFlagHashKeyOverride references Person, so it must go before persons are deleted._delete_hash_key_overrides_for_teams(team_ids)_delete_llm_evaluations_for_teams(team_ids)+ _delete_retired_session_summaries_for_teams(team_ids)def _delete_llm_evaluations_for_teams(team_ids: list[int]) -> None:@@ -105,6 +119,32 @@ def _delete_llm_evaluations_for_teams(team_ids: list[int]) -> None:Evaluation.objects.filter(team_id__in=team_ids).delete()+def _delete_retired_session_summaries_for_teams(team_ids: list[int], batch_size: int = 10000) -> None:+ """Batch-delete the teams' rows in the retired session-summary tables.++ A table is skipped when it no longer exists, so team deletion keeps working once the migration+ that drops these tables lands.+ """+ if not team_ids:+ return++ db_connection = connections["default"]+ for table in RETIRED_SESSION_SUMMARY_TABLES:+ # The table name is a module constant, never user input, so interpolating it is safe.+ statement = f'DELETE FROM "{table}" WHERE ctid IN (SELECT ctid FROM "{table}" WHERE team_id = ANY(%s) LIMIT %s)'+ with db_connection.cursor() as cursor:+ cursor.execute("SELECT to_regclass(%s)", [table])+ row = cursor.fetchone()+ if row is None or row[0] is None:+ continue++ while True:+ cursor.execute(statement, [team_ids, batch_size])+ if cursor.rowcount < batch_size:+ break+ time.sleep(0.1)++def _delete_hash_key_overrides_for_teams(team_ids: list[int]) -> None:"""Delete FeatureFlagHashKeyOverride rows for the given teams via personhog.diff --git a/posthog/temporal/tests/delete_teams/test_retired_table_predelete.py b/posthog/temporal/tests/delete_teams/test_retired_table_predelete.pynew file mode 100644index 000000000000..889adeb374da--- /dev/null+++ b/posthog/temporal/tests/delete_teams/test_retired_table_predelete.py@@ -0,0 +1,40 @@+import pytest++from django.db import connection++from posthog.models.organization import Organization+from posthog.models.team import Team+from posthog.models.team.util import _delete_misc_small_tables_for_teams, delete_team_records++# transaction=True is required, not incidental: the foreign keys these tables hold on posthog_team+# are DEFERRABLE INITIALLY DEFERRED, so Postgres only checks them at COMMIT. Under a plain TestCase+# the inner atomic() is a savepoint, releasing it never checks them, and the regression is invisible.+pytestmark = [pytest.mark.django_db(transaction=True)]++_ROW_INSERTS = {+ "ee_teamsessionsummariesconfig": (+ "INSERT INTO ee_teamsessionsummariesconfig (team_id, product_context, custom_tags) VALUES (%s, '', '{}'::jsonb)"+ ),+ "ee_single_session_summary": (+ "INSERT INTO ee_single_session_summary "+ "(id, created_at, team_id, session_id, summary, exception_event_ids) "+ "VALUES (gen_random_uuid(), now(), %s, 'session-1', '{}'::jsonb, ARRAY['event-1'])"+ ),+ "ee_group_session_summary": (+ "INSERT INTO ee_group_session_summary (id, created_at, team_id, title, session_ids, summary) "+ "VALUES (gen_random_uuid(), now(), %s, 'Group summary', ARRAY['session-1'], '{}'::jsonb)"+ ),+}++[email protected]("table", sorted(_ROW_INSERTS))+def test_team_deletion_clears_rows_in_retired_session_summary_table(table: str):+ _, _, team = Organization.objects.bootstrap(None)+ team_id = team.id+ with connection.cursor() as cursor:+ cursor.execute(_ROW_INSERTS[table], [team_id])++ _delete_misc_small_tables_for_teams([team_id])+ delete_team_records([team_id])++ assert not Team.objects.filter(id=team_id).exists()