: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): harden recalculation terminal-state writes (#98298)
Juraj Majerika0da044f1bae
diff --git a/products/experiments/backend/admin/recalculation_admin.py b/products/experiments/backend/admin/recalculation_admin.pyindex 698bca47e7a3..c78a5a844ba1 100644--- a/products/experiments/backend/admin/recalculation_admin.py+++ b/products/experiments/backend/admin/recalculation_admin.py@@ -137,6 +137,12 @@ class ExperimentMetricsRecalculationAdmin(admin.ModelAdmin):if request.method != "POST":return HttpResponseRedirect(change_url)+ # A run with no query_to never started, so "completed" would be a lie the API then serves: the+ # latest-run endpoint would return it with zero results and stop falling back to timeseries data.+ if status == ExperimentMetricsRecalculation.Status.COMPLETED and obj.query_to is None:+ messages.error(request, "This recalculation never started, so it cannot be completed; mark it failed.")+ return HttpResponseRedirect(change_url)+# First-write-wins guard: only stamp a terminal status on a run that hasn't already finalized, so this# never clobbers a run the workflow completed a moment earlier. Mirrors the activity's completed_at guard.# for_team scopes the fail-closed write to the row's own team (admin runs outside request/team scope).diff --git a/products/experiments/backend/admin/recalculation_panel.py b/products/experiments/backend/admin/recalculation_panel.pyindex 4d902bc2f687..7dfdceffb959 100644--- a/products/experiments/backend/admin/recalculation_panel.py+++ b/products/experiments/backend/admin/recalculation_panel.py@@ -163,9 +163,15 @@ def start_recalculation_for_experiment(try:start_metrics_recalculation_workflow(recalculation_id, str(experiment.team.organization_id))except Exception as e:- ExperimentMetricsRecalculation.objects.for_team(experiment.team_id).filter(id=recalculation_id).update(- status=ExperimentMetricsRecalculation.Status.FAILED- )+ # start_workflow can raise after the server accepted the start, so only roll back a row that is+ # still PENDING with no query_to; a run past mark_started proceeds untouched, and one caught in+ # the discovery window is terminated cleanly by the mark_started/mark_completed guards+ # (mirrors the API rollback).+ ExperimentMetricsRecalculation.objects.for_team(experiment.team_id).filter(+ id=recalculation_id,+ status=ExperimentMetricsRecalculation.Status.PENDING,+ query_to__isnull=True,+ ).update(status=ExperimentMetricsRecalculation.Status.FAILED)messages.error(request, f"Created the row but failed to start the workflow (marked failed): {e}")return HttpResponseRedirect(fallback_url)diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex 2a61006cfcb5..f8a9a31891f5 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -1262,9 +1262,18 @@ class EnterpriseExperimentsViewSet(except Exception:# team-scoped filter: defense in depth so the rollback can never reach across teams even if# recalculation_id were ever sourced from somewhere less trusted than the row we just created.- ExperimentMetricsRecalculation.objects.filter(team=self.team, id=recalculation_id).update(- status=ExperimentMetricsRecalculation.Status.FAILED- )+ # start_workflow can raise after the server accepted the start (e.g. RPC deadline on the+ # response leg), so only roll back a row that is still PENDING with no query_to. A row past+ # mark_started belongs to its running workflow and proceeds untouched. In the narrow window+ # where only discovery ran, the rollback wins deliberately: the mark_started and+ # mark_completed guards then terminate that orphan cleanly, and the client's retry of the+ # failed POST starts the replacement.+ ExperimentMetricsRecalculation.objects.filter(+ team=self.team,+ id=recalculation_id,+ status=ExperimentMetricsRecalculation.Status.PENDING,+ query_to__isnull=True,+ ).update(status=ExperimentMetricsRecalculation.Status.FAILED)raisereturn Response(diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex bad3deac72f8..5154cbbca87a 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -279,9 +279,19 @@ def _update_recalculation_progress_sync(update: RecalculationProgressUpdate) ->return existing_query_to.isoformat() if existing_query_to is not None else None# Finish: same first-write-wins guard so a retried mark_completed activity doesn't re-stamp the- # completion timestamp (and, by symmetry with mark_started, doesn't reopen a closed run).+ # completion timestamp (and, by symmetry with mark_started, doesn't reopen a closed run). The status+ # filter makes an out-of-band terminal write (staleness force-fail, admin action) authoritative even+ # when its completed_at is still NULL: the force-fail leaves completed_at unset and its workflow+ # cancel is best-effort, so without the filter a surviving workflow would overwrite the tombstone.won = (- ExperimentMetricsRecalculation.objects.filter(id=update.recalculation_id, completed_at__isnull=True).update(+ ExperimentMetricsRecalculation.objects.filter(+ id=update.recalculation_id,+ completed_at__isnull=True,+ status__in=[+ ExperimentMetricsRecalculation.Status.PENDING,+ ExperimentMetricsRecalculation.Status.IN_PROGRESS,+ ],+ ).update(completed_at=timezone.now(),status=update.status or ExperimentMetricsRecalculation.Status.COMPLETED,# The run is terminal, so no retry can be pending. Sweeps entries orphaned by a hard-killed@@ -294,6 +304,20 @@ def _update_recalculation_progress_sync(update: RecalculationProgressUpdate) -># mark_completed doesn't double-count.if won:_capture_results_refresh_completed(update)+ else:+ existing_finish_state = (+ ExperimentMetricsRecalculation.objects.filter(id=update.recalculation_id)+ .values_list("status", "completed_at")+ .first()+ )+ # completed_at set means a retried activity lost the normal dedupe race — silence. completed_at+ # NULL means the run was force-failed out-of-band while this workflow was still executing.+ if existing_finish_state is not None and existing_finish_state[1] is None:+ logger.warning(+ "mark_completed_rejected_run_terminal",+ recalculation_id=update.recalculation_id,+ status=existing_finish_state[0],+ )return Nonediff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.pyindex 9142a84e9dae..0d221bd9fb15 100644--- a/products/experiments/backend/temporal/test_recalculation_activities.py+++ b/products/experiments/backend/temporal/test_recalculation_activities.py@@ -269,6 +269,42 @@ class TestRecalculationActivities(BaseTest):# fails the run non-retryably instead of proceeding to calc activities on a dead run.assert returned is None+ @parameterized.expand(+ [+ # The workflow's finish write can carry either terminal status; neither may touch a tombstone.+ ("workflow_finishes_completed", "completed"),+ ("backstop_stamps_failed", "failed"),+ ]+ )+ @freeze_time("2026-06-23T05:00:00Z")+ def test_mark_completed_does_not_revive_a_force_failed_run(self, name: str, finish_status: str):+ # The staleness sweep force-fails a run with completed_at left NULL, and its workflow cancel is+ # best-effort. If the workflow survives to its finish write, the tombstone must win: without the+ # status guard the write matches on completed_at IS NULL and either flips the tombstone to+ # COMPLETED (becoming the "latest terminal run" the API serves) or stamps completed_at, turning+ # an invisible tombstone into a displayable failed run.+ recalc = self._recalc(self._experiment(flag_key=f"progress-finish-force-failed-{name}"))+ pinned_query_to = timezone.now()+ ExperimentMetricsRecalculation.objects.filter(id=recalc.id).update(+ status=ExperimentMetricsRecalculation.Status.FAILED,+ completed_at=None,+ query_to=pinned_query_to,+ started_at=timezone.now(),+ )++ returned = _update(+ RecalculationProgressUpdate(+ recalculation_id=str(recalc.id),+ status=finish_status,+ mark_completed=True,+ )+ )++ assert returned is None+ recalc.refresh_from_db()+ assert recalc.status == ExperimentMetricsRecalculation.Status.FAILED+ assert recalc.completed_at is None+@freeze_time("2026-06-23T05:00:00Z")def test_mark_started_returns_none_when_force_failed_after_query_to_pinned(self):# mark_started ran first and pinned query_to (run went IN_PROGRESS), then an admin force-failed it.diff --git a/products/experiments/backend/test/test_metrics_recalculation_api.py b/products/experiments/backend/test/test_metrics_recalculation_api.pyindex 3c2062496b8d..a6ddc86fcf04 100644--- a/products/experiments/backend/test/test_metrics_recalculation_api.py+++ b/products/experiments/backend/test/test_metrics_recalculation_api.py@@ -134,6 +134,28 @@ class TestMetricsRecalculationAPI(APIBaseTest):row = ExperimentMetricsRecalculation.objects.get(experiment=exp)assert row.status == ExperimentMetricsRecalculation.Status.FAILED+ @mock.patch("products.experiments.backend.presentation.views.sync_connect")+ @mock.patch("products.experiments.backend.presentation.views.asyncio.run")+ def test_post_rollback_spares_row_already_started_by_workflow(self, mock_run, mock_connect):+ # start_workflow can raise after Temporal accepted the start (RPC failure on the response leg).+ # By then the worker may have run mark_started; flipping that row to FAILED would release the+ # per-experiment uniqueness constraint and let a retry launch a second concurrent workflow.+ exp = self._launched_experiment()++ def _start_lands_then_rpc_fails(*args, **kwargs):+ ExperimentMetricsRecalculation.objects.filter(experiment=exp).update(+ status=ExperimentMetricsRecalculation.Status.IN_PROGRESS,+ started_at=datetime(2026, 1, 2, tzinfo=UTC),+ query_to=datetime(2026, 1, 2, tzinfo=UTC),+ )+ raise RuntimeError("deadline exceeded")++ mock_run.side_effect = _start_lands_then_rpc_fails+ resp = self.client.post(self._post_url(exp.id), {"trigger": "manual"}, format="json")+ assert resp.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR+ row = ExperimentMetricsRecalculation.objects.get(experiment=exp)+ assert row.status == ExperimentMetricsRecalculation.Status.IN_PROGRESS+# ------------------------------------------------------------------# GET /metrics_recalculation/latest/# ------------------------------------------------------------------diff --git a/products/experiments/backend/test/test_recalculation_admin.py b/products/experiments/backend/test/test_recalculation_admin.pyindex 8f5ae2dca967..de99abcea549 100644--- a/products/experiments/backend/test/test_recalculation_admin.py+++ b/products/experiments/backend/test/test_recalculation_admin.py@@ -175,6 +175,32 @@ class TestRecalculationAdminPanel(BaseTest):assert str(new_run.pk) in response.urlmock_start.assert_called_once()+ @patch("products.experiments.backend.admin.recalculation_admin.cancel_recalculation_workflow")+ def test_mark_completed_rejected_for_run_that_never_started(self, mock_cancel: MagicMock) -> None:+ # A run with no query_to never started; completing it would make /latest serve a completed run+ # with zero results and stop the timeseries fallback.+ exp = self._launched_experiment()+ recalc = ExperimentMetricsRecalculation.objects.create(+ team=self.team,+ experiment=exp,+ status=ExperimentMetricsRecalculation.Status.PENDING,+ total_metrics=2,+ metric_uuids=["m-named", "m-discovery"],+ )++ admin = ExperimentMetricsRecalculationAdmin(ExperimentMetricsRecalculation, AdminSite())+ request = RequestFactory().post("/")+ request.user = self.user+ request.session = SessionStore()+ request._messages = FallbackStorage(request) # type: ignore[attr-defined]+ with patch.object(admin, "has_change_permission", return_value=True):+ admin.mark_completed_view(request, str(recalc.pk))++ recalc.refresh_from_db()+ assert recalc.status == ExperimentMetricsRecalculation.Status.PENDING+ assert recalc.completed_at is None+ mock_cancel.assert_not_called()+@patch("products.experiments.backend.admin.recalculation_panel.start_metrics_recalculation_workflow")def test_retry_failures_denied_without_change_permission(self, mock_start: MagicMock) -> None:exp = self._launched_experiment()