: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
refactor(experiments): centralize analysis-window derivation (#65488)
Anders79a7f4a0b133
diff --git a/posthog/management/commands/populate_experiment_timeseries.py b/posthog/management/commands/populate_experiment_timeseries.pyindex 4db88f101902..b53cd76b3d89 100644--- a/posthog/management/commands/populate_experiment_timeseries.py+++ b/posthog/management/commands/populate_experiment_timeseries.py@@ -128,10 +128,8 @@ class Command(BaseCommand):metric=metric_obj,)- # Use query_to_utc as the override end date for the query runner- query_runner = ExperimentQueryRunner(- query=experiment_query, team=experiment.team, override_end_date=query_to_utc- )+ # Evaluate the experiment as of query_to_utc (clamped to end_date inside the runner)+ query_runner = ExperimentQueryRunner(query=experiment_query, team=experiment.team, as_of=query_to_utc)result = query_runner._calculate()result_data = result.model_dump()diff --git a/posthog/temporal/experiments/activities.py b/posthog/temporal/experiments/activities.pyindex da8122969f37..7ca81c3216dd 100644--- a/posthog/temporal/experiments/activities.py+++ b/posthog/temporal/experiments/activities.py@@ -27,6 +27,7 @@ from posthog.temporal.experiments.utils import (get_metric,)+from products.experiments.backend.hogql_queries.base_query_utils import experiment_window_endfrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprintfrom products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunnerfrom products.experiments.backend.hogql_queries.utils import get_experiment_stats_method@@ -181,7 +182,8 @@ def _calculate_experiment_regular_metric_sync()query_from_utc = experiment.start_date- query_to_utc = datetime.now(ZoneInfo("UTC"))+ now_utc = datetime.now(ZoneInfo("UTC"))+ query_to_utc = experiment_window_end(experiment, now_utc)try:experiment_query = ExperimentQuery(@@ -192,6 +194,7 @@ def _calculate_experiment_regular_metric_sync(query_runner = ExperimentQueryRunner(query=experiment_query,team=experiment.team,+ as_of=query_to_utc,workload=Workload.OFFLINE,# Scheduled recalc has no request user. Attribute the query to the experiment's creator so# warehouse HogQL access control is enforced.@@ -451,7 +454,8 @@ def _calculate_experiment_saved_metric_sync()query_from_utc = experiment.start_date- query_to_utc = datetime.now(ZoneInfo("UTC"))+ now_utc = datetime.now(ZoneInfo("UTC"))+ query_to_utc = experiment_window_end(experiment, now_utc)try:experiment_query = ExperimentQuery(@@ -462,6 +466,7 @@ def _calculate_experiment_saved_metric_sync(query_runner = ExperimentQueryRunner(query=experiment_query,team=experiment.team,+ as_of=query_to_utc,workload=Workload.OFFLINE,# Scheduled recalc has no request user. Attribute the query to the experiment's creator so# warehouse HogQL access control is enforced.@@ -625,7 +630,7 @@ def _backfill_experiment_metric_sync(recalculation_id: str) -> dict[str, Any]:query_runner = ExperimentQueryRunner(query=experiment_query,team=experiment.team,- override_end_date=query_to_utc,+ as_of=query_to_utc,workload=Workload.OFFLINE,# Scheduled backfill has no request user. Attribute the query to the experiment's creator# so warehouse HogQL access control is enforced.diff --git a/posthog/temporal/experiments/test_cache_warming.py b/posthog/temporal/experiments/test_cache_warming.pyindex 1094df8bf2f5..9b3a520ff10b 100644--- a/posthog/temporal/experiments/test_cache_warming.py+++ b/posthog/temporal/experiments/test_cache_warming.py@@ -20,11 +20,85 @@ from products.experiments.backend.hogql_queries.experiment_metric_fingerprint imfrom products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunnerfrom products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTestfrom products.experiments.backend.hogql_queries.utils import get_experiment_stats_method-from products.experiments.backend.models.experiment import ExperimentSavedMetric, ExperimentToSavedMetric+from products.experiments.backend.models.experiment import (+ ExperimentMetricResult,+ ExperimentSavedMetric,+ ExperimentToSavedMetric,+)@override_settings(IN_UNIT_TESTING=True)class TestTemporalRecalcWarmsResponseCache(ExperimentQueryRunnerBaseTest):+ @freeze_time("2020-01-10T12:00:00Z")+ def test_regular_metric_activity_pins_runner_to_stored_query_to(self):+ feature_flag = self.create_feature_flag()+ experiment = self.create_experiment(+ feature_flag=feature_flag,+ start_date=datetime(2020, 1, 1, 0, 0, 0),+ end_date=datetime(2020, 1, 5, 0, 0, 0),+ )+ metric = ExperimentMeanMetric(uuid=str(uuid4()), source=EventsNode(event="purchase"))+ metric_dict = metric.model_dump(mode="json")+ experiment.metrics = [metric_dict]+ experiment.save()+ expected_query_to = datetime.fromisoformat("2020-01-05T00:00:00+00:00")++ with (+ patch("posthog.temporal.experiments.activities.close_old_connections"),+ patch("posthog.temporal.experiments.activities.ExperimentQueryRunner") as mock_runner_class,+ ):+ mock_runner_class.return_value.run.return_value.model_dump.return_value = {"variant_results": []}++ activity_result = _calculate_experiment_regular_metric_sync.func( # type: ignore[attr-defined]+ experiment.id, metric_dict["uuid"], "fingerprint"+ )++ self.assertTrue(activity_result.success, msg=activity_result.error_message)+ mock_runner_class.assert_called_once()+ assert mock_runner_class.call_args.kwargs["as_of"] == expected_query_to+ result_row = ExperimentMetricResult.objects.get(experiment=experiment, metric_uuid=metric_dict["uuid"])+ assert result_row.query_to == expected_query_to++ @freeze_time("2020-01-10T12:00:00Z")+ def test_saved_metric_activity_pins_runner_to_stored_query_to(self):+ feature_flag = self.create_feature_flag()+ experiment = self.create_experiment(+ feature_flag=feature_flag,+ start_date=datetime(2020, 1, 1, 0, 0, 0),+ end_date=datetime(2020, 1, 5, 0, 0, 0),+ )+ metric = ExperimentMeanMetric(uuid=str(uuid4()), source=EventsNode(event="purchase"))+ metric_dict = metric.model_dump(mode="json")+ expected_query_to = datetime.fromisoformat("2020-01-05T00:00:00+00:00")++ saved_metric = ExperimentSavedMetric.objects.create(+ name="test saved metric",+ team=self.team,+ query=metric_dict,+ created_by=self.user,+ )+ ExperimentToSavedMetric.objects.create(+ experiment=experiment,+ saved_metric=saved_metric,+ metadata={"type": "primary"},+ )++ with (+ patch("posthog.temporal.experiments.activities.close_old_connections"),+ patch("posthog.temporal.experiments.activities.ExperimentQueryRunner") as mock_runner_class,+ ):+ mock_runner_class.return_value.run.return_value.model_dump.return_value = {"variant_results": []}++ activity_result = _calculate_experiment_saved_metric_sync.func( # type: ignore[attr-defined]+ experiment.id, metric_dict["uuid"], "fingerprint"+ )++ self.assertTrue(activity_result.success, msg=activity_result.error_message)+ mock_runner_class.assert_called_once()+ assert mock_runner_class.call_args.kwargs["as_of"] == expected_query_to+ result_row = ExperimentMetricResult.objects.get(experiment=experiment, metric_uuid=metric_dict["uuid"])+ assert result_row.query_to == expected_query_to+@freeze_time("2020-01-10T12:00:00Z")def test_temporal_activity_warms_query_cache(self):"""diff --git a/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.md b/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.mdindex 33eb08bafd8d..3978f4ba30fa 100644--- a/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.md+++ b/products/experiments/backend/hogql_queries/LAZY_COMPUTATION.md@@ -32,7 +32,8 @@ This scans millions of events. If the experiment results page is viewed 10 timesself.experiment = Experiment.objects.get(id=self.query.experiment_id)self.feature_flag = self.experiment.feature_flagself.variants = [variant["key"] for variant in self.feature_flag.variants]-self.date_range = get_experiment_date_range(self.experiment, self.team, self.override_end_date)+self.as_of = as_of if as_of is not None else (self.experiment.end_date or datetime.now(UTC))+self.date_range = experiment_window(self.experiment, self.team, self.as_of)```---@@ -46,7 +47,7 @@ def _ensure_exposures_precomputed(self, builder: ExperimentQueryBuilder) -> Lazyquery_string, placeholders = builder.get_exposure_query_for_precomputation()date_from = self.experiment.start_date- date_to = self.override_end_date or self.experiment.end_date or datetime.now(UTC)+ date_to = experiment_window_end(self.experiment, self.as_of)return ensure_precomputed(team=self.team,diff --git a/products/experiments/backend/hogql_queries/base_query_utils.py b/products/experiments/backend/hogql_queries/base_query_utils.pyindex 9998635ae890..7d54388665f2 100644--- a/products/experiments/backend/hogql_queries/base_query_utils.py+++ b/products/experiments/backend/hogql_queries/base_query_utils.py@@ -238,39 +238,73 @@ def conversion_window_to_seconds(conversion_window: int, conversion_window_unit:return conversion_window * multipliers[conversion_window_unit]-def get_experiment_date_range(- experiment: Experiment, team: Team, override_end_date: Optional[datetime] = None-) -> DateRange:+def analysis_window_end(end_date: Optional[datetime], as_of: datetime) -> datetime:+ """Upper edge of an experiment's analysis window, evaluated at ``as_of``.++ The window can't extend past the evaluation point ``as_of`` nor past the experiment's+ ``end_date``, so the edge is the earlier of the two (``end_date`` acts as +infinity when unset):++ - running (``end_date is None``) -> ``as_of``+ - ``as_of`` at/after ``end_date`` -> ``end_date`` (stopped; the common "view it later" case)+ - ``as_of`` before ``end_date`` -> ``as_of`` (a timeseries point taken mid-experiment)++ For an ordinary "current results" query the caller passes ``as_of = end_date or now``, so a stopped+ experiment resolves to ``end_date`` and a running one to ``now``. A recalc passes its frozen run+ snapshot; a timeseries backfill passes each historical day — which is why an ``as_of`` *below*+ ``end_date`` must win, so per-day points stay distinct instead of all collapsing onto ``end_date``.++ The historical "results keep growing after end_date" bug: the run snapshot (``now``, always at or+ after a stopped experiment's ``end_date``) was used as the edge *instead of* ``end_date``, so the+ window kept extending to now. Capping at ``end_date`` fixes it while preserving the sub-window.++ Value-based on purpose. A caller holding a serialized query whose result is cached under a key+ hashed from that query (the exposure runner) must pass the query's ``end_date`` here, not live+ model state — otherwise the key can describe a window the result wasn't computed for. Callers that+ hold the model use the :func:`experiment_window_end` wrapper.++ ``as_of`` (and ``end_date`` when set) must be timezone-aware."""- Returns an DateRange object based on the experiment's start and end dates,- adjusted for the team's timezone if applicable.+ if end_date is None:+ return as_of+ return min(as_of, end_date)+++def analysis_window(+ start_date: Optional[datetime], end_date: Optional[datetime], team: Team, as_of: datetime+) -> DateRange:+ """Single source of truth for an experiment's analysis ``DateRange``, from raw start/end dates.- Args:- experiment: The experiment to get date range for- team: The team to get timezone settings from- override_end_date: Optional datetime to use as end date instead of experiment.end_date, used for calculating timeseries results+ Replaces the scattered ``override_end_date or end_date or now`` derivations. The upper edge always+ comes from :func:`analysis_window_end` (earlier of ``as_of`` and ``end_date``), so no call site can+ extend the window past ``end_date``. A draft experiment (no ``start_date``) has no window."""+ if start_date is None:+ return DateRange(date_from=None, date_to=None, explicitDate=True)++ resolved_end = analysis_window_end(end_date, as_of)+if team.timezone:tz = ZoneInfo(team.timezone)- start_date: Optional[datetime] = experiment.start_date.astimezone(tz) if experiment.start_date else None- if override_end_date:- end_date: Optional[datetime] = override_end_date.astimezone(tz)- else:- end_date = experiment.end_date.astimezone(tz) if experiment.end_date else None- else:- start_date = experiment.start_date- if override_end_date:- end_date = override_end_date- else:- end_date = experiment.end_date+ start_date = start_date.astimezone(tz)+ resolved_end = resolved_end.astimezone(tz)return DateRange(- date_from=start_date.isoformat() if start_date else None,- date_to=end_date.isoformat() if end_date else None,+ date_from=start_date.isoformat(),+ date_to=resolved_end.isoformat(),explicitDate=True,)+def experiment_window_end(experiment: Experiment, as_of: datetime) -> datetime:+ """:func:`analysis_window_end` for a caller that holds the experiment model."""+ return analysis_window_end(experiment.end_date, as_of)+++def experiment_window(experiment: Experiment, team: Team, as_of: datetime) -> DateRange:+ """:func:`analysis_window` for a caller that holds the experiment model."""+ return analysis_window(experiment.start_date, experiment.end_date, team, as_of)++def get_source_time_window(date_range_query: QueryDateRange,left: ast.Expr,diff --git a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.pyindex 8832393f4a7b..5b5645ce5f52 100644--- a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py@@ -1,7 +1,6 @@import uuidfrom datetime import UTC, datetime, timedeltafrom typing import Optional-from zoneinfo import ZoneInfoimport structlogfrom rest_framework.exceptions import ValidationError@@ -35,6 +34,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu)from products.experiments.backend.analysis_health import evaluate_bias_riskfrom products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEY+from products.experiments.backend.hogql_queries.base_query_utils import analysis_window, analysis_window_endfrom products.experiments.backend.hogql_queries.error_handling import experiment_error_handlerfrom products.experiments.backend.hogql_queries.experiment_query_builder import (ExperimentQueryBuilder,@@ -73,6 +73,15 @@ class ExperimentExposuresQueryRunner(QueryRunner):self.experiment = Experiment.objects.get(id=self.query.experiment_id, team=self.team)self.feature_flag_key: str = self.experiment.feature_flag.key_without_tombstone()+ # The analysis window comes from the query, not live model state: this runner's result is+ # cached under a key hashed from self.query (see get_cache_payload), so the window it computes+ # must match the window the query declares — otherwise the key can describe a window the result+ # wasn't computed for. A running experiment serializes end_date=None; expand that to now() here+ # (lazily, so the moving instant stays out of the cache key and the 24h TTL governs refresh).+ self.window_start = datetime.fromisoformat(self.query.start_date) if self.query.start_date else None+ self.window_end_date = datetime.fromisoformat(self.query.end_date) if self.query.end_date else None+ self.as_of = self.window_end_date or datetime.now(UTC)+# Holdout is intentionally not appended: holdout users were never exposed to# the experiment, so they don't belong in the exposure chart. self.query.holdout# is still consulted by _calculate_srm for the holdout-adjusted rollout math.@@ -93,38 +102,17 @@ class ExperimentExposuresQueryRunner(QueryRunner):)def _get_date_range(self) -> DateRange:- """- Returns a DateRange object based on the experiment's start and end dates from the query,- adjusted for the team's timezone if applicable.- """- start_date_str = self.query.start_date- end_date_str = self.query.end_date-- if not start_date_str:- return DateRange(date_from=None, date_to=None, explicitDate=True)-- start_date = datetime.fromisoformat(start_date_str)- end_date = datetime.fromisoformat(end_date_str) if end_date_str else None-- if self.team.timezone:- tz = ZoneInfo(self.team.timezone)- start_date = start_date.astimezone(tz) if start_date else start_date- end_date = end_date.astimezone(tz) if end_date else end_date-- return DateRange(- date_from=start_date.isoformat() if start_date else None,- date_to=end_date.isoformat() if end_date else None,- explicitDate=True,- )+ """The experiment's analysis DateRange, derived from the query (see analysis_window)."""+ return analysis_window(self.window_start, self.window_end_date, self.team, self.as_of)def _ensure_exposures_precomputed(self, builder: ExperimentQueryBuilder) -> LazyComputationResult:query_string, placeholders = builder.get_exposure_query_for_precomputation()- if not self.experiment.start_date:+ if not self.window_start:raise ValidationError("Experiment must have a start date for lazy computation")- date_from = self.experiment.start_date- date_to = self.experiment.end_date or datetime.now(UTC)+ date_from = self.window_start+ date_to = analysis_window_end(self.window_end_date, self.as_of)return ensure_precomputed(team=self.team,@@ -270,8 +258,9 @@ class ExperimentExposuresQueryRunner(QueryRunner):def _evaluate_bias_risk(self, total_exposures: dict[str, int]) -> BiasRisk | None:# Shipping a variant rewrites the flag to 100/0, which would falsely trip the# uneven-split check on data collected under the original split. The warning is- # also unactionable post-stop — both CTAs only help while running.- if self.query.end_date is not None:+ # also unactionable post-stop — both CTAs only help while running. Read end from the+ # query (the cache key), so the running/stopped decision matches the cached window.+ if self.window_end_date is not None:return Nonemultivariate_data = self.query.feature_flag.get("filters", {}).get("multivariate", {})flag_variants = multivariate_data.get("variants", [])diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.pyindex d3f9fb12635c..9874aaf0e7b3 100644--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py@@ -41,7 +41,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execuensure_precomputed,)from products.experiments.backend.hogql_queries import CONTROL_VARIANT_KEY, MULTIPLE_VARIANT_KEY-from products.experiments.backend.hogql_queries.base_query_utils import get_experiment_date_range+from products.experiments.backend.hogql_queries.base_query_utils import experiment_window, experiment_window_endfrom products.experiments.backend.hogql_queries.cuped_config import get_cuped_configfrom products.experiments.backend.hogql_queries.error_handling import experiment_error_handlerfrom products.experiments.backend.hogql_queries.experiment_query_builder import (@@ -109,6 +109,12 @@ def experiment_has_min_runtime_for_precomputation(completed experiments (end_date in the past), the actual run length isused. A future end_date (planned end) is ignored so we don't creditruntime that hasn't happened yet.++ Note: this is elapsed *runtime*, a different concept from the analysis+ window. It deliberately clamps to min(now, end_date) — the opposite of+ experiment_window_end, which lets a future end_date win for the query+ window (no events exist beyond now anyway). Keep the two rules separate;+ do not fold this into the window primitive."""if start_date is None:return False@@ -125,14 +131,13 @@ class ExperimentQueryRunner(QueryRunner):def __init__(self,*args,- override_end_date: Optional[datetime] = None,+ as_of: Optional[datetime] = None,user_facing: bool = True,max_execution_time: Optional[int] = None,bypass_warehouse_access_control: bool = False,**kwargs,):super().__init__(*args, **kwargs)- self.override_end_date = override_end_dateself.user_facing = user_facingself.max_execution_time = max_execution_time if max_execution_time is not None else MAX_EXECUTION_TIMEself.bypass_warehouse_access_control = bypass_warehouse_access_control@@ -144,6 +149,12 @@ class ExperimentQueryRunner(QueryRunner):self.experiment = Experiment.objects.get(id=self.query.experiment_id, team=self.team)except Experiment.DoesNotExist:raise ValidationError(f"Experiment with id {self.query.experiment_id} not found")++ # Evaluation point for the analysis window; experiment_window_end caps it at end_date. An+ # explicit as_of is a recalc's frozen run snapshot or a timeseries backfill's per-day point.+ # The default — end_date for a stopped experiment, else now — makes a plain results query+ # cover the full [start, end_date] window (or [start, now] while running).+ self.as_of = as_of if as_of is not None else (self.experiment.end_date or datetime.now(UTC))self.feature_flag = self.experiment.feature_flagself.feature_flag_key = self.feature_flag.key_without_tombstone()self.group_type_index = self.feature_flag.filters.get("aggregation_group_type_index")@@ -161,7 +172,7 @@ class ExperimentQueryRunner(QueryRunner):stats_config = self.experiment.stats_config or {}self.baseline_variant_key = stats_config.get("baseline_variant_key", CONTROL_VARIANT_KEY)- self.date_range = get_experiment_date_range(self.experiment, self.team, self.override_end_date)+ self.date_range = experiment_window(self.experiment, self.team, self.as_of)self.date_range_query = QueryDateRange(date_range=self.date_range,team=self.team,@@ -239,7 +250,7 @@ class ExperimentQueryRunner(QueryRunner):raise ValidationError("Experiment must have a start date for lazy computation")date_from = self.experiment.start_date- date_to = self.override_end_date or self.experiment.end_date or datetime.now(UTC)+ date_to = experiment_window_end(self.experiment, self.as_of)return ensure_precomputed(team=self.team,@@ -265,7 +276,7 @@ class ExperimentQueryRunner(QueryRunner):raise ValidationError("Experiment must have a start date for lazy computation")date_from = self.experiment.start_date- date_to = self.override_end_date or self.experiment.end_date or datetime.now(UTC)+ date_to = experiment_window_end(self.experiment, self.as_of)# Extend time range by conversion window — funnel step events can occur after experiment endconversion_window_seconds = builder._get_conversion_window_seconds()diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.pyindex 5e4ab7287b0c..b7a58d29c28d 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_experiment_exposures_query_runner.py@@ -1674,28 +1674,49 @@ class TestExperimentExposuresQueryRunner(ExperimentQueryRunnerBaseTest):total_exposures = {"control": 800, "test": 200, MULTIPLE_VARIANT_KEY: 20}- ended_query = ExperimentExposureQuery(- kind="ExperimentExposureQuery",- experiment_id=experiment.id,- experiment_name=experiment.name,- feature_flag=model_to_dict(feature_flag),- start_date=experiment.start_date.isoformat(),- end_date=experiment.end_date.isoformat(),- exposure_criteria=experiment.exposure_criteria,- )- ended_runner = ExperimentExposuresQueryRunner(team=self.team, query=ended_query)- self.assertIsNone(ended_runner._evaluate_bias_risk(total_exposures))+ def _runner(end_date: str | None) -> ExperimentExposuresQueryRunner:+ query = ExperimentExposureQuery(+ kind="ExperimentExposureQuery",+ experiment_id=experiment.id,+ experiment_name=experiment.name,+ feature_flag=model_to_dict(feature_flag),+ start_date=experiment.start_date.isoformat(),+ end_date=end_date,+ exposure_criteria=experiment.exposure_criteria,+ )+ return ExperimentExposuresQueryRunner(team=self.team, query=query)++ # The running/stopped decision is read from the query, not the model — the experiment row is+ # left ended throughout. Query end_date set -> reads as stopped, warning skipped.+ self.assertIsNone(_runner(experiment.end_date.isoformat())._evaluate_bias_risk(total_exposures))++ # Query end_date cleared -> reads as running, warning evaluated.+ risk = _runner(None)._evaluate_bias_risk(total_exposures)+ assert risk is not None+ self.assertGreater(risk.multiple_variant_percentage, 0)- running_query = ExperimentExposureQuery(+ def test_date_range_follows_query_not_model(self):+ # The result is cached under a key hashed from the query (see get_cache_payload), so the window+ # must come from the query — not live model state. A query whose end_date differs from the+ # model's must yield the query's window, or the cache key would describe a window the result+ # wasn't computed for.+ feature_flag = self.create_feature_flag(key="stateless-window")+ experiment = self.create_experiment(+ feature_flag=feature_flag,+ start_date=datetime(2024, 1, 1),+ end_date=datetime(2024, 1, 31),+ )+ query_end = datetime(2024, 1, 10).replace(tzinfo=ZoneInfo("UTC"))+ query = ExperimentExposureQuery(kind="ExperimentExposureQuery",experiment_id=experiment.id,experiment_name=experiment.name,feature_flag=model_to_dict(feature_flag),start_date=experiment.start_date.isoformat(),- end_date=None,+ end_date=query_end.isoformat(),exposure_criteria=experiment.exposure_criteria,)- running_runner = ExperimentExposuresQueryRunner(team=self.team, query=running_query)- risk = running_runner._evaluate_bias_risk(total_exposures)- assert risk is not None- self.assertGreater(risk.multiple_variant_percentage, 0)+ runner = ExperimentExposuresQueryRunner(team=self.team, query=query)+ date_to = runner._get_date_range().date_to+ assert date_to is not None+ assert datetime.fromisoformat(date_to) == query_enddiff --git a/products/experiments/backend/hogql_queries/test/test_experiment_exposure_preaggregation.py b/products/experiments/backend/hogql_queries/test/test_experiment_exposure_preaggregation.pyindex 7f14ca93f9e6..b726add31d25 100644--- a/products/experiments/backend/hogql_queries/test/test_experiment_exposure_preaggregation.py+++ b/products/experiments/backend/hogql_queries/test/test_experiment_exposure_preaggregation.py@@ -27,7 +27,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execu_get_insert_settings,ensure_precomputed,)-from products.experiments.backend.hogql_queries.base_query_utils import get_experiment_date_range+from products.experiments.backend.hogql_queries.base_query_utils import experiment_windowfrom products.experiments.backend.hogql_queries.experiment_query_builder import (ExperimentQueryBuilder,get_exposure_config_params_for_builder,@@ -61,7 +61,8 @@ class TestExperimentExposurePreaggregation(ExperimentQueryRunnerBaseTest):exposure_config, multiple_variant_handling, filter_test_accounts = get_exposure_config_params_for_builder(experiment.exposure_criteria)- date_range = get_experiment_date_range(experiment, self.team, None)+ as_of = experiment.end_date or datetime.now(UTC)+ date_range = experiment_window(experiment, self.team, as_of)return ExperimentQueryBuilder(team=self.team,feature_flag_key=feature_flag.key,@@ -70,7 +71,7 @@ class TestExperimentExposurePreaggregation(ExperimentQueryRunnerBaseTest):multiple_variant_handling=multiple_variant_handling,variants=[v["key"] for v in feature_flag.variants],date_range_query=QueryDateRange(- date_range=date_range, team=self.team, interval=IntervalType.DAY, now=datetime.now()+ date_range=date_range, team=self.team, interval=IntervalType.DAY, now=as_of),entity_key=get_entity_key(feature_flag.filters.get("aggregation_group_type_index")),metric=metric,diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_funnel_metric_events_preaggregation.py b/products/experiments/backend/hogql_queries/test/test_experiment_funnel_metric_events_preaggregation.pyindex f104e97adb24..16684764855b 100644--- a/products/experiments/backend/hogql_queries/test/test_experiment_funnel_metric_events_preaggregation.py+++ b/products/experiments/backend/hogql_queries/test/test_experiment_funnel_metric_events_preaggregation.py@@ -21,7 +21,7 @@ from products.analytics_platform.backend.lazy_computation.lazy_computation_execuLazyComputationTable,ensure_precomputed,)-from products.experiments.backend.hogql_queries.base_query_utils import get_experiment_date_range+from products.experiments.backend.hogql_queries.base_query_utils import experiment_windowfrom products.experiments.backend.hogql_queries.experiment_query_builder import (ExperimentQueryBuilder,get_exposure_config_params_for_builder,@@ -52,12 +52,13 @@ class TestExperimentFunnelMetricEventsPreaggregation(ExperimentQueryRunnerBaseTereturn cast(ExperimentQueryResponse, runner.calculate())def _build_lazy_computation_builder(- self, experiment, feature_flag, metric, override_end_date: datetime | None = None+ self, experiment, feature_flag, metric, as_of: datetime | None = None) -> ExperimentQueryBuilder:exposure_config, multiple_variant_handling, filter_test_accounts = get_exposure_config_params_for_builder(experiment.exposure_criteria)- date_range = get_experiment_date_range(experiment, self.team, override_end_date)+ as_of = as_of if as_of is not None else datetime.now(UTC)+ date_range = experiment_window(experiment, self.team, as_of)return ExperimentQueryBuilder(team=self.team,feature_flag_key=feature_flag.key,@@ -69,17 +70,17 @@ class TestExperimentFunnelMetricEventsPreaggregation(ExperimentQueryRunnerBaseTedate_range=date_range,team=self.team,interval=IntervalType.DAY,- now=override_end_date or datetime.now(),+ now=as_of,),entity_key=get_entity_key(feature_flag.filters.get("aggregation_group_type_index")),metric=metric,)def _build_runner(- self, experiment, metric: ExperimentFunnelMetric, override_end_date: datetime | None = None+ self, experiment, metric: ExperimentFunnelMetric, as_of: datetime | None = None) -> ExperimentQueryRunner:query = ExperimentQuery(experiment_id=experiment.id, kind="ExperimentQuery", metric=metric)- return ExperimentQueryRunner(query=query, team=self.team, override_end_date=override_end_date)+ return ExperimentQueryRunner(query=query, team=self.team, as_of=as_of)def _precompute_and_compare(self, experiment, feature_flag, metric@@ -141,6 +142,37 @@ class TestExperimentFunnelMetricEventsPreaggregation(ExperimentQueryRunnerBaseTe@patch("products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute")def test_metric_events_precomputation_hash_ignores_moving_experiment_end(self, mock_sync_execute):feature_flag = self.create_feature_flag(key="stable-metric-events-hash")+ # Running experiment (no end_date) so the window end follows as_of and the two values below stay+ # distinct — the point of the test: the experiment_date_to sentinel keeps the job hash stable+ # across a moving as_of. (A stopped experiment would resolve both to end_date, defeating the test.)+ experiment = self.create_experiment(+ feature_flag=feature_flag,+ start_date=datetime(2024, 1, 1),+ end_date=None,+ )+ # create_experiment defaults end_date when None is passed, so clear it after creation.+ experiment.end_date = None+ experiment.save(update_fields=["end_date"])+ metric = ExperimentFunnelMetric(series=[EventsNode(event="purchase")])++ first_as_of = datetime(2024, 1, 5, 12, 0, tzinfo=UTC)+ second_as_of = datetime(2024, 1, 5, 12, 30, tzinfo=UTC)++ first_result = self._build_runner(experiment, metric, as_of=first_as_of)._ensure_metric_events_precomputed(+ self._build_lazy_computation_builder(experiment, feature_flag, metric, as_of=first_as_of)+ )+ second_result = self._build_runner(experiment, metric, as_of=second_as_of)._ensure_metric_events_precomputed(+ self._build_lazy_computation_builder(experiment, feature_flag, metric, as_of=second_as_of)+ )++ assert first_result.ready is True+ assert second_result.ready is True+ assert first_result.job_ids == second_result.job_ids+ assert mock_sync_execute.call_count == len(first_result.job_ids)++ @patch("products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute")+ def test_metric_events_precomputation_for_stopped_experiment_uses_end_date(self, mock_sync_execute):+ feature_flag = self.create_feature_flag(key="stopped-metric-events-hash")experiment = self.create_experiment(feature_flag=feature_flag,start_date=datetime(2024, 1, 1),@@ -148,18 +180,16 @@ class TestExperimentFunnelMetricEventsPreaggregation(ExperimentQueryRunnerBaseTe)metric = ExperimentFunnelMetric(series=[EventsNode(event="purchase")])- first_end = datetime(2024, 1, 5, 12, 0, tzinfo=UTC)- second_end = datetime(2024, 1, 5, 12, 30, tzinfo=UTC)+ # This is the stopped-experiment complement to the moving-as_of sentinel case above. Both calls+ # resolve to end_date before hashing, so they should reuse the same precomputation jobs.+ first_as_of = datetime(2024, 1, 6, 12, 0, tzinfo=UTC)+ second_as_of = datetime(2024, 1, 7, 12, 0, tzinfo=UTC)- first_result = self._build_runner(- experiment, metric, override_end_date=first_end- )._ensure_metric_events_precomputed(- self._build_lazy_computation_builder(experiment, feature_flag, metric, override_end_date=first_end)+ first_result = self._build_runner(experiment, metric, as_of=first_as_of)._ensure_metric_events_precomputed(+ self._build_lazy_computation_builder(experiment, feature_flag, metric, as_of=first_as_of))- second_result = self._build_runner(- experiment, metric, override_end_date=second_end- )._ensure_metric_events_precomputed(- self._build_lazy_computation_builder(experiment, feature_flag, metric, override_end_date=second_end)+ second_result = self._build_runner(experiment, metric, as_of=second_as_of)._ensure_metric_events_precomputed(+ self._build_lazy_computation_builder(experiment, feature_flag, metric, as_of=second_as_of))assert first_result.ready is Truediff --git a/products/experiments/backend/hogql_queries/test/test_experiment_window.py b/products/experiments/backend/hogql_queries/test/test_experiment_window.pynew file mode 100644index 000000000000..ef26e9ccb25d--- /dev/null+++ b/products/experiments/backend/hogql_queries/test/test_experiment_window.py@@ -0,0 +1,66 @@+from datetime import UTC, datetime++from unittest import TestCase++from parameterized import parameterized++from posthog.models.team.team import Team++from products.experiments.backend.hogql_queries.base_query_utils import experiment_window, experiment_window_end+from products.experiments.backend.models.experiment import Experiment+++def _exp(start: datetime | None, end: datetime | None) -> Experiment:+ # Unsaved instance: the window helpers only read start_date / end_date, no DB access needed.+ return Experiment(start_date=start, end_date=end)+++_START = datetime(2026, 1, 1, tzinfo=UTC)+_AS_OF = datetime(2026, 1, 20, tzinfo=UTC)+_PAST_END = datetime(2026, 1, 10, tzinfo=UTC)+_FUTURE_END = datetime(2026, 2, 1, tzinfo=UTC)+++class TestExperimentWindow(TestCase):+ @parameterized.expand(+ [+ # The edge is the earlier of as_of and end_date (end_date is +inf when unset). _AS_OF is+ # after _PAST_END but before _FUTURE_END.+ ("running_returns_as_of", None, _AS_OF),+ ("ended_capped_at_end_date", _PAST_END, _PAST_END),+ ("future_end_capped_at_as_of", _FUTURE_END, _AS_OF),+ ]+ )+ def test_window_end(self, _name: str, end_date: datetime | None, expected: datetime) -> None:+ assert experiment_window_end(_exp(_START, end_date), _AS_OF) == expected++ def test_ended_window_is_stable_once_as_of_passes_end_date(self) -> None:+ # Core invariant: once as_of reaches end_date, the window end stays end_date no matter when (or+ # how often) results are recomputed. This is what prevents post-end data from leaking in.+ exp = _exp(_START, _PAST_END)+ for as_of in [+ datetime(2026, 1, 11, tzinfo=UTC),+ datetime(2026, 6, 1, tzinfo=UTC),+ datetime(2027, 1, 1, tzinfo=UTC),+ ]:+ assert experiment_window_end(exp, as_of) == _PAST_END++ def test_as_of_before_end_date_wins(self) -> None:+ # The timeseries case: a per-day backfill point mid-experiment must keep its own as_of so the+ # daily points stay distinct rather than all collapsing onto end_date.+ mid_experiment = datetime(2026, 1, 5, tzinfo=UTC)+ assert experiment_window_end(_exp(_START, _PAST_END), mid_experiment) == mid_experiment++ def test_window_uses_end_date_when_set(self) -> None:+ date_range = experiment_window(_exp(_START, _PAST_END), Team(timezone="UTC"), _AS_OF)+ assert date_range.date_from == _START.isoformat()+ assert date_range.date_to == _PAST_END.isoformat()++ def test_running_window_ends_at_as_of(self) -> None:+ date_range = experiment_window(_exp(_START, None), Team(timezone="UTC"), _AS_OF)+ assert date_range.date_to == _AS_OF.isoformat()++ def test_draft_experiment_has_empty_window(self) -> None:+ date_range = experiment_window(_exp(None, None), Team(timezone="UTC"), _AS_OF)+ assert date_range.date_from is None+ assert date_range.date_to is Nonediff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex 83fa2561c802..43cc83240e0f 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -26,6 +26,7 @@ from posthog.models.scoping import team_scopefrom posthog.ph_client import ph_scoped_capturefrom posthog.sync import database_sync_to_async+from products.experiments.backend.hogql_queries.base_query_utils import experiment_window_endfrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprintfrom products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunnerfrom products.experiments.backend.hogql_queries.utils import get_experiment_stats_method@@ -174,10 +175,12 @@ 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)+ # 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(query_to=proposed_query_to,@@ -493,13 +496,13 @@ def _calculate_experiment_metric_for_recalculation_sync(calc_started_at = time.perf_counter()try:# Metric build + query live inside the try so unexpected shapes surface as a calculation-step failure.- # override_end_date forces the run's shared query_to into the ClickHouse query bounds. Without it- # the runner falls back to its default ("now-ish"), so every metric in the run would query a- # slightly different time window — defeating the "one query_to for the whole run" guarantee.+ # as_of pins the run's shared query_to as the window's evaluation instant (the runner caps it at+ # end_date). Without it each metric defaults to its own now(), giving slightly different windows —+ # defeating the "one query_to for the whole run" guarantee.runner = ExperimentQueryRunner(query=ExperimentQuery(experiment_id=experiment_id, metric=build_metric(metric_dict)),team=experiment.team,- override_end_date=query_to_dt,+ as_of=query_to_dt,workload=Workload.OFFLINE,# Scheduled recalc has no request user. Attribute the query to the experiment's creator so# warehouse HogQL access control is enforced against an accountable user instead of bypassed.diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.pyindex 8ca9718fb708..03564e495640 100644--- a/products/experiments/backend/temporal/test_recalculation_activities.py+++ b/products/experiments/backend/temporal/test_recalculation_activities.py@@ -216,18 +216,19 @@ class TestRecalculationActivities(BaseTest):@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),+ # name, end_date_offset_days (None = running experiment), expect query_to == end_date+ ("running_uses_now", None, False),+ ("stopped_uses_end_date", -5, True),+ ("future_end_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.+ def test_mark_started_query_to_is_data_window_end(self, name: str, end_date_offset_days, expect_end_date: bool):+ # query_to is the data-window end (experiment_window_end), not bare now. For a stopped experiment it+ # resolves to end_date — a fixed value — so reruns reuse the same result row instead of appending a+ # redundant post-end timeseries point. Running / future-dated experiments still advance with now.now = timezone.now()- exp = self._experiment(flag_key=f"cap-{name}")+ exp = self._experiment(flag_key=f"window-end-{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"])@@ -245,7 +246,7 @@ class TestRecalculationActivities(BaseTest):recalc.refresh_from_db()assert recalc.query_to is not None- if expect_capped:+ if expect_end_date:assert recalc.query_to == now + timedelta(days=end_date_offset_days)else:assert recalc.query_to == now@@ -439,13 +440,13 @@ class TestCalculateActivity(BaseTest):recalc.refresh_from_db()assert "m1" in recalc.metric_errors- def test_query_to_is_passed_as_override_end_date_to_runner(self):- # The run's shared query_to MUST be threaded into the ClickHouse query bounds via- # override_end_date, not just stored on the result row. Without override_end_date the runner falls back- # to its default ("now-ish"), so every metric in the run queries a slightly different time window —- # silently violating the "one query_to for the whole run" guarantee. Stored value would look correct;- # actual query bounds would not. Reference: workflow #3's backfill activity does the same thing.- exp = self._experiment(flag_key="calc-override-end-date", metrics=[_mean_metric("m1")])+ def test_query_to_is_passed_as_as_of_to_runner(self):+ # The run's shared query_to MUST be threaded into the ClickHouse query bounds via the runner's+ # as_of, not just stored on the result row. Without as_of the runner falls back to its own now(),+ # so every metric in the run queries a slightly different time window — silently violating the+ # "one query_to for the whole run" guarantee. Stored value would look correct; actual query bounds+ # would not. Reference: workflow #3's backfill activity does the same thing.+ exp = self._experiment(flag_key="calc-as-of", metrics=[_mean_metric("m1")])recalc = self._recalc(exp, metric_uuids=["m1"])with patch("products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner") as mock_runner:@@ -454,10 +455,10 @@ class TestCalculateActivity(BaseTest):mock_runner.assert_called_once()kwargs = mock_runner.call_args.kwargs- assert kwargs["override_end_date"] == datetime.fromisoformat(_QUERY_TO)+ assert kwargs["as_of"] == datetime.fromisoformat(_QUERY_TO)def test_query_from_matches_experiment_start_date_on_result_row(self):- # Companion to test_query_to_is_passed_as_override_end_date_to_runner: the lower bound of the run's+ # Companion to test_query_to_is_passed_as_as_of_to_runner: the lower bound of the run's# time window is experiment.start_date, threaded into the runner via the experiment object it# constructs and stored on the result row via _store_result(query_from=experiment.start_date).# This test pins the stored-row side. If the runner ever changes how it derives query_from, or if a