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): extract metric-events precompute from the query runner (#116755)

Juraj Majerik8509209cc06f
diff --git a/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md b/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md
index 8c11e2a56b1e..7b4879a289a6 100644
--- a/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md
+++ b/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md
@@ -219,7 +219,8 @@ Retention stores one row per event matching the start or completion predicate, w
| ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `experiment_funnel_query_builder.py` | `get_funnel_metric_events_query_for_precomputation()` (write), precomputed CTE in `build_funnel_query_legacy()` (read) |
| `metric_source_precompute.py` | Per-source build query and precomputed read CTE shared by mean metrics and both ratio sides |
-| `experiment_query_runner.py` | `_ensure_metric_events_precomputed()`, wiring in `_get_experiment_query()` |
+| `metric_events_precompute.py` | `MetricEventsPrecompute`: eligibility per metric type, the ratio kill switch, and the builds that fill the table |
+| `experiment_query_runner.py` | Wiring in `_get_experiment_query()`: builds, then reads precomputed or direct |
| `lazy_computation_executor.py` | Core lazy computation: `ensure_precomputed()`, job management |
| `experiment_metric_events_sql.py` | ClickHouse table definition |
| `experiment_metric_events_preaggregated.py` | HogQL schema for the table |
diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.py
index 38701991ab13..9bafe329dee7 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py
@@ -8,15 +8,11 @@ import posthoganalytics
from rest_framework.exceptions import ValidationError
from posthog.schema import (
- ActionsNode,
CachedExperimentQueryResponse,
- EventsNode,
ExperimentActorsQuery,
ExperimentBreakdownResult,
- ExperimentDataWarehouseNode,
ExperimentFunnelMetric,
ExperimentMeanMetric,
- ExperimentMetricMathType,
ExperimentQuery,
ExperimentQueryResponse,
ExperimentRatioMetric,
@@ -33,29 +29,17 @@ from posthog.hogql.modifiers import create_default_modifiers_for_team
from posthog.hogql.query import execute_hogql_query
from posthog.clickhouse.query_tagging import Product, tag_queries, tags_context
-from posthog.constants import EXPERIMENTS_RATIO_METRIC_EVENTS_PREAGGREGATION_FEATURE_FLAG_KEY
-from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
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.hogql_queries import MULTIPLE_VARIANT_KEY, get_baseline_variant_key
-from products.experiments.backend.hogql_queries.base_query_utils import (
- conversion_window_to_seconds,
- experiment_window,
- experiment_window_end,
- is_session_property_metric,
-)
+from products.experiments.backend.hogql_queries.base_query_utils import experiment_window, experiment_window_end
from products.experiments.backend.hogql_queries.cuped_config import get_cuped_config
from products.experiments.backend.hogql_queries.error_handling import experiment_error_handler
from products.experiments.backend.hogql_queries.experiment_actors_query import build_experiment_actors_query
-from products.experiments.backend.hogql_queries.experiment_metric_values import get_conversion_window_seconds
from products.experiments.backend.hogql_queries.experiment_query_builder import (
ExperimentQueryBuilder,
get_exposure_config_params_for_builder,
@@ -65,11 +49,13 @@ 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.metric_events_precompute import (
+ MetricEventsPrecompute,
+ RatioPrecomputeResults,
+)
from products.experiments.backend.hogql_queries.precompute_policy import (
BLOCKING_PRECOMPUTE_SKIP_REASONS,
- METRIC_EVENTS_MAX_WINDOW_EXTENSION_SECONDS,
ensure_exposures_precomputed,
- experiment_precompute_ttl_schedule,
team_precompute_skip_reason,
)
from products.experiments.backend.hogql_queries.types import PrecomputeSkipReason
@@ -93,18 +79,6 @@ MAX_EXECUTION_TIME = 600
MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY = 37 * 1024 * 1024 * 1024 # 37 GB
-@frozen
-class RatioPrecomputeResults:
- """The metric-events build result of each ratio side."""
-
- numerator: LazyComputationResult
- denominator: LazyComputationResult
-
- @property
- def ready(self) -> bool:
- return self.numerator.ready and self.denominator.ready
-
-
class ExperimentResultsCacheMixin:
"""24-hour result cache, shared by the experiment query runners."""
@@ -235,53 +209,24 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
experiment_window_end(self.experiment, self.as_of),
)
- def _ensure_metric_events_precomputed(self, builder: ExperimentQueryBuilder) -> LazyComputationResult:
- """
- Ensures lazy-computed metric event data exists for this experiment.
-
- Stores one row per matching event in the experiment_metric_events_preaggregated
- table: funnel metrics store step indicators, mean metrics the per-event value.
- """
- query_string, placeholders = builder.get_metric_events_query_for_precomputation()
- return self._ensure_metric_events_build(builder, query_string, placeholders)
-
- def _ensure_ratio_metric_events_precomputed(self, builder: ExperimentQueryBuilder) -> RatioPrecomputeResults:
- """One build per side. Each side is a mean-shaped build of its source."""
- queries = builder.get_ratio_metric_events_queries_for_precomputation()
- return RatioPrecomputeResults(
- numerator=self._ensure_metric_events_build(builder, *queries.numerator),
- denominator=self._ensure_metric_events_build(builder, *queries.denominator),
+ @cached_property
+ def _metric_events_precompute(self) -> MetricEventsPrecompute:
+ return MetricEventsPrecompute(
+ team=self.team,
+ experiment=self.experiment,
+ as_of=self.as_of,
+ metric=self.metric,
+ group_type_index=self.group_type_index,
+ has_breakdowns=bool(self._get_breakdowns_for_builder()),
+ cuped_enabled=self.cuped_config.enabled,
+ is_data_warehouse_query=self.is_data_warehouse_query,
)
- def _ensure_metric_events_build(
- self, builder: ExperimentQueryBuilder, query_string: str, placeholders: dict[str, ast.Expr]
- ) -> LazyComputationResult:
- 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)
-
- # Extend the time range past the experiment end, because metric events can occur after
- # it: within the conversion window, and for retention also within the retention window
- # (a completion can land up to retention_window_end after a start event, which itself
- # can land up to conversion_window after the last exposure).
- extension_seconds = builder.get_metric_events_window_extension_seconds()
- if extension_seconds > 0:
- date_to = date_to + timedelta(seconds=extension_seconds)
+ def _ensure_metric_events_precomputed(self, builder: ExperimentQueryBuilder) -> LazyComputationResult:
+ return self._metric_events_precompute.ensure_precomputed(builder)
- 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_METRIC_EVENTS_PREAGGREGATED,
- placeholders=placeholders,
- sentinel_placeholders={"experiment_date_to"},
- end_is_data_horizon=True,
- spill_to_disk=True,
- )
+ def _ensure_ratio_metric_events_precomputed(self, builder: ExperimentQueryBuilder) -> RatioPrecomputeResults:
+ return self._metric_events_precompute.ensure_ratio_precomputed(builder)
@cached_property
def _team_experiments_config(self) -> TeamExperimentsConfig:
@@ -314,108 +259,10 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
return None # precompute was attempted; a direct path means the build failed / wasn't ready
def _metric_events_precompute_applicable(self) -> bool:
- return self._metric_events_ineligibility_reason() is None
+ return self._metric_events_precompute.applicable
def _metric_events_ineligibility_reason(self) -> Optional[str]:
- """
- Why metric-events precompute cannot serve this metric, or None when it can.
- Supported: ordered funnels, mean metrics with numeric math (count/sum/avg/min/max)
- or ID-valued math (unique users / unique sessions), ratio metrics whose two sides
- each pass the mean rules, and retention metrics, in all cases without breakdowns,
- CUPED, or data warehouse sources.
-
- Tagged on the read as `experiment_metric_events_skip_reason`, the metric-events
- counterpart of `experiment_precompute_skip_reason`, so query-log analysis can split
- the not_applicable path by cause. Values are part of that reporting contract.
- """
- if self._get_breakdowns_for_builder():
- return "breakdown"
- # CUPED extends the metric scan back by lookback_days for the pre-exposure covariate,
- # but the precomputed metric_events table covers only the experiment window.
- if self.cuped_config.enabled:
- return "cuped"
- if self.is_data_warehouse_query:
- return "data_warehouse"
- if isinstance(self.metric, ExperimentFunnelMetric):
- if (self.metric.funnel_order_type or "ordered") == "ordered":
- return None
- return "funnel_order_type"
- if isinstance(self.metric, ExperimentMeanMetric):
- return self._metric_source_ineligibility_reason(self.metric.source)
- if isinstance(self.metric, ExperimentRatioMetric):
- if not self._ratio_metric_events_precomputation_enabled():
- return "ratio_flag_off"
- # Each side is built and read like a mean metric on that source, so the
- # per-source rules apply to both.
- return self._metric_source_ineligibility_reason(
- self.metric.numerator
- ) or self._metric_source_ineligibility_reason(self.metric.denominator)
- if isinstance(self.metric, ExperimentRetentionMetric):
- if not isinstance(self.metric.start_event, (EventsNode, ActionsNode)) or not isinstance(
- self.metric.completion_event, (EventsNode, ActionsNode)
- ):
- return "non_event_source"
- extension_seconds = get_conversion_window_seconds(self.metric) + conversion_window_to_seconds(
- self.metric.retention_window_end, self.metric.retention_window_unit
- )
- if extension_seconds <= METRIC_EVENTS_MAX_WINDOW_EXTENSION_SECONDS:
- return None
- return "retention_window"
-
- def _metric_source_ineligibility_reason(
- self, source: EventsNode | ActionsNode | ExperimentDataWarehouseNode
- ) -> Optional[str]:
- """The per-source rules for a mean-shaped build: a mean metric's source or either ratio side."""
- if not isinstance(source, (EventsNode, ActionsNode)):
- return "non_event_source"
- # Session-property means aggregate via a per-session dedup CTE that the
- # precomputed table can't feed. Unique-group math is excluded because
- # the build INSERT can't resolve $group_N (MATERIALIZED on
- # sharded_events), and HogQL math because user expressions are arbitrary.
- if is_session_property_metric(source):
- return "session_property_math"
- math_type = getattr(source, "math", None) or ExperimentMetricMathType.TOTAL
- # Numeric math types are safe because the build query stores the same
- # coalesced per-event float regardless of math type, and the math is
- # applied at read time by build_value_aggregation_expr on both paths.
- if math_type in (
- ExperimentMetricMathType.TOTAL,
- ExperimentMetricMathType.SUM,
- ExperimentMetricMathType.AVG,
- ExperimentMetricMathType.MIN,
- ExperimentMetricMathType.MAX,
- ):
- return None
- # unique_session counts distinct session_id, which every mean build stores.
- if math_type == ExperimentMetricMathType.UNIQUE_SESSION:
- return None
- # dau counts distinct entity_id, which is the person id only when the
- # experiment is person-keyed. Group experiments never reach precompute,
- # but keep the guard explicit in case that exclusion is ever lifted.
- if math_type == ExperimentMetricMathType.DAU:
- return None if self.group_type_index is None else "group_math"
- return "unsupported_math"
-
- def _ratio_metric_events_precomputation_enabled(self) -> bool:
- """
- Kill switch for ratio metric-events precomputation, independent of the other
- metric types. Default-off and fail-safe: an absent or unevaluable flag keeps ratio
- metric events on the direct scan while exposures and the other types keep their
- precomputed tables.
- """
- return bool(
- posthoganalytics.feature_enabled(
- EXPERIMENTS_RATIO_METRIC_EVENTS_PREAGGREGATION_FEATURE_FLAG_KEY,
- str(self.team.uuid),
- groups={"organization": str(self.team.organization_id), "project": str(self.team.id)},
- group_properties={
- "organization": {"id": str(self.team.organization_id)},
- "project": {"id": str(self.team.id), "uuid": str(self.team.uuid)},
- },
- only_evaluate_locally=True,
- send_feature_flag_events=False,
- )
- )
+ return self._metric_events_precompute.ineligibility_reason()
@property
def metric_events_path(self) -> str:
diff --git a/products/experiments/backend/hogql_queries/metric_events_precompute.py b/products/experiments/backend/hogql_queries/metric_events_precompute.py
new file mode 100644
index 000000000000..a39d44565080
--- /dev/null
+++ b/products/experiments/backend/hogql_queries/metric_events_precompute.py
@@ -0,0 +1,227 @@
+"""
+Metric-events precomputation for one experiment query: whether the metric can read
+from experiment_metric_events_preaggregated, and the lazy-computation builds that fill it.
+
+The per-source build query and read CTE live in metric_source_precompute; this module
+decides when they apply and runs the builds.
+"""
+
+from datetime import datetime, timedelta
+from typing import Optional
+
+import posthoganalytics
+from rest_framework.exceptions import ValidationError
+
+from posthog.schema import (
+ ActionsNode,
+ EventsNode,
+ ExperimentDataWarehouseNode,
+ ExperimentFunnelMetric,
+ ExperimentMeanMetric,
+ ExperimentMetricMathType,
+ ExperimentRatioMetric,
+ ExperimentRetentionMetric,
+)
+
+from posthog.hogql import ast
+
+from posthog.constants import EXPERIMENTS_RATIO_METRIC_EVENTS_PREAGGREGATION_FEATURE_FLAG_KEY
+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.hogql_queries.base_query_utils import (
+ conversion_window_to_seconds,
+ experiment_window_end,
+ is_session_property_metric,
+)
+from products.experiments.backend.hogql_queries.experiment_metric_values import get_conversion_window_seconds
+from products.experiments.backend.hogql_queries.experiment_query_builder import ExperimentQueryBuilder
+from products.experiments.backend.hogql_queries.precompute_policy import (
+ METRIC_EVENTS_MAX_WINDOW_EXTENSION_SECONDS,
+ experiment_precompute_ttl_schedule,
+)
+from products.experiments.backend.models.experiment import Experiment
+
+
+@frozen
+class RatioPrecomputeResults:
+ """The metric-events build result of each ratio side."""
+
+ numerator: LazyComputationResult
+ denominator: LazyComputationResult
+
+ @property
+ def ready(self) -> bool:
+ return self.numerator.ready and self.denominator.ready
+
+
+@frozen
+class MetricEventsPrecompute:
+ """The metric-events precompute decisions and builds for one experiment query."""
+
+ team: Team
+ experiment: Experiment
+ as_of: datetime
+ metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric
+ group_type_index: Optional[int]
+ has_breakdowns: bool
+ cuped_enabled: bool
+ is_data_warehouse_query: bool
+
+ def ensure_precomputed(self, builder: ExperimentQueryBuilder) -> LazyComputationResult:
+ """
+ Ensures lazy-computed metric event data exists for this experiment.
+
+ Stores one row per matching event in the experiment_metric_events_preaggregated
+ table: funnel metrics store step indicators, mean metrics the per-event value.
+ """
+ query_string, placeholders = builder.get_metric_events_query_for_precomputation()
+ return self._ensure_build(builder, query_string, placeholders)
+
+ def ensure_ratio_precomputed(self, builder: ExperimentQueryBuilder) -> RatioPrecomputeResults:
+ """One build per side. Each side is a mean-shaped build of its source."""
+ queries = builder.get_ratio_metric_events_queries_for_precomputation()
+ return RatioPrecomputeResults(
+ numerator=self._ensure_build(builder, *queries.numerator),
+ denominator=self._ensure_build(builder, *queries.denominator),
+ )
+
+ def _ensure_build(
+ self, builder: ExperimentQueryBuilder, query_string: str, placeholders: dict[str, ast.Expr]
+ ) -> LazyComputationResult:
+ 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)
+
+ # Extend the time range past the experiment end, because metric events can occur after
+ # it: within the conversion window, and for retention also within the retention window
+ # (a completion can land up to retention_window_end after a start event, which itself
+ # can land up to conversion_window after the last exposure).
+ extension_seconds = builder.get_metric_events_window_extension_seconds()
+ if extension_seconds > 0:
+ date_to = date_to + timedelta(seconds=extension_seconds)
+
+ 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_METRIC_EVENTS_PREAGGREGATED,
+ placeholders=placeholders,
+ sentinel_placeholders={"experiment_date_to"},
+ end_is_data_horizon=True,
+ spill_to_disk=True,
+ )
+
+ @property
+ def applicable(self) -> bool:
+ return self.ineligibility_reason() is None
+
+ def ineligibility_reason(self) -> Optional[str]:
+ """
+ Why metric-events precompute cannot serve this metric, or None when it can.
+ Supported: ordered funnels, mean metrics with numeric math (count/sum/avg/min/max)
+ or ID-valued math (unique users / unique sessions), ratio metrics whose two sides
+ each pass the mean rules, and retention metrics, in all cases without breakdowns,
+ CUPED, or data warehouse sources.
+
+ Tagged on the read as `experiment_metric_events_skip_reason`, the metric-events
+ counterpart of `experiment_precompute_skip_reason`, so query-log analysis can split
+ the not_applicable path by cause. Values are part of that reporting contract.
+ """
+ if self.has_breakdowns:
+ return "breakdown"
+ # CUPED extends the metric scan back by lookback_days for the pre-exposure covariate,
+ # but the precomputed metric_events table covers only the experiment window.
+ if self.cuped_enabled:
+ return "cuped"
+ if self.is_data_warehouse_query:
+ return "data_warehouse"
+ if isinstance(self.metric, ExperimentFunnelMetric):
+ if (self.metric.funnel_order_type or "ordered") == "ordered":
+ return None
+ return "funnel_order_type"
+ if isinstance(self.metric, ExperimentMeanMetric):
+ return self._source_ineligibility_reason(self.metric.source)
+ if isinstance(self.metric, ExperimentRatioMetric):
+ if not self.ratio_flag_enabled():
+ return "ratio_flag_off"
+ # Each side is built and read like a mean metric on that source, so the
+ # per-source rules apply to both.
+ return self._source_ineligibility_reason(self.metric.numerator) or self._source_ineligibility_reason(
+ self.metric.denominator
+ )
+ if isinstance(self.metric, ExperimentRetentionMetric):
+ if not isinstance(self.metric.start_event, (EventsNode, ActionsNode)) or not isinstance(
+ self.metric.completion_event, (EventsNode, ActionsNode)
+ ):
+ return "non_event_source"
+ extension_seconds = get_conversion_window_seconds(self.metric) + conversion_window_to_seconds(
+ self.metric.retention_window_end, self.metric.retention_window_unit
+ )
+ if extension_seconds <= METRIC_EVENTS_MAX_WINDOW_EXTENSION_SECONDS:
+ return None
+ return "retention_window"
+
+ def _source_ineligibility_reason(
+ self, source: EventsNode | ActionsNode | ExperimentDataWarehouseNode
+ ) -> Optional[str]:
+ """The per-source rules for a mean-shaped build: a mean metric's source or either ratio side."""
+ if not isinstance(source, (EventsNode, ActionsNode)):
+ return "non_event_source"
+ # Session-property means aggregate via a per-session dedup CTE that the
+ # precomputed table can't feed. Unique-group math is excluded because
+ # the build INSERT can't resolve $group_N (MATERIALIZED on
+ # sharded_events), and HogQL math because user expressions are arbitrary.
+ if is_session_property_metric(source):
+ return "session_property_math"
+ math_type = getattr(source, "math", None) or ExperimentMetricMathType.TOTAL
+ # Numeric math types are safe because the build query stores the same
+ # coalesced per-event float regardless of math type, and the math is
+ # applied at read time by build_value_aggregation_expr on both paths.
+ if math_type in (
+ ExperimentMetricMathType.TOTAL,
+ ExperimentMetricMathType.SUM,
+ ExperimentMetricMathType.AVG,
+ ExperimentMetricMathType.MIN,
+ ExperimentMetricMathType.MAX,
+ ):
+ return None
+ # unique_session counts distinct session_id, which every mean build stores.
+ if math_type == ExperimentMetricMathType.UNIQUE_SESSION:
+ return None
+ # dau counts distinct entity_id, which is the person id only when the
+ # experiment is person-keyed. Group experiments never reach precompute,
+ # but keep the guard explicit in case that exclusion is ever lifted.
+ if math_type == ExperimentMetricMathType.DAU:
+ return None if self.group_type_index is None else "group_math"
+ return "unsupported_math"
+
+ def ratio_flag_enabled(self) -> bool:
+ """
+ Kill switch for ratio metric-events precomputation, independent of the other
+ metric types. Default-off and fail-safe: an absent or unevaluable flag keeps ratio
+ metric events on the direct scan while exposures and the other types keep their
+ precomputed tables.
+ """
+ return bool(
+ posthoganalytics.feature_enabled(
+ EXPERIMENTS_RATIO_METRIC_EVENTS_PREAGGREGATION_FEATURE_FLAG_KEY,
+ str(self.team.uuid),
+ groups={"organization": str(self.team.organization_id), "project": str(self.team.id)},
+ group_properties={
+ "organization": {"id": str(self.team.organization_id)},
+ "project": {"id": str(self.team.id), "uuid": str(self.team.uuid)},
+ },
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ )
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/base.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/base.py
index 44e4047ea006..59dd308451be 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/base.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/base.py
@@ -21,7 +21,7 @@ from posthog.models.team.extensions import get_or_create_team_extension
from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob
from products.data_tools.backend.models.join import DataWarehouseJoin
-from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
+from products.experiments.backend.hogql_queries.metric_events_precompute import MetricEventsPrecompute
from products.experiments.backend.hogql_queries.precompute_policy import MIN_PRECOMPUTATION_DURATION_SECONDS
from products.experiments.backend.models.experiment import Experiment
from products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig
@@ -94,9 +94,7 @@ class ExperimentQueryRunnerBaseTest(ClickhouseTestMixin, APIBaseTest):
# Ratio metric-events precomputation has an additional default-off kill-switch
# flag; force it on so tests still exercise the precomputed metric-events path.
if not getattr(self, "_ratio_metric_events_precompute_patched", False):
- patcher = patch.object(
- ExperimentQueryRunner, "_ratio_metric_events_precomputation_enabled", return_value=True
- )
+ patcher = patch.object(MetricEventsPrecompute, "ratio_flag_enabled", return_value=True)
patcher.start()
self.addCleanup(patcher.stop)
self._ratio_metric_events_precompute_patched = True
diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_ratio_metric_events_preaggregation.py b/products/experiments/backend/hogql_queries/test/test_experiment_ratio_metric_events_preaggregation.py
index 6e6c69caabc1..ee5b060a8e9c 100644
--- a/products/experiments/backend/hogql_queries/test/test_experiment_ratio_metric_events_preaggregation.py
+++ b/products/experiments/backend/hogql_queries/test/test_experiment_ratio_metric_events_preaggregation.py
@@ -24,6 +24,7 @@ from products.experiments.backend.hogql_queries.experiment_query_builder import
)
from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
from products.experiments.backend.hogql_queries.exposure_query_logic import get_entity_key
+from products.experiments.backend.hogql_queries.metric_events_precompute import MetricEventsPrecompute
from products.experiments.backend.hogql_queries.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
PURCHASE_SUM = EventsNode(event="purchase", math=ExperimentMetricMathType.SUM, math_property="amount")
@@ -114,8 +115,6 @@ class TestExperimentRatioMetricEventsPreaggregation(ExperimentQueryRunnerBaseTes
)
runner = self._build_runner(experiment, ExperimentRatioMetric(numerator=numerator, denominator=denominator))
- with patch.object(
- ExperimentQueryRunner, "_ratio_metric_events_precomputation_enabled", return_value=flag_enabled
- ):
+ with patch.object(MetricEventsPrecompute, "ratio_flag_enabled", return_value=flag_enabled):
assert runner._metric_events_ineligibility_reason() == skip_reason
assert runner._metric_events_precompute_applicable() is (skip_reason is None)