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): workflow owns terminal state (#75160)

Rodrigo Ilorob8c7a9b5d4c8
diff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.py
index 887b1d856a09..8e4f3f2c5c3f 100644
--- a/products/experiments/backend/temporal/models.py
+++ b/products/experiments/backend/temporal/models.py
@@ -44,6 +44,8 @@ METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS = 300
# also stops the orphaned query from burning ClickHouse for the full default 600s.
METRIC_CALC_MAX_EXECUTION_TIME_SECONDS = 270
+RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS = 90
+
@dataclasses.dataclass
class ExperimentMetricsRecalculationWorkflowInputs:
diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.py
index cc6be028a2d7..d6d845d57994 100644
--- a/products/experiments/backend/temporal/recalculation_logic.py
+++ b/products/experiments/backend/temporal/recalculation_logic.py
@@ -26,7 +26,7 @@ from posthog.exceptions import ClickHouseAtCapacity
from posthog.exceptions_capture import capture_exception
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models.scoping import team_scope
-from posthog.sync import database_sync_to_async
+from posthog.sync import database_sync_to_async_pool
from products.experiments.backend.hogql_queries.base_query_utils import experiment_window_end
from products.experiments.backend.hogql_queries.error_handling import (
@@ -146,7 +146,7 @@ def discover_experiment_metrics(experiment: Experiment) -> list[ExperimentMetric
return metrics_to_recalculate
-@database_sync_to_async
+@database_sync_to_async_pool
def _discover_experiment_metrics_sync(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:
close_old_connections()
@@ -173,7 +173,7 @@ def _discover_experiment_metrics_sync(recalculation_id: str) -> list[ExperimentM
# ---------------------------------------------------------------------------
-@database_sync_to_async
+@database_sync_to_async_pool
def _update_recalculation_progress_sync(update: RecalculationProgressUpdate) -> str | None:
close_old_connections()
@@ -525,7 +525,7 @@ def _capture_experiment_metric_event(
# ---------------------------------------------------------------------------
-@database_sync_to_async
+@database_sync_to_async_pool
def _calculate_experiment_metric_for_recalculation_sync(
experiment_id: int,
metric_uuid: str,
diff --git a/products/experiments/backend/temporal/recalculation_workflow.py b/products/experiments/backend/temporal/recalculation_workflow.py
index 1856217fbe76..a45a371c4163 100644
--- a/products/experiments/backend/temporal/recalculation_workflow.py
+++ b/products/experiments/backend/temporal/recalculation_workflow.py
@@ -11,6 +11,7 @@ with temporalio.workflow.unsafe.imports_passed_through():
from products.experiments.backend.temporal.models import (
MAX_METRIC_ATTEMPTS,
METRIC_CALC_ACTIVITY_TIMEOUT_SECONDS,
+ RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS,
RECALCULATION_RETRY_BACKOFF_COEFFICIENT,
RECALCULATION_RETRY_INITIAL_INTERVAL_SECONDS,
RECALCULATION_RETRY_MAX_INTERVAL_SECONDS,
@@ -44,6 +45,14 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):
@temporalio.workflow.run
async def run(self, inputs: ExperimentMetricsRecalculationWorkflowInputs) -> dict:
+ try:
+ return await self._run_recalculation(inputs)
+ except Exception:
+ if temporalio.workflow.patched("recalc-terminal-fail-on-error-2026-07"):
+ await self._best_effort_mark_terminal(inputs.recalculation_id, status="failed")
+ raise
+
+ async def _run_recalculation(self, inputs: ExperimentMetricsRecalculationWorkflowInputs) -> dict:
recalculation_id = inputs.recalculation_id
metrics = await temporalio.workflow.execute_activity(
@@ -65,19 +74,30 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):
metric_uuids=[],
mark_started=True,
),
- start_to_close_timeout=timedelta(seconds=30),
- retry_policy=RetryPolicy(maximum_attempts=3),
- )
- await temporalio.workflow.execute_activity(
- update_recalculation_progress,
- RecalculationProgressUpdate(
- recalculation_id=recalculation_id,
- status="completed",
- mark_completed=True,
- ),
- start_to_close_timeout=timedelta(seconds=30),
+ start_to_close_timeout=timedelta(seconds=RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS),
retry_policy=RetryPolicy(maximum_attempts=3),
)
+ try:
+ await temporalio.workflow.execute_activity(
+ update_recalculation_progress,
+ RecalculationProgressUpdate(
+ recalculation_id=recalculation_id,
+ status="completed",
+ mark_completed=True,
+ ),
+ start_to_close_timeout=timedelta(seconds=RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ except Exception:
+ # A zero-metric run genuinely completed; record that via the backstop rather than letting run()'s
+ # except mislabel it failed. If the backstop also fails (or the patch is off), re-raise so the
+ # workflow fails instead of reporting success on a non-terminal row.
+ recorded = temporalio.workflow.patched("recalc-terminal-fail-on-error-2026-07") and (
+ await self._best_effort_mark_terminal(recalculation_id, status="completed", succeeded=0, failed=0)
+ )
+ if not recorded:
+ raise
+
temporalio.workflow.logger.info(f"recalc {recalculation_id} had no metrics; completing immediately")
increment_workflow_finished("completed")
return {"total": 0, "succeeded": 0, "failed": 0}
@@ -93,7 +113,7 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):
metric_uuids=[m.metric_uuid for m in metrics],
mark_started=True,
),
- start_to_close_timeout=timedelta(seconds=30),
+ start_to_close_timeout=timedelta(seconds=RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS),
retry_policy=RetryPolicy(maximum_attempts=3),
)
# The activity returns Optional[str] in general, but with mark_started=True it always returns the ISO
@@ -134,30 +154,65 @@ class ExperimentMetricsRecalculationWorkflow(PostHogWorkflow):
],
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-only
- # check then can't mistake a 9-of-10-failed run for a healthy one.
final_status = "failed" if failed > 0 else "completed"
- await temporalio.workflow.execute_activity(
- update_recalculation_progress,
- RecalculationProgressUpdate(
- recalculation_id=recalculation_id,
- status=final_status,
- mark_completed=True,
- succeeded_metrics=succeeded,
- failed_metrics=failed,
- ),
- start_to_close_timeout=timedelta(seconds=30),
- retry_policy=RetryPolicy(maximum_attempts=3),
- )
+
+ try:
+ await temporalio.workflow.execute_activity(
+ update_recalculation_progress,
+ RecalculationProgressUpdate(
+ recalculation_id=recalculation_id,
+ status=final_status,
+ mark_completed=True,
+ succeeded_metrics=succeeded,
+ failed_metrics=failed,
+ ),
+ start_to_close_timeout=timedelta(seconds=RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ except Exception:
+ # The finalize write exhausted its retries. Record the real status/counts via the backstop so the
+ # row still goes terminal. If the backstop also fails (or the patch is disabled for a replaying
+ # older execution), re-raise: the workflow must fail rather than report success on a non-terminal
+ # row, and the interceptor + staleness TTL take over as before.
+ recorded = temporalio.workflow.patched("recalc-terminal-fail-on-error-2026-07") and (
+ await self._best_effort_mark_terminal(
+ recalculation_id, status=final_status, succeeded=succeeded, failed=failed
+ )
+ )
+ if not recorded:
+ raise
temporalio.workflow.logger.info(
f"recalc {recalculation_id} finished: {succeeded} succeeded, {failed} failed (status={final_status})"
)
increment_workflow_finished(final_status)
return {"total": len(metrics), "succeeded": succeeded, "failed": failed}
+
+ async def _best_effort_mark_terminal(
+ self, recalculation_id: str, *, status: str, succeeded: int | None = None, failed: int | None = None
+ ) -> bool:
+ # Returns True if the terminal write landed, False if it too exhausted its retries. Callers that need
+ # the row to be terminal (the finalize-failure path) re-raise on False so the run still fails and the
+ # staleness TTL reaps it; the pre-finalize caller re-raises the original exception regardless.
+ try:
+ await temporalio.workflow.execute_activity(
+ update_recalculation_progress,
+ RecalculationProgressUpdate(
+ recalculation_id=recalculation_id,
+ status=status,
+ mark_completed=True,
+ succeeded_metrics=succeeded,
+ failed_metrics=failed,
+ ),
+ start_to_close_timeout=timedelta(seconds=RECALCULATION_PROGRESS_ACTIVITY_TIMEOUT_SECONDS),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ return True
+ except Exception:
+ temporalio.workflow.logger.exception(
+ f"recalc {recalculation_id} failed to record terminal status; staleness TTL will reap it"
+ )
+ return False
diff --git a/products/experiments/backend/temporal/test_recalculation_workflow.py b/products/experiments/backend/temporal/test_recalculation_workflow.py
index 44e45a3d85e8..ac1db380a77e 100644
--- a/products/experiments/backend/temporal/test_recalculation_workflow.py
+++ b/products/experiments/backend/temporal/test_recalculation_workflow.py
@@ -295,3 +295,109 @@ class TestExperimentMetricsRecalculationWorkflow:
assert isinstance(cause, ApplicationError)
assert cause.non_retryable is True
assert "expected str" in str(cause)
+
+ async def test_failure_before_finalize_records_terminal_failed_status(self):
+ # A failure after the workflow starts but before it finalizes (here: discovery raises) must still leave
+ # the job row terminal. The workflow catches the error, writes status=failed via the progress activity,
+ # then re-raises so Temporal still sees the run as failed. Without this backstop the row stays
+ # non-terminal and the UI polls it until the 30-min staleness TTL reaps it (the orphan we are guarding).
+ progress_updates: list[RecalculationProgressUpdate] = []
+
+ @activity.defn(name="discover_experiment_metrics")
+ async def failing_discover(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:
+ raise ApplicationError("discovery boom", non_retryable=True)
+
+ @activity.defn(name="update_recalculation_progress")
+ async def mock_update_progress(update: RecalculationProgressUpdate) -> str | None:
+ progress_updates.append(update)
+ return _START_QUERY_TO if update.mark_started else 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:
+ return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)
+
+ with pytest.raises(WorkflowFailureError):
+ await _run_workflow([failing_discover, mock_update_progress, mock_calculate])
+
+ # Exactly the terminal-fail write: the backstop marks the run completed with status=failed even though
+ # discovery never produced metrics or a mark_started call.
+ assert len(progress_updates) == 1
+ assert progress_updates[0].mark_completed is True
+ assert progress_updates[0].mark_started is False
+ assert progress_updates[0].status == "failed"
+
+ async def test_finalize_write_failure_records_real_status_not_failed(self):
+ # A run where every metric succeeded, but the finalize write (mark_completed, status=completed) exhausts
+ # its retries. The workflow must record the REAL status via the finalize-failure backstop, not let
+ # run()'s except overwrite it with a spurious "failed" (which would mislabel a healthy run).
+ progress_updates: list[RecalculationProgressUpdate] = []
+ finalize_attempts = {"count": 0}
+
+ @activity.defn(name="discover_experiment_metrics")
+ async def mock_discover(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:
+ return [_metric("m1")]
+
+ @activity.defn(name="update_recalculation_progress")
+ async def mock_update_progress(update: RecalculationProgressUpdate) -> str | None:
+ # Fail the finish write (mark_completed) hard on its first invocation to simulate the finalize
+ # activity exhausting its retries; the workflow's finalize-failure path then re-writes via the
+ # backstop, which we let succeed.
+ if update.mark_completed and finalize_attempts["count"] == 0:
+ finalize_attempts["count"] += 1
+ raise ApplicationError("finalize boom", non_retryable=True)
+ progress_updates.append(update)
+ return _START_QUERY_TO if update.mark_started else 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:
+ return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)
+
+ result = await _run_workflow([mock_discover, mock_update_progress, mock_calculate])
+
+ # The run is recorded completed with the real counts, NOT failed.
+ assert result == {"total": 1, "succeeded": 1, "failed": 0}
+ terminal = progress_updates[-1]
+ assert terminal.mark_completed is True
+ assert terminal.status == "completed"
+ assert terminal.succeeded_metrics == 1
+ assert terminal.failed_metrics == 0
+
+ async def test_finalize_and_backstop_both_failing_fails_the_workflow(self):
+ # The finalize write AND the backstop write both exhaust their retries (every mark_completed throws).
+ # The workflow must FAIL, not swallow the error and report success on a non-terminal row; the row's
+ # terminality then falls to the interceptor + staleness TTL, as it did before the terminal-state wrapper.
+ @activity.defn(name="discover_experiment_metrics")
+ async def mock_discover(recalculation_id: str) -> list[ExperimentMetricToRecalculate]:
+ return [_metric("m1")]
+
+ @activity.defn(name="update_recalculation_progress")
+ async def mock_update_progress(update: RecalculationProgressUpdate) -> str | None:
+ # Every terminal write fails (finalize and its backstop), only mark_started succeeds.
+ if update.mark_completed:
+ raise ApplicationError("terminal write down", non_retryable=True)
+ return _START_QUERY_TO if update.mark_started else 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:
+ return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)
+
+ with pytest.raises(WorkflowFailureError):
+ await _run_workflow([mock_discover, mock_update_progress, mock_calculate])