: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(experiments): update error classification to prevent unnecessary retries (#70915)
Rodrigo Iloro23f3de758535
diff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.pyindex f05cd9e48fe9..8394d498e9ce 100644--- a/products/experiments/backend/temporal/models.py+++ b/products/experiments/backend/temporal/models.py@@ -16,10 +16,17 @@ MAX_CANARY_DETAIL_LENGTH = 1000# Max attempts per metric before it's marked failed on the recalculation workflow.MAX_METRIC_ATTEMPTS = 8-# Retry delay for a calc attempt that bounced off the per-org ClickHouse concurrency limiter, applied via-# ApplicationError(next_retry_delay=...) instead of the retry policy's 5s exponential schedule.+# Retry delay for a calc attempt that bounced off the per-org ClickHouse concurrency limiter or the cluster's+# at-capacity guard, applied via ApplicationError(next_retry_delay=...) instead of the retry policy's 5s+# exponential schedule.CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS = 60+# classify_experiment_query_error classes that are deterministic for a fixed query and data window: retrying+# burns a full ClickHouse query per attempt without changing the outcome, so the activity fails non-retryable+# and persists immediately. timeout is deliberately absent — the class conflates TIMEOUT_EXCEEDED with+# SOCKET_TIMEOUT (a transient network blip), and recalc timeouts are rare enough to keep the retry budget.+NON_RETRYABLE_ERROR_TYPES = frozenset({"out_of_memory", "byte_limit", "validation_error"})+# Per-attempt ceiling for the calc activity (its start_to_close_timeout). The activity has no heartbeat, so# this is the real per-attempt limit — when it fires, Temporal kills the attempt from the outside and nothing# inside the activity (result persistence, the terminal error event) runs.diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex 63d44c6cb06a..7e7bdd6e9b1b 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -22,6 +22,7 @@ from posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.event_usage import groups+from posthog.exceptions import ClickHouseAtCapacityfrom posthog.exceptions_capture import capture_exceptionfrom posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models.scoping import team_scope@@ -41,6 +42,7 @@ from products.experiments.backend.temporal.metric_resolution import build_metricfrom products.experiments.backend.temporal.models import (CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS,METRIC_CALC_MAX_EXECUTION_TIME_SECONDS,+ NON_RETRYABLE_ERROR_TYPES,ExperimentMetricToRecalculate,MetricRecalculationResult,RecalculationProgressUpdate,@@ -88,6 +90,7 @@ def _get_recalc_state(recalculation_id: str) -> _RecalcState:# Non-retryable so Temporal terminates promptly instead of burning retries on each activity.raise ApplicationError(f"ExperimentMetricsRecalculation {recalculation_id} not found",+ type="recalculation_not_found",non_retryable=True,)return _RecalcState(@@ -172,6 +175,7 @@ def _update_recalculation_progress_sync(update: RecalculationProgressUpdate) -># workflow bug — fail non-retryable so Temporal terminates promptly.raise ApplicationError("RecalculationProgressUpdate must set exactly one of mark_started or mark_completed",+ type="invalid_input",non_retryable=True,)@@ -448,6 +452,7 @@ def _calculate_experiment_metric_for_recalculation_sync(except ValueError as e:raise ApplicationError(f"query_to {query_to!r} is not a valid ISO datetime string: {e}",+ type="invalid_input",non_retryable=True,)state = _get_recalc_state(recalculation_id)@@ -458,21 +463,25 @@ def _calculate_experiment_metric_for_recalculation_sync(if experiment_id != state.experiment_id:raise ApplicationError(f"experiment_id {experiment_id} does not match recalc.experiment_id {state.experiment_id}",+ type="input_mismatch",non_retryable=True,)if metric_uuid not in state.metric_uuids:raise ApplicationError(f"metric_uuid {metric_uuid} is not in recalc {recalculation_id}'s metric set",+ type="input_mismatch",non_retryable=True,)if state.query_to is None:raise ApplicationError(f"recalc {recalculation_id} has no query_to set — calculate activity ran before start activity",+ type="invalid_state",non_retryable=True,)if query_to_dt != state.query_to:raise ApplicationError(f"query_to {query_to_dt.isoformat()} does not match recalc.query_to {state.query_to.isoformat()}",+ type="input_mismatch",non_retryable=True,)@@ -613,11 +622,7 @@ def _calculate_experiment_metric_for_recalculation_sync()return _fail(recalculation_id, metric_uuid, "calculation", message)- except ConcurrencyLimitExceeded as e:- # The org's ClickHouse app-query quota is saturated: backpressure, not a fault. No exception- # capture, and the exponential retry schedule is overridden with a flat delay long enough for the- # org's earlier runs to release query slots. Persisted only on the final attempt, so the metric- # stays in its loading state while it waits for quota.+ except (ConcurrencyLimitExceeded, ClickHouseAtCapacity) as e:message = str(e)[:_MAX_ERROR_MESSAGE_LENGTH]if is_final_attempt:_store_result(@@ -646,24 +651,22 @@ def _calculate_experiment_metric_for_recalculation_sync(trigger=state.trigger,)logger.warning(- "Experiment metric recalculation deferred by org concurrency limit",+ "Experiment metric recalculation deferred by ClickHouse backpressure",experiment_id=experiment_id,metric_uuid=metric_uuid,is_final_attempt=is_final_attempt,+ error_class=type(e).__name__,)raise ApplicationError(message,- type="ConcurrencyLimitExceeded",+ type=type(e).__name__,next_retry_delay=timedelta(seconds=CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS),) from eexcept Exception as e:- # Could be transient (ClickHouse connection blip, network glitch, or other infrastructure issue).- # Persist the failure ONLY on the final attempt, then re-raise; on earlier attempts we re-raise- # without persisting so Temporal retries while the metric stays in its loading/dim state on the- # frontend, rather than flashing an error for a failure that may yet succeed on the next attempt.- # StatisticError and ZeroDivisionError are handled above as permanent and return success=False.message = str(e)[:_MAX_ERROR_MESSAGE_LENGTH]+ error_type = classify_experiment_query_error(e)+ is_permanent = error_type in NON_RETRYABLE_ERROR_TYPES or isinstance(e, ValueError)capture_exception(e,additional_properties={@@ -672,7 +675,7 @@ def _calculate_experiment_metric_for_recalculation_sync("recalculation_id": recalculation_id,},)- if is_final_attempt:+ if is_final_attempt or is_permanent:_store_result(experiment_id=experiment_id,metric_uuid=metric_uuid,@@ -685,9 +688,6 @@ def _calculate_experiment_metric_for_recalculation_sync(query_id=client_query_id,)_record_failure(recalculation_id, metric_uuid, "calculation", message)- # Emit only on the terminal failure (retries exhausted) — the error the user actually- # sees. error_type mirrors the client taxonomy so it lands on the same dashboards.- # Earlier attempts re-raise silently to avoid double-counting a failure that may still succeed._capture_experiment_metric_event(experiment,metric_uuid,@@ -696,7 +696,7 @@ def _calculate_experiment_metric_for_recalculation_sync("experiment metric error",{"duration_ms": round((time.perf_counter() - calc_started_at) * 1000),- "error_type": classify_experiment_query_error(e),+ "error_type": error_type,"error_message": message,},trigger=state.trigger,@@ -706,5 +706,8 @@ def _calculate_experiment_metric_for_recalculation_sync(experiment_id=experiment_id,metric_uuid=metric_uuid,is_final_attempt=is_final_attempt,+ error_type=error_type,)+ if is_permanent:+ raise ApplicationError(message, type=error_type, non_retryable=True) from eraisediff --git a/products/experiments/backend/temporal/recalculation_metrics.py b/products/experiments/backend/temporal/recalculation_metrics.pyindex b5d1534ba68c..c67a2a066904 100644--- a/products/experiments/backend/temporal/recalculation_metrics.py+++ b/products/experiments/backend/temporal/recalculation_metrics.py@@ -12,6 +12,7 @@ import typingfrom django.conf import settingsfrom temporalio import activity, workflow+from temporalio.exceptions import ApplicationErrorfrom temporalio.worker import (ActivityInboundInterceptor,ExecuteActivityInput,@@ -94,6 +95,14 @@ def increment_workflow_finished(status: str) -> None:).add(1)+def _failure_error_type(exc: BaseException) -> str:+ """Low-cardinality label for the failure counter: the ApplicationError type set by the activity+ (taxonomy strings like out_of_memory, or the backpressure class names), else the exception class name."""+ if isinstance(exc, ApplicationError) and exc.type:+ return exc.type+ return type(exc).__name__++class _ActivityInboundInterceptor(ActivityInboundInterceptor):async def execute_activity(self, input: ExecuteActivityInput) -> typing.Any:info = activity.info()@@ -104,13 +113,14 @@ class _ActivityInboundInterceptor(ActivityInboundInterceptor):meter = activity.metric_meter().with_additional_attributes({"activity_type": activity_type, "workflow_type": _RECALCULATION_WORKFLOW_TYPE})- # Queue-pressure signal (see bucket comment above). Pattern mirrors mcp_analytics' intent_clustering.- if info.scheduled_time and info.started_time:+ # Queue-pressure signal (see bucket comment above). Per-attempt scheduling time, so retry backoff+ # (including the intentional quota-wait delays) doesn't read as queue pressure.+ if info.current_attempt_scheduled_time and info.started_time:meter.create_histogram_timedelta(name="experiment_metrics_recalculation_activity_schedule_to_start_latency",- description="Time between activity scheduling and start (task queue wait).",+ description="Time between the current attempt's scheduling and start (task queue wait).",unit="ms",- ).record(info.started_time - info.scheduled_time)+ ).record(info.started_time - info.current_attempt_scheduled_time)# Fires on every attempt (first run + each retry). Comparing this to `_activity_successes` reveals# retry rate; without it a transient ClickHouse blip is indistinguishable from a healthy first-try# success. Pattern mirrors batch_exports' `batch_exports_activity_attempts`.@@ -129,8 +139,8 @@ class _ActivityInboundInterceptor(ActivityInboundInterceptor):},):result = await super().execute_activity(input)- except Exception:- meter.create_counter(+ except Exception as e:+ meter.with_additional_attributes({"error_type": _failure_error_type(e)}).create_counter("experiment_metrics_recalculation_activity_failures","Number of failed experiment metrics recalculation activity executions.",).add(1)diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.pyindex 1f809e50d90b..bfe39c7f8776 100644--- a/products/experiments/backend/temporal/test_recalculation_activities.py+++ b/products/experiments/backend/temporal/test_recalculation_activities.py@@ -10,6 +10,7 @@ from django.utils import timezonefrom clickhouse_driver.errors import ServerExceptionfrom parameterized import parameterized+from rest_framework.exceptions import ValidationErrorfrom temporalio.exceptions import ApplicationErrorfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceeded@@ -451,23 +452,30 @@ class TestCalculateActivity(BaseTest):recalc.refresh_from_db()assert "m1" in recalc.metric_errors- def test_concurrency_limit_bounce_defers_with_retry_delay_and_no_capture(self):- # A query bouncing off the per-org ClickHouse limiter is backpressure, not a fault: it must re-raise- # as an ApplicationError carrying next_retry_delay (overriding the retry policy's 5s exponential- # schedule with the flat quota-wait delay), must never reach capture_exception (a saturated org would- # spam error tracking with expected bounces), and must persist nothing before the final attempt.- exp = self._experiment(flag_key="calc-quota", metrics=[_mean_metric("m1")])+ @parameterized.expand(+ [+ ("org_quota", ConcurrencyLimitExceeded("org quota saturated")),+ ("cluster_at_capacity", ClickHouseAtCapacity()),+ ]+ )+ def test_backpressure_bounce_defers_with_retry_delay_and_no_capture(self, name: str, exc: Exception):+ # A query bouncing off the per-org ClickHouse limiter or the cluster's at-capacity guard is+ # backpressure, not a fault: it must re-raise as an ApplicationError carrying next_retry_delay+ # (overriding the retry policy's 5s exponential schedule with the flat quota-wait delay), must never+ # reach capture_exception (a saturated org would spam error tracking with expected bounces), and must+ # persist nothing before the final attempt.+ exp = self._experiment(flag_key=f"calc-quota-{name}", metrics=[_mean_metric("m1")])recalc = self._recalc(exp, metric_uuids=["m1"])with (patch("products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner") as mock_runner,patch("products.experiments.backend.temporal.recalculation_logic.capture_exception") as mock_capture,):- mock_runner.return_value.run.side_effect = ConcurrencyLimitExceeded("org quota saturated")+ mock_runner.return_value.run.side_effect = excwith pytest.raises(ApplicationError) as exc_info:_calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=False)- assert exc_info.value.type == "ConcurrencyLimitExceeded"+ assert exc_info.value.type == type(exc).__name__assert exc_info.value.next_retry_delay == timedelta(seconds=CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS)mock_capture.assert_not_called()recalc.refresh_from_db()@@ -483,6 +491,36 @@ class TestCalculateActivity(BaseTest):row = ExperimentMetricResult.objects.get(experiment=exp, metric_uuid="m1")assert row.status == ExperimentMetricResult.Status.FAILED+ @parameterized.expand(+ [+ ("out_of_memory", ClickHouseQueryMemoryLimitExceeded(), "out_of_memory"),+ ("byte_limit", ServerException("too many bytes", code=307), "byte_limit"),+ ("validation_error", ValidationError("bad metric config"), "validation_error"),+ ("config_value_error", ValueError("No control variant found"), "server_error"),+ ]+ )+ def test_permanent_error_fails_non_retryable_and_persists_on_first_attempt(+ self, name: str, exc: Exception, expected_type: str+ ):+ # Deterministic failures (out-of-memory, byte limits, invalid config) can't succeed on retry, so+ # even a NON-final attempt must persist the FAILED row immediately and raise non_retryable — every+ # retry would burn a full ClickHouse query without changing the outcome.+ exp = self._experiment(flag_key=f"calc-permanent-{name}", metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])++ with patch("products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner") as mock_runner:+ mock_runner.return_value.run.side_effect = exc++ with pytest.raises(ApplicationError) as exc_info:+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=False)++ assert exc_info.value.non_retryable is True+ assert exc_info.value.type == expected_type+ recalc.refresh_from_db()+ assert "m1" in recalc.metric_errors+ row = ExperimentMetricResult.objects.get(experiment=exp, metric_uuid="m1")+ assert row.status == ExperimentMetricResult.Status.FAILED+def test_query_to_is_passed_as_as_of_to_runner(self):# The run's shared query_to MUST be threaded into the ClickHouse query bounds via the runner's# as_of, not just stored on the result row. Without as_of the runner falls back to its own now(),@@ -919,18 +957,21 @@ class TestRecalculationAnalytics(BaseTest):@parameterized.expand([- ("wrapped_oom", ClickHouseQueryMemoryLimitExceeded(), "out_of_memory"),- ("wrapped_timeout", ClickHouseQueryTimeOut(), "timeout"),- ("wrapped_at_capacity", ClickHouseAtCapacity(), "rate_limited"),- ("ch_timeout_code", ServerException("timed out", code=159), "timeout"),- ("ch_socket_timeout_code", ServerException("socket timed out", code=209), "timeout"),- ("ch_memory_limit_code", ServerException("memory limit exceeded", code=241), "out_of_memory"),- ("ch_too_many_bytes_code", ServerException("too many bytes", code=307), "byte_limit"),- ("ch_too_many_queries_code", ServerException("too many queries", code=202), "rate_limited"),- ("other", RuntimeError("kaboom"), "server_error"),+ # name, exc, expected_error_type, raises_application_error+ # Permanent classes (oom/byte_limit/validation) and backpressure (at_capacity) re-raise as+ # ApplicationError; genuinely transient classes re-raise the original exception for Temporal.+ ("wrapped_oom", ClickHouseQueryMemoryLimitExceeded(), "out_of_memory", True),+ ("wrapped_timeout", ClickHouseQueryTimeOut(), "timeout", False),+ ("wrapped_at_capacity", ClickHouseAtCapacity(), "rate_limited", True),+ ("ch_timeout_code", ServerException("timed out", code=159), "timeout", False),+ ("ch_socket_timeout_code", ServerException("socket timed out", code=209), "timeout", False),+ ("ch_memory_limit_code", ServerException("memory limit exceeded", code=241), "out_of_memory", True),+ ("ch_too_many_bytes_code", ServerException("too many bytes", code=307), "byte_limit", True),+ ("ch_too_many_queries_code", ServerException("too many queries", code=202), "rate_limited", False),+ ("other", RuntimeError("kaboom"), "server_error", False),])- def test_terminal_failure_emits_metric_error_event(self, name, exc, expected_error_type):+ def test_terminal_failure_emits_metric_error_event(self, name, exc, expected_error_type, raises_application_error):# On the terminal attempt (retries exhausted) an infra failure emits 'experiment metric error'# with the shared backend error_type taxonomy — including byte_limit (307) and rate_limited (202),# the two real failure modes that used to collapse into server_error and stay invisible.@@ -942,7 +983,7 @@ class TestRecalculationAnalytics(BaseTest):"products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner") as mock_runner:mock_runner.return_value.run.side_effect = exc- with pytest.raises(type(exc)):+ with pytest.raises(ApplicationError if raises_application_error else type(exc)):_calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=True)assert len(captured) == 1diff --git a/products/experiments/backend/temporal/test_recalculation_metrics.py b/products/experiments/backend/temporal/test_recalculation_metrics.pyindex d3b5d124352f..c13c2fb90cc7 100644--- a/products/experiments/backend/temporal/test_recalculation_metrics.py+++ b/products/experiments/backend/temporal/test_recalculation_metrics.py@@ -4,6 +4,7 @@ from unittest.mock import MagicMock, patchfrom django.conf import settingsfrom parameterized import parameterized+from temporalio.exceptions import ApplicationErrorfrom temporalio.worker import ActivityInboundInterceptorfrom posthog.temporal.ai_observability.metrics import ExecutionTimeRecorder@@ -14,10 +15,29 @@ from products.experiments.backend.temporal.recalculation_metrics import (EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_BUCKETS,EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_METRICS,ExperimentsRecalculationMetricsInterceptor,+ _failure_error_type,increment_workflow_finished,)+ [+ # ApplicationError.type carries the activity's classification (backpressure class names, permanent+ # taxonomy strings); anything else falls back to the exception class. If this drifts, backpressure+ # bounces become indistinguishable from real failures on the failures counter.+ (+ "application_error_with_type",+ ApplicationError("m", type="ConcurrencyLimitExceeded"),+ "ConcurrencyLimitExceeded",+ ),+ ("application_error_without_type", ApplicationError("m"), "ApplicationError"),+ ("plain_exception", RuntimeError("m"), "RuntimeError"),+ ]+)+def test_failure_error_type_label(name: str, exc: BaseException, expected: str):+ assert _failure_error_type(exc) == expected++def test_registered_on_recalculation_queue():# Pins the interceptor's `task_queue` ClassVar to the recalc worker's queue — without a match,# `is_task_queue_supported` filters the interceptor out of every worker and the metrics emit nothing.