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.

chore(experiments): dedup the precompute gates across the query runners (#101463)

Anders94a1871e3634
diff --git a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
index 29303ab59641..40c47617636e 100644
--- a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py
@@ -1,6 +1,5 @@
import uuid
from datetime import UTC, datetime, timedelta
-from typing import Optional
import structlog
from rest_framework.exceptions import ValidationError
@@ -27,11 +26,7 @@ from posthog.hogql_queries.query_runner import QueryRunner
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models.team.extensions import get_or_create_team_extension
-from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
- LazyComputationResult,
- LazyComputationTable,
- ensure_precomputed,
-)
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import LazyComputationResult
from products.experiments.backend.analysis_health import evaluate_bias_risk
from products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEY
from products.experiments.backend.hogql_queries.base_query_utils import analysis_window, analysis_window_end
@@ -41,11 +36,11 @@ from products.experiments.backend.hogql_queries.experiment_query_builder import
get_exposure_config_params_for_builder,
)
from products.experiments.backend.hogql_queries.experiment_query_runner import (
- experiment_has_min_runtime_for_precomputation,
- experiment_precompute_ttl_schedule,
- has_uncalculated_cohorts,
+ ExperimentResultsCacheMixin,
+ ensure_exposures_precomputed,
+ team_precompute_skip_reason,
)
-from products.experiments.backend.hogql_queries.exposure_query_logic import get_entity_key, has_activation_config
+from products.experiments.backend.hogql_queries.exposure_query_logic import get_entity_key
from products.experiments.backend.models.experiment import Experiment
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
@@ -55,7 +50,7 @@ QUERY_ROW_LIMIT = 5000 # Should be sufficient for all experiments (days * varia
SRM_MINIMUM_SAMPLE_SIZE = 100 # Minimum total exposures required for SRM calculation
-class ExperimentExposuresQueryRunner(QueryRunner):
+class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
query: ExperimentExposureQuery
cached_response: CachedExperimentExposureQueryResponse
@@ -124,25 +119,14 @@ class ExperimentExposuresQueryRunner(QueryRunner):
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.window_start:
raise ValidationError("Experiment must have a start date for lazy computation")
- date_from = self.window_start
- date_to = analysis_window_end(self.window_end_date, self.as_of)
-
- return ensure_precomputed(
- team=self.team,
- insert_query=query_string,
- time_range_start=date_from,
- time_range_end=date_to,
- ttl_seconds=experiment_precompute_ttl_schedule(self.team.timezone),
- table=LazyComputationTable.EXPERIMENT_EXPOSURES_PREAGGREGATED,
- placeholders=placeholders,
- sentinel_placeholders={"experiment_date_to"},
- end_is_data_horizon=True,
- spill_to_disk=True,
+ return ensure_exposures_precomputed(
+ self.team,
+ builder,
+ self.window_start,
+ analysis_window_end(self.window_end_date, self.as_of),
)
def _get_exposure_query(self) -> ast.SelectQuery:
@@ -167,20 +151,17 @@ class ExperimentExposuresQueryRunner(QueryRunner):
# lets PrecomputationMode.PRECOMPUTED bypass the gate, but this path has
# no equivalent escape hatch yet, so callers cannot force precomputation
# on a sub-12h experiment for the exposures view.
- config = get_or_create_team_extension(self.team, TeamExperimentsConfig)
# group_type_index gate: mirrors the main runner — group builds always fail
# (the INSERT can't resolve the materialized $group_N column on sharded_events).
if (
self.group_type_index is None
- and config.experiment_precomputation_enabled
- and experiment_has_min_runtime_for_precomputation(
- self.experiment.start_date,
- self.experiment.end_date,
+ and team_precompute_skip_reason(
+ self.team,
+ get_or_create_team_extension(self.team, TeamExperimentsConfig),
+ self.experiment,
+ self.exposure_criteria,
)
- and not has_uncalculated_cohorts(self.team, self.exposure_criteria)
- # Activation-mode exposures can't be cached per day: the flag→activation
- # ordering crosses bucket boundaries.
- and not has_activation_config(self.exposure_criteria)
+ is None
):
try:
with tags_context(experiment_query_surface="precompute_build", experiment_precompute_table="exposures"):
@@ -420,18 +401,7 @@ class ExperimentExposuresQueryRunner(QueryRunner):
return complete_results
- # Cache results for 24 hours
- def cache_target_age(self, last_refresh: Optional[datetime], lazy: bool = False) -> Optional[datetime]:
- if last_refresh is None:
- return None
- return last_refresh + timedelta(hours=24)
-
def get_cache_payload(self) -> dict:
payload = super().get_cache_payload()
payload["experiment_exposures_response_version"] = 2
return payload
-
- def _is_stale(self, last_refresh: Optional[datetime], lazy: bool = False) -> bool:
- if not last_refresh:
- return True
- return (datetime.now(UTC) - last_refresh) > timedelta(hours=24)
diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.py
index 961975d2ea47..06e8d6c9de5d 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py
@@ -223,7 +223,80 @@ def has_uncalculated_cohorts(team: Team, *filter_sources: Any) -> bool:
).exists()
-class ExperimentQueryRunner(QueryRunner):
+# Reasons that mean "do not precompute". The other PrecomputeSkipReason members explain a
+# direct-path query that precompute was attempted for, so they must not gate the bool.
+BLOCKING_PRECOMPUTE_SKIP_REASONS = frozenset(
+ {
+ PrecomputeSkipReason.OVERRIDE_DIRECT,
+ PrecomputeSkipReason.TEAM_DISABLED,
+ PrecomputeSkipReason.MIN_RUNTIME,
+ PrecomputeSkipReason.ACTIVATION_CONFIG,
+ PrecomputeSkipReason.COHORT_NOT_CALCULATED,
+ }
+)
+
+
+def team_precompute_skip_reason(
+ team: Team,
+ config: TeamExperimentsConfig,
+ experiment: Experiment,
+ exposure_criteria: Any,
+ *cohort_filter_sources: Any,
+) -> Optional[PrecomputeSkipReason]:
+ """The precompute gates that apply to every experiment query, shared by both runners."""
+ if not config.experiment_precomputation_enabled:
+ return PrecomputeSkipReason.TEAM_DISABLED
+ if not experiment_has_min_runtime_for_precomputation(experiment.start_date, experiment.end_date):
+ return PrecomputeSkipReason.MIN_RUNTIME
+ # Activation-mode exposures can't be cached per day: the flag→activation ordering
+ # crosses bucket boundaries.
+ if has_activation_config(exposure_criteria):
+ return PrecomputeSkipReason.ACTIVATION_CONFIG
+ if has_uncalculated_cohorts(team, exposure_criteria, *cohort_filter_sources):
+ return PrecomputeSkipReason.COHORT_NOT_CALCULATED
+ return None
+
+
+def ensure_exposures_precomputed(
+ team: Team,
+ builder: ExperimentQueryBuilder,
+ time_range_start: datetime,
+ time_range_end: datetime,
+) -> LazyComputationResult:
+ """Ensure lazy-computed exposure data exists for the window, and return its job_ids."""
+ query_string, placeholders = builder.get_exposure_query_for_precomputation()
+
+ return ensure_precomputed(
+ team=team,
+ insert_query=query_string,
+ time_range_start=time_range_start,
+ time_range_end=time_range_end,
+ ttl_seconds=experiment_precompute_ttl_schedule(team.timezone),
+ table=LazyComputationTable.EXPERIMENT_EXPOSURES_PREAGGREGATED,
+ placeholders=placeholders,
+ sentinel_placeholders={"experiment_date_to"},
+ end_is_data_horizon=True,
+ # High-volume teams' builds OOM even at capped window widths; spilling the
+ # GROUP BY to disk degrades gracefully instead of failing the build.
+ spill_to_disk=True,
+ )
+
+
+class ExperimentResultsCacheMixin:
+ """24-hour result cache, shared by the experiment query runners."""
+
+ def cache_target_age(self, last_refresh: Optional[datetime], lazy: bool = False) -> Optional[datetime]:
+ if last_refresh is None:
+ return None
+ return last_refresh + timedelta(hours=24)
+
+ def _is_stale(self, last_refresh: Optional[datetime], lazy: bool = False) -> bool:
+ if not last_refresh:
+ return True
+ return (datetime.now(UTC) - last_refresh) > timedelta(hours=24)
+
+
+class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
query: ExperimentQuery
cached_response: CachedExperimentQueryResponse
actors_query: Optional[ExperimentActorsQuery] = None
@@ -341,36 +414,14 @@ class ExperimentQueryRunner(QueryRunner):
return breakdowns
def _ensure_exposures_precomputed(self, builder: ExperimentQueryBuilder) -> LazyComputationResult:
- """
- Ensures lazy-computed exposure data exists for this experiment.
-
- Gets the exposure query from the builder and passes it to the lazy computation
- system, which will compute and store the exposure data if not already cached.
-
- Returns:
- LazyComputationResult with job_ids that can be used to query the data
- """
- query_string, placeholders = builder.get_exposure_query_for_precomputation()
-
if not self.experiment.start_date:
raise ValidationError("Experiment must have a start date for lazy computation")
- date_from = self.experiment.start_date
- date_to = experiment_window_end(self.experiment, self.as_of)
-
- return ensure_precomputed(
- team=self.team,
- insert_query=query_string,
- time_range_start=date_from,
- time_range_end=date_to,
- ttl_seconds=experiment_precompute_ttl_schedule(self.team.timezone),
- table=LazyComputationTable.EXPERIMENT_EXPOSURES_PREAGGREGATED,
- placeholders=placeholders,
- sentinel_placeholders={"experiment_date_to"},
- end_is_data_horizon=True,
- # High-volume teams' builds OOM even at capped window widths; spilling the
- # GROUP BY to disk degrades gracefully instead of failing the build.
- spill_to_disk=True,
+ return ensure_exposures_precomputed(
+ self.team,
+ builder,
+ self.experiment.start_date,
+ experiment_window_end(self.experiment, self.as_of),
)
def _ensure_metric_events_precomputed(self, builder: ExperimentQueryBuilder) -> LazyComputationResult:
@@ -415,26 +466,7 @@ class ExperimentQueryRunner(QueryRunner):
def _should_precompute(self) -> bool:
"""Resolve whether to use precomputation: query-level override > team-level default + duration gate."""
- if self.query.precomputation_mode == PrecomputationMode.PRECOMPUTED:
- return True
- if self.query.precomputation_mode == PrecomputationMode.DIRECT:
- return False
-
- if not self._team_experiments_config.experiment_precomputation_enabled:
- return False
-
- if not experiment_has_min_runtime_for_precomputation(
- self.experiment.start_date,
- self.experiment.end_date,
- ):
- return False
-
- # Activation-mode exposures can't be cached per day: the flag→activation ordering
- # crosses bucket boundaries.
- if has_activation_config(self.experiment.exposure_criteria):
- return False
-
- return not has_uncalculated_cohorts(self.team, self.experiment.exposure_criteria, self.metric)
+ return self._precompute_skip_reason() not in BLOCKING_PRECOMPUTE_SKIP_REASONS
def _precompute_skip_reason(self) -> Optional[PrecomputeSkipReason]:
"""Why precompute was not used, for the query-performance UI. None when it was attempted."""
@@ -442,17 +474,17 @@ class ExperimentQueryRunner(QueryRunner):
return None
if self.query.precomputation_mode == PrecomputationMode.DIRECT:
return PrecomputeSkipReason.OVERRIDE_DIRECT
- if not self._team_experiments_config.experiment_precomputation_enabled:
- return PrecomputeSkipReason.TEAM_DISABLED
- if not experiment_has_min_runtime_for_precomputation(
- self.experiment.start_date,
- self.experiment.end_date,
- ):
- return PrecomputeSkipReason.MIN_RUNTIME
- if has_activation_config(self.experiment.exposure_criteria):
- return PrecomputeSkipReason.ACTIVATION_CONFIG
- if has_uncalculated_cohorts(self.team, self.experiment.exposure_criteria, self.metric):
- return PrecomputeSkipReason.COHORT_NOT_CALCULATED
+
+ blocked = team_precompute_skip_reason(
+ self.team,
+ self._team_experiments_config,
+ self.experiment,
+ self.experiment.exposure_criteria,
+ self.metric,
+ )
+ if blocked is not None:
+ return blocked
+
if self.is_data_warehouse_query:
return PrecomputeSkipReason.DATA_WAREHOUSE
if self.group_type_index is not None:
@@ -1017,12 +1049,6 @@ class ExperimentQueryRunner(QueryRunner):
def to_query(self) -> ast.SelectQuery:
raise ValidationError(f"Cannot convert source query of type {self.query.metric.kind} to query")
- # Cache results for 24 hours
- def cache_target_age(self, last_refresh: Optional[datetime], lazy: bool = False) -> Optional[datetime]:
- if last_refresh is None:
- return None
- return last_refresh + timedelta(hours=24)
-
def single_flight_variant(self) -> str:
# A recalculation passes its own window end, warehouse access, and execution time. None of
# them reach the cache key, so a recalculation must not pair with a results request.
@@ -1038,8 +1064,3 @@ class ExperimentQueryRunner(QueryRunner):
payload["experiment_response_version"] = 2
payload["stats_method"] = self.stats_method
return payload
-
- def _is_stale(self, last_refresh: Optional[datetime], lazy: bool = False) -> bool:
- if not last_refresh:
- return True
- return (datetime.now(UTC) - last_refresh) > timedelta(hours=24)