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): add ExposuresPrecompute for exposures precompute decisions and builds (#127776)

Rodrigo Iloroba02cfb7b848
diff --git a/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md b/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md
index 7b4879a289a6..0c511863ce1c 100644
--- a/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md
+++ b/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md
@@ -162,7 +162,7 @@ metric_events AS (
The runner orchestrates both precomputations, then hands the job ids to `build_query()`:
```python
-if should_precompute and not self.is_data_warehouse_query and self.group_type_index is None:
+if self._exposures_precompute_applicable():
result = self._ensure_exposures_precomputed(builder)
if result.ready:
exposure_job_ids = [str(job_id) for job_id in result.job_ids]
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 c8ce296ca346..5ffd74509c89 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,7 @@
import uuid
from dataclasses import replace
from datetime import UTC, date, datetime, timedelta
+from functools import cached_property
from typing import Any
import structlog
@@ -84,10 +85,7 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (
get_entity_key,
has_positive_test_account_filter,
)
-from products.experiments.backend.hogql_queries.precompute_policy import (
- ensure_exposures_precomputed,
- team_precompute_skip_reason,
-)
+from products.experiments.backend.hogql_queries.exposures_precompute import ExposuresPrecompute
from products.experiments.backend.models.experiment import Experiment
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
@@ -197,17 +195,27 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
def _get_date_range(self) -> DateRange:
return analysis_window(self.window_start, self.window_end_date, self.team, self.as_of)
- def _ensure_exposures_precomputed(self, builder: ExperimentQueryBuilder) -> LazyComputationResult:
- if not self.window_start:
- raise ValidationError("Experiment must have a start date for lazy computation")
-
- return ensure_exposures_precomputed(
- self.team,
- builder,
- self.window_start,
- analysis_window_end(self.window_end_date, self.as_of),
+ @cached_property
+ def _exposures_precompute(self) -> ExposuresPrecompute:
+ return ExposuresPrecompute(
+ team=self.team,
+ team_experiments_config=get_or_create_team_extension(self.team, TeamExperimentsConfig),
+ experiment=self.experiment,
+ window_start=self.window_start,
+ window_end=analysis_window_end(self.window_end_date, self.as_of),
+ exposure_criteria=self.exposure_criteria,
+ cohort_filter_sources=(),
+ precomputation_mode=None,
+ is_data_warehouse_query=False,
+ group_type_index=self.group_type_index,
)
+ def _exposures_precompute_applicable(self) -> bool:
+ return self._exposures_precompute.applicable
+
+ def _ensure_exposures_precomputed(self, builder: ExperimentQueryBuilder) -> LazyComputationResult:
+ return self._exposures_precompute.ensure_precomputed(builder)
+
def _query_builder(self, exposure_params: ExposureQueryParams) -> ExperimentQueryBuilder:
return ExperimentQueryBuilder(
team=self.team,
@@ -227,18 +235,7 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
# TODO: Add a query-level precomputation_mode override for ExperimentExposureQuery. The main
# runner lets PrecomputationMode.PRECOMPUTED bypass the duration gate. This path has no such
# override, so callers cannot force precomputation for an experiment below the minimum duration.
- # The group_type_index check mirrors the main runner: group builds always fail, because the
- # INSERT cannot resolve the materialized $group_N column on sharded_events.
- if (
- self.group_type_index is None
- and team_precompute_skip_reason(
- self.team,
- get_or_create_team_extension(self.team, TeamExperimentsConfig),
- self.experiment,
- self.exposure_criteria,
- )
- is None
- ):
+ if self._exposures_precompute_applicable():
try:
with tags_context(experiment_query_surface="precompute_build", experiment_precompute_table="exposures"):
result = self._ensure_exposures_precomputed(builder)
diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.py
index 71473d214567..d0d93ec732db 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py
@@ -22,7 +22,6 @@ from posthog.schema import (
HogQLQueryModifiers,
IntervalType,
MultipleVariantHandling,
- PrecomputationMode,
)
from posthog.hogql import ast
@@ -56,15 +55,11 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (
get_entity_key,
get_multiple_variant_handling_from_experiment,
)
+from products.experiments.backend.hogql_queries.exposures_precompute import ExposuresPrecompute
from products.experiments.backend.hogql_queries.metric_events_precompute import (
MetricEventsPrecompute,
RatioPrecomputeResults,
)
-from products.experiments.backend.hogql_queries.precompute_policy import (
- BLOCKING_PRECOMPUTE_SKIP_REASONS,
- ensure_exposures_precomputed,
- team_precompute_skip_reason,
-)
from products.experiments.backend.hogql_queries.utils import (
aggregate_variants_across_breakdowns,
get_bayesian_experiment_result,
@@ -220,17 +215,24 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
return breakdowns
- def _ensure_exposures_precomputed(self, builder: ExperimentQueryBuilder) -> LazyComputationResult:
- if not self.experiment.start_date:
- raise ValidationError("Experiment must have a start date for lazy computation")
-
- return ensure_exposures_precomputed(
- self.team,
- builder,
- self.experiment.start_date,
- experiment_window_end(self.experiment, self.as_of),
+ @cached_property
+ def _exposures_precompute(self) -> ExposuresPrecompute:
+ return ExposuresPrecompute(
+ team=self.team,
+ team_experiments_config=self._team_experiments_config,
+ experiment=self.experiment,
+ window_start=self.experiment.start_date,
+ window_end=experiment_window_end(self.experiment, self.as_of),
+ exposure_criteria=self.experiment.exposure_criteria,
+ cohort_filter_sources=(self.metric,),
+ precomputation_mode=self.query.precomputation_mode,
+ is_data_warehouse_query=self.is_data_warehouse_query,
+ group_type_index=self.group_type_index,
)
+ def _ensure_exposures_precomputed(self, builder: ExperimentQueryBuilder) -> LazyComputationResult:
+ return self._exposures_precompute.ensure_precomputed(builder)
+
@cached_property
def _metric_events_precompute(self) -> MetricEventsPrecompute:
return MetricEventsPrecompute(
@@ -254,31 +256,12 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
def _team_experiments_config(self) -> TeamExperimentsConfig:
return get_or_create_team_extension(self.team, TeamExperimentsConfig)
- def _should_precompute(self) -> bool:
- return self._precompute_skip_reason() not in BLOCKING_PRECOMPUTE_SKIP_REASONS
+ def _exposures_precompute_applicable(self) -> bool:
+ return self._exposures_precompute.applicable
def _precompute_skip_reason(self) -> Optional[PrecomputeSkipReason]:
"""Why precompute was not used, for the query-performance UI. None when it was attempted."""
- if self.query.precomputation_mode == PrecomputationMode.PRECOMPUTED:
- return None
- if self.query.precomputation_mode == PrecomputationMode.DIRECT:
- return PrecomputeSkipReason.OVERRIDE_DIRECT
-
- 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:
- return PrecomputeSkipReason.GROUP_AGGREGATION
- return None # precompute was attempted; a direct path means the build failed / wasn't ready
+ return self._exposures_precompute.ineligibility_reason()
def _metric_events_precompute_applicable(self) -> bool:
return self._metric_events_precompute.applicable
@@ -326,19 +309,12 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
def _get_experiment_query(self) -> ast.SelectQuery:
builder = self._query_builder()
- should_precompute = self._should_precompute()
-
exposure_job_ids: list[str] | None = None
metric_events_job_ids: list[str] | None = None
numerator_job_ids: list[str] | None = None
denominator_job_ids: list[str] | None = None
- # Skip precomputation for data warehouse metrics because the precomputed table
- # doesn't include the join keys needed to link exposures to data warehouse tables.
- # Group-aggregated experiments are excluded too: their build INSERT references
- # $group_N, which the INSERT ... SELECT analysis path can't resolve (MATERIALIZED
- # on sharded_events), so every build fails with UNKNOWN_IDENTIFIER.
- if should_precompute and not self.is_data_warehouse_query and self.group_type_index is None:
+ if self._exposures_precompute_applicable():
try:
with tags_context(experiment_query_surface="precompute_build", experiment_precompute_table="exposures"):
result = self._ensure_exposures_precomputed(builder)
diff --git a/products/experiments/backend/hogql_queries/exposures_precompute.py b/products/experiments/backend/hogql_queries/exposures_precompute.py
new file mode 100644
index 000000000000..2a9ceaa11058
--- /dev/null
+++ b/products/experiments/backend/hogql_queries/exposures_precompute.py
@@ -0,0 +1,102 @@
+"""
+Exposures precomputation for one experiment query: whether the query can read
+from experiment_exposures_preaggregated, and the lazy-computation build that fills it.
+
+The gates that every experiment query shares live in precompute_policy; this module
+composes them with the build limits and runs the build.
+"""
+
+from datetime import datetime
+from typing import Any, Optional
+
+from rest_framework.exceptions import ValidationError
+
+from posthog.schema import PrecomputationMode
+
+from posthog.dataclasses import frozen
+from posthog.models.team.team import Team
+
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LazyComputationResult,
+ LazyComputationTable,
+ ensure_precomputed,
+)
+from products.experiments.backend.facade.enums import PrecomputeSkipReason
+from products.experiments.backend.hogql_queries.experiment_query_builder import ExperimentQueryBuilder
+from products.experiments.backend.hogql_queries.precompute_policy import (
+ BLOCKING_PRECOMPUTE_SKIP_REASONS,
+ experiment_precompute_ttl_schedule,
+ team_precompute_skip_reason,
+)
+from products.experiments.backend.models.experiment import Experiment
+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
+
+
+@frozen
+class ExposuresPrecompute:
+ """The exposures precompute decisions and builds for one experiment query."""
+
+ team: Team
+ team_experiments_config: TeamExperimentsConfig
+ experiment: Experiment
+ window_start: Optional[datetime]
+ window_end: datetime
+ exposure_criteria: Any
+ cohort_filter_sources: tuple[Any, ...]
+ precomputation_mode: Optional[PrecomputationMode]
+ is_data_warehouse_query: bool
+ group_type_index: Optional[int]
+
+ def ensure_precomputed(self, builder: ExperimentQueryBuilder) -> LazyComputationResult:
+ if not self.window_start:
+ raise ValidationError("Experiment must have a start date for lazy computation")
+
+ query_string, placeholders = builder.get_exposure_query_for_precomputation()
+ return ensure_precomputed(
+ team=self.team,
+ insert_query=query_string,
+ time_range_start=self.window_start,
+ time_range_end=self.window_end,
+ 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,
+ )
+
+ @property
+ def applicable(self) -> bool:
+ # The PRECOMPUTED mode skips the policy gates, but no mode makes these builds work.
+ # The precomputed table doesn't include the join keys needed to link exposures to
+ # data warehouse tables. A group-aggregated build INSERT references $group_N, which
+ # the INSERT ... SELECT analysis path can't resolve (MATERIALIZED on sharded_events),
+ # so every build fails with UNKNOWN_IDENTIFIER.
+ if self.is_data_warehouse_query or self.group_type_index is not None:
+ return False
+ return self.ineligibility_reason() not in BLOCKING_PRECOMPUTE_SKIP_REASONS
+
+ def ineligibility_reason(self) -> Optional[PrecomputeSkipReason]:
+ """Why precompute was not used, for the query-performance UI. None when it was attempted."""
+ if self.precomputation_mode == PrecomputationMode.PRECOMPUTED:
+ return None
+ if self.precomputation_mode == PrecomputationMode.DIRECT:
+ return PrecomputeSkipReason.OVERRIDE_DIRECT
+
+ blocked = team_precompute_skip_reason(
+ self.team,
+ self.team_experiments_config,
+ self.experiment,
+ self.exposure_criteria,
+ *self.cohort_filter_sources,
+ )
+ 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:
+ return PrecomputeSkipReason.GROUP_AGGREGATION
+ return None # precompute was attempted; a direct path means the build failed / wasn't ready
diff --git a/products/experiments/backend/hogql_queries/precompute_policy.py b/products/experiments/backend/hogql_queries/precompute_policy.py
index 9253e3fdc1cb..040d878562d6 100644
--- a/products/experiments/backend/hogql_queries/precompute_policy.py
+++ b/products/experiments/backend/hogql_queries/precompute_policy.py
@@ -15,15 +15,11 @@ from pydantic import BaseModel
from posthog.models.team.team import Team
from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
- LazyComputationResult,
- LazyComputationTable,
TtlSchedule,
- ensure_precomputed,
parse_ttl_schedule,
)
from products.cohorts.backend.models.cohort import Cohort
from products.experiments.backend.facade.enums import PrecomputeSkipReason
-from products.experiments.backend.hogql_queries.experiment_query_builder import ExperimentQueryBuilder
from products.experiments.backend.hogql_queries.exposure_query_logic import has_activation_config
from products.experiments.backend.models.experiment import Experiment
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
@@ -191,27 +187,3 @@ def team_precompute_skip_reason(
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:
- 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,
- )
diff --git a/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py b/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py
index 8ec20148dcb5..1414c44b2df1 100644
--- a/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py
+++ b/products/experiments/backend/hogql_queries/test/test_precomputation_gate.py
@@ -8,14 +8,19 @@ from parameterized import parameterized
from posthog.schema import EventsNode, ExperimentMeanMetric, ExperimentQuery, PrecomputationMode
+from posthog.models.team.extensions import get_or_create_team_extension
+
from products.cohorts.backend.models.cohort import Cohort
+from products.experiments.backend.facade.enums import PrecomputeSkipReason
from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
+from products.experiments.backend.hogql_queries.exposures_precompute import ExposuresPrecompute
from products.experiments.backend.hogql_queries.precompute_policy import (
MIN_PRECOMPUTATION_DURATION_SECONDS,
experiment_has_min_runtime_for_precomputation,
has_uncalculated_cohorts,
)
from products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
+from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
class TestPrecomputationDurationGate:
@@ -43,72 +48,6 @@ class TestPrecomputationDurationGate:
assert experiment_has_min_runtime_for_precomputation(start_date, end_date) is expected
-@override_settings(IN_UNIT_TESTING=True)
-class TestShouldPrecomputeRespectsGate(ExperimentQueryRunnerBaseTest):
- def _build_runner(self, experiment, precomputation_mode: PrecomputationMode | None = None) -> ExperimentQueryRunner:
- metric = ExperimentMeanMetric(source=EventsNode(event="purchase"))
- kwargs = {"experiment_id": experiment.id, "kind": "ExperimentQuery", "metric": metric}
- if precomputation_mode is not None:
- kwargs["precomputation_mode"] = precomputation_mode
- query = ExperimentQuery(**kwargs)
- return ExperimentQueryRunner(query=query, team=self.team)
-
- @time_machine.travel("2026-04-30T12:00:00Z", tick=False)
- def test_team_default_skips_when_under_threshold(self):
- feature_flag = self.create_feature_flag()
- experiment = self.create_experiment(
- feature_flag=feature_flag,
- start_date=datetime(2026, 4, 30, 6, 0, 0), # 6h before frozen now
- )
- self._enable_precomputation()
- runner = self._build_runner(experiment)
- assert runner._should_precompute() is False
-
- @time_machine.travel("2026-04-30T12:00:00Z", tick=False)
- def test_team_default_enables_when_over_threshold(self):
- feature_flag = self.create_feature_flag()
- experiment = self.create_experiment(
- feature_flag=feature_flag,
- start_date=datetime(2026, 4, 29, 0, 0, 0), # 36h before frozen now
- )
- self._enable_precomputation()
- runner = self._build_runner(experiment)
- assert runner._should_precompute() is True
-
- @time_machine.travel("2026-04-30T12:00:00Z", tick=False)
- def test_explicit_precomputed_mode_bypasses_gate(self):
- feature_flag = self.create_feature_flag()
- experiment = self.create_experiment(
- feature_flag=feature_flag,
- start_date=datetime(2026, 4, 30, 11, 0, 0), # 1h before frozen now — under threshold
- )
- self._enable_precomputation()
- runner = self._build_runner(experiment, precomputation_mode=PrecomputationMode.PRECOMPUTED)
- assert runner._should_precompute() is True
-
- @time_machine.travel("2026-04-30T12:00:00Z", tick=False)
- def test_explicit_direct_mode_overrides_passing_gate(self):
- feature_flag = self.create_feature_flag()
- experiment = self.create_experiment(
- feature_flag=feature_flag,
- start_date=datetime(2026, 4, 28, 0, 0, 0), # well over threshold
- )
- self._enable_precomputation()
- runner = self._build_runner(experiment, precomputation_mode=PrecomputationMode.DIRECT)
- assert runner._should_precompute() is False
-
- @time_machine.travel("2026-04-30T12:00:00Z", tick=False)
- def test_team_disabled_skips_regardless_of_gate(self):
- feature_flag = self.create_feature_flag()
- experiment = self.create_experiment(
- feature_flag=feature_flag,
- start_date=datetime(2026, 4, 28, 0, 0, 0), # well over threshold
- )
- self._disable_precomputation()
- runner = self._build_runner(experiment)
- assert runner._should_precompute() is False
-
-
def _cohort_exposure_criteria(cohort_id: int) -> dict:
return {
"exposure_config": {
@@ -155,7 +94,7 @@ class TestUncalculatedCohortGate(ExperimentQueryRunnerBaseTest):
assert has_uncalculated_cohorts(self.team, metric) is True
@time_machine.travel("2026-04-30T12:00:00Z", tick=False)
- def test_should_precompute_waits_for_first_cohort_calculation(self):
+ def test_exposures_precompute_waits_for_first_cohort_calculation(self):
feature_flag = self.create_feature_flag()
experiment = self.create_experiment(
feature_flag=feature_flag,
@@ -169,9 +108,176 @@ class TestUncalculatedCohortGate(ExperimentQueryRunnerBaseTest):
metric = ExperimentMeanMetric(source=EventsNode(event="purchase"))
query = ExperimentQuery(experiment_id=experiment.id, kind="ExperimentQuery", metric=metric)
runner = ExperimentQueryRunner(query=query, team=self.team)
- assert runner._should_precompute() is False
+ assert runner._exposures_precompute_applicable() is False
assert runner._precompute_skip_reason() == "cohort_not_calculated"
Cohort.objects.filter(pk=cohort.pk).update(version=1, is_calculating=False)
- assert runner._should_precompute() is True
+ assert runner._exposures_precompute_applicable() is True
assert runner._precompute_skip_reason() is None
+
+
+ACTIVATION_CRITERIA = {
+ "activation_config": {"kind": "ExperimentEventExposureConfig", "event": "activated", "properties": []},
+}
+
+OLD_ENOUGH = datetime(2026, 4, 29, 0, 0, 0)
+TOO_YOUNG = datetime(2026, 4, 30, 6, 0, 0)
+
+
+@override_settings(IN_UNIT_TESTING=True)
+@time_machine.travel("2026-04-30T12:00:00Z", tick=False)
+class TestExposuresPrecompute(ExperimentQueryRunnerBaseTest):
+ @parameterized.expand(
+ [
+ # name, start_date, team_enabled, criteria, mode, is_data_warehouse_query, group_type_index, reason, applicable
+ ("eligible", OLD_ENOUGH, True, "none", None, False, None, None, True),
+ (
+ "precomputed_mode_skips_gates",
+ TOO_YOUNG,
+ False,
+ "none",
+ PrecomputationMode.PRECOMPUTED,
+ False,
+ None,
+ None,
+ True,
+ ),
+ (
+ "direct_mode",
+ OLD_ENOUGH,
+ True,
+ "none",
+ PrecomputationMode.DIRECT,
+ False,
+ None,
+ PrecomputeSkipReason.OVERRIDE_DIRECT,
+ False,
+ ),
+ ("team_disabled", OLD_ENOUGH, False, "none", None, False, None, PrecomputeSkipReason.TEAM_DISABLED, False),
+ ("below_min_runtime", TOO_YOUNG, True, "none", None, False, None, PrecomputeSkipReason.MIN_RUNTIME, False),
+ (
+ "activation_exposures",
+ OLD_ENOUGH,
+ True,
+ "activation",
+ None,
+ False,
+ None,
+ PrecomputeSkipReason.ACTIVATION_CONFIG,
+ False,
+ ),
+ (
+ "uncalculated_cohort",
+ OLD_ENOUGH,
+ True,
+ "uncalculated_cohort",
+ None,
+ False,
+ None,
+ PrecomputeSkipReason.COHORT_NOT_CALCULATED,
+ False,
+ ),
+ ("data_warehouse", OLD_ENOUGH, True, "none", None, True, None, PrecomputeSkipReason.DATA_WAREHOUSE, False),
+ (
+ "group_aggregation",
+ OLD_ENOUGH,
+ True,
+ "none",
+ None,
+ False,
+ 0,
+ PrecomputeSkipReason.GROUP_AGGREGATION,
+ False,
+ ),
+ (
+ "precomputed_mode_with_data_warehouse",
+ OLD_ENOUGH,
+ True,
+ "none",
+ PrecomputationMode.PRECOMPUTED,
+ True,
+ None,
+ None,
+ False,
+ ),
+ (
+ "precomputed_mode_with_group",
+ OLD_ENOUGH,
+ True,
+ "none",
+ PrecomputationMode.PRECOMPUTED,
+ False,
+ 0,
+ None,
+ False,
+ ),
+ ]
+ )
+ def test_decisions(
+ self,
+ _name: str,
+ start_date: datetime,
+ team_enabled: bool,
+ criteria: str,
+ mode: PrecomputationMode | None,
+ is_data_warehouse_query: bool,
+ group_type_index: int | None,
+ expected_reason: PrecomputeSkipReason | None,
+ expected_applicable: bool,
+ ) -> None:
+ experiment = self.create_experiment(feature_flag=self.create_feature_flag(), start_date=start_date)
+ if criteria == "activation":
+ experiment.exposure_criteria = ACTIVATION_CRITERIA
+ elif criteria == "uncalculated_cohort":
+ cohort = Cohort.objects.create(team=self.team, name="fresh cohort", is_calculating=True)
+ experiment.exposure_criteria = _cohort_exposure_criteria(cohort.pk)
+ if team_enabled:
+ self._enable_precomputation()
+ else:
+ self._disable_precomputation()
+
+ precompute = ExposuresPrecompute(
+ team=self.team,
+ team_experiments_config=get_or_create_team_extension(self.team, TeamExperimentsConfig),
+ experiment=experiment,
+ window_start=experiment.start_date,
+ window_end=datetime(2026, 4, 30, 12, 0, 0, tzinfo=UTC),
+ exposure_criteria=experiment.exposure_criteria,
+ cohort_filter_sources=(),
+ precomputation_mode=mode,
+ is_data_warehouse_query=is_data_warehouse_query,
+ group_type_index=group_type_index,
+ )
+
+ assert precompute.ineligibility_reason() == expected_reason
+ assert precompute.applicable is expected_applicable
+
+ @parameterized.expand(
+ [
+ ("precomputed_mode_passes_through", TOO_YOUNG, PrecomputationMode.PRECOMPUTED, False, None, True),
+ ("metric_cohorts_are_checked", OLD_ENOUGH, None, True, PrecomputeSkipReason.COHORT_NOT_CALCULATED, False),
+ ]
+ )
+ def test_query_runner_wiring(
+ self,
+ _name: str,
+ start_date: datetime,
+ mode: PrecomputationMode | None,
+ metric_has_uncalculated_cohort: bool,
+ expected_reason: PrecomputeSkipReason | None,
+ expected_applicable: bool,
+ ) -> None:
+ experiment = self.create_experiment(feature_flag=self.create_feature_flag(), start_date=start_date)
+ self._enable_precomputation()
+ properties = []
+ if metric_has_uncalculated_cohort:
+ cohort = Cohort.objects.create(team=self.team, name="fresh cohort", is_calculating=True)
+ properties = [{"key": "id", "type": "cohort", "value": cohort.pk}]
+ metric = ExperimentMeanMetric(source=EventsNode(event="purchase", properties=properties))
+ query = ExperimentQuery(
+ experiment_id=experiment.id, kind="ExperimentQuery", metric=metric, precomputation_mode=mode
+ )
+ runner = ExperimentQueryRunner(query=query, team=self.team)
+
+ assert runner._precompute_skip_reason() == expected_reason
+ assert runner._exposures_precompute_applicable() is expected_applicable