: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
chore(experiments): build recalc calc activity calls inline (#127949)
Rodrigo Iloro935aa97e0c86
diff --git a/products/experiments/backend/temporal/ARCHITECTURE.md b/products/experiments/backend/temporal/ARCHITECTURE.mdindex 48ada1fb242b..940cd4de9897 100644--- a/products/experiments/backend/temporal/ARCHITECTURE.md+++ b/products/experiments/backend/temporal/ARCHITECTURE.md@@ -272,7 +272,7 @@ The split is intentional: Grafana tells you about the worker process, PostHog te- **`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-metric time budget.** A calc on the workflow's own queue gets `schedule_to_close_timeout` set to `METRIC_CALC_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS` (20 minutes). It covers all attempts of one metric, the retry delays between them, and the time each attempt waits in the task queue. Without it, one metric could use 8 attempts of 300s plus backoff, which is more than the 30-minute staleness threshold, and a slow but healthy run could be marked stale while it still ran.- A calc on the activity queue or the precompute queue gets no `schedule_to_close_timeout` (`_calc_schedule_to_close_timeout` in `recalculation_workflow.py`). Those queues have a fixed slot count, so a full queue is backpressure: the calc waits for a slot instead of failing at the budget. `start_to_close`, the heartbeat timeout and the retry policy still bound each attempt and the number of attempts. Replay needs no patch marker, because sdk-core matches a scheduled activity only by its id and type. A run that waits longer than `_STALE_RECALC_THRESHOLD` can still be marked FAILED and cancelled by a new request.+ A calc on the activity queue or the precompute queue gets no `schedule_to_close_timeout` (the calc's `execute_activity` call in `_run_recalculation`). Those queues have a fixed slot count, so a full queue is backpressure: the calc waits for a slot instead of failing at the budget. `start_to_close`, the heartbeat timeout and the retry policy still bound each attempt and the number of attempts. Replay needs no patch marker, because sdk-core matches a scheduled activity only by its id and type. A run that waits longer than `_STALE_RECALC_THRESHOLD` can still be marked FAILED and cancelled by a new request.On the workflow's own queue, the IN_PROGRESS phase is this budget, the failure backstop below (120s `schedule_to_close_timeout`, queue wait included), and the finish step (3 attempts of 90s), about 26 minutes in the worst case. `test_in_progress_phase_ends_before_the_staleness_ttl` keeps that sum below `_STALE_RECALC_THRESHOLD`.With the budget, a metric with slow attempts can stop before `MAX_METRIC_ATTEMPTS`.diff --git a/products/experiments/backend/temporal/recalculation_workflow.py b/products/experiments/backend/temporal/recalculation_workflow.pyindex ba38b4d104cb..82c09fe2614b 100644--- a/products/experiments/backend/temporal/recalculation_workflow.py+++ b/products/experiments/backend/temporal/recalculation_workflow.py@@ -10,12 +10,9 @@ from temporalio.exceptions import (TimeoutError as TemporalTimeoutError,)-from posthog.dataclasses import frozenfrom posthog.temporal.common.base import PostHogWorkflowwith temporalio.workflow.unsafe.imports_passed_through():- from posthog.schema import PrecomputationMode-from products.experiments.backend.temporal.models import (MAX_METRIC_ATTEMPTS,METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS,@@ -44,46 +41,6 @@ with temporalio.workflow.unsafe.imports_passed_through():from products.experiments.backend.temporal.recalculation_metrics import increment_workflow_finished-@frozen-class _CalcDispatch:- """Where one metric's calc activity runs, the precompute mode it passes, and its total time budget."""-- task_queue: str | None- precomputation_mode: PrecomputationMode | None- schedule_to_close_timeout: timedelta | None---def _calc_schedule_to_close_timeout(task_queue: str | None) -> timedelta | None:- # The activity and precompute queues have a fixed slot count, so a calc there waits for a slot instead of- # failing when the queue is full. Only a calc on the workflow's own queue keeps the total budget.- return None if task_queue else timedelta(seconds=METRIC_CALC_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS)---def _calc_dispatch(metric: ExperimentMetricToRecalculate, activity_task_queue: str | None) -> _CalcDispatch:- # Only a run on the activity queue flag uses the route that discovery set.- if activity_task_queue and metric.task_queue:- return _CalcDispatch(- task_queue=metric.task_queue,- precomputation_mode=metric.precomputation_mode,- schedule_to_close_timeout=_calc_schedule_to_close_timeout(metric.task_queue),- )- return _CalcDispatch(- task_queue=activity_task_queue,- precomputation_mode=None,- schedule_to_close_timeout=_calc_schedule_to_close_timeout(activity_task_queue),- )---def _calc_args(- metric: ExperimentMetricToRecalculate, recalculation_id: str, query_to: str, dispatch: _CalcDispatch-) -> list[object]:- args: list[object] = [metric.experiment_id, metric.metric_uuid, recalculation_id, query_to, metric.role]- # An AUTO calc keeps the five arguments, so a worker that predates the mode argument still runs it.- if dispatch.precomputation_mode is not None:- args.append(dispatch.precomputation_mode)- return args--def _ended_by_temporal(error: ActivityError) -> bool:"""True when Temporal ended the metric's retries from the outside, so no attempt persisted its outcome.@@ -207,25 +164,35 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):if inputs.activity_task_queue and temporalio.workflow.patched("recalc-activity-task-queue-2026-10")else None)- dispatches = [_calc_dispatch(metric, activity_task_queue) for metric in metrics]- results = await asyncio.gather(- *[+ calcs = []+ for metric in metrics:+ # Only a run on the activity queue flag uses the route that discovery set.+ routed = bool(activity_task_queue and metric.task_queue)+ task_queue = metric.task_queue if routed else activity_task_queue+ # The activity and precompute queues have a fixed slot count, so a calc there waits for a slot instead+ # of failing when the queue is full. Only a calc on the workflow's own queue keeps the total budget.+ schedule_to_close_timeout = (+ None if task_queue else timedelta(seconds=METRIC_CALC_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS)+ )+ args: list[object] = [metric.experiment_id, metric.metric_uuid, recalculation_id, query_to, metric.role]+ # An AUTO calc keeps the five arguments, so a worker that predates the mode argument still runs it.+ if routed and metric.precomputation_mode is not None:+ args.append(metric.precomputation_mode)+ calcs.append(temporalio.workflow.execute_activity(calculate_experiment_metric_for_recalculation,- args=_calc_args(metric, recalculation_id, query_to, dispatch),+ args=args,start_to_close_timeout=timedelta(seconds=METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS),- schedule_to_close_timeout=dispatch.schedule_to_close_timeout,+ schedule_to_close_timeout=schedule_to_close_timeout,heartbeat_timeout=timedelta(seconds=METRIC_CALC_HEARTBEAT_TIMEOUT_SECONDS),retry_policy=calc_retry_policy,- task_queue=dispatch.task_queue,+ task_queue=task_queue,# Round-robin dispatch across orgs under backlog; a no-op on namespaces without# fairness support.priority=Priority(fairness_key=inputs.fairness_key),)- for metric, dispatch in zip(metrics, dispatches)- ],- return_exceptions=True,- )+ )+ results = await asyncio.gather(*calcs, return_exceptions=True)out_of_time = [metricdiff --git a/products/experiments/backend/temporal/test_recalculation_workflow.py b/products/experiments/backend/temporal/test_recalculation_workflow.pyindex 8f4153cfe4a2..4acad509db80 100644--- a/products/experiments/backend/temporal/test_recalculation_workflow.py+++ b/products/experiments/backend/temporal/test_recalculation_workflow.py@@ -1,5 +1,7 @@+import jsonimport uuidimport asyncio+import dataclassesfrom collections.abc import Callablefrom contextlib import ExitStackfrom datetime import timedelta@@ -35,11 +37,7 @@ from products.experiments.backend.temporal.models import (RecalculationProgressUpdate,)from products.experiments.backend.temporal.recalculation_activities import calculate_experiment_metric_for_recalculation-from products.experiments.backend.temporal.recalculation_workflow import (- ExperimentMetricsRecalculationWorkflow,- _calc_dispatch,- _CalcDispatch,-)+from products.experiments.backend.temporal.recalculation_workflow import ExperimentMetricsRecalculationWorkflow_START_QUERY_TO = "2026-05-29T12:00:00+00:00"_CALC_BUDGET = timedelta(seconds=METRIC_CALC_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS)@@ -210,6 +208,35 @@ async def _run_with_calc_queue_workers()+def _as_recorded_by_older_workflow_code(history: WorkflowHistory, metric: ExperimentMetricToRecalculate) -> None:+ # A rolling deploy can pair a new discovery worker, which returns routes, with workflow code that ignores them.+ discover_scheduled_ids = {+ event.event_id+ for event in history.events+ if event.HasField("activity_task_scheduled_event_attributes")+ and event.activity_task_scheduled_event_attributes.activity_type.name == "discover_experiment_metrics"+ }+ completed = next(+ event.activity_task_completed_event_attributes+ for event in history.events+ if event.HasField("activity_task_completed_event_attributes")+ and event.activity_task_completed_event_attributes.scheduled_event_id in discover_scheduled_ids+ )+ payload = completed.result.payloads[0]+ discovered = json.loads(payload.data)+ assert [item["metric_uuid"] for item in discovered] == [metric.metric_uuid]+ for item in discovered:+ item["task_queue"] = metric.task_queue+ item["precomputation_mode"] = metric.precomputation_mode+ payload.data = json.dumps(discovered).encode()+ # The older code also gave every calc the 20-minute budget.+ for event in history.events:+ if event.HasField("activity_task_scheduled_event_attributes"):+ scheduled = event.activity_task_scheduled_event_attributes+ if scheduled.activity_type.name == "calculate_experiment_metric_for_recalculation":+ scheduled.schedule_to_close_timeout.FromTimedelta(_CALC_BUDGET)++@pytest.mark.asyncioclass TestExperimentMetricsRecalculationWorkflow:async def test_no_metrics_completes_immediately(self):@@ -702,7 +729,7 @@ class TestExperimentMetricsRecalculationWorkflow:("precompute_route", True, True, False, [], [], [("m1", None)], False),("direct_route", False, True, False, [], [("m1", PrecomputationMode.DIRECT)], [], False),("run_off_the_flag_ignores_the_route", True, False, False, [("m1", None)], [], [], True),- ("history_without_routes_replays_on_another_queue", True, True, True, [], [("m1", None)], [], True),+ ("history_without_routes_replays_on_another_queue", True, True, True, [], [("m1", None)], [], False),("history_without_routes_replays_with_another_arity",False,@@ -711,7 +738,7 @@ class TestExperimentMetricsRecalculationWorkflow:[],[("m1", None)],[],- True,+ False,),])@@ -736,23 +763,14 @@ class TestExperimentMetricsRecalculationWorkflow:precomputation_mode=None if routed_to_precompute else PrecomputationMode.DIRECT,)- def dispatch_without_routes(- metric: ExperimentMetricToRecalculate, activity_task_queue: str | None- ) -> _CalcDispatch:- return _CalcDispatch(- task_queue=activity_task_queue, precomputation_mode=None, schedule_to_close_timeout=_CALC_BUDGET- )-- with patch(- f"{_WORKFLOW_MODULE}._calc_dispatch",- side_effect=dispatch_without_routes if recorded_without_routes else _calc_dispatch,- ):- run = await _run_with_calc_queue_workers(- activity_task_queue=activity_worker_task_queue if run_on_activity_queue else None,- activity_worker_task_queue=activity_worker_task_queue,- precompute_worker_task_queue=precompute_worker_task_queue,- metric=metric,- )+ run = await _run_with_calc_queue_workers(+ activity_task_queue=activity_worker_task_queue if run_on_activity_queue else None,+ activity_worker_task_queue=activity_worker_task_queue,+ precompute_worker_task_queue=precompute_worker_task_queue,+ metric=dataclasses.replace(metric, task_queue=None, precomputation_mode=None)+ if recorded_without_routes+ else metric,+ )assert run.result == {"total": 1, "succeeded": 1, "failed": 0}assert run.workflow_queue_calls == expected_workflow_queue_calls@@ -764,6 +782,8 @@ class TestExperimentMetricsRecalculationWorkflow:else:# The test server reports an unset budget as a ten-year one.assert run.schedule_to_close_timeouts[0] in (None, timedelta(days=3650))+ if recorded_without_routes:+ _as_recorded_by_older_workflow_code(run.history, metric)await temporalio.worker.Replayer(workflows=[ExperimentMetricsRecalculationWorkflow],workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),