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.

feat(experiments): precompute metric events for ratio metrics (#115871)

Juraj Majerikc2cd5c6467db
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index e6c521b38e22..ac7af773d1ca 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -516,8 +516,8 @@ class QueryTags(BaseModel):
experiment_metric_events_path: Optional[str] = None # "direct_scan", "precomputed", or "not_applicable"
# Why the metric-events side is not precomputable (set on the metric read when metric_events_path is
# "not_applicable"): "breakdown", "cuped", "data_warehouse", "funnel_order_type", "non_event_source",
- # "session_property_math", "group_math", "unsupported_math", "retention_window", or "metric_type"
- # (ratio). None/absent when the metric-events side is precomputable.
+ # "session_property_math", "group_math", "unsupported_math", "retention_window", or "ratio_flag_off".
+ # None/absent when the metric-events side is precomputable.
experiment_metric_events_skip_reason: Optional[str] = None
experiment_query_surface: Optional[str] = None # "metric", "exposures_timeseries", "actors", "precompute_build"
experiment_precompute_table: Optional[str] = None # on precompute_build rows: "exposures" or "metric_events"
diff --git a/posthog/constants.py b/posthog/constants.py
index b4900df1349f..f6ec39e9a46a 100644
--- a/posthog/constants.py
+++ b/posthog/constants.py
@@ -323,6 +323,7 @@ SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEY = "ai-subscriptions"
# Enable only after every subscriptions worker has deployed the gallery claim boundary. Older workers
# share the v2 activity name and would otherwise send the legacy layout during a rolling deployment.
SUBSCRIPTION_SLACK_GALLERY_FEATURE_FLAG_KEY = "subscription-slack-gallery"
+EXPERIMENTS_RATIO_METRIC_EVENTS_PREAGGREGATION_FEATURE_FLAG_KEY = "experiments-ratio-metric-events-preaggregation"
GENERATED_DASHBOARD_PREFIX = "Generated Dashboard"
ENRICHED_DASHBOARD_INSIGHT_IDENTIFIER = "Feature Viewed"
diff --git a/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md b/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md
index 2b2ba43b832d..8c11e2a56b1e 100644
--- a/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md
+++ b/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md
@@ -209,7 +209,7 @@ The exposure precomputation does NOT need this extension — exposures only occu
## Scope
-Implemented for **ordered funnels**, **count/sum/avg/min/max mean metrics** (per-event value stored in `numeric_value`, deduplicated on read by event identity since replayed build rows would double sums and skew averages; the aggregation itself runs at read time, so all five math types store identical rows), **dau/unique_session mean metrics** (the read counts distinct IDs from `entity_id`/`session_id`, which every mean build stores; `numeric_value` holds the same constant a count metric stores, so a count metric and an ID-math metric on the same source share build jobs), and **retention metrics**. Unordered funnels, unique-group and HogQL math, and ratio metrics are not precomputed; breakdowns, CUPED, and data warehouse sources always fall back to a direct scan.
+Implemented for **ordered funnels**, **count/sum/avg/min/max mean metrics** (per-event value stored in `numeric_value`, deduplicated on read by event identity since replayed build rows would double sums and skew averages; the aggregation itself runs at read time, so all five math types store identical rows), **dau/unique_session mean metrics** (the read counts distinct IDs from `entity_id`/`session_id`, which every mean build stores; `numeric_value` holds the same constant a count metric stores, so a count metric and an ID-math metric on the same source share build jobs), **ratio metrics** (one build per side, each the build a mean metric on that source would produce, so a side shares jobs with such a metric; the read serves both sides from the table or neither, and the whole type sits behind the default-off `experiments-ratio-metric-events-preaggregation` kill-switch flag), and **retention metrics**. Unordered funnels and unique-group and HogQL math are not precomputed; breakdowns, CUPED, and data warehouse sources always fall back to a direct scan.
Retention stores one row per event matching the start or completion predicate, with two flags in `steps` (`steps[1]` = matched start_event, `steps[2]` = matched completion_event; one event can match both). The read path swaps the two raw-events CTE sources for flag-filtered reads of the precomputed table; start anchoring (FIRST_SEEN/LAST_SEEN), the per-user retention window, the maturity gate, and the same-event exclusion all stay read-time, so they behave identically on both paths. The scan extension past the experiment end is `conversion_window + retention_window_end` rather than the conversion window alone, capped at 90 days (`METRIC_EVENTS_MAX_WINDOW_EXTENSION_SECONDS`); oversized windows fall back to a direct scan.
@@ -218,6 +218,7 @@ Retention stores one row per event matching the start or completion predicate, w
| File | Purpose |
| ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `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()` |
| `lazy_computation_executor.py` | Core lazy computation: `ensure_precomputed()`, job management |
| `experiment_metric_events_sql.py` | ClickHouse table definition |
diff --git a/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py b/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py
index e2a5233a02df..411002710605 100644
--- a/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py
+++ b/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py
@@ -1,23 +1,21 @@
from typing import TYPE_CHECKING, cast
-from posthog.schema import (
- ActionsNode,
- EventsNode,
- ExperimentDataWarehouseNode,
- ExperimentMeanMetric,
- ExperimentMetricMathType,
-)
+from posthog.schema import ActionsNode, EventsNode, ExperimentDataWarehouseNode, ExperimentMeanMetric
from posthog.hogql import ast
from posthog.hogql.parser import parse_expr, parse_select
from products.experiments.backend.hogql_queries.base_query_utils import (
- event_or_action_to_filter,
is_session_property_metric,
validate_session_property,
)
from products.experiments.backend.hogql_queries.experiment_exposure_query_builder import ExposureQueryBuilder
from products.experiments.backend.hogql_queries.metric_source import MetricSourceInfo
+from products.experiments.backend.hogql_queries.metric_source_precompute import (
+ build_metric_events_precompute_query,
+ build_precomputed_metric_events_cte,
+ build_precomputed_metric_events_placeholders,
+)
if TYPE_CHECKING:
from products.experiments.backend.hogql_queries.experiment_query_builder import ExperimentQueryBuilder
@@ -134,38 +132,13 @@ class MeanQueryBuilder:
# Read from the precomputed table instead of scanning events. Only reachable
# for eligible metrics (no breakdowns/CUPED/DW/session properties), so the
# branches above never coexist with this one.
- # Filter by experiment date range: jobs can cover broader time ranges than
- # the experiment for cache reuse, so the read must filter. The upper
- # bound includes the conversion window since metric events can occur after
- # experiment end, mirroring build_metric_predicate() on the direct path.
- # GROUP BY collapses replayed rows by event identity: ReplacingMergeTree only
- # dedups at merge time and this read doesn't use FINAL, so a re-applied build
- # INSERT would otherwise double-count sums. Same defense as the exposures read;
- # the funnel read skips it because funnel evaluation tolerates duplicate events.
- entity_id_cast = "toUUID(t.entity_id)" if self._b.entity_key == "person_id" else "t.entity_id"
- # For ID-valued math the value is the ID itself: the stored entity_id
- # is the person id (dau) and session_id is the unique_session value,
- # so the downstream count(distinct) matches the direct path.
- math_type = getattr(self._b.metric.source, "math", None) or ExperimentMetricMathType.TOTAL
- if math_type == ExperimentMetricMathType.DAU:
- value_select = entity_id_cast
- elif math_type == ExperimentMetricMathType.UNIQUE_SESSION:
- value_select = "any(t.session_id)"
- else:
- value_select = "any(t.numeric_value)"
- metric_events_cte = f"""
- metric_events AS (
- SELECT
- {entity_id_cast} AS entity_id,
- t.timestamp AS timestamp,
- {value_select} AS value
- FROM experiment_metric_events_preaggregated AS t
- WHERE t.job_id IN {{metric_events_job_ids}}
- AND t.team_id = {{metric_events_team_id}}
- AND t.timestamp >= {{metric_events_date_from}}
- AND t.timestamp < {{metric_events_date_to}} + toIntervalSecond({{metric_events_conversion_window_seconds}})
- GROUP BY t.entity_id, t.timestamp, t.event_uuid
- )"""
+ assert isinstance(self._b.metric.source, (ActionsNode, EventsNode))
+ metric_events_cte = build_precomputed_metric_events_cte(
+ cte_name="metric_events",
+ source=self._b.metric.source,
+ entity_key=self._b.entity_key,
+ job_ids_placeholder="metric_events_job_ids",
+ )
else:
metric_events_cte = """
metric_events AS (
@@ -263,11 +236,12 @@ class MeanQueryBuilder:
if self._metric_events_job_ids:
placeholders["metric_events_job_ids"] = ast.Constant(value=self._metric_events_job_ids)
- placeholders["metric_events_team_id"] = ast.Constant(value=self._b.team.id)
- placeholders["metric_events_date_from"] = self._b.date_range_query.date_from_as_hogql()
- placeholders["metric_events_date_to"] = self._b.date_range_query.date_to_as_hogql()
- placeholders["metric_events_conversion_window_seconds"] = ast.Constant(
- value=self._b._get_conversion_window_seconds()
+ placeholders.update(
+ build_precomputed_metric_events_placeholders(
+ team=self._b.team,
+ date_range_query=self._b.date_range_query,
+ conversion_window_seconds=self._b._get_conversion_window_seconds(),
+ )
)
if source_info.kind == "datawarehouse":
@@ -292,66 +266,18 @@ class MeanQueryBuilder:
}
def get_mean_metric_events_query_for_precomputation(self) -> tuple[str, dict[str, ast.Expr]]:
- """
- Returns the SELECT query that the lazy computation system wraps in an
- INSERT INTO experiment_metric_events_preaggregated. This is the write
- path. It scans the events table and stores one row per matching metric
- event with its per-event value in numeric_value. For numeric math the
- value is already coalesced to a non-null float by _build_value_expr(),
- so storing it in the non-nullable numeric_value column is lossless.
- For ID-valued math (dau, unique_session) the read side counts distinct
- IDs from entity_id/session_id instead, and numeric_value stores the
- same constant a count metric stores, so the build query hashes the same
- as a count metric on the same source and the two share precompute jobs.
-
- The query uses {time_window_min} and {time_window_max} placeholders filled
- by the lazy computation system for each daily bucket. The experiment date
- bounds must stay named placeholders (the caller declares experiment_date_to
- a sentinel) rather than reusing _build_metric_predicate(), which bakes the
- resolved dates into the AST. The window end of a running experiment moves,
- so baked dates would change the job hash and defeat cache reuse.
- """
+ """The write-path SELECT for this metric's source; see build_metric_events_precompute_query()."""
assert isinstance(self._b.metric, ExperimentMeanMetric)
source = self._b.metric.source
assert isinstance(source, (ActionsNode, EventsNode))
- query_string = """
- SELECT
- {entity_key} AS entity_id,
- timestamp AS timestamp,
- uuid AS event_uuid,
- `$session_id` AS session_id,
- {value_expr} AS numeric_value
- FROM events
- WHERE timestamp >= {time_window_min}
- AND timestamp < {time_window_max}
- AND timestamp >= {experiment_date_from}
- AND timestamp < {experiment_date_to} + toIntervalSecond({conversion_window_seconds})
- AND {metric_event_filter}
- """
-
- math_type = getattr(source, "math", None) or ExperimentMetricMathType.TOTAL
- if math_type in (ExperimentMetricMathType.DAU, ExperimentMetricMathType.UNIQUE_SESSION):
- # _build_value_expr() returns the ID itself for these math types, which
- # cannot go into the Float64 column. Build the count-metric expression
- # node for node so repr-based job hashing matches a count metric build.
- value_expr: ast.Expr = ast.Call(
- name="coalesce",
- args=[ast.Call(name="toFloat", args=[ast.Constant(value=1)]), ast.Constant(value=0)],
- )
- else:
- value_expr = self._b._build_value_expr()
-
- placeholders: dict[str, ast.Expr] = {
- "entity_key": parse_expr(self._b.entity_key),
- "value_expr": value_expr,
- "experiment_date_from": self._b.date_range_query.date_from_as_hogql(),
- "experiment_date_to": self._b.date_range_query.date_to_as_hogql(),
- "conversion_window_seconds": ast.Constant(value=self._b._get_conversion_window_seconds()),
- "metric_event_filter": event_or_action_to_filter(self._b.team, source),
- }
-
- return query_string, placeholders
+ return build_metric_events_precompute_query(
+ team=self._b.team,
+ source=source,
+ entity_key=self._b.entity_key,
+ date_range_query=self._b.date_range_query,
+ conversion_window_seconds=self._b._get_conversion_window_seconds(),
+ )
def build_mean_query(self) -> ast.SelectQuery:
assert isinstance(self._b.metric, ExperimentMeanMetric)
diff --git a/products/experiments/backend/hogql_queries/experiment_query_builder.py b/products/experiments/backend/hogql_queries/experiment_query_builder.py
index 11e10801f32f..b25dbcde9942 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_builder.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_builder.py
@@ -45,7 +45,10 @@ from products.experiments.backend.hogql_queries.experiment_query_context import
ExperimentQueryContext,
MaturityGate,
)
-from products.experiments.backend.hogql_queries.experiment_ratio_query_builder import RatioQueryBuilder
+from products.experiments.backend.hogql_queries.experiment_ratio_query_builder import (
+ RatioPrecomputeQueries,
+ RatioQueryBuilder,
+)
from products.experiments.backend.hogql_queries.experiment_retention_query_builder import RetentionQueryBuilder
from products.experiments.backend.hogql_queries.exposure_query_logic import (
DEFAULT_EXPOSURE_EVENT,
@@ -230,7 +233,12 @@ class ExperimentQueryBuilder:
case ExperimentMeanMetric():
query = MeanQueryBuilder(self, exposure, metric_events_job_ids=metric_events_job_ids).build_mean_query()
case ExperimentRatioMetric():
- query = RatioQueryBuilder(self, exposure).build_ratio_query()
+ query = RatioQueryBuilder(
+ self,
+ exposure,
+ numerator_job_ids=job_ids.numerator_job_ids,
+ denominator_job_ids=job_ids.denominator_job_ids,
+ ).build_ratio_query()
case ExperimentRetentionMetric():
query = RetentionQueryBuilder(
self, exposure, maturity=maturity, metric_events_job_ids=metric_events_job_ids
@@ -271,6 +279,10 @@ class ExperimentQueryBuilder:
"""For the precompute write query, which takes no per-build inputs."""
return MeanQueryBuilder(self, self._exposure_query_builder())
+ def _ratio_query_builder(self) -> RatioQueryBuilder:
+ """For the precompute write queries, which take no per-build inputs."""
+ return RatioQueryBuilder(self, self._exposure_query_builder())
+
def _cuped_query_builder(self) -> CupedQueryBuilder:
return CupedQueryBuilder(self)
@@ -437,6 +449,8 @@ class ExperimentQueryBuilder:
type. This is the write path. It scans the events table and stores one
row per matching event: funnel and retention metrics pack step indicators
into an Array(UInt8), mean metrics store the per-event value in numeric_value.
+ A ratio metric needs one build per side; see
+ get_ratio_metric_events_queries_for_precomputation().
The query uses {time_window_min} and {time_window_max} placeholders filled
by the lazy computation system for each daily bucket.
@@ -451,6 +465,10 @@ class ExperimentQueryBuilder:
case _:
raise NotImplementedError(f"Metric-events precomputation is not supported for {type(self.metric)}")
+ def get_ratio_metric_events_queries_for_precomputation(self) -> RatioPrecomputeQueries:
+ """The write-path SELECT of each ratio side."""
+ return self._ratio_query_builder().get_ratio_metric_events_queries_for_precomputation()
+
def get_metric_events_window_extension_seconds(self) -> int:
"""
How far past the experiment end date the metric-events precompute scan must
diff --git a/products/experiments/backend/hogql_queries/experiment_query_context.py b/products/experiments/backend/hogql_queries/experiment_query_context.py
index f129275a1d4f..8bf7032a5964 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_context.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_context.py
@@ -50,7 +50,11 @@ class ExperimentPrecomputationContext:
"""
exposure_job_ids: list[str] | None = None
+ # Funnel, mean and retention metrics have one metric-events build. A ratio
+ # metric has one per side, and each read CTE filters on its own jobs.
metric_events_job_ids: list[str] | None = None
+ numerator_job_ids: list[str] | None = None
+ denominator_job_ids: list[str] | None = None
@frozen
diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.py
index 52e4e99a2eac..38701991ab13 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py
@@ -13,6 +13,7 @@ from posthog.schema import (
EventsNode,
ExperimentActorsQuery,
ExperimentBreakdownResult,
+ ExperimentDataWarehouseNode,
ExperimentFunnelMetric,
ExperimentMeanMetric,
ExperimentMetricMathType,
@@ -32,6 +33,8 @@ 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
@@ -90,6 +93,18 @@ 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."""
@@ -228,7 +243,19 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
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),
+ )
+ 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")
@@ -293,8 +320,9 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
"""
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), and retention metrics, in all
- cases without breakdowns, CUPED, or data warehouse sources.
+ 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
@@ -313,36 +341,15 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
return None
return "funnel_order_type"
if isinstance(self.metric, ExperimentMeanMetric):
- source = self.metric.source
- 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"
+ 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)
@@ -354,7 +361,61 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
if extension_seconds <= METRIC_EVENTS_MAX_WINDOW_EXTENSION_SECONDS:
return None
return "retention_window"
- return "metric_type"
+
+ 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,
+ )
+ )
@property
def metric_events_path(self) -> str:
@@ -397,6 +458,8 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
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.
@@ -430,11 +493,20 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
with tags_context(
experiment_query_surface="precompute_build", experiment_precompute_table="metric_events"
):
- metric_result = self._ensure_metric_events_precomputed(builder)
- if metric_result.ready:
- metric_events_job_ids = [str(job_id) for job_id in metric_result.job_ids]
- self._metric_events_precomputed = True
- else:
+ if isinstance(self.metric, ExperimentRatioMetric):
+ ratio_result = self._ensure_ratio_metric_events_precomputed(builder)
+ # Both sides or neither: a half-served read would report a
+ # metric_events_path that is neither precomputed nor direct_scan.
+ if ratio_result.ready:
+ numerator_job_ids = [str(job_id) for job_id in ratio_result.numerator.job_ids]
+ denominator_job_ids = [str(job_id) for job_id in ratio_result.denominator.job_ids]
+ self._metric_events_precomputed = True
+ else:
+ metric_result = self._ensure_metric_events_precomputed(builder)
+ if metric_result.ready:
+ metric_events_job_ids = [str(job_id) for job_id in metric_result.job_ids]
+ self._metric_events_precomputed = True
+ if not self._metric_events_precomputed:
logger.warning("metric_events_lazy_computation_not_ready", experiment_id=self.experiment.id)
except Exception as e:
capture_exception(
@@ -451,6 +523,8 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):
precomputation_context=ExperimentPrecomputationContext(
exposure_job_ids=exposure_job_ids,
metric_events_job_ids=metric_events_job_ids,
+ numerator_job_ids=numerator_job_ids,
+ denominator_job_ids=denominator_job_ids,
)
)
diff --git a/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.py b/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.py
index 0f381783c175..3525873d32ad 100644
--- a/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.py
+++ b/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.py
@@ -1,17 +1,38 @@
from typing import TYPE_CHECKING, cast
-from posthog.schema import ExperimentDataWarehouseNode, ExperimentMetricOutlierHandling, ExperimentRatioMetric
+from posthog.schema import (
+ ActionsNode,
+ EventsNode,
+ ExperimentDataWarehouseNode,
+ ExperimentMetricOutlierHandling,
+ ExperimentRatioMetric,
+)
from posthog.hogql import ast
from posthog.hogql.parser import parse_expr, parse_select
+from posthog.dataclasses import frozen
+
from products.experiments.backend.hogql_queries.experiment_exposure_query_builder import ExposureQueryBuilder
from products.experiments.backend.hogql_queries.metric_source import MetricSourceInfo
+from products.experiments.backend.hogql_queries.metric_source_precompute import (
+ build_metric_events_precompute_query,
+ build_precomputed_metric_events_cte,
+ build_precomputed_metric_events_placeholders,
+)
if TYPE_CHECKING:
from products.experiments.backend.hogql_queries.experiment_query_builder import ExperimentQueryBuilder
+@frozen
+class RatioPrecomputeQueries:
+ """The write-path SELECT and placeholders of each ratio side, keyed by side so they cannot be swapped."""
+
+ numerator: tuple[str, dict[str, ast.Expr]]
+ denominator: tuple[str, dict[str, ast.Expr]]
+
+
class RatioQueryBuilder:
"""
Builds ratio-metric queries, including the winsorized variant.
@@ -21,9 +42,46 @@ class RatioQueryBuilder:
exposure and metric-value helpers through it.
"""
- def __init__(self, builder: "ExperimentQueryBuilder", exposure: ExposureQueryBuilder):
+ def __init__(
+ self,
+ builder: "ExperimentQueryBuilder",
+ exposure: ExposureQueryBuilder,
+ *,
+ numerator_job_ids: list[str] | None = None,
+ denominator_job_ids: list[str] | None = None,
+ ):
self._b = builder
self._exposure = exposure
+ self._numerator_job_ids = numerator_job_ids
+ self._denominator_job_ids = denominator_job_ids
+
+ def reads_precomputed_metric_events(self) -> bool:
+ """Both sides must be served from the precomputed table, or neither is."""
+ return bool(self._numerator_job_ids and self._denominator_job_ids)
+
+ def get_ratio_metric_events_queries_for_precomputation(self) -> RatioPrecomputeQueries:
+ """
+ Each side's query is the build query a mean metric on that source would
+ produce, so a side shares precompute jobs with such a metric. See
+ build_metric_events_precompute_query().
+ """
+ assert isinstance(self._b.metric, ExperimentRatioMetric)
+ return RatioPrecomputeQueries(
+ numerator=self._metric_events_query_for_precomputation(self._b.metric.numerator),
+ denominator=self._metric_events_query_for_precomputation(self._b.metric.denominator),
+ )
+
+ def _metric_events_query_for_precomputation(
+ self, source: EventsNode | ActionsNode | ExperimentDataWarehouseNode
+ ) -> tuple[str, dict[str, ast.Expr]]:
+ assert isinstance(source, (ActionsNode, EventsNode))
+ return build_metric_events_precompute_query(
+ team=self._b.team,
+ source=source,
+ entity_key=self._b.entity_key,
+ date_range_query=self._b.date_range_query,
+ conversion_window_seconds=self._b._get_conversion_window_seconds(),
+ )
def build_ratio_query(self) -> ast.SelectQuery:
assert isinstance(self._b.metric, ExperimentRatioMetric)
@@ -263,28 +321,51 @@ class RatioQueryBuilder:
else:
denom_preagg_join = "exposures.entity_id = denominator_events.entity_id"
+ if self.reads_precomputed_metric_events():
+ # Only reachable for eligible metrics (events/actions sources on both sides, no
+ # breakdowns/CUPED), so the data warehouse join branches above never apply here.
+ assert isinstance(self._b.metric.numerator, (ActionsNode, EventsNode))
+ assert isinstance(self._b.metric.denominator, (ActionsNode, EventsNode))
+ numerator_events_cte = build_precomputed_metric_events_cte(
+ cte_name="numerator_events",
+ source=self._b.metric.numerator,
+ entity_key=self._b.entity_key,
+ job_ids_placeholder="numerator_job_ids",
+ )
+ denominator_events_cte = build_precomputed_metric_events_cte(
+ cte_name="denominator_events",
+ source=self._b.metric.denominator,
+ entity_key=self._b.entity_key,
+ job_ids_placeholder="denominator_job_ids",
+ )
+ else:
+ numerator_events_cte = """
+ numerator_events AS (
+ SELECT
+ {num_entity_key} AS entity_id,
+ {num_timestamp_field} AS timestamp,
+ {numerator_value_expr} AS value
+ FROM {num_table}
+ WHERE {numerator_predicate}
+ )"""
+ denominator_events_cte = """
+ denominator_events AS (
+ SELECT
+ {denom_entity_key} AS entity_id,
+ {denom_timestamp_field} AS timestamp,
+ {denominator_value_expr} AS value
+ FROM {denom_table}
+ WHERE {denominator_predicate}
+ )"""
+
common_ctes = f"""
exposures AS (
{{exposure_select_query}}
),
- numerator_events AS (
- SELECT
- {{num_entity_key}} AS entity_id,
- {{num_timestamp_field}} AS timestamp,
- {{numerator_value_expr}} AS value
- FROM {{num_table}}
- WHERE {{numerator_predicate}}
- ),
+ {numerator_events_cte},
- denominator_events AS (
- SELECT
- {{denom_entity_key}} AS entity_id,
- {{denom_timestamp_field}} AS timestamp,
- {{denominator_value_expr}} AS value
- FROM {{denom_table}}
- WHERE {{denominator_predicate}}
- ),
+ {denominator_events_cte},
numerator_agg AS (
SELECT
@@ -349,4 +430,15 @@ class RatioQueryBuilder:
),
}
+ if self.reads_precomputed_metric_events():
+ placeholders["numerator_job_ids"] = ast.Constant(value=self._numerator_job_ids)
+ placeholders["denominator_job_ids"] = ast.Constant(value=self._denominator_job_ids)
+ placeholders.update(
+ build_precomputed_metric_events_placeholders(
+ team=self._b.team,
+ date_range_query=self._b.date_range_query,
+ conversion_window_seconds=self._b._get_conversion_window_seconds(),
+ )
+ )
+
return common_ctes, placeholders
diff --git a/products/experiments/backend/hogql_queries/metric_source_precompute.py b/products/experiments/backend/hogql_queries/metric_source_precompute.py
new file mode 100644
index 000000000000..68748f355024
--- /dev/null
+++ b/products/experiments/backend/hogql_queries/metric_source_precompute.py
@@ -0,0 +1,153 @@
+"""
+Metric-events precomputation for one events/actions metric source.
+
+A mean metric has one source, a ratio metric has two (numerator and denominator),
+and all of them aggregate the same (entity_id, timestamp, value) rows at read time.
+The build query and the precomputed read below are therefore written per source, so
+a ratio side with the same source and conversion window as a mean metric produces the
+same build query, hashes the same, and shares its precompute jobs.
+"""
+
+from posthog.schema import ActionsNode, EventsNode, ExperimentMetricMathType
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_expr
+
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+from posthog.models.team.team import Team
+
+from products.experiments.backend.hogql_queries.base_query_utils import event_or_action_to_filter
+from products.experiments.backend.hogql_queries.experiment_metric_values import build_value_expr
+
+
+def build_metric_events_precompute_query(
+ *,
+ team: Team,
+ source: EventsNode | ActionsNode,
+ entity_key: str,
+ date_range_query: QueryDateRange,
+ conversion_window_seconds: int,
+) -> tuple[str, dict[str, ast.Expr]]:
+ """
+ Returns the SELECT query that the lazy computation system wraps in an
+ INSERT INTO experiment_metric_events_preaggregated. This is the write
+ path. It scans the events table and stores one row per matching metric
+ event with its per-event value in numeric_value. For numeric math the
+ value is already coalesced to a non-null float by build_value_expr(),
+ so storing it in the non-nullable numeric_value column is lossless.
+ For ID-valued math (dau, unique_session) the read side counts distinct
+ IDs from entity_id/session_id instead, and numeric_value stores the
+ same constant a count metric stores, so the build query hashes the same
+ as a count metric on the same source and the two share precompute jobs.
+
+ The query uses {time_window_min} and {time_window_max} placeholders filled
+ by the lazy computation system for each daily bucket. The experiment date
+ bounds must stay named placeholders (the caller declares experiment_date_to
+ a sentinel) rather than reusing build_metric_predicate(), which bakes the
+ resolved dates into the AST. The window end of a running experiment moves,
+ so baked dates would change the job hash and defeat cache reuse.
+ """
+ # The job hash includes the parser source position of each node, so a change to
+ # this template's whitespace invalidates every cached job. Keep it byte for byte.
+ query_string = """
+ SELECT
+ {entity_key} AS entity_id,
+ timestamp AS timestamp,
+ uuid AS event_uuid,
+ `$session_id` AS session_id,
+ {value_expr} AS numeric_value
+ FROM events
+ WHERE timestamp >= {time_window_min}
+ AND timestamp < {time_window_max}
+ AND timestamp >= {experiment_date_from}
+ AND timestamp < {experiment_date_to} + toIntervalSecond({conversion_window_seconds})
+ AND {metric_event_filter}
+ """
+
+ math_type = getattr(source, "math", None) or ExperimentMetricMathType.TOTAL
+ if math_type in (ExperimentMetricMathType.DAU, ExperimentMetricMathType.UNIQUE_SESSION):
+ # build_value_expr() returns the ID itself for these math types, which
+ # cannot go into the Float64 column. Build the count-metric expression
+ # node for node so repr-based job hashing matches a count metric build.
+ value_expr: ast.Expr = ast.Call(
+ name="coalesce",
+ args=[ast.Call(name="toFloat", args=[ast.Constant(value=1)]), ast.Constant(value=0)],
+ )
+ else:
+ value_expr = build_value_expr(source)
+
+ placeholders: dict[str, ast.Expr] = {
+ "entity_key": parse_expr(entity_key),
+ "value_expr": value_expr,
+ "experiment_date_from": date_range_query.date_from_as_hogql(),
+ "experiment_date_to": date_range_query.date_to_as_hogql(),
+ "conversion_window_seconds": ast.Constant(value=conversion_window_seconds),
+ "metric_event_filter": event_or_action_to_filter(team, source),
+ }
+
+ return query_string, placeholders
+
+
+def build_precomputed_metric_events_cte(
+ *,
+ cte_name: str,
+ source: EventsNode | ActionsNode,
+ entity_key: str,
+ job_ids_placeholder: str,
+) -> str:
+ """
+ A CTE that reads one source's metric events from the precomputed table instead
+ of scanning events, with the same (entity_id, timestamp, value) columns as the
+ direct-scan CTE it replaces. Uses the placeholders from
+ build_precomputed_metric_events_placeholders() plus {job_ids_placeholder}.
+
+ cte_name and job_ids_placeholder are internal identifiers, never user input, so
+ interpolating them into the query string is safe.
+ """
+ # Filter by experiment date range: jobs can cover broader time ranges than
+ # the experiment for cache reuse, so the read must filter. The upper
+ # bound includes the conversion window since metric events can occur after
+ # experiment end, mirroring build_metric_predicate() on the direct path.
+ # GROUP BY collapses replayed rows by event identity: ReplacingMergeTree only
+ # dedups at merge time and this read doesn't use FINAL, so a re-applied build
+ # INSERT would otherwise double-count sums. Same defense as the exposures read;
+ # the funnel read skips it because funnel evaluation tolerates duplicate events.
+ entity_id_cast = "toUUID(t.entity_id)" if entity_key == "person_id" else "t.entity_id"
+ # For ID-valued math the value is the ID itself: the stored entity_id
+ # is the person id (dau) and session_id is the unique_session value,
+ # so the downstream count(distinct) matches the direct path.
+ math_type = getattr(source, "math", None) or ExperimentMetricMathType.TOTAL
+ if math_type == ExperimentMetricMathType.DAU:
+ value_select = entity_id_cast
+ elif math_type == ExperimentMetricMathType.UNIQUE_SESSION:
+ value_select = "any(t.session_id)"
+ else:
+ value_select = "any(t.numeric_value)"
+ return f"""
+ {cte_name} AS (
+ SELECT
+ {entity_id_cast} AS entity_id,
+ t.timestamp AS timestamp,
+ {value_select} AS value
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE t.job_id IN {{{job_ids_placeholder}}}
+ AND t.team_id = {{metric_events_team_id}}
+ AND t.timestamp >= {{metric_events_date_from}}
+ AND t.timestamp < {{metric_events_date_to}} + toIntervalSecond({{metric_events_conversion_window_seconds}})
+ GROUP BY t.entity_id, t.timestamp, t.event_uuid
+ )"""
+
+
+def build_precomputed_metric_events_placeholders(
+ *,
+ team: Team,
+ date_range_query: QueryDateRange,
+ conversion_window_seconds: int,
+) -> dict[str, ast.Expr]:
+ """The placeholders every build_precomputed_metric_events_cte() CTE of one query shares."""
+ return {
+ "metric_events_team_id": ast.Constant(value=team.id),
+ "metric_events_date_from": date_range_query.date_from_as_hogql(),
+ "metric_events_date_to": date_range_query.date_to_as_hogql(),
+ "metric_events_conversion_window_seconds": ast.Constant(value=conversion_window_seconds),
+ }
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_ratio_metric.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_ratio_metric.ambr
index a6b0737d48d9..d13f4afa83b2 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_ratio_metric.ambr
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_ratio_metric.ambr
@@ -104,31 +104,23 @@
WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), greaterOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC'))))
GROUP BY entity_id),
numerator_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- toTimeZone(events.timestamp, 'UTC') AS timestamp,
- coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'amount'), ''), 'null'), '^"|"$', ''), 'Float64'), 0) AS value
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, toDateTime64(plus(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalSecond(0)), 6, 'UTC')), equals(events.event, 'purchase'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ any(t.numeric_value) AS value
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(t.timestamp, toDateTime64(plus(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalSecond(0)), 6, 'UTC')))
+ GROUP BY t.entity_id,
+ toTimeZone(t.timestamp, 'UTC'),
+ t.event_uuid),
denominator_events AS
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
- toTimeZone(events.timestamp, 'UTC') AS timestamp,
- coalesce(accurateCastOrNull(1, 'Float64'), 0) AS value
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, toDateTime64(plus(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalSecond(0)), 6, 'UTC')), equals(events.event, 'purchase'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ any(t.numeric_value) AS value
+ FROM experiment_metric_events_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(t.timestamp, toDateTime64(plus(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalSecond(0)), 6, 'UTC')))
+ GROUP BY t.entity_id,
+ toTimeZone(t.timestamp, 'UTC'),
+ t.event_uuid),
numerator_agg AS
(SELECT exposures.entity_id AS entity_id,
sum(coalesce(accurateCastOrNull(numerator_events.value, 'Float64'), 0)) AS value
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 32e034c1ba47..44e4047ea006 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
@@ -3,6 +3,7 @@ from pathlib import Path
from typing import Any, Optional
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person
+from unittest.mock import patch
from django.test import override_settings
from django.utils import timezone
@@ -20,6 +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.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
@@ -89,6 +91,15 @@ class ExperimentQueryRunnerBaseTest(ClickhouseTestMixin, APIBaseTest):
config = get_or_create_team_extension(self.team, TeamExperimentsConfig)
config.experiment_precomputation_enabled = True
config.save()
+ # 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.start()
+ self.addCleanup(patcher.stop)
+ self._ratio_metric_events_precompute_patched = True
def _disable_precomputation(self):
config = get_or_create_team_extension(self.team, TeamExperimentsConfig)
diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py
index bf599475ef42..76b71867f6f9 100644
--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py
+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py
@@ -153,6 +153,9 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
result = cast(ExperimentQueryResponse, query_runner.calculate())
+ # A broken precomputed read silently falls back to the direct scan; assert the intended path ran.
+ assert query_runner._metric_events_precomputed is use_precomputation
+
assert result.baseline is not None
assert result.variant_results is not None
self.assertEqual(len(result.variant_results), 1)
@@ -275,6 +278,9 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):
query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
result = cast(ExperimentQueryResponse, query_runner.calculate())
+ # A broken precomputed read silently falls back to the direct scan; assert the intended path ran.
+ assert query_runner._metric_events_precomputed is use_precomputation
+
assert result.baseline is not None
assert result.variant_results is not None
self.assertEqual(len(result.variant_results), 1)
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
new file mode 100644
index 000000000000..6e6c69caabc1
--- /dev/null
+++ b/products/experiments/backend/hogql_queries/test/test_experiment_ratio_metric_events_preaggregation.py
@@ -0,0 +1,121 @@
+from datetime import UTC, datetime
+
+from unittest.mock import patch
+
+from django.test import override_settings
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ EventsNode,
+ ExperimentMeanMetric,
+ ExperimentMetricMathType,
+ ExperimentQuery,
+ ExperimentRatioMetric,
+ IntervalType,
+)
+
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+
+from products.experiments.backend.hogql_queries.base_query_utils import experiment_window
+from products.experiments.backend.hogql_queries.experiment_query_builder import (
+ ExperimentQueryBuilder,
+ get_exposure_config_params_for_builder,
+)
+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.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
+
+PURCHASE_SUM = EventsNode(event="purchase", math=ExperimentMetricMathType.SUM, math_property="amount")
+PURCHASE_COUNT = EventsNode(event="purchase")
+
+
+@override_settings(IN_UNIT_TESTING=True)
+class TestExperimentRatioMetricEventsPreaggregation(ExperimentQueryRunnerBaseTest):
+ def _build_lazy_computation_builder(self, experiment, feature_flag, metric) -> ExperimentQueryBuilder:
+ exposure_params = get_exposure_config_params_for_builder(
+ experiment.exposure_criteria, experiment.team, experiment.start_date
+ )
+ as_of = datetime.now(UTC)
+ date_range = experiment_window(experiment, self.team, as_of)
+ return ExperimentQueryBuilder(
+ team=self.team,
+ feature_flag_key=feature_flag.key,
+ exposure_config=exposure_params.exposure_config,
+ filter_test_accounts=exposure_params.filter_test_accounts,
+ multiple_variant_handling=exposure_params.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=as_of,
+ ),
+ entity_key=get_entity_key(feature_flag.filters.get("aggregation_group_type_index")),
+ metric=metric,
+ )
+
+ def _build_runner(self, experiment, metric: ExperimentMeanMetric | ExperimentRatioMetric):
+ query = ExperimentQuery(experiment_id=experiment.id, kind="ExperimentQuery", metric=metric)
+ return ExperimentQueryRunner(query=query, team=self.team)
+
+ @patch("products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute")
+ def test_ratio_sides_build_separately_and_share_jobs_with_mean_metrics(self, mock_sync_execute):
+ feature_flag = self.create_feature_flag(key="ratio-metric-events-shared-jobs")
+ experiment = self.create_experiment(
+ feature_flag=feature_flag,
+ start_date=datetime(2024, 1, 1),
+ end_date=datetime(2024, 1, 10),
+ )
+ mean_metric = ExperimentMeanMetric(source=PURCHASE_SUM)
+ ratio_metric = ExperimentRatioMetric(numerator=PURCHASE_SUM, denominator=PURCHASE_COUNT)
+
+ mean_result = self._build_runner(experiment, mean_metric)._ensure_metric_events_precomputed(
+ self._build_lazy_computation_builder(experiment, feature_flag, mean_metric)
+ )
+ ratio_result = self._build_runner(experiment, ratio_metric)._ensure_ratio_metric_events_precomputed(
+ self._build_lazy_computation_builder(experiment, feature_flag, ratio_metric)
+ )
+
+ assert mean_result.ready is True
+ assert ratio_result.ready is True
+ # The numerator is the same build as the mean metric, so it reused those jobs
+ # without running an INSERT; the denominator's value differs, so it built its own.
+ assert ratio_result.numerator.job_ids == mean_result.job_ids
+ assert set(ratio_result.denominator.job_ids).isdisjoint(mean_result.job_ids)
+ assert mock_sync_execute.call_count == len(mean_result.job_ids) + len(ratio_result.denominator.job_ids)
+
+ @parameterized.expand(
+ [
+ ("both_sides_eligible", PURCHASE_SUM, PURCHASE_COUNT, True, None),
+ ("flag_off", PURCHASE_SUM, PURCHASE_COUNT, False, "ratio_flag_off"),
+ (
+ "numerator_session_property",
+ EventsNode(event="purchase", math=ExperimentMetricMathType.SUM, math_property="$session_duration"),
+ PURCHASE_COUNT,
+ True,
+ "session_property_math",
+ ),
+ (
+ "denominator_unique_group",
+ PURCHASE_SUM,
+ EventsNode(event="purchase", math=ExperimentMetricMathType.UNIQUE_GROUP, math_group_type_index=1),
+ True,
+ "unsupported_math",
+ ),
+ ]
+ )
+ def test_ratio_metric_events_precompute_gate(self, _name, numerator, denominator, flag_enabled, skip_reason):
+ feature_flag = self.create_feature_flag(key="ratio-metric-events-gate")
+ experiment = self.create_experiment(
+ feature_flag=feature_flag,
+ start_date=datetime(2024, 1, 1),
+ end_date=datetime(2024, 1, 10),
+ )
+ runner = self._build_runner(experiment, ExperimentRatioMetric(numerator=numerator, denominator=denominator))
+
+ with patch.object(
+ ExperimentQueryRunner, "_ratio_metric_events_precomputation_enabled", return_value=flag_enabled
+ ):
+ assert runner._metric_events_ineligibility_reason() == skip_reason
+ assert runner._metric_events_precompute_applicable() is (skip_reason is None)