Skip to content

: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.

fix(experiments): emit metric error on terminal recalculation failure (#66538)

Juraj Majerik599e9b71ecde
diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.py
index 529da5ac61ba..7a18c6f52529 100644
--- a/products/experiments/backend/temporal/recalculation_logic.py
+++ b/products/experiments/backend/temporal/recalculation_logic.py
@@ -13,13 +13,20 @@ from django.db import close_old_connections, transaction
from django.utils import timezone
import structlog
+from clickhouse_driver.errors import ServerException
from temporalio.exceptions import ApplicationError
from posthog.schema import ExperimentQuery
from posthog.clickhouse.client.connection import Workload
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.errors import look_up_clickhouse_error_code_meta
from posthog.event_usage import groups
+from posthog.exceptions import (
+ ClickHouseEstimatedQueryExecutionTimeTooLong,
+ ClickHouseQueryMemoryLimitExceeded,
+ ClickHouseQueryTimeOut,
+)
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models.scoping import team_scope
@@ -414,6 +421,22 @@ def _capture_experiment_metric_event(
)
+# error_type values mirror the client-side `classifyError` taxonomy (experimentLogic.tsx) so
+# recalculation failures land on the same dashboards as the legacy client events.
+def _classify_query_error_type(e: Exception) -> str:
+ if isinstance(e, (ClickHouseQueryTimeOut, ClickHouseEstimatedQueryExecutionTimeTooLong)):
+ return "timeout"
+ if isinstance(e, ClickHouseQueryMemoryLimitExceeded):
+ return "out_of_memory"
+ if isinstance(e, ServerException):
+ name = look_up_clickhouse_error_code_meta(e).name
+ if name in ("TIMEOUT_EXCEEDED", "SOCKET_TIMEOUT"):
+ return "timeout"
+ if name == "MEMORY_LIMIT_EXCEEDED":
+ return "out_of_memory"
+ return "server_error"
+
+
# ---------------------------------------------------------------------------
# Calculation
# ---------------------------------------------------------------------------
@@ -619,13 +642,25 @@ 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,
+ metric_type,
+ metric_dict,
+ "experiment metric error",
+ {
+ "duration_ms": round((time.perf_counter() - calc_started_at) * 1000),
+ "error_type": _classify_query_error_type(e),
+ "error_message": message,
+ },
+ )
logger.exception(
"Experiment metric recalculation failed",
experiment_id=experiment_id,
metric_uuid=metric_uuid,
is_final_attempt=is_final_attempt,
)
- # No 'experiment metric error' event here: this path re-raises and Temporal retries, so
- # emitting would double-count per attempt. The final failed count is reported once at the
- # run level ('experiment results refresh completed').
raise
diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.py
index 53af61d8d808..9cc2a9f64c8f 100644
--- a/products/experiments/backend/temporal/test_recalculation_activities.py
+++ b/products/experiments/backend/temporal/test_recalculation_activities.py
@@ -8,9 +8,12 @@ from unittest.mock import patch
from django.utils import timezone
+from clickhouse_driver.errors import ServerException
from parameterized import parameterized
from temporalio.exceptions import ApplicationError
+from posthog.exceptions import ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut
+
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
from products.experiments.backend.hogql_queries.utils import get_experiment_stats_method
from products.experiments.backend.models.experiment import (
@@ -866,9 +869,9 @@ class TestRecalculationAnalytics(BaseTest):
assert captured[0]["properties"]["is_primary"] is False
- def test_transient_failure_emits_no_per_metric_event(self):
- # The transient except-Exception path re-raises for Temporal to retry; emitting there would
- # double-count per attempt. The failure is reflected in the run-level event instead.
+ def test_non_final_failure_emits_no_per_metric_event(self):
+ # A non-final attempt re-raises for Temporal to retry; emitting there would double-count a
+ # failure that may still succeed on a later attempt. Only the terminal attempt emits.
exp = self._experiment(flag_key="an-transient", metrics=[_mean_metric("m1")])
recalc = self._recalc(exp, metric_uuids=["m1"])
@@ -878,10 +881,41 @@ class TestRecalculationAnalytics(BaseTest):
) as mock_runner:
mock_runner.return_value.run.side_effect = RuntimeError("kaboom")
with pytest.raises(RuntimeError, match="kaboom"):
- _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO)
+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=False)
assert captured == []
+ @parameterized.expand(
+ [
+ ("wrapped_oom", ClickHouseQueryMemoryLimitExceeded(), "out_of_memory"),
+ ("wrapped_timeout", ClickHouseQueryTimeOut(), "timeout"),
+ ("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"),
+ ("other", RuntimeError("kaboom"), "server_error"),
+ ]
+ )
+ def test_terminal_failure_emits_metric_error_event(self, name, exc, expected_error_type):
+ # On the terminal attempt (retries exhausted) an infra failure emits 'experiment metric error'
+ # with the client-side error_type taxonomy, so recalc failures land on the same dashboards.
+ # Covers both the wrapped exception classes and the raw ServerException code-lookup arm.
+ exp = self._experiment(flag_key=f"an-terminal-{name}", metrics=[_mean_metric("m1")])
+ recalc = self._recalc(exp, metric_uuids=["m1"])
+
+ with _record_captures() as captured:
+ with patch(
+ "products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner"
+ ) as mock_runner:
+ mock_runner.return_value.run.side_effect = exc
+ with pytest.raises(type(exc)):
+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=True)
+
+ assert len(captured) == 1
+ assert captured[0]["event"] == "experiment metric error"
+ props = captured[0]["properties"]
+ assert props["error_type"] == expected_error_type
+ assert props["execution_mode"] == "recalculation"
+
def test_results_refresh_completed_event_on_finish(self):
exp = self._experiment(flag_key="an-finish", metrics=[_mean_metric("m1")])
recalc = self._recalc(exp, metric_uuids=["m1"])