: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(deletion): fail fast on RecursionError in team deletion (#64333)
Yasenb756c040a900
diff --git a/posthog/temporal/delete_teams/activities.py b/posthog/temporal/delete_teams/activities.pyindex 09517b569741..3c17e8dfc71b 100644--- a/posthog/temporal/delete_teams/activities.py+++ b/posthog/temporal/delete_teams/activities.py@@ -1,4 +1,5 @@import temporalio.activity+from temporalio.exceptions import ApplicationErrorfrom posthog.sync import database_sync_to_async_poolfrom posthog.temporal.common.heartbeat import Heartbeater@@ -90,7 +91,22 @@ 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)+ try:+ await database_sync_to_async_pool(delete_team_records)(inputs.team_ids)+ except RecursionError:+ # The cascade delete materializes full rows for models with delete signals, which+ # decodes their JSON columns via json.loads. A pathologically deeply-nested JSON+ # value (deep enough that Postgres stores it but json.loads cannot decode it under+ # Python's fixed C-recursion limit) overflows here. Retrying is futile — the data is+ # unchanged — and the multi-thousand-frame traceback exceeds Temporal's failure-size+ # limit, so re-raise a small, non-retryable error that surfaces cleanly instead.+ raise ApplicationError(+ f"Recursion limit exceeded deleting team records for {inputs.team_ids}; a cascaded "+ "row most likely holds a deeply-nested JSON value that json.loads cannot decode. "+ "Repair that row before retrying.",+ type="RecursionError",+ non_retryable=True,+ ) from Nonedef _enqueue_clickhouse_deletion(team_ids: list[int], user_id: int) -> None:diff --git a/posthog/temporal/delete_teams/workflows.py b/posthog/temporal/delete_teams/workflows.pyindex f86d8ee295aa..8bddc7059ca8 100644--- a/posthog/temporal/delete_teams/workflows.py+++ b/posthog/temporal/delete_teams/workflows.py@@ -34,13 +34,13 @@ from posthog.temporal.delete_teams.types import (# 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.+# phase ordering doesn't account for, or a RecursionError decoding a deeply-nested JSON column on+# a cascaded row) are non-retryable so the workflow fails fast and surfaces instead of looping forever.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"],+ non_retryable_error_types=["ProtectedError", "RecursionError"],)# Bounded retries for the lighter orchestration / side-effect activities.SIDE_EFFECT_RETRY_POLICY = temporalio.common.RetryPolicy(diff --git a/posthog/temporal/tests/delete_teams/test_workflows.py b/posthog/temporal/tests/delete_teams/test_workflows.pyindex 44ff07b58e77..d61b4d14f32a 100644--- a/posthog/temporal/tests/delete_teams/test_workflows.py+++ b/posthog/temporal/tests/delete_teams/test_workflows.py@@ -1,13 +1,16 @@import uuidimport pytest+from unittest.mock import patchimport temporalio.workerfrom temporalio import activityfrom temporalio.client import WorkflowFailureError-from temporalio.testing import WorkflowEnvironment+from temporalio.exceptions import ApplicationError+from temporalio.testing import ActivityEnvironment, WorkflowEnvironmentfrom temporalio.worker import Worker+from posthog.temporal.delete_teams.activities import delete_team_records_activityfrom posthog.temporal.delete_teams.types import (DeleteOrganizationWorkflowInputs,DeleteProjectDataWorkflowInputs,@@ -209,3 +212,35 @@ async def test_transient_error_is_retried():await _run_core_with(activities) # completes despite the first failureassert len(attempts) == 2 # retried once, then succeeded+++async def test_recursion_error_fails_fast_without_retry():+ # A RecursionError is deterministic (e.g. json.loads can't decode a deeply-nested JSON column+ # on a cascaded row), so the retry policy must not loop on it.+ attempts: list[str] = []++ async def raises_recursion(inputs: TeamDataActivityInputs) -> None:+ attempts.append("attempt")+ raise ApplicationError("recursion limit exceeded", type="RecursionError")++ activities = _core_activities_with("delete_team_records_activity", raises_recursion)+ with pytest.raises(WorkflowFailureError):+ await _run_core_with(activities)++ assert len(attempts) == 1+++async def test_delete_team_records_activity_converts_recursion_error():+ # The real activity turns a RecursionError from the cascade into a small, non-retryable+ # ApplicationError so it surfaces instead of looping and overflowing Temporal's failure-size limit.+ def raise_recursion(team_ids: list[int]) -> None:+ raise RecursionError("maximum recursion depth exceeded")++ with patch("posthog.models.team.util.delete_team_records", raise_recursion):+ with pytest.raises(ApplicationError) as exc_info:+ await ActivityEnvironment().run(+ delete_team_records_activity, TeamDataActivityInputs(team_ids=[1], user_id=7)+ )++ assert exc_info.value.type == "RecursionError"+ assert exc_info.value.non_retryable