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): manage retries when CH concurrency limit is reached (#70801)

Rodrigo Ilorof611c331eac6
diff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.py
index 591aa0f96b55..14d9894c22e8 100644
--- a/products/experiments/backend/recalculation.py
+++ b/products/experiments/backend/recalculation.py
@@ -9,6 +9,7 @@ Module-level free functions (not methods on ExperimentService) so the API view c
the run id).
"""
+import asyncio
from datetime import timedelta
from uuid import UUID
@@ -26,6 +27,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.models.scoping import get_current_team_id, team_scope
from posthog.models.user import User
from posthog.settings import CLICKHOUSE_CLUSTER
+from posthog.temporal.common.client import sync_connect
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
@@ -202,6 +204,22 @@ def build_job_payload(
return payload
+def _cancel_superseded_workflows(recalculation_ids: list[str]) -> None:
+ """Best-effort cancellation of workflows whose rows were force-failed by the staleness cleanup."""
+ try:
+ temporal = sync_connect()
+ except Exception as e:
+ capture_exception(e)
+ return
+ for recalculation_id in recalculation_ids:
+ try:
+ handle = temporal.get_workflow_handle(f"experiment-metrics-recalculation-{recalculation_id}")
+ asyncio.run(handle.cancel())
+ except Exception:
+ # Expected for rows whose workflow never started (Temporal connect failure) or already finished.
+ pass
+
+
def request_recalculation(experiment: Experiment, user: User, trigger: str = "manual") -> dict:
"""Create an idempotent batch recalculation request for all experiment metrics.
@@ -240,16 +258,23 @@ def request_recalculation(experiment: Experiment, user: User, trigger: str = "ma
# No fresh active row, but stale tombstones might still hold the per-experiment uniqueness constraint
# (unique_active_metrics_recalculation_per_experiment). Mark them FAILED so the constraint releases
- # and the new row can land. Status reflects reality — these workflows are not coming back.
- cleaned_count = ExperimentMetricsRecalculation.objects.filter(
- experiment=experiment,
- status__in=[
- ExperimentMetricsRecalculation.Status.PENDING,
- ExperimentMetricsRecalculation.Status.IN_PROGRESS,
- ],
- ).update(status=ExperimentMetricsRecalculation.Status.FAILED, completed_at=timezone.now())
- if cleaned_count:
- _recalculation_stale_cleanup_counter.inc(cleaned_count)
+ # and the new row can land, and cancel their workflows after commit — a superseded run that is still
+ # executing would otherwise keep burning worker slots and ClickHouse quota alongside its replacement.
+ stale_ids = list(
+ ExperimentMetricsRecalculation.objects.filter(
+ experiment=experiment,
+ status__in=[
+ ExperimentMetricsRecalculation.Status.PENDING,
+ ExperimentMetricsRecalculation.Status.IN_PROGRESS,
+ ],
+ ).values_list("id", flat=True)
+ )
+ if stale_ids:
+ ExperimentMetricsRecalculation.objects.filter(
+ team=experiment.team, experiment=experiment, id__in=stale_ids
+ ).update(status=ExperimentMetricsRecalculation.Status.FAILED, completed_at=timezone.now())
+ _recalculation_stale_cleanup_counter.inc(len(stale_ids))
+ transaction.on_commit(lambda: _cancel_superseded_workflows([str(stale_id) for stale_id in stale_ids]))
# Set total_metrics up front from the experiment definition so the client can show progress
# ("N of M") immediately, before the workflow's discovery activity confirms the same count.
diff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.py
index 149b1b8d0b8e..6bf11b0c2983 100644
--- a/products/experiments/backend/temporal/models.py
+++ b/products/experiments/backend/temporal/models.py
@@ -13,10 +13,12 @@ ALL_OUTCOMES = (OUTCOME_PASS, OUTCOME_DIVERGENCE, OUTCOME_PATH_FLIP, OUTCOME_ERR
# Cap CanaryMetricResult.detail so a pathological error message can't bloat the Temporal payload.
MAX_CANARY_DETAIL_LENGTH = 1000
-# Max attempts per metric before it's marked failed. The workflow's requeue loop owns retries (the activity
-# runs with maximum_attempts=1), so this caps how many times a transient failure is requeued. Kept low because
-# each extra attempt adds backoff (5s, 10s, 20s, ...) to the tail of a fully-failing run.
-MAX_METRIC_ATTEMPTS = 3
+# 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.
+CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS = 60
# 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
diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.py
index 7ba8c9597ae0..63d44c6cb06a 100644
--- a/products/experiments/backend/temporal/recalculation_logic.py
+++ b/products/experiments/backend/temporal/recalculation_logic.py
@@ -6,7 +6,7 @@ module holds the DB-touching ``_*_sync`` implementations plus the pure helpers t
import time
import dataclasses
-from datetime import datetime
+from datetime import datetime, timedelta
from typing import Any
from django.db import close_old_connections, transaction
@@ -19,6 +19,7 @@ from temporalio.exceptions import ApplicationError
from posthog.schema import ExperimentQuery
from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.event_usage import groups
from posthog.exceptions_capture import capture_exception
@@ -38,6 +39,7 @@ from products.experiments.backend.models.experiment import (
)
from products.experiments.backend.temporal.metric_resolution import build_metric, find_metric_dict
from products.experiments.backend.temporal.models import (
+ CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS,
METRIC_CALC_MAX_EXECUTION_TIME_SECONDS,
ExperimentMetricToRecalculate,
MetricRecalculationResult,
@@ -611,6 +613,50 @@ 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.
+ message = str(e)[:_MAX_ERROR_MESSAGE_LENGTH]
+ if is_final_attempt:
+ _store_result(
+ experiment_id=experiment_id,
+ metric_uuid=metric_uuid,
+ recalc_fp=recalc_fp,
+ query_from=experiment.start_date,
+ query_to=query_to_dt,
+ status=ExperimentMetricResult.Status.FAILED,
+ result=None,
+ error_message=message,
+ query_id=client_query_id,
+ )
+ _record_failure(recalculation_id, metric_uuid, "calculation", message)
+ _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_experiment_query_error(e),
+ "error_message": message,
+ },
+ trigger=state.trigger,
+ )
+ logger.warning(
+ "Experiment metric recalculation deferred by org concurrency limit",
+ experiment_id=experiment_id,
+ metric_uuid=metric_uuid,
+ is_final_attempt=is_final_attempt,
+ )
+ raise ApplicationError(
+ message,
+ type="ConcurrencyLimitExceeded",
+ next_retry_delay=timedelta(seconds=CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS),
+ ) from e
+
except 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
diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.py
index 2e2432435ff3..1f809e50d90b 100644
--- a/products/experiments/backend/temporal/test_recalculation_activities.py
+++ b/products/experiments/backend/temporal/test_recalculation_activities.py
@@ -12,6 +12,7 @@ from clickhouse_driver.errors import ServerException
from parameterized import parameterized
from temporalio.exceptions import ApplicationError
+from posthog.clickhouse.client.limit import ConcurrencyLimitExceeded
from posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceeded, ClickHouseQueryTimeOut
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
@@ -23,7 +24,10 @@ from products.experiments.backend.models.experiment import (
ExperimentSavedMetric,
ExperimentToSavedMetric,
)
-from products.experiments.backend.temporal.models import RecalculationProgressUpdate
+from products.experiments.backend.temporal.models import (
+ CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS,
+ RecalculationProgressUpdate,
+)
from products.experiments.backend.temporal.recalc_fingerprint import compute_recalc_fingerprint
from products.experiments.backend.temporal.recalculation_logic import (
_calculate_experiment_metric_for_recalculation_sync,
@@ -447,6 +451,38 @@ 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")])
+ 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")
+
+ with 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.next_retry_delay == timedelta(seconds=CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS)
+ mock_capture.assert_not_called()
+ recalc.refresh_from_db()
+ assert recalc.metric_errors == {}
+ assert not ExperimentMetricResult.objects.filter(experiment=exp, metric_uuid="m1").exists()
+
+ # Final attempt: the failure is persisted for the UI, still without exception capture.
+ with pytest.raises(ApplicationError):
+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=True)
+ mock_capture.assert_not_called()
+ 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(),
diff --git a/products/experiments/backend/test/test_recalculation_service.py b/products/experiments/backend/test/test_recalculation_service.py
index 0c3e8032847c..0949b3de2587 100644
--- a/products/experiments/backend/test/test_recalculation_service.py
+++ b/products/experiments/backend/test/test_recalculation_service.py
@@ -129,13 +129,19 @@ class TestRecalculationService(BaseTest):
else:
stale_row = ExperimentMetricsRecalculation.objects.create(**stale_kwargs, started_at=long_ago)
- result = request_recalculation(exp, self.user, "manual")
+ with (
+ patch("products.experiments.backend.recalculation._cancel_superseded_workflows") as mock_cancel,
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ result = request_recalculation(exp, self.user, "manual")
- # A fresh row was created (NOT the stale one) and the stale row was marked FAILED.
+ # A fresh row was created (NOT the stale one), the stale row was marked FAILED, and its workflow
+ # was cancelled so it can't keep executing alongside the replacement run.
assert result["is_existing"] is False
assert result["id"] != str(stale_row.id)
stale_row.refresh_from_db()
assert stale_row.status == "failed"
+ mock_cancel.assert_called_once_with([str(stale_row.id)])
def test_request_recalculation_does_not_recover_recent_active_row(self):
# Defensive: a row created N minutes ago (well under the threshold) must still block, no matter the