: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): stop retrying metric config errors in timeseries (#105662)
Juraj Majerik13f6c8f8a9fb
diff --git a/posthog/temporal/experiments/activities.py b/posthog/temporal/experiments/activities.pyindex 857511421b94..f1c8f077096a 100644--- a/posthog/temporal/experiments/activities.py+++ b/posthog/temporal/experiments/activities.py@@ -7,8 +7,16 @@ from django.db.models import Qimport structlogimport temporalio.activity--from posthog.schema import ExperimentQuery+from pydantic import ValidationError as PydanticValidationError+from rest_framework.exceptions import ValidationError++from posthog.schema import (+ ExperimentFunnelMetric,+ ExperimentMeanMetric,+ ExperimentQuery,+ ExperimentRatioMetric,+ ExperimentRetentionMetric,+)from posthog.clickhouse.client.connection import Workloadfrom posthog.clickhouse.query_tagging import tag_queries@@ -32,7 +40,10 @@ from products.experiments.backend.facade.timeseries import (sync_timeseries_recalculation,)from products.experiments.backend.hogql_queries.base_query_utils import experiment_window_end-from products.experiments.backend.hogql_queries.error_handling import capture_experiment_metric_error_event+from products.experiments.backend.hogql_queries.error_handling import (+ capture_experiment_metric_error_event,+ classify_experiment_query_error,+)from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprintfrom products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunnerfrom products.experiments.backend.hogql_queries.utils import get_experiment_stats_method, sanitize_non_finite@@ -47,6 +58,17 @@ logger = structlog.get_logger(__name__)EXPERIMENT_RECALCULATION_MAX_AGE_DAYS = 60+def _build_metric_validated(+ metric_dict: dict[str, Any],+) -> ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric:+ """A malformed stored metric dict is a config error, not a transient failure: convert the+ pydantic construction error to the DRF type classify_experiment_query_error marks permanent."""+ try:+ return build_metric(metric_dict)+ except PydanticValidationError as e:+ raise ValidationError(str(e)) from e++@database_sync_to_asyncdef _get_experiment_regular_metrics_for_hour_sync(hour: int) -> list[ExperimentRegularMetricInput]:close_old_connections()@@ -171,7 +193,6 @@ def _calculate_experiment_regular_metric_sync(success=False,error_message=f"Unknown metric type: {metric_type}",)- metric_obj = build_metric(metric_dict)if not experiment.start_date:return ExperimentRegularMetricResult(@@ -187,6 +208,9 @@ def _calculate_experiment_regular_metric_sync(query_to_utc = experiment_window_end(experiment, now_utc)try:+ # Inside the try so a malformed stored metric dict follows the same+ # failure path as a query error instead of escaping the activity.+ metric_obj = _build_metric_validated(metric_dict)experiment_query = ExperimentQuery(experiment_id=experiment_id,metric=metric_obj,@@ -288,6 +312,10 @@ def _calculate_experiment_regular_metric_sync()except Exception as e:+ # A broken metric config fails deterministically: return it (not raise) so Temporal+ # doesn't retry and the worker interceptor doesn't report it to error tracking.+ is_permanent = classify_experiment_query_error(e) == "validation_error"+ExperimentMetricResultModel.objects.update_or_create(experiment_id=experiment_id,metric_uuid=metric_uuid,@@ -303,15 +331,23 @@ def _calculate_experiment_regular_metric_sync(},)- logger.exception(- "Experiment metric calculation failed",- experiment_id=experiment_id,- metric_uuid=metric_uuid,- )+ if is_permanent:+ logger.warning(+ "Experiment metric calculation failed due to invalid metric configuration",+ experiment_id=experiment_id,+ metric_uuid=metric_uuid,+ error=str(e),+ )+ else:+ logger.exception(+ "Experiment metric calculation failed",+ experiment_id=experiment_id,+ metric_uuid=metric_uuid,+ )- # Temporal retries this activity; emit only when retries are exhausted so a transient+ # Temporal retries this activity; emit only on the terminal attempt so a transient# failure that recovers on a later attempt is never counted.- if attempt >= TIMESERIES_METRIC_MAX_ATTEMPTS:+ if is_permanent or attempt >= TIMESERIES_METRIC_MAX_ATTEMPTS:capture_experiment_metric_error_event(team=experiment.team,error=e,@@ -323,6 +359,15 @@ def _calculate_experiment_regular_metric_sync(user=experiment.created_by,)+ if is_permanent:+ return ExperimentRegularMetricResult(+ experiment_id=experiment_id,+ metric_uuid=metric_uuid,+ fingerprint=fingerprint,+ success=False,+ error_message=str(e),+ )+raise@@ -471,7 +516,6 @@ def _calculate_experiment_saved_metric_sync(success=False,error_message=f"Unknown metric type: {metric_type}",)- metric_obj = build_metric(query)if not experiment.start_date:return ExperimentSavedMetricResult(@@ -487,6 +531,9 @@ def _calculate_experiment_saved_metric_sync(query_to_utc = experiment_window_end(experiment, now_utc)try:+ # Inside the try so a malformed stored metric dict follows the same+ # failure path as a query error instead of escaping the activity.+ metric_obj = _build_metric_validated(query)experiment_query = ExperimentQuery(experiment_id=experiment_id,metric=metric_obj,@@ -588,6 +635,10 @@ def _calculate_experiment_saved_metric_sync()except Exception as e:+ # A broken metric config fails deterministically: return it (not raise) so Temporal+ # doesn't retry and the worker interceptor doesn't report it to error tracking.+ is_permanent = classify_experiment_query_error(e) == "validation_error"+ExperimentMetricResultModel.objects.update_or_create(experiment_id=experiment_id,metric_uuid=metric_uuid,@@ -603,15 +654,23 @@ def _calculate_experiment_saved_metric_sync(},)- logger.exception(- "Experiment saved metric calculation failed",- experiment_id=experiment_id,- metric_uuid=metric_uuid,- )+ if is_permanent:+ logger.warning(+ "Experiment saved metric calculation failed due to invalid metric configuration",+ experiment_id=experiment_id,+ metric_uuid=metric_uuid,+ error=str(e),+ )+ else:+ logger.exception(+ "Experiment saved metric calculation failed",+ experiment_id=experiment_id,+ metric_uuid=metric_uuid,+ )- # Temporal retries this activity; emit only when retries are exhausted so a transient+ # Temporal retries this activity; emit only on the terminal attempt so a transient# failure that recovers on a later attempt is never counted.- if attempt >= TIMESERIES_METRIC_MAX_ATTEMPTS:+ if is_permanent or attempt >= TIMESERIES_METRIC_MAX_ATTEMPTS:capture_experiment_metric_error_event(team=experiment.team,error=e,@@ -623,6 +682,15 @@ def _calculate_experiment_saved_metric_sync(user=experiment.created_by,)+ if is_permanent:+ return ExperimentSavedMetricResult(+ experiment_id=experiment_id,+ metric_uuid=metric_uuid,+ fingerprint=fingerprint,+ success=False,+ error_message=str(e),+ )+raisediff --git a/posthog/temporal/experiments/test_cache_warming.py b/posthog/temporal/experiments/test_cache_warming.pyindex 3ccaa99b3d0f..5cc00a563aa4 100644--- a/posthog/temporal/experiments/test_cache_warming.py+++ b/posthog/temporal/experiments/test_cache_warming.py@@ -8,6 +8,8 @@ from unittest.mock import patchfrom django.core.cache import cachefrom django.test import override_settings+from rest_framework.exceptions import ValidationError+from posthog.schema import CachedExperimentQueryResponse, EventsNode, ExperimentMeanMetric, ExperimentQueryfrom posthog.hogql_queries.query_runner import ExecutionMode@@ -15,6 +17,7 @@ from posthog.temporal.experiments.activities import (_calculate_experiment_regular_metric_sync,_calculate_experiment_saved_metric_sync,)+from posthog.temporal.experiments.models import TIMESERIES_METRIC_MAX_ATTEMPTSfrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprintfrom products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner@@ -269,3 +272,205 @@ class TestTemporalRecalcWarmsResponseCache(ExperimentQueryRunnerBaseTest):)assert isinstance(warm_response, CachedExperimentQueryResponse)self.assertTrue(warm_response.is_cached)++ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)+ def test_regular_metric_activity_returns_permanent_failure_on_validation_error(self):+ feature_flag = self.create_feature_flag()+ experiment = self.create_experiment(+ feature_flag=feature_flag,+ start_date=datetime(2020, 1, 1, 0, 0, 0),+ end_date=datetime(2020, 1, 5, 0, 0, 0),+ )+ metric = ExperimentMeanMetric(uuid=str(uuid4()), source=EventsNode(event="purchase"))+ metric_dict = metric.model_dump(mode="json")+ experiment.metrics = [metric_dict]+ experiment.save()++ with (+ patch("posthog.temporal.experiments.activities.close_old_connections"),+ patch("posthog.temporal.experiments.activities.ExperimentQueryRunner") as mock_runner_class,+ patch("posthog.temporal.experiments.activities.capture_experiment_metric_error_event") as mock_event,+ ):+ mock_runner_class.return_value.run.side_effect = ValidationError("compound expressions not supported")++ activity_result = _calculate_experiment_regular_metric_sync.func( # type: ignore[attr-defined]+ experiment.id, metric_dict["uuid"], "fingerprint"+ )++ self.assertFalse(activity_result.success)+ result_row = ExperimentMetricResult.objects.get(experiment=experiment, metric_uuid=metric_dict["uuid"])+ assert result_row.status == ExperimentMetricResult.Status.FAILED+ mock_event.assert_called_once()++ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)+ def test_saved_metric_activity_returns_permanent_failure_on_validation_error(self):+ feature_flag = self.create_feature_flag()+ experiment = self.create_experiment(+ feature_flag=feature_flag,+ start_date=datetime(2020, 1, 1, 0, 0, 0),+ end_date=datetime(2020, 1, 5, 0, 0, 0),+ )+ metric = ExperimentMeanMetric(uuid=str(uuid4()), source=EventsNode(event="purchase"))+ metric_dict = metric.model_dump(mode="json")++ saved_metric = ExperimentSavedMetric.objects.create(+ name="test saved metric",+ team=self.team,+ query=metric_dict,+ created_by=self.user,+ )+ ExperimentToSavedMetric.objects.create(+ experiment=experiment,+ saved_metric=saved_metric,+ metadata={"type": "primary"},+ )++ with (+ patch("posthog.temporal.experiments.activities.close_old_connections"),+ patch("posthog.temporal.experiments.activities.ExperimentQueryRunner") as mock_runner_class,+ patch("posthog.temporal.experiments.activities.capture_experiment_metric_error_event") as mock_event,+ ):+ mock_runner_class.return_value.run.side_effect = ValidationError("compound expressions not supported")++ activity_result = _calculate_experiment_saved_metric_sync.func( # type: ignore[attr-defined]+ experiment.id, metric_dict["uuid"], "fingerprint"+ )++ self.assertFalse(activity_result.success)+ result_row = ExperimentMetricResult.objects.get(experiment=experiment, metric_uuid=metric_dict["uuid"])+ assert result_row.status == ExperimentMetricResult.Status.FAILED+ mock_event.assert_called_once()++ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)+ def test_regular_metric_activity_returns_permanent_failure_on_malformed_config(self):+ feature_flag = self.create_feature_flag()+ experiment = self.create_experiment(+ feature_flag=feature_flag,+ start_date=datetime(2020, 1, 1, 0, 0, 0),+ end_date=datetime(2020, 1, 5, 0, 0, 0),+ )+ bad_metric = {"kind": "ExperimentMetric", "metric_type": "mean", "uuid": str(uuid4())}+ experiment.metrics = [bad_metric]+ experiment.save()++ with (+ patch("posthog.temporal.experiments.activities.close_old_connections"),+ patch("posthog.temporal.experiments.activities.capture_experiment_metric_error_event") as mock_event,+ ):+ activity_result = _calculate_experiment_regular_metric_sync.func( # type: ignore[attr-defined]+ experiment.id, bad_metric["uuid"], "fingerprint"+ )++ self.assertFalse(activity_result.success)+ result_row = ExperimentMetricResult.objects.get(experiment=experiment, metric_uuid=bad_metric["uuid"])+ assert result_row.status == ExperimentMetricResult.Status.FAILED+ mock_event.assert_called_once()++ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)+ def test_saved_metric_activity_returns_permanent_failure_on_malformed_config(self):+ feature_flag = self.create_feature_flag()+ experiment = self.create_experiment(+ feature_flag=feature_flag,+ start_date=datetime(2020, 1, 1, 0, 0, 0),+ end_date=datetime(2020, 1, 5, 0, 0, 0),+ )+ bad_metric = {"kind": "ExperimentMetric", "metric_type": "mean", "uuid": str(uuid4())}++ saved_metric = ExperimentSavedMetric.objects.create(+ name="test saved metric",+ team=self.team,+ query=bad_metric,+ created_by=self.user,+ )+ ExperimentToSavedMetric.objects.create(+ experiment=experiment,+ saved_metric=saved_metric,+ metadata={"type": "primary"},+ )++ with (+ patch("posthog.temporal.experiments.activities.close_old_connections"),+ patch("posthog.temporal.experiments.activities.capture_experiment_metric_error_event") as mock_event,+ ):+ activity_result = _calculate_experiment_saved_metric_sync.func( # type: ignore[attr-defined]+ experiment.id, bad_metric["uuid"], "fingerprint"+ )++ self.assertFalse(activity_result.success)+ result_row = ExperimentMetricResult.objects.get(experiment=experiment, metric_uuid=bad_metric["uuid"])+ assert result_row.status == ExperimentMetricResult.Status.FAILED+ mock_event.assert_called_once()++ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)+ def test_regular_metric_activity_still_raises_transient_errors(self):+ feature_flag = self.create_feature_flag()+ experiment = self.create_experiment(+ feature_flag=feature_flag,+ start_date=datetime(2020, 1, 1, 0, 0, 0),+ end_date=datetime(2020, 1, 5, 0, 0, 0),+ )+ metric = ExperimentMeanMetric(uuid=str(uuid4()), source=EventsNode(event="purchase"))+ metric_dict = metric.model_dump(mode="json")+ experiment.metrics = [metric_dict]+ experiment.save()++ with (+ patch("posthog.temporal.experiments.activities.close_old_connections"),+ patch("posthog.temporal.experiments.activities.ExperimentQueryRunner") as mock_runner_class,+ patch("posthog.temporal.experiments.activities.capture_experiment_metric_error_event") as mock_event,+ ):+ mock_runner_class.return_value.run.side_effect = Exception("transient query failure")++ with self.assertRaises(Exception):+ _calculate_experiment_regular_metric_sync.func( # type: ignore[attr-defined]+ experiment.id, metric_dict["uuid"], "fingerprint", attempt=1+ )+ mock_event.assert_not_called()++ with self.assertRaises(Exception):+ _calculate_experiment_regular_metric_sync.func( # type: ignore[attr-defined]+ experiment.id, metric_dict["uuid"], "fingerprint", attempt=TIMESERIES_METRIC_MAX_ATTEMPTS+ )+ mock_event.assert_called_once()++ @time_machine.travel("2020-01-10T12:00:00Z", tick=False)+ def test_saved_metric_activity_still_raises_transient_errors(self):+ feature_flag = self.create_feature_flag()+ experiment = self.create_experiment(+ feature_flag=feature_flag,+ start_date=datetime(2020, 1, 1, 0, 0, 0),+ end_date=datetime(2020, 1, 5, 0, 0, 0),+ )+ metric = ExperimentMeanMetric(uuid=str(uuid4()), source=EventsNode(event="purchase"))+ metric_dict = metric.model_dump(mode="json")++ saved_metric = ExperimentSavedMetric.objects.create(+ name="test saved metric",+ team=self.team,+ query=metric_dict,+ created_by=self.user,+ )+ ExperimentToSavedMetric.objects.create(+ experiment=experiment,+ saved_metric=saved_metric,+ metadata={"type": "primary"},+ )++ with (+ patch("posthog.temporal.experiments.activities.close_old_connections"),+ patch("posthog.temporal.experiments.activities.ExperimentQueryRunner") as mock_runner_class,+ patch("posthog.temporal.experiments.activities.capture_experiment_metric_error_event") as mock_event,+ ):+ mock_runner_class.return_value.run.side_effect = Exception("transient query failure")++ with self.assertRaises(Exception):+ _calculate_experiment_saved_metric_sync.func( # type: ignore[attr-defined]+ experiment.id, metric_dict["uuid"], "fingerprint", attempt=1+ )+ mock_event.assert_not_called()++ with self.assertRaises(Exception):+ _calculate_experiment_saved_metric_sync.func( # type: ignore[attr-defined]+ experiment.id, metric_dict["uuid"], "fingerprint", attempt=TIMESERIES_METRIC_MAX_ATTEMPTS+ )+ mock_event.assert_called_once()