: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): bound recalc metric time and heartbeat the calc activity (#117931)
Rodrigo Iloro4aa0404cabf0
diff --git a/docs/internal/experiment-metric-recalculation.md b/docs/internal/experiment-metric-recalculation.mdindex f250b4b00cd8..ceca4f326137 100644--- a/docs/internal/experiment-metric-recalculation.md+++ b/docs/internal/experiment-metric-recalculation.md@@ -19,9 +19,10 @@ The deadline bounds cleanup, not the underlying thread's lifetime.Precomputation, executor queuing, statistics, and database waits can extend beyond the final ClickHouse query's execution limit.A calculation can therefore continue after the cleanup deadline expires.-The workflow does not configure activity heartbeats.-Temporal requires heartbeats and a heartbeat timeout to deliver workflow cancellation to a running activity, so supersession does not promptly interrupt the calculation.-Prompt cancellation would require heartbeat delivery plus cooperative cancellation through precomputation and the query runner, with cleanup for any active ClickHouse query.+Temporal delivers a workflow cancellation to a running activity only in a heartbeat response.+The calc activity heartbeats every `METRIC_CALC_HEARTBEAT_TIMEOUT_SECONDS / 4` while the calculation thread runs, and the workflow sets that heartbeat timeout on the call.+A workflow cancellation, or a timeout the server enforces, therefore reaches the activity and starts the cleanup above, which kills the active ClickHouse query.+Precomputation and the query runner do not cancel cooperatively, so the thread can still run past the kill.Result-write protection must remain independent of cancellation delivery.See the [workflow architecture](../../products/experiments/backend/temporal/ARCHITECTURE.md) and [Temporal's cancellation contract](https://github.com/temporalio/sdk-python#heartbeating-and-cancellation).diff --git a/products/experiments/backend/metric_calculation/results.py b/products/experiments/backend/metric_calculation/results.pyindex 4d35d6bf428f..8b6ddafebce2 100644--- a/products/experiments/backend/metric_calculation/results.py+++ b/products/experiments/backend/metric_calculation/results.py@@ -214,9 +214,12 @@ class MetricResultStore:query_from: datetime,result: dict[str, Any],query_id: str | None,- ) -> None:- """Store the completed result of one metric of a recalculation run, unless the run is terminal or missing."""- self._record_for_run(+ ) -> bool:+ """Store the completed result of one metric of a recalculation run, unless the run is terminal or missing.++ Returns whether the result was stored.+ """+ return self._record_for_run(recalculation_id,calculation_config,window=window,@@ -328,7 +331,7 @@ class MetricResultStore:result: dict[str, Any] | None,error_message: str | None,query_id: str | None,- ) -> None:+ ) -> bool:team_id = calculation_config.settings.team_idwith transaction.atomic():# Match request_recalculation's lock order; result inserts also take an experiment FK lock.@@ -346,7 +349,7 @@ class MetricResultStore:metric_uuid=calculation_config.metric_id,recalculation_status=current_status,)- return+ return Falseself._upsert(calculation_config.metric_id,@@ -359,6 +362,7 @@ class MetricResultStore:query_id=query_id,completed_at=django_timezone.now() if status == _COMPLETED else None,)+ return Truedef _upsert(self,diff --git a/products/experiments/backend/recalculation.py b/products/experiments/backend/recalculation.pyindex d3b46d5d9dc3..9e7dbcd64c57 100644--- a/products/experiments/backend/recalculation.py+++ b/products/experiments/backend/recalculation.py@@ -45,12 +45,13 @@ from products.experiments.backend.temporal.models import (from products.experiments.backend.temporal.recalculation_logic import discover_experiment_metrics# How long an active (PENDING/IN_PROGRESS) row blocks new recalculations. Beyond this, the row is treated as-# stale and a fresh recalc is allowed. Sized to be safely above the workflow's worst-case end-to-end runtime-# (discovery retries + per-metric calc retries + progress activities) so a legitimately-slow run can finish-# without being clobbered, but tight enough that an operator can recover within an hour if the workflow-# never started (Temporal connect failure, transient infra issue, etc.). See the rollback in-# start_metrics_recalculation_workflow for the happy-path failure handling; this TTL is the defense-in-depth-# backstop if that rollback itself fails.+# stale and a fresh recalc is allowed. An IN_PROGRESS row counts from started_at, so it must outlast the phase+# after the start activity: the calc budget (METRIC_CALC_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS), the failure+# backstop and the finish step. test_in_progress_phase_ends_before_the_staleness_ttl keeps that sum below this+# value, so a legitimately-slow run can finish without being clobbered. It is also tight enough that an operator+# can recover within an hour if the workflow never started (Temporal connect failure, transient infra issue,+# etc.). See the rollback in start_metrics_recalculation_workflow for the happy-path failure handling; this TTL+# is the defense-in-depth backstop if that rollback itself fails._STALE_RECALC_THRESHOLD = timedelta(minutes=30)# rate limiting manual reloads (including agents).diff --git a/products/experiments/backend/temporal/ARCHITECTURE.md b/products/experiments/backend/temporal/ARCHITECTURE.mdindex 8500be435cea..486db50f9520 100644--- a/products/experiments/backend/temporal/ARCHITECTURE.md+++ b/products/experiments/backend/temporal/ARCHITECTURE.md@@ -51,6 +51,7 @@ sequenceDiagramWorker->>Activity: wrap execute (latency + success/failure counters)Activity->>Result: upsert recalc-fingerprinted row (scoped by query_to)Activity->>DB: merge metric_errors on final-attempt failure+ Workflow->>Activity: persist the failure of a metric Temporal ended from the outside (backstop)Workflow->>DB: mark completed/failed (first-write-wins)loop poll until terminal@@ -128,7 +129,8 @@ Two safeguards on the POST endpoint:### Activity-aware staleness-The "still active" check uses different timestamps depending on the row's status: PENDING anchors on `created_at` (workflow never reached the start activity), IN_PROGRESS anchors on `started_at` (workflow began executing then stalled). Past the 30-minute threshold, the row is treated as dead, marked FAILED, and a fresh run is allowed. This protects against the failure mode where a Temporal-connect failure leaves a PENDING row behind and the rollback UPDATE also fails: without this, the experiment would be permanently locked out of recalculations.+The "still active" check uses different timestamps depending on the row's status: PENDING anchors on `created_at` (workflow never reached the start activity), IN_PROGRESS anchors on `started_at` (workflow began executing then stalled). Past the 30-minute threshold, the row is treated as dead, marked FAILED, and a fresh run is allowed.+The calc activity's total budget keeps a healthy run below that threshold; see "Per-metric time budget" below. This protects against the failure mode where a Temporal-connect failure leaves a PENDING row behind and the rollback UPDATE also fails: without this, the experiment would be permanently locked out of recalculations.### Terminal-failure backstop@@ -247,13 +249,21 @@ 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.** The calc activity call sets `schedule_to_close_timeout` 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.+ 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`.++- **Failure backstop for metrics Temporal ends from the outside.** The activity can persist its own failure only when an attempt runs to the end. Temporal ends a metric without that in three cases: the budget has no room for the next retry, the last attempt passes `start_to_close_timeout`, or the last attempt misses its heartbeats (a dead worker). The workflow detects these from the activity error (a `TIMEOUT` retry state or a timeout cause) and runs `record_metric_out_of_time_failure` for each such metric. That activity writes the FAILED row, a `metric_errors` entry with `error_type="timeout"` and `retriable=True`, and the terminal `experiment metric error` event. It does nothing when the metric already has a `metric_errors` entry from its final attempt. It also keeps a COMPLETED row, because a last attempt can write its result and then die before it reports success. The check and both failure writes run under the result store's run-write locks. If the killed attempt's thread still finishes later, its result write removes the timeout entry from `metric_errors`, so the frontend shows the result. The new commands are gated on `workflow.patched("recalc-persist-out-of-time-metrics-2026-10")`, so executions that started before the gate replay without them.+- **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.- **In-query execution guard.** The calc activity sets ClickHouse `max_execution_time=270s` (`METRIC_CALC_MAX_EXECUTION_TIME_SECONDS`), deliberately below the 300s activity timeout. A slow query then fails inside the activity with a typed ClickHouse timeout error, so the FAILED result row and the terminal event still get written, instead of Temporal killing the attempt from the outside and losing all of that.- **5-minute per-attempt budget.** `start_to_close_timeout=timedelta(minutes=5)` limits the attempt in Temporal, but cannot stop the synchronous calculation thread.- Local activity cancellation waits for that thread with a bounded cleanup deadline.- The activity has no heartbeats, so workflow cancellation does not promptly reach it.+ Local activity cancellation kills the ClickHouse query and waits for that thread with a bounded cleanup deadline.+- **Heartbeat.** The calc activity heartbeats through `Heartbeater` every `METRIC_CALC_HEARTBEAT_TIMEOUT_SECONDS / 4` (15s) while the thread runs, and the call sets a 60s `heartbeat_timeout`.+ Temporal delivers a cancellation only in a heartbeat response, so a workflow cancel or a server-side timeout now reaches the running attempt and starts the cleanup above.+ A dead worker misses its heartbeats, so Temporal retries the metric after 60s instead of after the full 300s attempt.See [cancellation and result-write protection](../../../../docs/internal/experiment-metric-recalculation.md) for the locking contract and cleanup limits.- **Calc queries run on the online ClickHouse cluster.** The calc activity builds its `ExperimentQueryRunner` with `workload=Workload.ONLINE`, so the queries hit the same replicas that serve interactive product traffic rather than the offline cluster that heavy background jobs use.diff --git a/products/experiments/backend/temporal/__init__.py b/products/experiments/backend/temporal/__init__.pyindex 70986e07e96b..6dd76a9035b9 100644--- a/products/experiments/backend/temporal/__init__.py+++ b/products/experiments/backend/temporal/__init__.py@@ -11,6 +11,7 @@ from products.experiments.backend.temporal.enrollment_census_workflow import (from products.experiments.backend.temporal.recalculation_activities import (calculate_experiment_metric_for_recalculation,discover_experiment_metrics,+ record_metric_out_of_time_failure,update_recalculation_progress,)from products.experiments.backend.temporal.recalculation_workflow import ExperimentMetricsRecalculationWorkflow@@ -56,6 +57,7 @@ ACTIVITIES = [discover_experiment_metrics,calculate_experiment_metric_for_recalculation,update_recalculation_progress,+ record_metric_out_of_time_failure,*EXPERIMENT_CANARY_ACTIVITIES,*EXPERIMENT_ENROLLMENT_CENSUS_ACTIVITIES,*EXPERIMENT_SCHEDULED_RECALCULATION_ACTIVITIES,@@ -78,6 +80,7 @@ __all__ = ["check_experiment_exposures","discover_experiment_metrics","discover_scheduled_recalculation_candidates",+ "record_metric_out_of_time_failure","report_experiment_canary_results","run_experiment_enrollment_census","run_experiment_metric_canary",diff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.pyindex f07fcb9da03e..75c3eb5db915 100644--- a/products/experiments/backend/temporal/models.py+++ b/products/experiments/backend/temporal/models.py@@ -56,11 +56,21 @@ RECALCULATION_RETRY_MAX_INTERVAL_SECONDS = 60# SOCKET_TIMEOUT (a transient network blip), and recalc timeouts are rare enough to keep the retry budget.NON_RETRYABLE_ERROR_TYPES = frozenset({"out_of_memory", "byte_limit", "validation_error"})-# 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-# inside the activity (result persistence, the terminal error event) runs.+# Per-attempt ceiling for the calc activity (its start_to_close_timeout). When it fires, Temporal ends the+# attempt from the outside. The next heartbeat delivers the cancellation, which kills the ClickHouse query, but+# the attempt persists nothing. If no further attempt follows, the workflow failure backstop persists it.METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS = 300+# Total budget for one metric across all its attempts and retry delays, queue wait included (the calc+# activity's schedule_to_close_timeout). It keeps the IN_PROGRESS phase (this budget, the failure backstop and+# the finish step) below the staleness TTL in recalculation.py, so a slow but healthy run is never treated as+# stale. The budget ends a metric before MAX_METRIC_ATTEMPTS when its attempts are slow.+METRIC_CALC_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS = 1200++# Without a heartbeat, Temporal can deliver a cancellation to the calc activity only after start_to_close,+# and it detects a dead worker only then. The activity heartbeats every heartbeat_timeout / 4.+METRIC_CALC_HEARTBEAT_TIMEOUT_SECONDS = 60+# ClickHouse max_execution_time for the recalc metric query. Deliberately below# METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS (minus headroom for metric build, stats, and persistence) so a slow# query fails INSIDE the activity with a typed ClickHouse error (159 TIMEOUT_EXCEEDED) instead of the activity@@ -70,6 +80,13 @@ METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS = 300METRIC_CALC_MAX_EXECUTION_TIME_SECONDS = 270RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS = 90+RECALCULATION_PROGRESS_MAX_ATTEMPTS = 3++# The failure backstop does only Postgres writes and one capture. Its worst case adds to the IN_PROGRESS phase,+# so it stays short. The schedule_to_close bound also covers queue wait, which start_to_close does not.+METRIC_FAILURE_BACKSTOP_ACTIVITY_TIMEOUT_SECONDS = 30+METRIC_FAILURE_BACKSTOP_MAX_ATTEMPTS = 3+METRIC_FAILURE_BACKSTOP_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS = 120@dataclasses.dataclass@@ -110,6 +127,16 @@ class MetricRecalculationResult:error_message: str | None = None+@frozen+class MetricOutOfTimeFailure:+ """A metric whose calc activity Temporal ended from the outside, so no attempt persisted its outcome."""++ recalculation_id: str+ experiment_id: int+ metric_uuid: str+ metric_type: str # "primary" or "secondary"++@dataclasses.dataclassclass ExperimentPrecomputeCanaryInputs:"""Input to the precompute canary workflow.diff --git a/products/experiments/backend/temporal/recalculation_activities.py b/products/experiments/backend/temporal/recalculation_activities.pyindex 8eb09c4021ef..201b3d2f70f3 100644--- a/products/experiments/backend/temporal/recalculation_activities.py+++ b/products/experiments/backend/temporal/recalculation_activities.py@@ -10,10 +10,13 @@ import asyncioimport structlogimport temporalio.activity+from posthog.temporal.common.heartbeat import Heartbeater+from products.experiments.backend.temporal.models import (MAX_METRIC_ATTEMPTS,METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS,ExperimentMetricToRecalculate,+ MetricOutOfTimeFailure,MetricRecalculationResult,RecalculationProgressUpdate,)@@ -21,6 +24,7 @@ from products.experiments.backend.temporal.recalculation_logic import (_calculate_experiment_metric_for_recalculation_sync,_cancel_metric_query_sync,_discover_experiment_metrics_sync,+ _record_metric_out_of_time_failure_sync,_update_recalculation_progress_sync,)@@ -28,6 +32,9 @@ logger = structlog.get_logger(__name__)_CANCEL_KILL_RETRY_INTERVAL_SECONDS = 2.0+# Heartbeat every heartbeat_timeout / 4, so three heartbeats can go missing before the attempt times out.+_HEARTBEAT_FACTOR = 4+async def _drain_cancelled_body(task: asyncio.Task[MetricRecalculationResult],@@ -45,7 +52,9 @@ async def _drain_cancelled_body(loop = asyncio.get_running_loop()while not task.done():try:- await _cancel_metric_query_sync(recalculation_id, metric_uuid, attempt)+ # A kill that hangs must not hold the drain past its deadline. The floor keeps the one kill after it.+ kill_timeout = max(deadline - loop.time(), _CANCEL_KILL_RETRY_INTERVAL_SECONDS)+ await asyncio.wait_for(_cancel_metric_query_sync(recalculation_id, metric_uuid, attempt), kill_timeout)except Exception:logger.warning("experiment_metric_recalculation_query_cancel_failed",@@ -108,26 +117,40 @@ async def calculate_experiment_metric_for_recalculation(Finality is derived from activity.info().attempt against MAX_METRIC_ATTEMPTS, the same constant theworkflow's RetryPolicy is built from, so both sides agree on which attempt is the last. On the finalattempt a transient failure is persisted rather than re-raised silently, so the row reflects the real- outcome once Temporal stops retrying.+ outcome once Temporal stops retrying. When Temporal ends the metric earlier (the schedule_to_close budget, or a+ kill from the outside), no attempt persists it and the workflow runs record_metric_out_of_time_failure."""attempt = temporalio.activity.info().attemptis_final_attempt = attempt >= MAX_METRIC_ATTEMPTSdeadline = asyncio.get_running_loop().time() + METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS- task = asyncio.ensure_future(- _calculate_experiment_metric_for_recalculation_sync(- experiment_id, metric_uuid, recalculation_id, query_to, metric_type, is_final_attempt, attempt+ # The heartbeat runs on the event loop beside the body's thread. Temporal delivers a cancellation (a workflow+ # cancel, or a timeout the server enforces) only in a heartbeat response, so the drain below depends on it.+ async with Heartbeater(factor=_HEARTBEAT_FACTOR):+ task = asyncio.ensure_future(+ _calculate_experiment_metric_for_recalculation_sync(+ experiment_id, metric_uuid, recalculation_id, query_to, metric_type, is_final_attempt, attempt+ ))- )- try:- return await asyncio.shield(task)- except asyncio.CancelledError:- # Keep the worker slot while the uncancellable thread finishes, but bound shutdown cleanup.- drain = asyncio.create_task(_drain_cancelled_body(task, deadline, recalculation_id, metric_uuid, attempt))- while True:- try:- await asyncio.shield(drain)- break- except asyncio.CancelledError:- if drain.cancelled():+ try:+ return await asyncio.shield(task)+ except asyncio.CancelledError:+ # Keep the worker slot while the uncancellable thread finishes, but bound shutdown cleanup.+ drain = asyncio.create_task(_drain_cancelled_body(task, deadline, recalculation_id, metric_uuid, attempt))+ while True:+ try:+ await asyncio.shield(drain)break- raise+ except asyncio.CancelledError:+ if drain.cancelled():+ break+ raise+++async def record_metric_out_of_time_failure(failure: MetricOutOfTimeFailure) -> None:+ """Persist the FAILED result and the terminal error event of a metric that Temporal ended from the outside.++ The calc activity persists a failure only when it runs its final attempt to the end. A schedule_to_close budget+ that ends the retries early, or a last attempt killed by start_to_close or heartbeat_timeout, leaves no outcome.+ """+ await _record_metric_out_of_time_failure_sync(failure)diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex aea0802daa73..5fdd79df62c1 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -7,6 +7,7 @@ module holds the DB-touching ``_*_sync`` implementations plus the pure helpers timport timeimport randomimport dataclasses+from concurrent.futures import ThreadPoolExecutorfrom datetime import datetime, timedeltafrom typing import Any@@ -55,6 +56,7 @@ from products.experiments.backend.temporal.models import (RECALCULATION_RETRY_MAX_INTERVAL_SECONDS,TIMEOUT_MAX_METRIC_ATTEMPTS,ExperimentMetricToRecalculate,+ MetricOutOfTimeFailure,MetricRecalculationResult,RecalculationProgressUpdate,)@@ -65,6 +67,11 @@ logger = structlog.get_logger(__name__)# Cap stored/returned error messages so a pathological traceback can't bloat the Temporal payload (~2 MiB cap)._MAX_ERROR_MESSAGE_LENGTH = 2000+_OUT_OF_TIME_MESSAGE = "The calculation ran out of time."++# Calculations can fill the event loop's default executor, so a query kill there waits behind the query it kills.+_CANCELLATION_EXECUTOR = ThreadPoolExecutor(max_workers=10, thread_name_prefix="experiment-recalc-cancel")+# ---------------------------------------------------------------------------# Discovery# ---------------------------------------------------------------------------@@ -488,6 +495,14 @@ def _clear_retry(recalculation_id: str, metric_uuid: str) -> None:recalc.save(update_fields=["metric_retries"])+def _clear_error(recalculation_id: str, metric_uuid: str) -> None:+ with transaction.atomic():+ recalc = ExperimentMetricsRecalculation.objects.select_for_update().get(id=recalculation_id)+ if metric_uuid in (recalc.metric_errors or {}):+ recalc.metric_errors.pop(metric_uuid)+ recalc.save(update_fields=["metric_errors"])++def _fail(recalculation_id: str, metric_uuid: str, step: str, message: str, *, error_type: str) -> MetricRecalculationResult:@@ -582,7 +597,7 @@ def _client_query_id(recalculation_id: str, metric_uuid: str, attempt: int) -> sreturn f"experiment_metric_recalc_{recalculation_id}_{metric_uuid}_attempt{attempt:02d}"-@database_sync_to_async_pool+@database_sync_to_async_pool(executor=_CANCELLATION_EXECUTOR)def _cancel_metric_query_sync(recalculation_id: str, metric_uuid: str, attempt: int) -> None:"""Kill the ClickHouse query the metric's calc left running, so the abandoned attempt stops reading."""close_old_connections()@@ -751,14 +766,19 @@ def _calculate_experiment_metric_for_recalculation_sync(result = runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS)result_dict = sanitize_non_finite(result.model_dump(mode="json"))- results.record_run_result(- recalculation_id,- calculation_config,- window=query_to_dt,- query_from=query_from,- result=result_dict,- query_id=client_query_id,- )+ with transaction.atomic():+ stored = results.record_run_result(+ recalculation_id,+ calculation_config,+ window=query_to_dt,+ query_from=query_from,+ result=result_dict,+ query_id=client_query_id,+ )+ # The workflow can record this metric as out of time while this attempt's thread still runs. The+ # frontend shows a metric_errors entry over a result, so a result that lands later removes it.+ if stored:+ _clear_error(recalculation_id, metric_uuid)_capture_experiment_metric_event(experiment,metric_uuid,@@ -922,3 +942,64 @@ def _calculate_experiment_metric_for_recalculation_sync(# 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 eraise+++@database_sync_to_async_pool+def _record_metric_out_of_time_failure_sync(failure: MetricOutOfTimeFailure) -> None:+ close_old_connections()+ state = _get_recalc_state(failure.recalculation_id)++ with team_scope(state.team_id, canonical=True):+ # A final attempt that ran to the end already persisted its own failure, with the real error type.+ if ExperimentMetricsRecalculation.objects.filter(+ id=failure.recalculation_id, metric_errors__has_key=failure.metric_uuid+ ).exists():+ return++ experiment = Experiment.objects.filter(id=failure.experiment_id, deleted=False).first()+ calculation_config = get_metric_calculation_config(experiment, failure.metric_uuid) if experiment else None+ if experiment is None or calculation_config is None or not experiment.start_date or state.query_to is None:+ _fail(+ failure.recalculation_id, failure.metric_uuid, "calculation", _OUT_OF_TIME_MESSAGE, error_type="timeout"+ )+ return++ results = MetricResultStore(experiment_id=experiment.id)+ with transaction.atomic():+ # The last attempt can write its result and die before it reports success, which Temporal sees as a+ # timeout. Its thread can also still be running. Take the result store's run-write locks, in its order,+ # so that no result write lands between this check and the two failure writes.+ Experiment.objects.select_for_update(no_key=True).filter(id=experiment.id, team_id=state.team_id).exists()+ ExperimentMetricsRecalculation.objects.select_for_update().filter(id=failure.recalculation_id).exists()+ completed = results.has_completed(calculation_config, window=state.query_to)+ if not completed:+ results.record_run_failure(+ failure.recalculation_id,+ calculation_config,+ window=state.query_to,+ query_from=experiment.start_date,+ error_message=_OUT_OF_TIME_MESSAGE,+ query_id=None,+ )+ _record_failure(+ failure.recalculation_id,+ failure.metric_uuid,+ "calculation",+ _OUT_OF_TIME_MESSAGE,+ error_type="timeout",+ retriable=True,+ )+ if completed:+ _clear_retry(failure.recalculation_id, failure.metric_uuid)+ return++ _clear_retry(failure.recalculation_id, failure.metric_uuid)+ _capture_experiment_metric_event(+ experiment,+ failure.metric_uuid,+ failure.metric_type,+ calculation_config.definition,+ "experiment metric error",+ {"error_type": "timeout", "error_message": _OUT_OF_TIME_MESSAGE},+ trigger=state.trigger,+ )diff --git a/products/experiments/backend/temporal/recalculation_metrics.py b/products/experiments/backend/temporal/recalculation_metrics.pyindex e80a2aa2ab97..619f975c4966 100644--- a/products/experiments/backend/temporal/recalculation_metrics.py+++ b/products/experiments/backend/temporal/recalculation_metrics.py@@ -31,6 +31,7 @@ _RECALCULATION_ACTIVITY_TYPES = {"discover_experiment_metrics","calculate_experiment_metric_for_recalculation","update_recalculation_progress",+ "record_metric_out_of_time_failure",}EXPERIMENT_METRICS_RECALCULATION_LATENCY_HISTOGRAM_METRICS = (diff --git a/products/experiments/backend/temporal/recalculation_workflow.py b/products/experiments/backend/temporal/recalculation_workflow.pyindex a9c7e8c1b2a2..172feed4dbfb 100644--- a/products/experiments/backend/temporal/recalculation_workflow.py+++ b/products/experiments/backend/temporal/recalculation_workflow.py@@ -3,7 +3,12 @@ from datetime import timedeltaimport temporalio.workflowfrom temporalio.common import Priority, RetryPolicy-from temporalio.exceptions import ApplicationError+from temporalio.exceptions import (+ ActivityError,+ ApplicationError,+ RetryState,+ TimeoutError as TemporalTimeoutError,+)from posthog.temporal.common.base import PostHogWorkflow@@ -11,22 +16,40 @@ with temporalio.workflow.unsafe.imports_passed_through():from products.experiments.backend.temporal.models import (MAX_METRIC_ATTEMPTS,METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS,+ METRIC_CALC_HEARTBEAT_TIMEOUT_SECONDS,+ METRIC_CALC_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS,+ METRIC_FAILURE_BACKSTOP_ACTIVITY_TIMEOUT_SECONDS,+ METRIC_FAILURE_BACKSTOP_MAX_ATTEMPTS,+ METRIC_FAILURE_BACKSTOP_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS,METRICS_RECALCULATION_WORKFLOW_NAME,RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS,+ RECALCULATION_PROGRESS_MAX_ATTEMPTS,RECALCULATION_RETRY_BACKOFF_COEFFICIENT,RECALCULATION_RETRY_INITIAL_INTERVAL_SECONDS,RECALCULATION_RETRY_MAX_INTERVAL_SECONDS,ExperimentMetricsRecalculationWorkflowInputs,+ ExperimentMetricToRecalculate,+ MetricOutOfTimeFailure,RecalculationProgressUpdate,)from products.experiments.backend.temporal.recalculation_activities import (calculate_experiment_metric_for_recalculation,discover_experiment_metrics,+ record_metric_out_of_time_failure,update_recalculation_progress,)from products.experiments.backend.temporal.recalculation_metrics import increment_workflow_finished+def _ended_by_temporal(error: ActivityError) -> bool:+ """True when Temporal ended the metric's retries from the outside, so no attempt persisted its outcome.++ A timeout cause is an attempt killed by start_to_close, heartbeat_timeout or schedule_to_close. A TIMEOUT retry+ state is an attempt that raised a retryable error when the schedule_to_close budget had no room for another.+ """+ return error.retry_state == RetryState.TIMEOUT or isinstance(error.cause, TemporalTimeoutError)++@temporalio.workflow.defn(name=METRICS_RECALCULATION_WORKFLOW_NAME)class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):"""Recalculate all metrics for an experiment on demand.@@ -76,7 +99,7 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):mark_started=True,),start_to_close_timeout=timedelta(seconds=RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS),- retry_policy=RetryPolicy(maximum_attempts=3),+ retry_policy=RetryPolicy(maximum_attempts=RECALCULATION_PROGRESS_MAX_ATTEMPTS),)try:await temporalio.workflow.execute_activity(@@ -87,7 +110,7 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):mark_completed=True,),start_to_close_timeout=timedelta(seconds=RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS),- retry_policy=RetryPolicy(maximum_attempts=3),+ retry_policy=RetryPolicy(maximum_attempts=RECALCULATION_PROGRESS_MAX_ATTEMPTS),)except Exception:# A zero-metric run genuinely completed; record that via the backstop rather than letting run()'s@@ -115,7 +138,7 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):mark_started=True,),start_to_close_timeout=timedelta(seconds=RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS),- retry_policy=RetryPolicy(maximum_attempts=3),+ retry_policy=RetryPolicy(maximum_attempts=RECALCULATION_PROGRESS_MAX_ATTEMPTS),)# The activity returns Optional[str] in general, but with mark_started=True it always returns the ISO# query_to string. Narrow with a real check (not assert, which is stripped under python -O) so calc@@ -146,6 +169,8 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):metric.metric_type,],start_to_close_timeout=timedelta(seconds=METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS),+ schedule_to_close_timeout=timedelta(seconds=METRIC_CALC_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS),+ heartbeat_timeout=timedelta(seconds=METRIC_CALC_HEARTBEAT_TIMEOUT_SECONDS),retry_policy=calc_retry_policy,# Round-robin dispatch across orgs under backlog; a no-op on namespaces without# fairness support.@@ -156,6 +181,14 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):return_exceptions=True,)+ out_of_time = [+ metric+ for metric, result in zip(metrics, results)+ if isinstance(result, ActivityError) and _ended_by_temporal(result)+ ]+ if out_of_time and temporalio.workflow.patched("recalc-persist-out-of-time-metrics-2026-10"):+ await self._record_out_of_time_failures(recalculation_id, out_of_time)+succeeded = sum(1 for result in results if not isinstance(result, BaseException) and result.success)failed = len(results) - succeededfinal_status = "failed" if failed > 0 else "completed"@@ -171,7 +204,7 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):failed_metrics=failed,),start_to_close_timeout=timedelta(seconds=RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS),- retry_policy=RetryPolicy(maximum_attempts=3),+ retry_policy=RetryPolicy(maximum_attempts=RECALCULATION_PROGRESS_MAX_ATTEMPTS),)except Exception:# The finalize write exhausted its retries. Record the real status/counts via the backstop so the@@ -192,6 +225,31 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):increment_workflow_finished(final_status)return {"total": len(metrics), "succeeded": succeeded, "failed": failed}+ async def _record_out_of_time_failures(+ self, recalculation_id: str, metrics: list[ExperimentMetricToRecalculate]+ ) -> None:+ # Best effort: a backstop failure must not stop the finish step, which still counts these metrics failed.+ await asyncio.gather(+ *[+ temporalio.workflow.execute_activity(+ record_metric_out_of_time_failure,+ MetricOutOfTimeFailure(+ recalculation_id=recalculation_id,+ experiment_id=metric.experiment_id,+ metric_uuid=metric.metric_uuid,+ metric_type=metric.metric_type,+ ),+ start_to_close_timeout=timedelta(seconds=METRIC_FAILURE_BACKSTOP_ACTIVITY_TIMEOUT_SECONDS),+ schedule_to_close_timeout=timedelta(+ seconds=METRIC_FAILURE_BACKSTOP_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS+ ),+ retry_policy=RetryPolicy(maximum_attempts=METRIC_FAILURE_BACKSTOP_MAX_ATTEMPTS),+ )+ for metric in metrics+ ],+ return_exceptions=True,+ )+async def _best_effort_mark_terminal(self, recalculation_id: str, *, status: str, succeeded: int | None = None, failed: int | None = None) -> bool:@@ -209,7 +267,7 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):failed_metrics=failed,),start_to_close_timeout=timedelta(seconds=RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS),- retry_policy=RetryPolicy(maximum_attempts=3),+ retry_policy=RetryPolicy(maximum_attempts=RECALCULATION_PROGRESS_MAX_ATTEMPTS),)return Trueexcept Exception:diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.pyindex a86bda426054..b2dc7dff858c 100644--- a/products/experiments/backend/temporal/test_recalculation_activities.py+++ b/products/experiments/backend/temporal/test_recalculation_activities.py@@ -1,4 +1,7 @@import asyncio+import threading+import dataclasses+from concurrent.futures import ThreadPoolExecutorfrom contextlib import contextmanagerfrom datetime import datetime, timedeltafrom types import SimpleNamespace@@ -14,6 +17,7 @@ from clickhouse_driver.errors import ServerExceptionfrom parameterized import parameterizedfrom rest_framework.exceptions import ValidationErrorfrom temporalio.exceptions import ApplicationError+from temporalio.testing import ActivityEnvironmentfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import Feature, Product, get_query_tags@@ -33,6 +37,7 @@ from products.experiments.backend.temporal.models import (CAPACITY_MAX_METRIC_ATTEMPTS,MAX_METRIC_ATTEMPTS,TIMEOUT_MAX_METRIC_ATTEMPTS,+ MetricOutOfTimeFailure,MetricRecalculationResult,RecalculationProgressUpdate,)@@ -41,6 +46,7 @@ from products.experiments.backend.temporal.recalculation_logic import (_calculate_experiment_metric_for_recalculation_sync,_cancel_metric_query_sync,_discover_experiment_metrics_sync,+ _record_metric_out_of_time_failure_sync,_update_recalculation_progress_sync,)from products.experiments.stats.shared.statistics import StatisticError@@ -50,6 +56,7 @@ _discover_raw = _discover_experiment_metrics_sync.func # type: ignore[attr-defi_update_raw = _update_recalculation_progress_sync.func # type: ignore[attr-defined]_calculate_raw = _calculate_experiment_metric_for_recalculation_sync.func # type: ignore[attr-defined]_cancel_raw = _cancel_metric_query_sync.func # type: ignore[attr-defined]+_record_out_of_time_raw = _record_metric_out_of_time_failure_sync.func # type: ignore[attr-defined]def _calculation_key(experiment: Experiment, metric_uuid: str) -> str:@@ -68,6 +75,11 @@ def _update(update: RecalculationProgressUpdate):return _update_raw(update)+def _record_out_of_time(failure: MetricOutOfTimeFailure) -> None:+ with patch("products.experiments.backend.temporal.recalculation_logic.close_old_connections"):+ _record_out_of_time_raw(failure)++def _calculate(experiment_id: int,metric_uuid: str,@@ -873,6 +885,78 @@ class TestCalculateActivity(BaseTest):assert recalc.metric_retries == {}assert "m1" in recalc.metric_errors+ @parameterized.expand(+ [+ ("not_persisted_by_any_attempt", RuntimeError("transient blip"), False),+ ("persisted_by_final_attempt", RuntimeError("transient blip"), True),+ # The last attempt wrote its result but died before it reported success.+ ("completed_by_last_attempt", None, False),+ ]+ )+ def test_out_of_time_failure_persists_once(+ self, name: str, last_attempt_error: Exception | None, final_attempt_persisted: bool+ ):+ exp = self._experiment(flag_key=f"calc-out-of-time-{name}", metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])+ with patch("products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner") as mock_runner:+ if last_attempt_error is None:+ mock_runner.return_value.run.return_value.model_dump.return_value = {}+ _calculate(exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=False, attempt=2)+ else:+ mock_runner.return_value.run.side_effect = last_attempt_error+ with pytest.raises(RuntimeError):+ _calculate(+ exp.id, "m1", str(recalc.id), _QUERY_TO, is_final_attempt=final_attempt_persisted, attempt=2+ )+ recalc.refresh_from_db()+ errors_before = dict(recalc.metric_errors)++ with _record_captures() as captured:+ _record_out_of_time(+ MetricOutOfTimeFailure(+ recalculation_id=str(recalc.id), experiment_id=exp.id, metric_uuid="m1", metric_type="primary"+ )+ )++ recalc.refresh_from_db()+ row = ExperimentMetricResult.objects.get(experiment=exp, metric_uuid="m1")+ assert row.fingerprint == _recalc_fingerprint(_calculation_key(exp, "m1"))+ assert recalc.metric_retries == {}+ if last_attempt_error is None:+ assert row.status == ExperimentMetricResult.Status.COMPLETED+ assert recalc.metric_errors == {}+ assert captured == []+ elif final_attempt_persisted:+ assert row.status == ExperimentMetricResult.Status.FAILED+ assert recalc.metric_errors == errors_before+ assert captured == []+ else:+ assert row.status == ExperimentMetricResult.Status.FAILED+ assert recalc.metric_errors["m1"]["error_type"] == "timeout"+ assert recalc.metric_errors["m1"]["retriable"] is True+ assert [c["event"] for c in captured] == ["experiment metric error"]+ assert captured[0]["properties"]["error_type"] == "timeout"++ def test_late_result_after_out_of_time_failure_replaces_the_timeout(self):+ exp = self._experiment(flag_key="calc-out-of-time-late-result", metrics=[_mean_metric("m1")])+ recalc = self._recalc(exp, metric_uuids=["m1"])+ _record_out_of_time(+ MetricOutOfTimeFailure(+ recalculation_id=str(recalc.id), experiment_id=exp.id, metric_uuid="m1", metric_type="primary"+ )+ )++ 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, is_final_attempt=False, attempt=3)++ recalc.refresh_from_db()+ assert result.success is True+ assert ExperimentMetricResult.objects.get(experiment=exp, metric_uuid="m1").status == (+ ExperimentMetricResult.Status.COMPLETED+ )+ assert recalc.metric_errors == {}+@parameterized.expand([("org_quota", ConcurrencyLimitExceeded("org quota saturated")),@@ -1298,6 +1382,10 @@ class TestMissingRecalcRow:assert exc_info.value.non_retryable is True+def _start_activity(env: ActivityEnvironment) -> asyncio.Task[MetricRecalculationResult]:+ return asyncio.create_task(env.run(calculate_experiment_metric_for_recalculation, 1, "m1", "r1", _QUERY_TO))++class TestCalculateActivityCancellation:@contextmanagerdef _patched_boundaries(self, body, cancel_query):@@ -1313,7 +1401,6 @@ class TestCalculateActivityCancellation:"products.experiments.backend.temporal.recalculation_activities._CANCEL_KILL_RETRY_INTERVAL_SECONDS",0.001,),- patch("temporalio.activity.info", return_value=SimpleNamespace(attempt=1)),):yield@@ -1334,7 +1421,7 @@ class TestCalculateActivityCancellation:return MetricRecalculationResult(metric_uuid="m1", success=True)with self._patched_boundaries(_slow_body, AsyncMock()):- task = asyncio.create_task(calculate_experiment_metric_for_recalculation(1, "m1", "r1", _QUERY_TO))+ task = _start_activity(ActivityEnvironment())await started.wait()try:for cancellation in range(cancellations):@@ -1367,7 +1454,7 @@ class TestCalculateActivityCancellation:"products.experiments.backend.temporal.recalculation_activities.METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS", 0),):- task = asyncio.create_task(calculate_experiment_metric_for_recalculation(1, "m1", "r1", _QUERY_TO))+ task = _start_activity(ActivityEnvironment())await started.wait()try:task.cancel("original cancellation")@@ -1408,7 +1495,7 @@ class TestCalculateActivityCancellation:"products.experiments.backend.temporal.recalculation_activities.METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS", 1),):- task = asyncio.create_task(calculate_experiment_metric_for_recalculation(1, "m1", "r1", _QUERY_TO))+ task = _start_activity(ActivityEnvironment())await started.wait()task.cancel()@@ -1433,6 +1520,56 @@ class TestCalculateActivityCancellation:assert observed["cancel_calls"] == 2assert observed["body_finished"] is True+ async def test_query_kill_runs_while_calculations_fill_the_default_executor(self) -> None:+ calculations_running = threading.Event()+ killed: list[str] = []+ busy_default_executor = ThreadPoolExecutor(max_workers=1)+ asyncio.get_running_loop().set_default_executor(busy_default_executor)+ busy_default_executor.submit(calculations_running.wait)+ try:+ with (+ patch("products.experiments.backend.temporal.recalculation_logic.close_old_connections"),+ patch(+ "products.experiments.backend.temporal.recalculation_logic._get_recalc_state",+ return_value=SimpleNamespace(team_id=1),+ ),+ patch(+ "products.experiments.backend.temporal.recalculation_logic.cancel_query_on_cluster",+ lambda team_id, query_id: killed.append(query_id),+ ),+ ):+ await asyncio.wait_for(_cancel_metric_query_sync("r1", "m1", 1), timeout=5)+ finally:+ calculations_running.set()++ assert killed == ["experiment_metric_recalc_r1_m1_attempt01"]++ async def test_heartbeats_while_the_body_runs_and_stops_after(self) -> None:+ # Temporal delivers a cancellation only in a heartbeat response, so without heartbeats the drain above+ # never runs for a workflow cancel or a server-side timeout.+ heartbeats = 0+ two_heartbeats = asyncio.Event()++ def _on_heartbeat(*details: object) -> None:+ nonlocal heartbeats+ heartbeats += 1+ if heartbeats >= 2:+ two_heartbeats.set()++ async def _body(*args: object, **kwargs: object) -> MetricRecalculationResult:+ await two_heartbeats.wait()+ return MetricRecalculationResult(metric_uuid="m1", success=True)++ env = ActivityEnvironment()+ env.info = dataclasses.replace(env.info, heartbeat_timeout=timedelta(seconds=0.2))+ env.on_heartbeat = _on_heartbeat+ tasks_before = asyncio.all_tasks()+ with self._patched_boundaries(_body, AsyncMock()):+ result = await asyncio.wait_for(_start_activity(env), timeout=5)++ assert result.success is True+ assert asyncio.all_tasks() - tasks_before == set()+@contextmanagerdef _record_captures():diff --git a/products/experiments/backend/temporal/test_recalculation_workflow.py b/products/experiments/backend/temporal/test_recalculation_workflow.pyindex ac1db380a77e..bb3fa28ae093 100644--- a/products/experiments/backend/temporal/test_recalculation_workflow.py+++ b/products/experiments/backend/temporal/test_recalculation_workflow.py@@ -1,4 +1,8 @@import uuid+import asyncio+from collections.abc import Callable+from contextlib import ExitStack+from datetime import timedeltaimport pytestfrom unittest.mock import patch@@ -11,10 +15,17 @@ from temporalio.exceptions import ApplicationErrorfrom temporalio.testing import WorkflowEnvironmentfrom temporalio.worker import Worker+from products.experiments.backend.recalculation import _STALE_RECALC_THRESHOLDfrom products.experiments.backend.temporal.models import (MAX_METRIC_ATTEMPTS,+ METRIC_CALC_HEARTBEAT_TIMEOUT_SECONDS,+ METRIC_CALC_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS,+ METRIC_FAILURE_BACKSTOP_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS,+ RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS,+ RECALCULATION_PROGRESS_MAX_ATTEMPTS,ExperimentMetricsRecalculationWorkflowInputs,ExperimentMetricToRecalculate,+ MetricOutOfTimeFailure,MetricRecalculationResult,RecalculationProgressUpdate,)@@ -22,6 +33,8 @@ from products.experiments.backend.temporal.recalculation_activities import calcufrom products.experiments.backend.temporal.recalculation_workflow import ExperimentMetricsRecalculationWorkflow_START_QUERY_TO = "2026-05-29T12:00:00+00:00"+_WORKFLOW_MODULE = "products.experiments.backend.temporal.recalculation_workflow"+_ACTIVITIES_MODULE = "products.experiments.backend.temporal.recalculation_activities"def _metric(metric_uuid: str) -> ExperimentMetricToRecalculate:@@ -62,6 +75,31 @@ def _make_mock_activities(return activities, progress_updates, calculate_calls+def _mock_out_of_time_backstop() -> tuple[Callable, list[MetricOutOfTimeFailure]]:+ recorded: list[MetricOutOfTimeFailure] = []++ @activity.defn(name="record_metric_out_of_time_failure")+ async def mock_backstop(failure: MetricOutOfTimeFailure) -> None:+ recorded.append(failure)++ return mock_backstop, recorded+++def _worst_case_seconds(timeout_seconds: float, max_attempts: int) -> float:+ # Temporal's default RetryPolicy waits 1 s before the first retry and doubles the wait after each one.+ return timeout_seconds * max_attempts + sum(2**retry for retry in range(max_attempts - 1))+++def test_in_progress_phase_ends_before_the_staleness_ttl():+ worst_case = (+ METRIC_CALC_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS+ + METRIC_FAILURE_BACKSTOP_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS+ + _worst_case_seconds(RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS, RECALCULATION_PROGRESS_MAX_ATTEMPTS)+ )++ assert worst_case < _STALE_RECALC_THRESHOLD.total_seconds()++async def _run_workflow(activities) -> dict:task_queue = str(uuid.uuid4())async with await WorkflowEnvironment.start_time_skipping() as env:@@ -188,17 +226,132 @@ class TestExperimentMetricsRecalculationWorkflow:recorded_flags.append(is_final_attempt)raise RuntimeError("always fails")+ mock_backstop, backstop_calls = _mock_out_of_time_backstop()+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]+ [mock_discover, mock_update_progress, calculate_experiment_metric_for_recalculation, mock_backstop])assert result == {"total": 1, "succeeded": 0, "failed": 1}# Only the final attempt is flagged final; earlier attempts must not be, or they'd persist early.assert recorded_flags == [False] * (MAX_METRIC_ATTEMPTS - 1) + [True]+ # The final attempt persisted the failure itself, so the backstop has nothing to do.+ assert backstop_calls == []++ async def test_calc_activity_has_a_total_budget_and_a_heartbeat_timeout(self):+ activities, _progress, _calls = _make_mock_activities(metrics=[_metric("m1")])+ timeouts: list[tuple[timedelta | None, timedelta | None]] = []++ @activity.defn(name="calculate_experiment_metric_for_recalculation")+ async def mock_calculate(+ experiment_id: int,+ metric_uuid: str,+ recalculation_id: str,+ query_to: str,+ metric_type: str = "primary",+ ) -> MetricRecalculationResult:+ info = activity.info()+ timeouts.append((info.schedule_to_close_timeout, info.heartbeat_timeout))+ return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)++ await _run_workflow([*activities[:2], mock_calculate])++ assert timeouts == [+ (+ timedelta(seconds=METRIC_CALC_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS),+ timedelta(seconds=METRIC_CALC_HEARTBEAT_TIMEOUT_SECONDS),+ )+ ]++ @parameterized.expand(+ [+ # Retryable errors until the total budget leaves no room for the next attempt.+ ("budget_ends_the_retries", False, {"METRIC_CALC_SCHEDULE_TO_CLOSE_TIMEOUT_SECONDS": 20}),+ # The only attempt hangs until Temporal ends it from the outside.+ (+ "last_attempt_killed_by_start_to_close",+ True,+ {"METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS": 1, "MAX_METRIC_ATTEMPTS": 1},+ ),+ ]+ )+ async def test_metric_ended_by_temporal_runs_the_failure_backstop(+ self, name: str, hangs: bool, workflow_overrides: dict[str, int]+ ):+ activities, _progress, _calls = _make_mock_activities(metrics=[_metric("m1"), _metric("m2")])+ mock_backstop, backstop_calls = _mock_out_of_time_backstop()+ attempts = 0++ @activity.defn(name="calculate_experiment_metric_for_recalculation")+ async def mock_calculate(+ experiment_id: int,+ metric_uuid: str,+ recalculation_id: str,+ query_to: str,+ metric_type: str = "primary",+ ) -> MetricRecalculationResult:+ nonlocal attempts+ if metric_uuid == "m2":+ return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)+ attempts += 1+ if hangs:+ await asyncio.sleep(3600)+ raise RuntimeError("transient blip")++ with ExitStack() as stack:+ for name, value in workflow_overrides.items():+ stack.enter_context(patch(f"{_WORKFLOW_MODULE}.{name}", value))+ result = await _run_workflow([*activities[:2], mock_calculate, mock_backstop])++ assert result == {"total": 2, "succeeded": 1, "failed": 1}+ assert attempts < MAX_METRIC_ATTEMPTS+ assert [(f.experiment_id, f.metric_uuid, f.metric_type) for f in backstop_calls] == [(1, "m1", "primary")]++ async def test_workflow_cancel_reaches_the_running_calc_and_kills_its_query(self):+ activities, _progress, _calls = _make_mock_activities(metrics=[_metric("m1")])+ body_started = asyncio.Event()+ query_killed = asyncio.Event()++ async def slow_sync(*args: object) -> MetricRecalculationResult:+ body_started.set()+ await query_killed.wait()+ return MetricRecalculationResult(metric_uuid="m1", success=True)++ async def fake_kill(recalculation_id: str, metric_uuid: str, attempt: int) -> None:+ query_killed.set()++ task_queue = str(uuid.uuid4())+ with (+ patch(f"{_ACTIVITIES_MODULE}._calculate_experiment_metric_for_recalculation_sync", new=slow_sync),+ patch(f"{_ACTIVITIES_MODULE}._cancel_metric_query_sync", new=fake_kill),+ patch(f"{_WORKFLOW_MODULE}.METRIC_CALC_HEARTBEAT_TIMEOUT_SECONDS", 8),+ ):+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[ExperimentMetricsRecalculationWorkflow],+ activities=[*activities[:2], calculate_experiment_metric_for_recalculation],+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ handle = await env.client.start_workflow(+ ExperimentMetricsRecalculationWorkflow.run,+ ExperimentMetricsRecalculationWorkflowInputs(recalculation_id=str(uuid.uuid4())),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )+ await asyncio.wait_for(body_started.wait(), timeout=10)+ await handle.cancel()++ # Shorter than the heartbeat timeout, so a missed heartbeat cannot end the attempt first:+ # only a heartbeat response can deliver the cancel in time.+ await asyncio.wait_for(query_killed.wait(), timeout=6)+ with pytest.raises(WorkflowFailureError):+ await handle.result()@parameterized.expand([diff --git a/products/experiments/backend/temporal/test_registration.py b/products/experiments/backend/temporal/test_registration.pyindex cd8b741c763b..fbc09153e9fa 100644--- a/products/experiments/backend/temporal/test_registration.py+++ b/products/experiments/backend/temporal/test_registration.py@@ -21,6 +21,7 @@ def test_activities_registered():"discover_experiment_metrics","calculate_experiment_metric_for_recalculation","update_recalculation_progress",+ "record_metric_out_of_time_failure","sample_experiment_canary_targets","run_experiment_metric_canary","report_experiment_canary_results",