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): cap recalc query_to at experiment end_date (#65449)

Anders527f226a9219
diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.py
index 59cf254dad72..be3d488a0366 100644
--- a/products/experiments/backend/temporal/recalculation_logic.py
+++ b/products/experiments/backend/temporal/recalculation_logic.py
@@ -174,7 +174,10 @@ 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:
+ end_date = Experiment.objects.filter(id=state.experiment_id).values_list("end_date", flat=True).first()
proposed_query_to = timezone.now()
+ if end_date is not None:
+ proposed_query_to = min(proposed_query_to, end_date)
won = (
ExperimentMetricsRecalculation.objects.filter(id=update.recalculation_id, query_to__isnull=True).update(
query_to=proposed_query_to,
diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.py
index 39ae9ac00a79..29c6ef001187 100644
--- a/products/experiments/backend/temporal/test_recalculation_activities.py
+++ b/products/experiments/backend/temporal/test_recalculation_activities.py
@@ -1,7 +1,8 @@
from contextlib import contextmanager
-from datetime import datetime
+from datetime import datetime, timedelta
import pytest
+from freezegun import freeze_time
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -212,6 +213,42 @@ 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, end_date_offset_days (None = running experiment), expect query_to clamped to end_date
+ ("running_experiment_uses_now", None, False),
+ ("stopped_experiment_caps_at_end_date", -5, True),
+ ("future_end_date_uses_now", 5, False),
+ ]
+ )
+ @freeze_time("2026-06-23T05:00:00Z")
+ def test_mark_started_caps_query_to_at_end_date(self, name: str, end_date_offset_days, expect_capped: bool):
+ # A stopped experiment's linked flag often keeps firing, so query_to must freeze at end_date — otherwise
+ # each recalc advances it to now and pulls post-end exposures (and their conversions) into the results.
+ now = timezone.now()
+ exp = self._experiment(flag_key=f"cap-{name}")
+ if end_date_offset_days is not None:
+ exp.end_date = now + timedelta(days=end_date_offset_days)
+ exp.save(update_fields=["end_date"])
+ recalc = self._recalc(exp)
+
+ _update(
+ RecalculationProgressUpdate(
+ recalculation_id=str(recalc.id),
+ status="in_progress",
+ total_metrics=1,
+ metric_uuids=["m1"],
+ mark_started=True,
+ )
+ )
+
+ recalc.refresh_from_db()
+ assert recalc.query_to is not None
+ if expect_capped:
+ assert recalc.query_to == now + timedelta(days=end_date_offset_days)
+ else:
+ assert recalc.query_to == now
+
def test_mark_completed_is_first_write_wins_on_retry(self):
# Symmetric to mark_started: a retried finish activity must not re-stamp completed_at.
recalc = self._recalc(self._experiment(flag_key="progress-retry-finish"))