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): prevent reviving forced failed runs (#75082)

Rodrigo Iloroe187708c45f8
diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.py
index 6e15afb88a25..cc6be028a2d7 100644
--- a/products/experiments/backend/temporal/recalculation_logic.py
+++ b/products/experiments/backend/temporal/recalculation_logic.py
@@ -192,14 +192,18 @@ def _update_recalculation_progress_sync(update: RecalculationProgressUpdate) ->
# Temporal retry of this activity can't move query_to forward (which would orphan any rows persisted by
# calc activities still in flight from the prior attempt).
if update.mark_started:
- # query_to is the run's data-window end, not bare "now": for a stopped experiment
- # experiment_window_end resolves it to end_date (a fixed value), so repeated recalcs reuse the
- # same (fingerprint, query_to)-keyed result row instead of appending a redundant post-end
- # timeseries point on every run. A running experiment still advances with now.
experiment = Experiment.objects.get(id=state.experiment_id)
proposed_query_to = experiment_window_end(experiment, timezone.now())
+
won = (
- ExperimentMetricsRecalculation.objects.filter(id=update.recalculation_id, query_to__isnull=True).update(
+ ExperimentMetricsRecalculation.objects.filter(
+ id=update.recalculation_id,
+ query_to__isnull=True,
+ status__in=[
+ ExperimentMetricsRecalculation.Status.PENDING,
+ ExperimentMetricsRecalculation.Status.IN_PROGRESS,
+ ],
+ ).update(
query_to=proposed_query_to,
started_at=timezone.now(),
status=update.status or ExperimentMetricsRecalculation.Status.IN_PROGRESS,
@@ -208,13 +212,32 @@ def _update_recalculation_progress_sync(update: RecalculationProgressUpdate) ->
)
== 1
)
+
if won:
return proposed_query_to.isoformat()
- existing_query_to = (
+
+ existing = (
ExperimentMetricsRecalculation.objects.filter(id=update.recalculation_id)
- .values_list("query_to", flat=True)
+ .values_list("query_to", "status")
.first()
)
+
+ if existing is None:
+ logger.warning("mark_started_rejected_row_missing", recalculation_id=update.recalculation_id)
+ return None
+
+ existing_query_to, existing_status = existing
+ if existing_status not in (
+ ExperimentMetricsRecalculation.Status.PENDING,
+ ExperimentMetricsRecalculation.Status.IN_PROGRESS,
+ ):
+ logger.warning(
+ "mark_started_rejected_run_terminal",
+ recalculation_id=update.recalculation_id,
+ status=existing_status,
+ )
+ return None
+
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
diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.py
index 548f9dfe4039..556802b7c19a 100644
--- a/products/experiments/backend/temporal/test_recalculation_activities.py
+++ b/products/experiments/backend/temporal/test_recalculation_activities.py
@@ -230,6 +230,74 @@ class TestRecalculationActivities(BaseTest):
# Both attempts return the same canonical query_to so the workflow threads the same value either way.
assert first == second == first_query_to.isoformat()
+ @parameterized.expand(
+ [
+ # name, set_completed_at — both force-fail shapes leave query_to NULL while discovery runs.
+ # admin "Mark as failed" stamps completed_at; the staleness sweep deliberately leaves it NULL, so
+ # a completed_at-only guard would miss the sweep. The status guard catches both.
+ ("admin_sets_completed_at", True),
+ ("sweep_leaves_completed_at_null", False),
+ ]
+ )
+ @freeze_time("2026-06-23T05:00:00Z")
+ def test_mark_started_does_not_revive_a_force_failed_run(self, name: str, set_completed_at: bool):
+ recalc = self._recalc(self._experiment(flag_key=f"progress-start-force-failed-{name}"))
+ completed_at = timezone.now() if set_completed_at else None
+ ExperimentMetricsRecalculation.objects.filter(id=recalc.id).update(
+ status=ExperimentMetricsRecalculation.Status.FAILED, completed_at=completed_at
+ )
+
+ returned = _update(
+ RecalculationProgressUpdate(
+ recalculation_id=str(recalc.id),
+ status="in_progress",
+ total_metrics=3,
+ metric_uuids=["m1", "m2", "m3"],
+ mark_started=True,
+ )
+ )
+
+ recalc.refresh_from_db()
+ # The run stays terminal: no revival, no started_at, query_to left NULL.
+ assert recalc.status == ExperimentMetricsRecalculation.Status.FAILED
+ assert recalc.completed_at == completed_at
+ assert recalc.started_at is None
+ assert recalc.query_to is None
+ # query_to was never pinned, so the read-back returns None; the workflow's isinstance(str) check then
+ # fails the run non-retryably instead of proceeding to calc activities on a dead run.
+ assert returned 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.
+ # A retried mark_started loses the guard, but the read-back must NOT hand back the pinned query_to as a
+ # string: that would pass the workflow's isinstance(str) check and let calc activities run ClickHouse
+ # queries and persist results for a terminal, superseded run (they don't re-check terminal status).
+ recalc = self._recalc(self._experiment(flag_key="progress-start-pinned-then-failed"))
+ pinned_query_to = timezone.now()
+ ExperimentMetricsRecalculation.objects.filter(id=recalc.id).update(
+ status=ExperimentMetricsRecalculation.Status.FAILED,
+ completed_at=timezone.now(),
+ query_to=pinned_query_to,
+ started_at=timezone.now(),
+ )
+
+ returned = _update(
+ RecalculationProgressUpdate(
+ recalculation_id=str(recalc.id),
+ status="in_progress",
+ total_metrics=3,
+ metric_uuids=["m1", "m2", "m3"],
+ mark_started=True,
+ )
+ )
+
+ # Terminal read-back returns None despite query_to being pinned, so the workflow fails the run.
+ assert returned is None
+ recalc.refresh_from_db()
+ assert recalc.status == ExperimentMetricsRecalculation.Status.FAILED
+ assert recalc.query_to == pinned_query_to
+
@parameterized.expand(
[
# name, end_date_offset_days (None = running experiment), expect query_to == end_date