: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): reverts retries to be idiomatic temporal (#70793)
Rodrigo Iloro9696ea4146cc
diff --git a/products/experiments/backend/temporal/recalculation_activities.py b/products/experiments/backend/temporal/recalculation_activities.pyindex 95f49a1d34b2..b32967fb271f 100644--- a/products/experiments/backend/temporal/recalculation_activities.py+++ b/products/experiments/backend/temporal/recalculation_activities.py@@ -8,6 +8,7 @@ and lets the logic be unit-tested without the activity decorator.import temporalio.activityfrom products.experiments.backend.temporal.models import (+ MAX_METRIC_ATTEMPTS,ExperimentMetricToRecalculate,MetricRecalculationResult,RecalculationProgressUpdate,@@ -41,7 +42,6 @@ async def calculate_experiment_metric_for_recalculation(recalculation_id: str,query_to: str,metric_type: str = "primary",- is_final_attempt: bool = True,) -> MetricRecalculationResult:"""Calculate one metric, write its recalc-fingerprinted result to ExperimentMetricResult, and fold theprogress update (counter + error) into the same job atomically. query_to is the run's shared data-window end.@@ -50,11 +50,12 @@ async def calculate_experiment_metric_for_recalculation(PostHog event so the capture path doesn't have to re-query the saved-metric M2M to resolve it. Defaults to"primary" so existing call sites and tests that don't pass it remain valid.- is_final_attempt is owned by the workflow's requeue loop (the activity runs with maximum_attempts=1, so it- can't infer this from activity.info().attempt). On the final attempt a transient failure is persisted rather- than re-raised silently, so the row reflects the real outcome once the workflow stops retrying. Defaults to- True so callers that don't pass it persist failures eagerly.+ Finality is derived from activity.info().attempt against MAX_METRIC_ATTEMPTS, the same constant the+ workflow's RetryPolicy is built from, so both sides agree on which attempt is the last. On the final+ attempt a transient failure is persisted rather than re-raised silently, so the row reflects the real+ outcome once Temporal stops retrying."""+ is_final_attempt = temporalio.activity.info().attempt >= MAX_METRIC_ATTEMPTSreturn await _calculate_experiment_metric_for_recalculation_sync(experiment_id, metric_uuid, recalculation_id, query_to, metric_type, is_final_attempt)diff --git a/products/experiments/backend/temporal/recalculation_workflow.py b/products/experiments/backend/temporal/recalculation_workflow.pyindex d7e4faa7cdab..21ab942119b4 100644--- a/products/experiments/backend/temporal/recalculation_workflow.py+++ b/products/experiments/backend/temporal/recalculation_workflow.py@@ -1,7 +1,5 @@import asyncio-import dataclasses-from collections import deque-from datetime import datetime, timedelta+from datetime import timedeltaimport temporalio.workflowfrom temporalio.common import RetryPolicy@@ -14,7 +12,6 @@ with temporalio.workflow.unsafe.imports_passed_through():MAX_METRIC_ATTEMPTS,METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS,ExperimentMetricsRecalculationWorkflowInputs,- ExperimentMetricToRecalculate,RecalculationProgressUpdate,)from products.experiments.backend.temporal.recalculation_activities import (@@ -24,22 +21,18 @@ with temporalio.workflow.unsafe.imports_passed_through():)from products.experiments.backend.temporal.recalculation_metrics import increment_workflow_finished-# Per-run metric fan-out: how many metric activities one run keeps in flight. Sized so two concurrent runs-# from the same org fit exactly inside the per-org ClickHouse app-query limit (DEFAULT_APP_ORG_CONCURRENT_QUERIES-# = 20 in posthog/clickhouse/client/limit.py); a third same-org run bounces off that limiter. Cross-run worker-# load is bounded separately by the dedicated recalc worker's activity-slot cap (MAX_CONCURRENT_ACTIVITIES).-MAX_CONCURRENT_METRICS = 10-@temporalio.workflow.defn(name="experiment-metrics-recalculation-workflow")class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):"""Recalculate all metrics for an experiment on demand.- Each run discovers all metrics, marks the job in_progress (which also pins the single data-window end), then- runs a pool of MAX_CONCURRENT_METRICS workers draining a requeue queue (one activity attempt at a time;- transient failures requeue with backoff, the workflow owns retries), and finalizes the job status. Per-metric- progress counters and errors are folded into the calc activity itself, so the workflow only writes progress- at start and finish.+ Each run discovers all metrics, marks the job in_progress (which also pins the single data-window end),+ schedules one calc activity per metric all at once, and finalizes the job status. The workflow imposes no+ concurrency of its own, pacing is owned by the layers that actually constrain it: worker 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. Per-metric progress counters and errors are folded into the calc activity+ itself, so the workflow only writes progress at start and finish."""@staticmethod@@ -111,101 +104,33 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):temporalio.workflow.logger.info(f"running recalc {recalculation_id} with {len(metrics)} metrics")- # Worker pool over a requeue queue. Retries are owned by the workflow, not the activity's retry policy,- # so a failing attempt frees its concurrency slot the moment it fails instead of holding it through the- # whole backoff chain (which would starve healthy metrics behind it). Each activity runs with- # maximum_attempts=1; on a transient failure (the activity raises) the metric is requeued at the BACK- # with a not-before delay, so other metrics run before its next attempt. A metric is permanently failed- # only after MAX_METRIC_ATTEMPTS trips. Permanent failures (StatisticError/ZeroDivisionError) are- # returned with success=False, not raised, so they terminate on the first trip.- #- # Determinism: all time comes from temporalio.workflow.now() (recorded by Temporal, stable on replay)- # and waits use temporalio.workflow.sleep(); no wall-clock, no Math.random, no host state.- @dataclasses.dataclass- class _QueuedMetric:- metric: ExperimentMetricToRecalculate- attempts: int # attempts already made (0 on first enqueue)- not_before: datetime # earliest workflow time this item may run-- def _backoff(attempts: int) -> timedelta:- # Same schedule the old activity retry policy used: 5s, 10s, 20s, 40s, capped at 60s.- return timedelta(seconds=min(5.0 * (2.0 ** (attempts - 1)), 60.0))-- start_now = temporalio.workflow.now()- queue: deque[_QueuedMetric] = deque(_QueuedMetric(metric=m, attempts=0, not_before=start_now) for m in metrics)- succeeded = 0- failed = 0- in_flight = 0-- # Re-evaluated by Temporal until true: either an item is queued again (a sibling requeued a retry) or- # all in-flight work has drained (so this worker can exit). Defined once, not per loop iteration.- def _queue_changed() -> bool:- return bool(queue) or in_flight == 0-- async def _worker() -> None:- nonlocal succeeded, failed, in_flight- while queue or in_flight:- if not queue:- # Work is still running in a sibling worker but nothing is runnable here yet. Wait on the- # in-flight work rather than busy-spin; it will requeue or finish, then re-check.- await temporalio.workflow.wait_condition(_queue_changed)- continue-- item = queue.popleft()- wait = (item.not_before - temporalio.workflow.now()).total_seconds()- if wait > 0:- # Not due yet. Requeue and, if every queued item is also not yet due, sleep until this one- # is (bounded by its own not_before) so we neither busy-spin nor oversleep past a due item.- queue.append(item)- if all((q.not_before - temporalio.workflow.now()).total_seconds() > 0 for q in queue):- await temporalio.workflow.sleep(timedelta(seconds=wait))- continue-- attempt_number = item.attempts + 1- is_final_attempt = attempt_number >= MAX_METRIC_ATTEMPTS- in_flight += 1- try:- result = await temporalio.workflow.execute_activity(- calculate_experiment_metric_for_recalculation,- args=[- item.metric.experiment_id,- item.metric.metric_uuid,- recalculation_id,- query_to,- item.metric.metric_type,- is_final_attempt,- ],- # No heartbeat: the activity's only long-running step is one blocking ClickHouse query- # with no progress hooks, so start_to_close_timeout is the real per-attempt ceiling.- # The query's ClickHouse max_execution_time is capped below this (see models.py) so- # slow queries fail typed inside the activity instead of being killed from outside.- start_to_close_timeout=timedelta(seconds=METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS),- # One attempt per invocation; the workflow owns requeue + backoff (see block comment).- retry_policy=RetryPolicy(maximum_attempts=1),- )- except Exception:- # Transient failure (the activity raised). Requeue at the back with a backoff delay unless- # this was the final attempt — in which case the activity already persisted the failure.- if is_final_attempt:- failed += 1- else:- queue.append(- _QueuedMetric(- metric=item.metric,- attempts=attempt_number,- not_before=temporalio.workflow.now() + _backoff(attempt_number),- )- )- else:- # Returned a result: success, or a permanent failure recorded with success=False.- if result.success:- succeeded += 1- else:- failed += 1- finally:- in_flight -= 1-- await asyncio.gather(*[_worker() for _ in range(MAX_CONCURRENT_METRICS)])+ calc_retry_policy = RetryPolicy(+ initial_interval=timedelta(seconds=5),+ maximum_interval=timedelta(seconds=60),+ maximum_attempts=MAX_METRIC_ATTEMPTS,+ )+ results = await asyncio.gather(+ *[+ temporalio.workflow.execute_activity(+ calculate_experiment_metric_for_recalculation,+ args=[+ metric.experiment_id,+ metric.metric_uuid,+ recalculation_id,+ query_to,+ metric.metric_type,+ ],+ start_to_close_timeout=timedelta(seconds=METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS),+ retry_policy=calc_retry_policy,+ )+ for metric in metrics+ ],+ return_exceptions=True,+ )+ # An exception here means retries were exhausted; the activity already persisted the FAILED row on its+ # final attempt. A returned result carries success=False for permanent failures recorded without retry.+ succeeded = sum(1 for result in results if not isinstance(result, BaseException) and result.success)+ failed = len(results) - succeeded# Any failure marks the run as "failed"; the succeeded/failed counts carry the partial-vs-total nuance# for consumers that need it (the UI shows "N succeeded, M failed" alongside the status). A status-onlydiff --git a/products/experiments/backend/temporal/test_recalculation_workflow.py b/products/experiments/backend/temporal/test_recalculation_workflow.pyindex 38802a8728cc..3ddd5b46351c 100644--- a/products/experiments/backend/temporal/test_recalculation_workflow.py+++ b/products/experiments/backend/temporal/test_recalculation_workflow.py@@ -18,6 +18,7 @@ from products.experiments.backend.temporal.models import (MetricRecalculationResult,RecalculationProgressUpdate,)+from products.experiments.backend.temporal.recalculation_activities import calculate_experiment_metric_for_recalculationfrom products.experiments.backend.temporal.recalculation_workflow import ExperimentMetricsRecalculationWorkflow_START_QUERY_TO = "2026-05-29T12:00:00+00:00"@@ -53,7 +54,6 @@ def _make_mock_activities(recalculation_id: str,query_to: str,metric_type: str = "primary",- is_final_attempt: bool = True,) -> MetricRecalculationResult:calculate_calls.append((experiment_id, metric_uuid, recalculation_id, query_to, metric_type))return metric_results.get(metric_uuid, MetricRecalculationResult(metric_uuid=metric_uuid, success=True))@@ -126,10 +126,10 @@ class TestExperimentMetricsRecalculationWorkflow:assert progress_updates[-1].status == expected_final_statusassert progress_updates[-1].mark_completed is True- async def test_transient_failure_is_requeued_and_retried_until_it_succeeds(self):- # A raised activity is a transient failure: the workflow requeues the metric and retries it, freeing- # the slot in between. m2 raises on its first two attempts, then succeeds on the third; m1 succeeds- # immediately. The run ends fully succeeded, and m2 was invoked three times.+ async def test_transient_failure_is_retried_until_it_succeeds(self):+ # A raised activity is a transient failure: Temporal's retry policy re-dispatches it. m2 raises on+ # its first two attempts, then succeeds on the third; m1 succeeds immediately. The run ends fully+ # succeeded, and m2 was invoked three times.metrics = [_metric("m1"), _metric("m2")]attempts: dict[str, int] = {}@@ -148,7 +148,6 @@ class TestExperimentMetricsRecalculationWorkflow:recalculation_id: str,query_to: str,metric_type: str = "primary",- is_final_attempt: bool = True,) -> MetricRecalculationResult:attempts[metric_uuid] = attempts.get(metric_uuid, 0) + 1if metric_uuid == "m2" and attempts[metric_uuid] <= 2:@@ -161,43 +160,44 @@ class TestExperimentMetricsRecalculationWorkflow:assert attempts["m1"] == 1assert attempts["m2"] == 3- async def test_transient_failure_is_marked_failed_after_max_attempts(self):- # A metric that raises on every attempt is requeued until MAX_METRIC_ATTEMPTS is exhausted, then- # counted as failed (the final attempt persists the failure inside the real activity).- metrics = [_metric("m1")]- attempts: dict[str, int] = {}- # is_final_attempt is the only signal that tells the real activity to persist the failure. Track it- # per call so we can assert the workflow flips it to True exactly on the last attempt; otherwise a- # run would be counted failed here while the metric row stayed in its loading state forever.- is_final_attempt_log: list[bool] = []+ async def test_exhausted_retries_mark_failed_and_finality_derives_from_attempt_count(self):+ # A metric that raises on every attempt is retried by the activity retry policy until+ # MAX_METRIC_ATTEMPTS is exhausted, then counted as failed. Runs the REAL activity wrapper (with the+ # DB-touching sync implementation patched out) because the wrapper derives is_final_attempt from+ # activity.info().attempt against the same constant the retry policy is built from — if those two+ # sides drift, the FAILED row never persists and the metric row stays in its loading state forever.+ recorded_flags: list[bool] = []@activity.defn(name="discover_experiment_metrics")async def mock_discover(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:- return metrics+ return [_metric("m1")]@activity.defn(name="update_recalculation_progress")async def mock_update_progress(update: RecalculationProgressUpdate) -> str | None:return _START_QUERY_TO if update.mark_started else None- @activity.defn(name="calculate_experiment_metric_for_recalculation")- async def mock_calculate(+ async def failing_sync(experiment_id: int,metric_uuid: str,recalculation_id: str,query_to: str,- metric_type: str = "primary",- is_final_attempt: bool = True,+ metric_type: str,+ is_final_attempt: bool,) -> MetricRecalculationResult:- attempts[metric_uuid] = attempts.get(metric_uuid, 0) + 1- is_final_attempt_log.append(is_final_attempt)+ recorded_flags.append(is_final_attempt)raise RuntimeError("always fails")- result = await _run_workflow([mock_discover, mock_update_progress, mock_calculate])+ with patch(+ "products.experiments.backend.temporal.recalculation_activities._calculate_experiment_metric_for_recalculation_sync",+ new=failing_sync,+ ):+ result = await _run_workflow(+ [mock_discover, mock_update_progress, calculate_experiment_metric_for_recalculation]+ )assert result == {"total": 1, "succeeded": 0, "failed": 1}- assert attempts["m1"] == MAX_METRIC_ATTEMPTS# Only the final attempt is flagged final; earlier attempts must not be, or they'd persist early.- assert is_final_attempt_log == [False] * (MAX_METRIC_ATTEMPTS - 1) + [True]+ assert recorded_flags == [False] * (MAX_METRIC_ATTEMPTS - 1) + [True]@parameterized.expand([