: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): cap recalculation retries on capacity and timeout errors (#115794)
Rodrigo Ilorocc92341b28c7
diff --git a/products/experiments/backend/temporal/ARCHITECTURE.md b/products/experiments/backend/temporal/ARCHITECTURE.mdindex 0c65d6880e3e..80c6b373438c 100644--- a/products/experiments/backend/temporal/ARCHITECTURE.md+++ b/products/experiments/backend/temporal/ARCHITECTURE.md@@ -223,13 +223,15 @@ The split is intentional: Grafana tells you about the worker process, PostHog te## Performance notes-- **Fan out all metrics at once, Temporal owns retries.** The workflow schedules one calc activity per metric in a single `asyncio.gather` (`recalculation_workflow.py`), with no concurrency of its own. Pacing is owned by the layers that actually constrain it: the worker's activity slots (`MAX_CONCURRENT_ACTIVITIES`, autoscaled on task-queue backlog) bound compute, and the per-org ClickHouse app-query limiter bounds query fan-out. Scheduling every metric up front also keeps the task-queue backlog honest for the autoscaler. The workflow runs on its own `experiments-recalculation-task-queue` (see `EXPERIMENTS_RECALCULATION_TASK_QUEUE`), served by a dedicated worker deployment, so recalc load can be scaled and throttled independently of the general-purpose worker.+- **Fan out all metrics at once, Temporal owns retries.** The workflow schedules one calc activity per metric in a single `asyncio.gather` (`recalculation_workflow.py`), with no concurrency of its own. Pacing is owned by the layers that actually constrain it: the worker's activity slots (`MAX_CONCURRENT_ACTIVITIES`, autoscaled on task-queue backlog) bound compute and query fan-out. The per-org ClickHouse app-query limiter does not apply inside Temporal activities. Scheduling every metric up front also keeps the task-queue backlog honest for the autoscaler. The workflow runs on its own `experiments-recalculation-task-queue` (see `EXPERIMENTS_RECALCULATION_TASK_QUEUE`), served by a dedicated worker deployment, so recalc load can be scaled and throttled independently of the general-purpose worker.Retries live in Temporal's `RetryPolicy` on the calc activity, not in the workflow. The policy is exponential: `initial_interval=5s`, `backoff_coefficient=2.0`, `maximum_interval=60s`, `maximum_attempts=MAX_METRIC_ATTEMPTS` (currently 8). So a metric backs off 5s, 10s, 20s, 40s, 60s, 60s, 60s across its retries, then the eighth attempt is final. `asyncio.gather(..., return_exceptions=True)` lets healthy metrics finish while a failing one retries; a retrying metric never blocks the others, because each activity retries on its own worker slot rather than holding a shared queue slot.- A permanent failure fails fast rather than burning the retry budget. `NON_RETRYABLE_ERROR_TYPES` (`out_of_memory`, `byte_limit`, `validation_error`) plus `ValueError` are raised non-retryable, so the metric is terminal on the first trip. A different bucket, the per-org ClickHouse concurrency limiter and the cluster at-capacity guard, is retried after a random delay between 30s and 90s (`CONCURRENCY_LIMIT_RETRY_DELAY_MIN_SECONDS` and `CONCURRENCY_LIMIT_RETRY_DELAY_MAX_SECONDS`) via `ApplicationError(next_retry_delay=...)`, out-of-band from the exponential schedule, because that error means "come back later", not "this query is wrong". The random delay spreads out metrics that bounced in the same burst, so their retries do not arrive together and hit the same full concurrency limit again.+ A permanent failure fails fast rather than burning the retry budget. `NON_RETRYABLE_ERROR_TYPES` (`out_of_memory`, `byte_limit`, `validation_error`) plus `ValueError` are raised non-retryable, so the metric is terminal on the first trip. A different bucket, the cluster at-capacity error (`ClickHouseAtCapacity`, from `TOO_MANY_SIMULTANEOUS_QUERIES` or `CANNOT_SCHEDULE_TASK`) and `ConcurrencyLimitExceeded`, is retried after a random delay between 2 and 5 minutes (`CONCURRENCY_LIMIT_RETRY_DELAY_MIN_SECONDS` and `CONCURRENCY_LIMIT_RETRY_DELAY_MAX_SECONDS`) via `ApplicationError(next_retry_delay=...)`, out-of-band from the exponential schedule, because that error means "come back later", not "this query is wrong". The random delay spreads out metrics that bounced in the same burst, so their retries do not arrive together and hit the same saturated cluster again.-- **`is_final_attempt` is derived inside the activity.** Because Temporal now owns retries, the activity reads its own attempt count from `activity.info().attempt` and compares it against `MAX_METRIC_ATTEMPTS` (the same constant the workflow's `RetryPolicy` is built from, so both sides agree on which attempt is last). The activity persists a transient failure (FAILED row + `metric_errors`) only on the final attempt, so a metric still being retried stays in its loading/dim state on the frontend instead of flashing an error that may yet resolve. Non-final transient state is tracked separately in the `metric_retries` column for the UI.+ Two error classes have a lower attempt cap than `MAX_METRIC_ATTEMPTS`, because their retries rarely succeed and each one costs ClickHouse capacity: capacity errors stop at `CAPACITY_MAX_METRIC_ATTEMPTS` (3) and the `timeout` class at `TIMEOUT_MAX_METRIC_ATTEMPTS` (2). The activity compares the attempt number with the cap of the error it just got. At the cap it persists the failure with `retriable=True` and raises non-retryable, so Temporal stops early without a change to the workflow's `RetryPolicy`. A user retry can recover the metric later.++- **`is_final_attempt` is derived inside the activity.** Because Temporal now owns retries, the activity reads its own attempt count from `activity.info().attempt` and compares it against `MAX_METRIC_ATTEMPTS` (the same constant the workflow's `RetryPolicy` is built from, so both sides agree on which attempt is last). The activity persists a transient failure (FAILED row + `metric_errors`) only on the final attempt (or at the error class cap above), so a metric still being retried stays in its loading/dim state on the frontend instead of flashing an error that may yet resolve. Non-final transient state is tracked separately in the `metric_retries` column for the UI.- **Per-org fairness.** Each calc activity is dispatched with `priority=Priority(fairness_key=inputs.fairness_key)`, where the key is the org id. Under backlog, Temporal round-robins across orgs so one org's large recalc does not starve another's. It is a no-op on namespaces without fairness support.diff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.pyindex ecf127cf016d..f07fcb9da03e 100644--- a/products/experiments/backend/temporal/models.py+++ b/products/experiments/backend/temporal/models.py@@ -35,12 +35,16 @@ METRICS_RECALCULATION_WORKFLOW_NAME = "experiment-metrics-recalculation-workflow# Max attempts per metric before it's marked failed on the recalculation workflow.MAX_METRIC_ATTEMPTS = 8-# Retry delay window 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. Each bounce picks a random delay in the window, so metrics that bounced in the same-# burst do not retry at the same moment and hit the same full limit again.-CONCURRENCY_LIMIT_RETRY_DELAY_MIN_SECONDS = 30-CONCURRENCY_LIMIT_RETRY_DELAY_MAX_SECONDS = 90+# Below MAX_METRIC_ATTEMPTS for errors where a retry rarely succeeds and adds ClickHouse load. At the cap the+# activity fails the metric non-retryable, so the RetryPolicy keeps MAX_METRIC_ATTEMPTS.+CAPACITY_MAX_METRIC_ATTEMPTS = 3+# The timeout class also holds SOCKET_TIMEOUT, so one retry stays for network failures.+TIMEOUT_MAX_METRIC_ATTEMPTS = 2++# Jittered delay after a capacity rejection (ClickHouseAtCapacity or ConcurrencyLimitExceeded), set via+# next_retry_delay. The per-org app limiter skips Temporal activities, so the delay lets the cluster drain.+CONCURRENCY_LIMIT_RETRY_DELAY_MIN_SECONDS = 120+CONCURRENCY_LIMIT_RETRY_DELAY_MAX_SECONDS = 300RECALCULATION_RETRY_INITIAL_INTERVAL_SECONDS = 5RECALCULATION_RETRY_BACKOFF_COEFFICIENT = 2.0diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex 4c41fdd43b5f..c84262c6be25 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -47,6 +47,7 @@ from products.experiments.backend.models.experiment import (ExperimentMetricsRecalculation,)from products.experiments.backend.temporal.models import (+ CAPACITY_MAX_METRIC_ATTEMPTS,CONCURRENCY_LIMIT_RETRY_DELAY_MAX_SECONDS,CONCURRENCY_LIMIT_RETRY_DELAY_MIN_SECONDS,MAX_METRIC_ATTEMPTS,@@ -55,6 +56,7 @@ from products.experiments.backend.temporal.models import (RECALCULATION_RETRY_BACKOFF_COEFFICIENT,RECALCULATION_RETRY_INITIAL_INTERVAL_SECONDS,RECALCULATION_RETRY_MAX_INTERVAL_SECONDS,+ TIMEOUT_MAX_METRIC_ATTEMPTS,ExperimentMetricToRecalculate,MetricRecalculationResult,RecalculationProgressUpdate,@@ -462,7 +464,13 @@ def _safe_retry_message(error: Exception, error_type: str) -> str:def _record_retry(- recalculation_id: str, metric_uuid: str, attempt: int, error_type: str, message: str, delay_seconds: float+ recalculation_id: str,+ metric_uuid: str,+ attempt: int,+ max_attempts: int,+ error_type: str,+ message: str,+ delay_seconds: float,) -> None:"""Transient attempt state for the UI, keyed by metric_uuid; overwritten per attempt, removed by themetric's terminal write. Carries a user-safe description of the error that triggered the retry;@@ -472,7 +480,7 @@ def _record_retry(metric_retries = recalc.metric_retries or {}metric_retries[metric_uuid] = {"attempt": attempt,- "max_attempts": MAX_METRIC_ATTEMPTS,+ "max_attempts": max_attempts,"error_type": error_type,"message": message[:_MAX_ERROR_MESSAGE_LENGTH],"next_retry_at": (timezone.now() + timedelta(seconds=delay_seconds)).isoformat(),@@ -876,16 +884,18 @@ def _calculate_experiment_metric_for_recalculation_sync(except (ConcurrencyLimitExceeded, ClickHouseAtCapacity) as e:message = str(e)[:_MAX_ERROR_MESSAGE_LENGTH]retry_delay_seconds = _concurrency_limit_retry_delay_seconds()- if is_final_attempt:+ capacity_attempts_exhausted = attempt >= CAPACITY_MAX_METRIC_ATTEMPTS+ is_last_attempt = is_final_attempt or capacity_attempts_exhausted+ if is_last_attempt:record_terminal_error(message, classify_experiment_query_error(e), retriable=True)logger.warning("Experiment metric recalculation deferred by ClickHouse backpressure",experiment_id=experiment_id,metric_uuid=metric_uuid,- is_final_attempt=is_final_attempt,+ is_final_attempt=is_last_attempt,error_class=type(e).__name__,)- if is_final_attempt:+ if is_last_attempt:_clear_retry(recalculation_id, metric_uuid)else:# Exact, not estimated: this branch sets the delay explicitly via next_retry_delay.@@ -895,6 +905,7 @@ def _calculate_experiment_metric_for_recalculation_sync(recalculation_id,metric_uuid,attempt,+ CAPACITY_MAX_METRIC_ATTEMPTS,error_type,safe_message,retry_delay_seconds,@@ -910,7 +921,7 @@ def _calculate_experiment_metric_for_recalculation_sync("error_type": error_type,"error_message": safe_message,"attempt": attempt,- "max_attempts": MAX_METRIC_ATTEMPTS,+ "max_attempts": CAPACITY_MAX_METRIC_ATTEMPTS,"next_retry_delay_seconds": round(retry_delay_seconds, 1),},trigger=state.trigger,@@ -919,12 +930,15 @@ def _calculate_experiment_metric_for_recalculation_sync(message,type=type(e).__name__,next_retry_delay=timedelta(seconds=retry_delay_seconds),+ non_retryable=capacity_attempts_exhausted,) from eexcept Exception as e: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)+ max_attempts = TIMEOUT_MAX_METRIC_ATTEMPTS if error_type == "timeout" else MAX_METRIC_ATTEMPTS+ is_last_attempt = is_final_attempt or attempt >= max_attempts# validation_error = the user's metric config is broken (e.g. HogQL referencing a# column outside an aggregate) — a stored failure, not a platform error to track.if error_type != "validation_error":@@ -936,16 +950,16 @@ def _calculate_experiment_metric_for_recalculation_sync("recalculation_id": recalculation_id,},)- if is_final_attempt or is_permanent:+ if is_last_attempt or is_permanent:record_terminal_error(message, error_type, retriable=not is_permanent)logger.exception("Experiment metric recalculation failed",experiment_id=experiment_id,metric_uuid=metric_uuid,- is_final_attempt=is_final_attempt,+ is_final_attempt=is_last_attempt,error_type=error_type,)- if is_final_attempt or is_permanent:+ if is_last_attempt or is_permanent:_clear_retry(recalculation_id, metric_uuid)else:retry_delay_seconds = _estimated_retry_delay_seconds(attempt)@@ -954,6 +968,7 @@ def _calculate_experiment_metric_for_recalculation_sync(recalculation_id,metric_uuid,attempt,+ max_attempts,error_type,safe_message,retry_delay_seconds,@@ -969,7 +984,7 @@ def _calculate_experiment_metric_for_recalculation_sync("error_type": error_type,"error_message": safe_message,"attempt": attempt,- "max_attempts": MAX_METRIC_ATTEMPTS,+ "max_attempts": max_attempts,"next_retry_delay_seconds": retry_delay_seconds,},trigger=state.trigger,@@ -981,4 +996,7 @@ def _calculate_experiment_metric_for_recalculation_sync(# stored failure out of error tracking.raise NonReportableApplicationError(message, type=error_type, non_retryable=True) from eraise ApplicationError(message, type=error_type, non_retryable=True) from e+ if is_last_attempt and not is_final_attempt:+ # The error class cap is below MAX_METRIC_ATTEMPTS, so stop the RetryPolicy from retrying further.+ raise ApplicationError(message, type=error_type, non_retryable=True) from eraisediff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.pyindex b928cec555e5..fc6038142582 100644--- a/products/experiments/backend/temporal/test_recalculation_activities.py+++ b/products/experiments/backend/temporal/test_recalculation_activities.py@@ -29,7 +29,9 @@ from products.experiments.backend.models.experiment import (ExperimentToSavedMetric,)from products.experiments.backend.temporal.models import (+ CAPACITY_MAX_METRIC_ATTEMPTS,MAX_METRIC_ATTEMPTS,+ TIMEOUT_MAX_METRIC_ATTEMPTS,MetricRecalculationResult,RecalculationProgressUpdate,)@@ -751,29 +753,50 @@ class TestCalculateActivity(BaseTest):@parameterized.expand([- # (name, exc, expected_error_type, expected_delay_seconds, expected_message) — backpressure uses- # the explicit next_retry_delay; a generic transient on attempt 2 follows the policy backoff- # (5 * 2^1). The generic exception carries a fake credential to lock in that raw exception text- # (which can embed the executed query, warehouse secrets included) never reaches the API field.+ # (name, exc, attempt, expected_error_type, expected_delay_seconds, expected_max_attempts,+ # expected_message) — backpressure uses the explicit next_retry_delay; a generic transient on+ # attempt 2 follows the policy backoff (5 * 2^1). The generic exception carries a fake credential+ # to lock in that raw exception text (which can embed the executed query, warehouse secrets+ # included) never reaches the API field.("backpressure",ConcurrencyLimitExceeded("quota"),+ 2,"rate_limited",47.5,+ CAPACITY_MAX_METRIC_ATTEMPTS,"The query was deferred because the cluster is at capacity.",),("generic_transient",RuntimeError("blip aws_access_key_id=AKIAFAKESECRET"),+ 2,"server_error",10,+ MAX_METRIC_ATTEMPTS,"The query failed with a server error.",),+ (+ "timeout",+ ClickHouseQueryTimeOut(),+ 1,+ "timeout",+ 5,+ TIMEOUT_MAX_METRIC_ATTEMPTS,+ "The query timed out.",+ ),])@time_machine.travel("2026-05-29T13:00:00Z", tick=False)def test_transient_attempt_records_retry_state_and_success_clears_it(- self, name: str, exc: Exception, expected_error_type: str, expected_delay_seconds: float, expected_message: str+ self,+ name: str,+ exc: Exception,+ attempt: int,+ expected_error_type: str,+ expected_delay_seconds: float,+ expected_max_attempts: int,+ expected_message: str,):# The retry entry is what the UI shows between attempts; without it the metric looks stuck. It must# carry the attempt counters and a next_retry_at estimate, and vanish once the metric resolves.@@ -786,12 +809,12 @@ class TestCalculateActivity(BaseTest):):mock_runner.return_value.run.side_effect = excwith pytest.raises((type(exc), ApplicationError)):- _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=False, attempt=2)+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=False, attempt=attempt)recalc.refresh_from_db()entry = recalc.metric_retries["m1"]- assert entry["attempt"] == 2- assert entry["max_attempts"] == MAX_METRIC_ATTEMPTS+ assert entry["attempt"] == attempt+ assert entry["max_attempts"] == expected_max_attemptsassert entry["error_type"] == expected_error_typeassert entry["message"] == expected_messageassert "AKIAFAKESECRET" not in entry["message"]@@ -800,7 +823,7 @@ class TestCalculateActivity(BaseTest):with patch("products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner") as mock_runner:mock_runner.return_value.run.return_value.model_dump.return_value = {}- result = _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, attempt=3)+ result = _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, attempt=attempt + 1)assert result.success is Truerecalc.refresh_from_db()@@ -891,6 +914,37 @@ class TestCalculateActivity(BaseTest):row = ExperimentMetricResult.objects.get(experiment=exp, metric_uuid="m1")assert row.status == ExperimentMetricResult.Status.FAILED+ @parameterized.expand(+ [+ ("capacity", ClickHouseAtCapacity(), CAPACITY_MAX_METRIC_ATTEMPTS, "rate_limited"),+ ("timeout", ClickHouseQueryTimeOut(), TIMEOUT_MAX_METRIC_ATTEMPTS, "timeout"),+ ]+ )+ def test_error_class_cap_fails_the_metric_before_the_policy_limit(+ self, name: str, exc: Exception, cap: int, expected_error_type: str+ ):+ exp = self._experiment(flag_key=f"calc-class-cap-{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((type(exc), ApplicationError)):+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=False, attempt=cap - 1)+ recalc.refresh_from_db()+ assert "m1" in recalc.metric_retries+ assert recalc.metric_errors == {}++ with pytest.raises(ApplicationError) as exc_info:+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=False, attempt=cap)++ assert exc_info.value.non_retryable is True+ recalc.refresh_from_db()+ assert recalc.metric_retries == {}+ assert recalc.metric_errors["m1"]["error_type"] == expected_error_type+ assert recalc.metric_errors["m1"]["retriable"] is True+ row = ExperimentMetricResult.objects.get(experiment=exp, metric_uuid="m1")+ assert row.status == ExperimentMetricResult.Status.FAILED+@parameterized.expand([("out_of_memory", ClickHouseQueryMemoryLimitExceeded(), "out_of_memory"),@@ -1572,8 +1626,8 @@ class TestRecalculationAnalytics(BaseTest):@parameterized.expand([- # (name, exc, expected_error_type, expected_delay_seconds, expected_message) — backpressure uses- # the explicit concurrency delay; a generic transient on attempt 2 follows the policy backoff+ # (name, exc, expected_error_type, expected_delay_seconds, expected_max_attempts, expected_message) —+ # backpressure uses the explicit concurrency delay; a generic transient on attempt 2 follows the policy backoff# (5 * 2^1). The generic exception carries a fake credential to lock in that raw exception text# (which can embed the executed query, warehouse secrets included) never reaches analytics.(@@ -1581,6 +1635,7 @@ class TestRecalculationAnalytics(BaseTest):ConcurrencyLimitExceeded("quota"),"rate_limited",47.5,+ CAPACITY_MAX_METRIC_ATTEMPTS,"The query was deferred because the cluster is at capacity.",),(@@ -1588,6 +1643,7 @@ class TestRecalculationAnalytics(BaseTest):RuntimeError("blip aws_access_key_id=AKIAFAKESECRET"),"server_error",10,+ MAX_METRIC_ATTEMPTS,"The query failed with a server error.",),]@@ -1598,6 +1654,7 @@ class TestRecalculationAnalytics(BaseTest):exc: Exception,expected_error_type: str,expected_delay_seconds: float,+ expected_max_attempts: int,expected_message: str,):# A non-final attempt re-raises for Temporal to retry. It emits 'experiment metric retry' (not@@ -1623,7 +1680,7 @@ class TestRecalculationAnalytics(BaseTest):assert props["error_message"] == expected_messageassert "AKIAFAKESECRET" not in props["error_message"]assert props["attempt"] == 2- assert props["max_attempts"] == MAX_METRIC_ATTEMPTS+ assert props["max_attempts"] == expected_max_attemptsassert props["next_retry_delay_seconds"] == expected_delay_secondsassert props["execution_mode"] == "recalculation"assert props["mechanism"] == "orchestrated"