: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): require a recent data window before skipping a scheduled run (#111679)
Rodrigo Iloro084a5061764b
diff --git a/products/experiments/backend/temporal/scheduled_recalculation_logic.py b/products/experiments/backend/temporal/scheduled_recalculation_logic.pyindex 6e6593b94522..b0145abe7307 100644--- a/products/experiments/backend/temporal/scheduled_recalculation_logic.py+++ b/products/experiments/backend/temporal/scheduled_recalculation_logic.py@@ -7,6 +7,7 @@ workflow's activities in `scheduled_recalculation_activities` are thin wrappersfrom datetime import timedeltafrom typing import Final+from django.db.models import Qfrom django.utils import timezoneimport structlog@@ -126,10 +127,11 @@ def find_scheduled_recalculation_candidates() -> ScheduledRecalculationDiscoverydef recent_recalculation_skip(experiment: Experiment, team_id: int) -> SkipDecision | None:- """Skip when a run is already active, or when one finished inside the freshness window.+ """Skip when a run is already active, or when one finished inside the freshness window on a+ window of data that is itself recent.- `timeseries_sync` rows never count toward freshness. The timeseries workflow publishes one- at :00 and this workflow runs at :30, so counting it would skip every experiment forever.+ `timeseries_sync` rows never count toward freshness: they carry a timeseries run's window, not a+ full recalculation, and counting one would skip the experiment that needs the real run.Scopes explicitly with `for_team`: the model is fail-closed and an activity carries no requestcontext, so an unscoped read would raise `TeamScopeError`.@@ -148,12 +150,18 @@ def recent_recalculation_skip(experiment: Experiment, team_id: int) -> SkipDecisif active is not None:return SkipDecision(reason=SKIP_ACTIVE_RUN, detail={"existing_recalculation_id": str(active.id)})+ freshness_cutoff = timezone.now() - MIN_TIME_SINCE_LAST_RECALCULATIONlatest = (scoped.filter(experiment=experiment,completed_at__isnull=False,- completed_at__gte=timezone.now() - MIN_TIME_SINCE_LAST_RECALCULATION,+ completed_at__gte=freshness_cutoff,)+ # A reused window makes a run recent without making its data recent: `_resolve_query_to`+ # keeps the previous `query_to` for metric_config_change, manual_retry and heal_latest_run,+ # and the page heals itself on load, so this is a routine shape rather than a rare one. A+ # null `query_to` still counts, because such a run resolved no window to judge.+ .filter(Q(query_to__isnull=True) | Q(query_to__gte=freshness_cutoff)).exclude(trigger=ExperimentMetricsRecalculation.Trigger.TIMESERIES_SYNC).order_by("-completed_at").first()diff --git a/products/experiments/backend/temporal/test_scheduled_recalculation_logic.py b/products/experiments/backend/temporal/test_scheduled_recalculation_logic.pyindex cdb46ef6d841..77564a952175 100644--- a/products/experiments/backend/temporal/test_scheduled_recalculation_logic.py+++ b/products/experiments/backend/temporal/test_scheduled_recalculation_logic.py@@ -240,19 +240,35 @@ class TestScheduledRecalculationLogic(BaseTest):ExperimentMetricsRecalculation.objects.filter(id=recalc.id).update(created_at=stale)assert recent_recalculation_skip(experiment, self.team.id) is None- def test_recent_completed_run_skips(self):+ @parameterized.expand(+ [+ # heal_latest_run and metric_config_change reuse the previous window, so a run can+ # finish minutes ago and still hold yesterday's data. Skipping on completed_at alone+ # would leave the page a day behind until the next slot.+ ("stale_window", timedelta(days=1), False),+ ("fresh_window", timedelta(minutes=10), True),+ # A run that resolved no window gives nothing to judge staleness by, so it still skips.+ ("no_window", None, True),+ ]+ )+ def test_a_recent_run_skips_only_on_a_recent_window(+ self, _name: str, query_to_age: timedelta | None, expected_skip: bool+ ):experiment = self._experiment()with team_scope(self.team.id, canonical=True):ExperimentMetricsRecalculation.objects.create(team=self.team,experiment=experiment,status=ExperimentMetricsRecalculation.Status.COMPLETED,+ trigger=ExperimentMetricsRecalculation.Trigger.HEAL_LATEST_RUN,completed_at=timezone.now() - timedelta(minutes=10),+ query_to=None if query_to_age is None else timezone.now() - query_to_age,)decision = recent_recalculation_skip(experiment, self.team.id)- assert decision is not None- assert decision.reason == SKIP_RECENT_RUN- assert decision.detail["minutes_since_completion"] == 10+ assert (decision is not None) is expected_skip+ if decision is not None:+ assert decision.reason == SKIP_RECENT_RUN+ assert decision.detail["minutes_since_completion"] == 10def test_old_completed_run_does_not_skip(self):experiment = self._experiment()