:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(experiments): extract mean and ratio query construction (#60790)
Anders463a81dbdcc1
diff --git a/posthog/hogql_queries/experiments/experiment_mean_query_builder.py b/posthog/hogql_queries/experiments/experiment_mean_query_builder.pynew file mode 100644index 000000000000..e3ff255aca68--- /dev/null+++ b/posthog/hogql_queries/experiments/experiment_mean_query_builder.py@@ -0,0 +1,390 @@+from typing import TYPE_CHECKING, cast++from posthog.schema import ActionsNode, EventsNode, ExperimentDataWarehouseNode, ExperimentMeanMetric++from posthog.hogql import ast+from posthog.hogql.parser import parse_expr, parse_select++from posthog.hogql_queries.experiments.base_query_utils import is_session_property_metric, validate_session_property+from posthog.hogql_queries.experiments.metric_source import MetricSourceInfo++if TYPE_CHECKING:+ from posthog.hogql_queries.experiments.experiment_query_builder import ExperimentQueryBuilder+++class MeanQueryBuilder:+ """+ Builds mean-metric queries (count, sum, avg, etc.), including the+ winsorized and session-property variants.++ Mean construction reuses the shared exposure, metric-value, and CUPED+ helpers already extracted from the experiment query builder. To keep the+ move behavior-preserving, this class holds a reference to the owning+ ``ExperimentQueryBuilder`` and reaches through it for shared state (the+ metric, entity key, CUPED config, breakdown injector) and those+ cross-cluster helpers.+ """++ def __init__(self, builder: "ExperimentQueryBuilder"):+ self._b = builder++ def get_session_property_ctes(self) -> str:+ """+ Returns CTEs for session property metrics with proper deduplication.++ Session properties require special handling to avoid the multiplication bug:+ - Without deduplication: each event in a session contributes the full session value+ - With deduplication: each session contributes exactly once++ Pattern:+ 1. metric_events_by_session: GROUP BY $session_id, get any(session.$property)+ 2. metric_events: Join with exposures, filter by temporal ordering+ 3. entity_metrics: Aggregate across sessions per entity+ """+ assert isinstance(self._b.metric, ExperimentMeanMetric)+ assert isinstance(self._b.metric.source, (ActionsNode, EventsNode))++ session_property = validate_session_property(self._b.metric.source)++ return f"""+ exposures AS (+ {{exposure_select_query}}+ ),++ -- Layer 1: Deduplicate within sessions+ -- Each session contributes exactly one value regardless of event count+ metric_events_by_session AS (+ SELECT+ {{entity_key}} AS entity_id,+ `$session_id` AS session_id,+ any(session.`{session_property}`) AS session_value,+ min(timestamp) AS first_event_timestamp+ FROM events+ WHERE {{metric_predicate}}+ AND `$session_id` IS NOT NULL+ AND `$session_id` != ''+ GROUP BY {{entity_key}}, `$session_id`+ ),++ -- Layer 2: Join with exposures, filter by temporal ordering+ metric_events AS (+ SELECT+ exposures.entity_id AS entity_id,+ exposures.variant AS variant,+ toFloat(coalesce(metric_events_by_session.session_value, 0)) AS value,+ metric_events_by_session.session_id AS session_id+ FROM exposures+ INNER JOIN metric_events_by_session+ ON exposures.entity_id = metric_events_by_session.entity_id+ AND metric_events_by_session.first_event_timestamp >= exposures.first_exposure_time+ AND {{session_conversion_window_predicate}}+ ),++ -- Layer 3: Aggregate across sessions per entity+ entity_metrics AS (+ SELECT+ entity_id,+ variant,+ {{value_agg}} AS value+ FROM metric_events+ GROUP BY entity_id, variant+ )+ """++ def get_mean_query_common_ctes(self) -> str:+ """+ Returns the common CTEs used by both regular and winsorized mean queries.+ Supports both regular events and data warehouse sources.+ """+ assert isinstance(self._b.metric, ExperimentMeanMetric)++ # Check if this is a session property metric - use special CTE structure+ if isinstance(self._b.metric.source, (ActionsNode, EventsNode)) and is_session_property_metric(+ self._b.metric.source+ ):+ return self.get_session_property_ctes()++ # Use MetricSourceInfo abstraction for source metadata+ source_info = MetricSourceInfo.from_source(self._b.metric.source, entity_key=self._b.entity_key)++ # Determine join condition based on source type+ if source_info.kind == "datawarehouse":+ join_condition = "{join_condition}"+ else:+ join_condition = "exposures.entity_id = metric_events.entity_id"++ if self._b.cuped_config.enabled:+ join_window_predicate = "({conversion_window_predicate} OR {cuped_pre_window_predicate})"+ entity_metric_selects = """+ {value_agg} AS value,+ {covariate_value_agg} AS covariate_value"""+ else:+ join_window_predicate = "{conversion_window_predicate}"+ entity_metric_selects = """+ {value_agg} AS value"""++ return f"""+ exposures AS (+ {{exposure_select_query}}+ ),++ metric_events AS (+ SELECT+ {{entity_key}} AS entity_id,+ {{metric_timestamp_field}} AS timestamp,+ {{value_expr}} AS value+ -- breakdown columns added programmatically below+ FROM {{metric_table}}+ WHERE {{metric_predicate}}+ ),++ entity_metrics AS (+ SELECT+ exposures.entity_id AS entity_id,+ exposures.variant AS variant,+{entity_metric_selects}+ -- breakdown columns added programmatically below+ FROM exposures+ LEFT JOIN metric_events ON {join_condition}+ AND {join_window_predicate}+ GROUP BY exposures.entity_id, exposures.variant+ -- breakdown columns added programmatically below+ )+ """++ def get_mean_query_common_placeholders(self) -> dict:+ """+ Returns the common placeholders used by both regular and winsorized mean queries.+ Supports both regular events and data warehouse sources.+ """+ assert isinstance(self._b.metric, ExperimentMeanMetric)++ # Check if this is a session property metric - use different placeholders+ is_session_property = isinstance(+ self._b.metric.source, (ActionsNode, EventsNode)+ ) and is_session_property_metric(self._b.metric.source)++ if is_session_property:+ return self.get_session_property_placeholders()++ # Use MetricSourceInfo abstraction for source metadata+ source_info = MetricSourceInfo.from_source(self._b.metric.source, entity_key=self._b.entity_key)++ # Build exposure query with exposure_identifier for data warehouse+ exposure_query = self._b._get_exposure_query()+ if source_info.kind == "datawarehouse":+ assert isinstance(self._b.metric.source, ExperimentDataWarehouseNode)+ events_join_key_parts = cast(list[str | int], self._b.metric.source.events_join_key.split("."))++ # Use argMin to pick one exposure_identifier per entity_id (from first exposure)+ # This prevents fan-out when a user has multiple exposures with different join key values+ exposure_query.select.append(+ ast.Alias(+ alias="exposure_identifier",+ expr=ast.Call(+ name="argMin",+ args=[ast.Field(chain=events_join_key_parts), ast.Field(chain=["timestamp"])],+ ),+ )+ )+ # Do NOT add to GROUP BY - that would cause fan-out when join key varies across exposures++ metric_predicate = self._b._build_metric_predicate(+ table_alias=source_info.table_name,+ cuped_lookback_days=self._b.cuped_config.lookback_days if self._b.cuped_config.enabled else None,+ )+ conversion_window_predicate = self._b._build_conversion_window_predicate()++ placeholders: dict = {+ "exposure_select_query": exposure_query,+ "entity_key": source_info.entity_key,+ "metric_timestamp_field": ast.Field(chain=[source_info.timestamp_field]),+ "metric_table": ast.Field(chain=[source_info.table_name]),+ "metric_predicate": metric_predicate,+ "value_expr": self._b._build_value_expr(),+ "value_agg": self._b._build_value_aggregation_expr(+ value_expr=self._b._build_windowed_metric_value_expr(conversion_window_predicate)+ if self._b.cuped_config.enabled+ else None+ ),+ "conversion_window_predicate": conversion_window_predicate,+ }++ if self._b.cuped_config.enabled:+ cuped_pre_window_predicate = self._b._build_cuped_pre_window_predicate()+ placeholders["cuped_pre_window_predicate"] = cuped_pre_window_predicate+ placeholders["covariate_value_agg"] = self._b._build_value_aggregation_expr(+ value_expr=self._b._build_windowed_metric_value_expr(cuped_pre_window_predicate)+ )++ # Add join condition for data warehouse+ if source_info.kind == "datawarehouse":+ placeholders["join_condition"] = parse_expr(+ "toString(exposures.exposure_identifier) = toString(metric_events.entity_id)"+ )++ return placeholders++ def get_session_property_placeholders(self) -> dict:+ """+ Returns placeholders specific to session property metrics.+ Session properties use a different CTE structure with deduplication per session.+ """+ assert isinstance(self._b.metric, ExperimentMeanMetric)++ exposure_query = self._b._get_exposure_query()++ return {+ "exposure_select_query": exposure_query,+ "entity_key": parse_expr(self._b.entity_key),+ "metric_predicate": self._b._build_metric_predicate(table_alias="events"),+ "value_agg": self._b._build_value_aggregation_expr(),+ "session_conversion_window_predicate": self._b._build_session_conversion_window_predicate(),+ }++ def build_mean_query(self) -> ast.SelectQuery:+ """+ Builds query for mean metrics (count, sum, avg, etc.)+ """+ assert isinstance(self._b.metric, ExperimentMeanMetric)++ # Check if we need to apply winsorization (outlier handling)+ needs_winsorization = (+ self._b.metric.lower_bound_percentile is not None or self._b.metric.upper_bound_percentile is not None+ )++ if needs_winsorization:+ return self.build_mean_query_with_winsorization()++ common_ctes = self.get_mean_query_common_ctes()+ cuped_selects = (+ """,+ sum(entity_metrics.covariate_value) AS covariate_sum,+ sum(power(entity_metrics.covariate_value, 2)) AS covariate_sum_squares,+ sum(entity_metrics.value * entity_metrics.covariate_value) AS covariate_sum_product"""+ if self._b.cuped_config.enabled+ else ""+ )++ query = parse_select(+ f"""+ WITH {common_ctes}++ SELECT+ entity_metrics.variant AS variant,+ count(entity_metrics.entity_id) AS num_users,+ sum(entity_metrics.value) AS total_sum,+ sum(power(entity_metrics.value, 2)) AS total_sum_of_squares{cuped_selects}+ -- breakdown columns added programmatically below+ FROM entity_metrics+ GROUP BY entity_metrics.variant+ -- breakdown columns added programmatically below+ """,+ placeholders=self.get_mean_query_common_placeholders(),+ )++ assert isinstance(query, ast.SelectQuery)++ # Inject breakdown columns into the query AST+ if self._b.breakdown_injector:+ self._b.breakdown_injector.inject_mean_breakdown_columns(query, final_cte_name="entity_metrics")++ return query++ def build_mean_query_with_winsorization(self) -> ast.SelectQuery:+ """+ Builds query for mean metrics with winsorization (outlier handling).+ This clamps entity-level values to percentile-based bounds.+ """+ assert isinstance(self._b.metric, ExperimentMeanMetric)++ # Build lower bound expression+ if self._b.metric.lower_bound_percentile is not None:+ lower_bound_expr = parse_expr(+ "quantileExact({level})(entity_metrics.value)",+ placeholders={"level": ast.Constant(value=self._b.metric.lower_bound_percentile)},+ )+ else:+ lower_bound_expr = parse_expr("min(entity_metrics.value)")++ # Build upper bound expression+ if self._b.metric.upper_bound_percentile is not None:+ # Handle ignore_zeros flag for upper bound calculation+ if getattr(self._b.metric, "ignore_zeros", False):+ upper_bound_expr = parse_expr(+ "quantileExact({level})(if(entity_metrics.value != 0, entity_metrics.value, null))",+ placeholders={"level": ast.Constant(value=self._b.metric.upper_bound_percentile)},+ )+ else:+ upper_bound_expr = parse_expr(+ "quantileExact({level})(entity_metrics.value)",+ placeholders={"level": ast.Constant(value=self._b.metric.upper_bound_percentile)},+ )+ else:+ upper_bound_expr = parse_expr("max(entity_metrics.value)")++ common_ctes = self.get_mean_query_common_ctes()+ placeholders = self.get_mean_query_common_placeholders()+ winsorized_cuped_select = (+ """,+ entity_metrics.covariate_value AS covariate_value"""+ if self._b.cuped_config.enabled+ else ""+ )+ cuped_selects = (+ """,+ sum(winsorized_entity_metrics.covariate_value) AS covariate_sum,+ sum(power(winsorized_entity_metrics.covariate_value, 2)) AS covariate_sum_squares,+ sum(winsorized_entity_metrics.value * winsorized_entity_metrics.covariate_value) AS covariate_sum_product"""+ if self._b.cuped_config.enabled+ else ""+ )++ # Add winsorization-specific placeholders+ placeholders["lower_bound"] = lower_bound_expr+ placeholders["upper_bound"] = upper_bound_expr++ query = parse_select(+ f"""+ WITH {common_ctes},++ percentiles AS (+ SELECT+ {{lower_bound}} AS lower_bound,+ {{upper_bound}} AS upper_bound+ -- breakdown columns added programmatically below+ FROM entity_metrics+ -- GROUP BY added programmatically below if breakdowns exist+ ),++ winsorized_entity_metrics AS (+ SELECT+ entity_metrics.entity_id AS entity_id,+ entity_metrics.variant AS variant,+ least(greatest(percentiles.lower_bound, entity_metrics.value), percentiles.upper_bound) AS value{winsorized_cuped_select}+ -- breakdown columns added programmatically below+ FROM entity_metrics+ CROSS JOIN percentiles+ -- JOIN conditions added programmatically below if breakdowns exist+ )++ SELECT+ winsorized_entity_metrics.variant AS variant,+ count(winsorized_entity_metrics.entity_id) AS num_users,+ sum(winsorized_entity_metrics.value) AS total_sum,+ sum(power(winsorized_entity_metrics.value, 2)) AS total_sum_of_squares{cuped_selects}+ -- breakdown columns added programmatically below+ FROM winsorized_entity_metrics+ GROUP BY winsorized_entity_metrics.variant+ -- breakdown columns added programmatically below+ """,+ placeholders=placeholders,+ )++ assert isinstance(query, ast.SelectQuery)++ # Inject breakdown columns into the query AST+ if self._b.breakdown_injector:+ self._b.breakdown_injector.inject_mean_breakdown_columns(query, final_cte_name="winsorized_entity_metrics")++ return querydiff --git a/posthog/hogql_queries/experiments/experiment_query_builder.py b/posthog/hogql_queries/experiments/experiment_query_builder.pyindex 2d45db6748d1..89b24051bc3c 100644--- a/posthog/hogql_queries/experiments/experiment_query_builder.py+++ b/posthog/hogql_queries/experiments/experiment_query_builder.py@@ -1,11 +1,10 @@-from typing import Optional, Union, cast+from typing import Optional, Unionfrom django.utils import timezonefrom posthog.schema import (ActionsNode,Breakdown,- EventsNode,ExperimentDataWarehouseNode,ExperimentEventExposureConfig,ExperimentExposureCriteria,@@ -19,13 +18,13 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS-from posthog.hogql.parser import parse_expr, parse_select+from posthog.hogql.parser import parse_expr-from posthog.hogql_queries.experiments.base_query_utils import is_session_property_metric, validate_session_propertyfrom posthog.hogql_queries.experiments.breakdown_injector import BreakdownInjectorfrom posthog.hogql_queries.experiments.cuped_config import CupedQueryConfigfrom posthog.hogql_queries.experiments.experiment_exposure_query_builder import ExposureQueryBuilderfrom posthog.hogql_queries.experiments.experiment_funnel_query_builder import FunnelQueryBuilder+from posthog.hogql_queries.experiments.experiment_mean_query_builder import MeanQueryBuilderfrom posthog.hogql_queries.experiments.experiment_metric_values import (build_conversion_window_predicate,build_conversion_window_predicate_for_events,@@ -39,6 +38,7 @@ from posthog.hogql_queries.experiments.experiment_query_context import (ExperimentPrecomputationContext,ExperimentQueryContext,)+from posthog.hogql_queries.experiments.experiment_ratio_query_builder import RatioQueryBuilderfrom posthog.hogql_queries.experiments.experiment_retention_query_builder import RetentionQueryBuilderfrom posthog.hogql_queries.experiments.exposure_query_logic import normalize_to_exposure_criteriafrom posthog.hogql_queries.experiments.funnel_step_builder import FunnelStepBuilder@@ -184,6 +184,14 @@ class ExperimentQueryBuilder:"""Construct a RetentionQueryBuilder backed by the current builder state."""return RetentionQueryBuilder(self)+ def _mean_query_builder(self) -> MeanQueryBuilder:+ """Construct a MeanQueryBuilder backed by the current builder state."""+ return MeanQueryBuilder(self)++ def _ratio_query_builder(self) -> RatioQueryBuilder:+ """Construct a RatioQueryBuilder backed by the current builder state."""+ return RatioQueryBuilder(self)+def get_exposure_timeseries_query(self) -> ast.SelectQuery:"""Returns a query for exposure timeseries data.@@ -325,351 +333,41 @@ class ExperimentQueryBuilder:2. metric_events: Join with exposures, filter by temporal ordering3. entity_metrics: Aggregate across sessions per entity"""- assert isinstance(self.metric, ExperimentMeanMetric)- assert isinstance(self.metric.source, (ActionsNode, EventsNode))-- session_property = validate_session_property(self.metric.source)-- return f"""- exposures AS (- {{exposure_select_query}}- ),-- -- Layer 1: Deduplicate within sessions- -- Each session contributes exactly one value regardless of event count- metric_events_by_session AS (- SELECT- {{entity_key}} AS entity_id,- `$session_id` AS session_id,- any(session.`{session_property}`) AS session_value,- min(timestamp) AS first_event_timestamp- FROM events- WHERE {{metric_predicate}}- AND `$session_id` IS NOT NULL- AND `$session_id` != ''- GROUP BY {{entity_key}}, `$session_id`- ),-- -- Layer 2: Join with exposures, filter by temporal ordering- metric_events AS (- SELECT- exposures.entity_id AS entity_id,- exposures.variant AS variant,- toFloat(coalesce(metric_events_by_session.session_value, 0)) AS value,- metric_events_by_session.session_id AS session_id- FROM exposures- INNER JOIN metric_events_by_session- ON exposures.entity_id = metric_events_by_session.entity_id- AND metric_events_by_session.first_event_timestamp >= exposures.first_exposure_time- AND {{session_conversion_window_predicate}}- ),-- -- Layer 3: Aggregate across sessions per entity- entity_metrics AS (- SELECT- entity_id,- variant,- {{value_agg}} AS value- FROM metric_events- GROUP BY entity_id, variant- )- """+ return self._mean_query_builder().get_session_property_ctes()def _get_mean_query_common_ctes(self) -> str:"""Returns the common CTEs used by both regular and winsorized mean queries.Supports both regular events and data warehouse sources."""- assert isinstance(self.metric, ExperimentMeanMetric)-- # Check if this is a session property metric - use special CTE structure- if isinstance(self.metric.source, (ActionsNode, EventsNode)) and is_session_property_metric(self.metric.source):- return self._get_session_property_ctes()-- # Use MetricSourceInfo abstraction for source metadata- source_info = MetricSourceInfo.from_source(self.metric.source, entity_key=self.entity_key)-- # Determine join condition based on source type- if source_info.kind == "datawarehouse":- join_condition = "{join_condition}"- else:- join_condition = "exposures.entity_id = metric_events.entity_id"-- if self.cuped_config.enabled:- join_window_predicate = "({conversion_window_predicate} OR {cuped_pre_window_predicate})"- entity_metric_selects = """- {value_agg} AS value,- {covariate_value_agg} AS covariate_value"""- else:- join_window_predicate = "{conversion_window_predicate}"- entity_metric_selects = """- {value_agg} AS value"""-- return f"""- exposures AS (- {{exposure_select_query}}- ),-- metric_events AS (- SELECT- {{entity_key}} AS entity_id,- {{metric_timestamp_field}} AS timestamp,- {{value_expr}} AS value- -- breakdown columns added programmatically below- FROM {{metric_table}}- WHERE {{metric_predicate}}- ),-- entity_metrics AS (- SELECT- exposures.entity_id AS entity_id,- exposures.variant AS variant,-{entity_metric_selects}- -- breakdown columns added programmatically below- FROM exposures- LEFT JOIN metric_events ON {join_condition}- AND {join_window_predicate}- GROUP BY exposures.entity_id, exposures.variant- -- breakdown columns added programmatically below- )- """+ return self._mean_query_builder().get_mean_query_common_ctes()def _get_mean_query_common_placeholders(self) -> dict:"""Returns the common placeholders used by both regular and winsorized mean queries.Supports both regular events and data warehouse sources."""- assert isinstance(self.metric, ExperimentMeanMetric)-- # Check if this is a session property metric - use different placeholders- is_session_property = isinstance(self.metric.source, (ActionsNode, EventsNode)) and is_session_property_metric(- self.metric.source- )-- if is_session_property:- return self._get_session_property_placeholders()-- # Use MetricSourceInfo abstraction for source metadata- source_info = MetricSourceInfo.from_source(self.metric.source, entity_key=self.entity_key)-- # Build exposure query with exposure_identifier for data warehouse- exposure_query = self._get_exposure_query()- if source_info.kind == "datawarehouse":- assert isinstance(self.metric.source, ExperimentDataWarehouseNode)- events_join_key_parts = cast(list[str | int], self.metric.source.events_join_key.split("."))-- # Use argMin to pick one exposure_identifier per entity_id (from first exposure)- # This prevents fan-out when a user has multiple exposures with different join key values- exposure_query.select.append(- ast.Alias(- alias="exposure_identifier",- expr=ast.Call(- name="argMin",- args=[ast.Field(chain=events_join_key_parts), ast.Field(chain=["timestamp"])],- ),- )- )- # Do NOT add to GROUP BY - that would cause fan-out when join key varies across exposures-- metric_predicate = self._build_metric_predicate(- table_alias=source_info.table_name,- cuped_lookback_days=self.cuped_config.lookback_days if self.cuped_config.enabled else None,- )- conversion_window_predicate = self._build_conversion_window_predicate()-- placeholders: dict = {- "exposure_select_query": exposure_query,- "entity_key": source_info.entity_key,- "metric_timestamp_field": ast.Field(chain=[source_info.timestamp_field]),- "metric_table": ast.Field(chain=[source_info.table_name]),- "metric_predicate": metric_predicate,- "value_expr": self._build_value_expr(),- "value_agg": self._build_value_aggregation_expr(- value_expr=self._build_windowed_metric_value_expr(conversion_window_predicate)- if self.cuped_config.enabled- else None- ),- "conversion_window_predicate": conversion_window_predicate,- }-- if self.cuped_config.enabled:- cuped_pre_window_predicate = self._build_cuped_pre_window_predicate()- placeholders["cuped_pre_window_predicate"] = cuped_pre_window_predicate- placeholders["covariate_value_agg"] = self._build_value_aggregation_expr(- value_expr=self._build_windowed_metric_value_expr(cuped_pre_window_predicate)- )-- # Add join condition for data warehouse- if source_info.kind == "datawarehouse":- placeholders["join_condition"] = parse_expr(- "toString(exposures.exposure_identifier) = toString(metric_events.entity_id)"- )-- return placeholders+ return self._mean_query_builder().get_mean_query_common_placeholders()def _get_session_property_placeholders(self) -> dict:"""Returns placeholders specific to session property metrics.Session properties use a different CTE structure with deduplication per session."""- assert isinstance(self.metric, ExperimentMeanMetric)-- exposure_query = self._get_exposure_query()-- return {- "exposure_select_query": exposure_query,- "entity_key": parse_expr(self.entity_key),- "metric_predicate": self._build_metric_predicate(table_alias="events"),- "value_agg": self._build_value_aggregation_expr(),- "session_conversion_window_predicate": self._build_session_conversion_window_predicate(),- }+ return self._mean_query_builder().get_session_property_placeholders()def _build_mean_query(self) -> ast.SelectQuery:"""Builds query for mean metrics (count, sum, avg, etc.)"""- assert isinstance(self.metric, ExperimentMeanMetric)-- # Check if we need to apply winsorization (outlier handling)- needs_winsorization = (- self.metric.lower_bound_percentile is not None or self.metric.upper_bound_percentile is not None- )-- if needs_winsorization:- return self._build_mean_query_with_winsorization()-- common_ctes = self._get_mean_query_common_ctes()- cuped_selects = (- """,- sum(entity_metrics.covariate_value) AS covariate_sum,- sum(power(entity_metrics.covariate_value, 2)) AS covariate_sum_squares,- sum(entity_metrics.value * entity_metrics.covariate_value) AS covariate_sum_product"""- if self.cuped_config.enabled- else ""- )-- query = parse_select(- f"""- WITH {common_ctes}-- SELECT- entity_metrics.variant AS variant,- count(entity_metrics.entity_id) AS num_users,- sum(entity_metrics.value) AS total_sum,- sum(power(entity_metrics.value, 2)) AS total_sum_of_squares{cuped_selects}- -- breakdown columns added programmatically below- FROM entity_metrics- GROUP BY entity_metrics.variant- -- breakdown columns added programmatically below- """,- placeholders=self._get_mean_query_common_placeholders(),- )-- assert isinstance(query, ast.SelectQuery)-- # Inject breakdown columns into the query AST- if self.breakdown_injector:- self.breakdown_injector.inject_mean_breakdown_columns(query, final_cte_name="entity_metrics")-- return query+ return self._mean_query_builder().build_mean_query()def _build_mean_query_with_winsorization(self) -> ast.SelectQuery:"""Builds query for mean metrics with winsorization (outlier handling).This clamps entity-level values to percentile-based bounds."""- assert isinstance(self.metric, ExperimentMeanMetric)-- # Build lower bound expression- if self.metric.lower_bound_percentile is not None:- lower_bound_expr = parse_expr(- "quantileExact({level})(entity_metrics.value)",- placeholders={"level": ast.Constant(value=self.metric.lower_bound_percentile)},- )- else:- lower_bound_expr = parse_expr("min(entity_metrics.value)")-- # Build upper bound expression- if self.metric.upper_bound_percentile is not None:- # Handle ignore_zeros flag for upper bound calculation- if getattr(self.metric, "ignore_zeros", False):- upper_bound_expr = parse_expr(- "quantileExact({level})(if(entity_metrics.value != 0, entity_metrics.value, null))",- placeholders={"level": ast.Constant(value=self.metric.upper_bound_percentile)},- )- else:- upper_bound_expr = parse_expr(- "quantileExact({level})(entity_metrics.value)",- placeholders={"level": ast.Constant(value=self.metric.upper_bound_percentile)},- )- else:- upper_bound_expr = parse_expr("max(entity_metrics.value)")-- common_ctes = self._get_mean_query_common_ctes()- placeholders = self._get_mean_query_common_placeholders()- winsorized_cuped_select = (- """,- entity_metrics.covariate_value AS covariate_value"""- if self.cuped_config.enabled- else ""- )- cuped_selects = (- """,- sum(winsorized_entity_metrics.covariate_value) AS covariate_sum,- sum(power(winsorized_entity_metrics.covariate_value, 2)) AS covariate_sum_squares,- sum(winsorized_entity_metrics.value * winsorized_entity_metrics.covariate_value) AS covariate_sum_product"""- if self.cuped_config.enabled- else ""- )-- # Add winsorization-specific placeholders- placeholders["lower_bound"] = lower_bound_expr- placeholders["upper_bound"] = upper_bound_expr-- query = parse_select(- f"""- WITH {common_ctes},-- percentiles AS (- SELECT- {{lower_bound}} AS lower_bound,- {{upper_bound}} AS upper_bound- -- breakdown columns added programmatically below- FROM entity_metrics- -- GROUP BY added programmatically below if breakdowns exist- ),-- winsorized_entity_metrics AS (- SELECT- entity_metrics.entity_id AS entity_id,- entity_metrics.variant AS variant,- least(greatest(percentiles.lower_bound, entity_metrics.value), percentiles.upper_bound) AS value{winsorized_cuped_select}- -- breakdown columns added programmatically below- FROM entity_metrics- CROSS JOIN percentiles- -- JOIN conditions added programmatically below if breakdowns exist- )-- SELECT- winsorized_entity_metrics.variant AS variant,- count(winsorized_entity_metrics.entity_id) AS num_users,- sum(winsorized_entity_metrics.value) AS total_sum,- sum(power(winsorized_entity_metrics.value, 2)) AS total_sum_of_squares{cuped_selects}- -- breakdown columns added programmatically below- FROM winsorized_entity_metrics- GROUP BY winsorized_entity_metrics.variant- -- breakdown columns added programmatically below- """,- placeholders=placeholders,- )-- assert isinstance(query, ast.SelectQuery)-- # Inject breakdown columns into the query AST- if self.breakdown_injector:- self.breakdown_injector.inject_mean_breakdown_columns(query, final_cte_name="winsorized_entity_metrics")-- return query+ return self._mean_query_builder().build_mean_query_with_winsorization()def _build_ratio_query(self) -> ast.SelectQuery:"""@@ -678,54 +376,11 @@ class ExperimentQueryBuilder:Dispatches to the winsorized variant when outlier handling is configured foreither the numerator or the denominator."""- assert isinstance(self.metric, ExperimentRatioMetric)-- if self._ratio_needs_winsorization():- return self._build_ratio_query_with_winsorization()-- common_ctes, placeholders = self._get_ratio_query_common()-- query = parse_select(- f"""- WITH {common_ctes}-- SELECT- entity_metrics.variant AS variant,- count(entity_metrics.entity_id) AS num_users,- sum(entity_metrics.numerator_value) AS total_sum,- sum(power(entity_metrics.numerator_value, 2)) AS total_sum_of_squares,- sum(entity_metrics.denominator_value) AS denominator_sum,- sum(power(entity_metrics.denominator_value, 2)) AS denominator_sum_squares,- sum(entity_metrics.numerator_value * entity_metrics.denominator_value) AS numerator_denominator_sum_product- -- breakdown columns added programmatically below- FROM entity_metrics- GROUP BY entity_metrics.variant- -- breakdown columns added programmatically below- """,- placeholders=placeholders,- )-- assert isinstance(query, ast.SelectQuery)-- # Inject breakdown columns into the query AST- if self.breakdown_injector:- self.breakdown_injector.inject_ratio_breakdown_columns(query)-- return query+ return self._ratio_query_builder().build_ratio_query()def _ratio_needs_winsorization(self) -> bool:"""Whether either component of a ratio metric has outlier handling configured."""- assert isinstance(self.metric, ExperimentRatioMetric)- for outlier_handling in (- self.metric.numerator_outlier_handling,- self.metric.denominator_outlier_handling,- ):- if outlier_handling is not None and (- outlier_handling.lower_bound_percentile is not None- or outlier_handling.upper_bound_percentile is not None- ):- return True- return False+ return self._ratio_query_builder().ratio_needs_winsorization()def _build_winsorization_bound_exprs(self,@@ -743,33 +398,7 @@ class ExperimentQueryBuilder:value_field is an internal column name (numerator_value / denominator_value), neveruser input, so interpolating it into the expression string is safe."""- lower_pct = outlier_handling.lower_bound_percentile if outlier_handling else None- upper_pct = outlier_handling.upper_bound_percentile if outlier_handling else None- ignore_zeros = bool(outlier_handling.ignore_zeros) if outlier_handling else False-- if lower_pct is not None:- lower_bound_expr = parse_expr(- f"quantileExact({{level}})(entity_metrics.{value_field})",- placeholders={"level": ast.Constant(value=lower_pct)},- )- else:- lower_bound_expr = parse_expr(f"min(entity_metrics.{value_field})")-- if upper_pct is not None:- if ignore_zeros:- upper_bound_expr = parse_expr(- f"quantileExact({{level}})(if(entity_metrics.{value_field} != 0, entity_metrics.{value_field}, null))",- placeholders={"level": ast.Constant(value=upper_pct)},- )- else:- upper_bound_expr = parse_expr(- f"quantileExact({{level}})(entity_metrics.{value_field})",- placeholders={"level": ast.Constant(value=upper_pct)},- )- else:- upper_bound_expr = parse_expr(f"max(entity_metrics.{value_field})")-- return lower_bound_expr, upper_bound_expr+ return self._ratio_query_builder().build_winsorization_bound_exprs(outlier_handling, value_field)def _build_ratio_query_with_winsorization(self) -> ast.SelectQuery:"""@@ -782,72 +411,7 @@ class ExperimentQueryBuilder:(including the cross-product) so the delta-method variance stays consistent with thecapped point estimate."""- assert isinstance(self.metric, ExperimentRatioMetric)-- common_ctes, placeholders = self._get_ratio_query_common()-- num_lower_bound, num_upper_bound = self._build_winsorization_bound_exprs(- self.metric.numerator_outlier_handling, "numerator_value"- )- denom_lower_bound, denom_upper_bound = self._build_winsorization_bound_exprs(- self.metric.denominator_outlier_handling, "denominator_value"- )-- placeholders["numerator_lower_bound"] = num_lower_bound- placeholders["numerator_upper_bound"] = num_upper_bound- placeholders["denominator_lower_bound"] = denom_lower_bound- placeholders["denominator_upper_bound"] = denom_upper_bound-- query = parse_select(- f"""- WITH {common_ctes},-- percentiles AS (- SELECT- {{numerator_lower_bound}} AS numerator_lower_bound,- {{numerator_upper_bound}} AS numerator_upper_bound,- {{denominator_lower_bound}} AS denominator_lower_bound,- {{denominator_upper_bound}} AS denominator_upper_bound- -- breakdown columns added programmatically below- FROM entity_metrics- -- GROUP BY added programmatically below if breakdowns exist- ),-- winsorized_entity_metrics AS (- SELECT- entity_metrics.entity_id AS entity_id,- entity_metrics.variant AS variant,- least(greatest(percentiles.numerator_lower_bound, entity_metrics.numerator_value), percentiles.numerator_upper_bound) AS numerator_value,- least(greatest(percentiles.denominator_lower_bound, entity_metrics.denominator_value), percentiles.denominator_upper_bound) AS denominator_value- -- breakdown columns added programmatically below- FROM entity_metrics- CROSS JOIN percentiles- -- JOIN conditions added programmatically below if breakdowns exist- )-- SELECT- winsorized_entity_metrics.variant AS variant,- count(winsorized_entity_metrics.entity_id) AS num_users,- sum(winsorized_entity_metrics.numerator_value) AS total_sum,- sum(power(winsorized_entity_metrics.numerator_value, 2)) AS total_sum_of_squares,- sum(winsorized_entity_metrics.denominator_value) AS denominator_sum,- sum(power(winsorized_entity_metrics.denominator_value, 2)) AS denominator_sum_squares,- sum(winsorized_entity_metrics.numerator_value * winsorized_entity_metrics.denominator_value) AS numerator_denominator_sum_product- -- breakdown columns added programmatically below- FROM winsorized_entity_metrics- GROUP BY winsorized_entity_metrics.variant- -- breakdown columns added programmatically below- """,- placeholders=placeholders,- )-- assert isinstance(query, ast.SelectQuery)-- # Inject breakdown columns into the query AST- if self.breakdown_injector:- self.breakdown_injector.inject_ratio_breakdown_columns(query, winsorized=True)-- return query+ return self._ratio_query_builder().build_ratio_query_with_winsorization()def _get_ratio_query_common(self) -> tuple[str, dict[str, ast.Expr]]:"""@@ -862,158 +426,7 @@ class ExperimentQueryBuilder:This approach reduces memory pressure by joining exposures to events only onceper component instead of fanning out the raw event rows."""- assert isinstance(self.metric, ExperimentRatioMetric)-- # Use MetricSourceInfo abstraction for both numerator and denominator- num_source_info = MetricSourceInfo.from_source(self.metric.numerator, entity_key=self.entity_key)- denom_source_info = MetricSourceInfo.from_source(self.metric.denominator, entity_key=self.entity_key)-- # Extract field names for numerator- num_table = num_source_info.table_name- num_entity_field = num_source_info.entity_key- num_timestamp_field = num_source_info.timestamp_field-- # Extract field names for denominator- denom_table = denom_source_info.table_name- denom_entity_field = denom_source_info.entity_key- denom_timestamp_field = denom_source_info.timestamp_field-- # Build exposure query with conditional exposure_identifier(s)- exposure_query = self._get_exposure_query()- if num_source_info.kind == "datawarehouse" or denom_source_info.kind == "datawarehouse":- # Add exposure_identifier fields for data warehouse joins- # Support different join keys for numerator and denominator- if num_source_info.kind == "datawarehouse":- num_source = cast(ExperimentDataWarehouseNode, self.metric.numerator)- num_join_key_parts = cast(list[str | int], num_source.events_join_key.split("."))-- # Use argMin to pick one exposure_identifier per entity_id (from first exposure)- # This prevents fan-out when a user has multiple exposures with different join key values- exposure_query.select.append(- ast.Alias(- alias="exposure_identifier_num",- expr=ast.Call(- name="argMin",- args=[ast.Field(chain=num_join_key_parts), ast.Field(chain=["timestamp"])],- ),- )- )- # Do NOT add to GROUP BY - that would cause fan-out when join key varies across exposures-- if denom_source_info.kind == "datawarehouse":- denom_source = cast(ExperimentDataWarehouseNode, self.metric.denominator)- denom_join_key_parts = cast(list[str | int], denom_source.events_join_key.split("."))-- # Use argMin to pick one exposure_identifier per entity_id (from first exposure)- # This prevents fan-out when a user has multiple exposures with different join key values- exposure_query.select.append(- ast.Alias(- alias="exposure_identifier_denom",- expr=ast.Call(- name="argMin",- args=[ast.Field(chain=denom_join_key_parts), ast.Field(chain=["timestamp"])],- ),- )- )- # Do NOT add to GROUP BY - that would cause fan-out when join key varies across exposures-- # Build join conditions for pre-aggregation CTEs based on DW scenario- if num_source_info.kind == "datawarehouse":- num_preagg_join = "toString(exposures.exposure_identifier_num) = toString(numerator_events.entity_id)"- else:- num_preagg_join = "exposures.entity_id = numerator_events.entity_id"-- if denom_source_info.kind == "datawarehouse":- denom_preagg_join = "toString(exposures.exposure_identifier_denom) = toString(denominator_events.entity_id)"- else:- denom_preagg_join = "exposures.entity_id = denominator_events.entity_id"-- # Pre-aggregation approach: aggregate events per entity_id FIRST, then join- # This dramatically reduces memory usage by avoiding large intermediate result sets- # Memory impact: 471M rows → ~2M rows in joins- 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}}- ),-- 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}}- ),-- numerator_agg AS (- SELECT- exposures.entity_id AS entity_id,- {{numerator_agg}} AS value- FROM numerator_events- JOIN exposures ON {num_preagg_join}- WHERE {{numerator_conversion_window}}- GROUP BY exposures.entity_id- ),-- denominator_agg AS (- SELECT- exposures.entity_id AS entity_id,- {{denominator_agg}} AS value- FROM denominator_events- JOIN exposures ON {denom_preagg_join}- WHERE {{denominator_conversion_window}}- GROUP BY exposures.entity_id- ),-- entity_metrics AS (- SELECT- exposures.variant AS variant,- exposures.entity_id AS entity_id,- any(coalesce(numerator_agg.value, 0)) AS numerator_value,- any(coalesce(denominator_agg.value, 0)) AS denominator_value- -- breakdown columns added programmatically below- FROM exposures- LEFT JOIN numerator_agg ON exposures.entity_id = numerator_agg.entity_id- LEFT JOIN denominator_agg ON exposures.entity_id = denominator_agg.entity_id- GROUP BY exposures.variant, exposures.entity_id- -- breakdown columns added programmatically below- )- """-- placeholders: dict[str, ast.Expr] = {- "exposure_select_query": exposure_query,- "num_entity_key": num_entity_field,- "denom_entity_key": denom_entity_field,- "num_timestamp_field": ast.Field(chain=[num_timestamp_field]),- "num_table": ast.Field(chain=[num_table]),- "denom_timestamp_field": ast.Field(chain=[denom_timestamp_field]),- "denom_table": ast.Field(chain=[denom_table]),- "numerator_predicate": self._build_metric_predicate(source=self.metric.numerator, table_alias=num_table),- "numerator_value_expr": self._build_value_expr(source=self.metric.numerator),- "numerator_agg": self._build_value_aggregation_expr(- source=self.metric.numerator, events_alias="numerator_events", column_name="value"- ),- "numerator_conversion_window": self._build_conversion_window_predicate_for_events("numerator_events"),- "denominator_predicate": self._build_metric_predicate(- source=self.metric.denominator, table_alias=denom_table- ),- "denominator_value_expr": self._build_value_expr(source=self.metric.denominator),- "denominator_agg": self._build_value_aggregation_expr(- source=self.metric.denominator, events_alias="denominator_events", column_name="value"- ),- "denominator_conversion_window": self._build_conversion_window_predicate_for_events("denominator_events"),- }-- return common_ctes, placeholders+ return self._ratio_query_builder().get_ratio_query_common()def _build_conversion_window_predicate(self) -> ast.Expr:"""diff --git a/posthog/hogql_queries/experiments/experiment_ratio_query_builder.py b/posthog/hogql_queries/experiments/experiment_ratio_query_builder.pynew file mode 100644index 000000000000..90ef878d7e5c--- /dev/null+++ b/posthog/hogql_queries/experiments/experiment_ratio_query_builder.py@@ -0,0 +1,374 @@+from typing import TYPE_CHECKING, cast++from posthog.schema import ExperimentDataWarehouseNode, ExperimentMetricOutlierHandling, ExperimentRatioMetric++from posthog.hogql import ast+from posthog.hogql.parser import parse_expr, parse_select++from posthog.hogql_queries.experiments.metric_source import MetricSourceInfo++if TYPE_CHECKING:+ from posthog.hogql_queries.experiments.experiment_query_builder import ExperimentQueryBuilder+++class RatioQueryBuilder:+ """+ Builds ratio-metric queries, including the winsorized variant.++ Ratio construction reuses the shared exposure and metric-value helpers+ already extracted from the experiment query builder. To keep the move+ behavior-preserving, this class holds a reference to the owning+ ``ExperimentQueryBuilder`` and reaches through it for shared state (the+ metric, entity key, breakdown injector) and those cross-cluster helpers.+ """++ def __init__(self, builder: "ExperimentQueryBuilder"):+ self._b = builder++ def build_ratio_query(self) -> ast.SelectQuery:+ """+ Builds query for ratio metrics.++ Dispatches to the winsorized variant when outlier handling is configured for+ either the numerator or the denominator.+ """+ assert isinstance(self._b.metric, ExperimentRatioMetric)++ if self.ratio_needs_winsorization():+ return self.build_ratio_query_with_winsorization()++ common_ctes, placeholders = self.get_ratio_query_common()++ query = parse_select(+ f"""+ WITH {common_ctes}++ SELECT+ entity_metrics.variant AS variant,+ count(entity_metrics.entity_id) AS num_users,+ sum(entity_metrics.numerator_value) AS total_sum,+ sum(power(entity_metrics.numerator_value, 2)) AS total_sum_of_squares,+ sum(entity_metrics.denominator_value) AS denominator_sum,+ sum(power(entity_metrics.denominator_value, 2)) AS denominator_sum_squares,+ sum(entity_metrics.numerator_value * entity_metrics.denominator_value) AS numerator_denominator_sum_product+ -- breakdown columns added programmatically below+ FROM entity_metrics+ GROUP BY entity_metrics.variant+ -- breakdown columns added programmatically below+ """,+ placeholders=placeholders,+ )++ assert isinstance(query, ast.SelectQuery)++ # Inject breakdown columns into the query AST+ if self._b.breakdown_injector:+ self._b.breakdown_injector.inject_ratio_breakdown_columns(query)++ return query++ def ratio_needs_winsorization(self) -> bool:+ """Whether either component of a ratio metric has outlier handling configured."""+ assert isinstance(self._b.metric, ExperimentRatioMetric)+ for outlier_handling in (+ self._b.metric.numerator_outlier_handling,+ self._b.metric.denominator_outlier_handling,+ ):+ if outlier_handling is not None and (+ outlier_handling.lower_bound_percentile is not None+ or outlier_handling.upper_bound_percentile is not None+ ):+ return True+ return False++ def build_winsorization_bound_exprs(+ self,+ outlier_handling: ExperimentMetricOutlierHandling | None,+ value_field: str,+ ) -> tuple[ast.Expr, ast.Expr]:+ """+ Build (lower_bound, upper_bound) expressions over entity_metrics.<value_field>.++ When a bound is not configured the threshold falls back to min()/max() so the+ least(greatest(...)) clamp becomes a no-op for that side. This lets the numerator+ and denominator be capped independently — a binomial denominator simply leaves its+ outlier handling unset and is never clamped.++ value_field is an internal column name (numerator_value / denominator_value), never+ user input, so interpolating it into the expression string is safe.+ """+ lower_pct = outlier_handling.lower_bound_percentile if outlier_handling else None+ upper_pct = outlier_handling.upper_bound_percentile if outlier_handling else None+ ignore_zeros = bool(outlier_handling.ignore_zeros) if outlier_handling else False++ if lower_pct is not None:+ lower_bound_expr = parse_expr(+ f"quantileExact({{level}})(entity_metrics.{value_field})",+ placeholders={"level": ast.Constant(value=lower_pct)},+ )+ else:+ lower_bound_expr = parse_expr(f"min(entity_metrics.{value_field})")++ if upper_pct is not None:+ if ignore_zeros:+ upper_bound_expr = parse_expr(+ f"quantileExact({{level}})(if(entity_metrics.{value_field} != 0, entity_metrics.{value_field}, null))",+ placeholders={"level": ast.Constant(value=upper_pct)},+ )+ else:+ upper_bound_expr = parse_expr(+ f"quantileExact({{level}})(entity_metrics.{value_field})",+ placeholders={"level": ast.Constant(value=upper_pct)},+ )+ else:+ upper_bound_expr = parse_expr(f"max(entity_metrics.{value_field})")++ return lower_bound_expr, upper_bound_expr++ def build_ratio_query_with_winsorization(self) -> ast.SelectQuery:+ """+ Builds query for ratio metrics with winsorization (outlier handling).++ The numerator and denominator are capped independently, each as if it were its own+ mean metric: percentile thresholds are computed separately for each component (pooled+ across all variations) and the per-entity numerator and denominator values are clamped+ against their own bounds. The capped components flow into the same aggregate columns+ (including the cross-product) so the delta-method variance stays consistent with the+ capped point estimate.+ """+ assert isinstance(self._b.metric, ExperimentRatioMetric)++ common_ctes, placeholders = self.get_ratio_query_common()++ num_lower_bound, num_upper_bound = self.build_winsorization_bound_exprs(+ self._b.metric.numerator_outlier_handling, "numerator_value"+ )+ denom_lower_bound, denom_upper_bound = self.build_winsorization_bound_exprs(+ self._b.metric.denominator_outlier_handling, "denominator_value"+ )++ placeholders["numerator_lower_bound"] = num_lower_bound+ placeholders["numerator_upper_bound"] = num_upper_bound+ placeholders["denominator_lower_bound"] = denom_lower_bound+ placeholders["denominator_upper_bound"] = denom_upper_bound++ query = parse_select(+ f"""+ WITH {common_ctes},++ percentiles AS (+ SELECT+ {{numerator_lower_bound}} AS numerator_lower_bound,+ {{numerator_upper_bound}} AS numerator_upper_bound,+ {{denominator_lower_bound}} AS denominator_lower_bound,+ {{denominator_upper_bound}} AS denominator_upper_bound+ -- breakdown columns added programmatically below+ FROM entity_metrics+ -- GROUP BY added programmatically below if breakdowns exist+ ),++ winsorized_entity_metrics AS (+ SELECT+ entity_metrics.entity_id AS entity_id,+ entity_metrics.variant AS variant,+ least(greatest(percentiles.numerator_lower_bound, entity_metrics.numerator_value), percentiles.numerator_upper_bound) AS numerator_value,+ least(greatest(percentiles.denominator_lower_bound, entity_metrics.denominator_value), percentiles.denominator_upper_bound) AS denominator_value+ -- breakdown columns added programmatically below+ FROM entity_metrics+ CROSS JOIN percentiles+ -- JOIN conditions added programmatically below if breakdowns exist+ )++ SELECT+ winsorized_entity_metrics.variant AS variant,+ count(winsorized_entity_metrics.entity_id) AS num_users,+ sum(winsorized_entity_metrics.numerator_value) AS total_sum,+ sum(power(winsorized_entity_metrics.numerator_value, 2)) AS total_sum_of_squares,+ sum(winsorized_entity_metrics.denominator_value) AS denominator_sum,+ sum(power(winsorized_entity_metrics.denominator_value, 2)) AS denominator_sum_squares,+ sum(winsorized_entity_metrics.numerator_value * winsorized_entity_metrics.denominator_value) AS numerator_denominator_sum_product+ -- breakdown columns added programmatically below+ FROM winsorized_entity_metrics+ GROUP BY winsorized_entity_metrics.variant+ -- breakdown columns added programmatically below+ """,+ placeholders=placeholders,+ )++ assert isinstance(query, ast.SelectQuery)++ # Inject breakdown columns into the query AST+ if self._b.breakdown_injector:+ self._b.breakdown_injector.inject_ratio_breakdown_columns(query, winsorized=True)++ return query++ def get_ratio_query_common(self) -> tuple[str, dict[str, ast.Expr]]:+ """+ Builds the shared CTE chain and placeholders for ratio metric queries.++ Optimized structure using pre-aggregation to reduce join operations:+ - exposures: all exposures with variant assignment (with exposure_identifier for data warehouse)+ - numerator_events / denominator_events: events for each component with value+ - numerator_agg / denominator_agg: per-entity aggregates joined to exposures+ - entity_metrics: single row per entity carrying numerator_value and denominator_value++ This approach reduces memory pressure by joining exposures to events only once+ per component instead of fanning out the raw event rows.+ """+ assert isinstance(self._b.metric, ExperimentRatioMetric)++ # Use MetricSourceInfo abstraction for both numerator and denominator+ num_source_info = MetricSourceInfo.from_source(self._b.metric.numerator, entity_key=self._b.entity_key)+ denom_source_info = MetricSourceInfo.from_source(self._b.metric.denominator, entity_key=self._b.entity_key)++ # Extract field names for numerator+ num_table = num_source_info.table_name+ num_entity_field = num_source_info.entity_key+ num_timestamp_field = num_source_info.timestamp_field++ # Extract field names for denominator+ denom_table = denom_source_info.table_name+ denom_entity_field = denom_source_info.entity_key+ denom_timestamp_field = denom_source_info.timestamp_field++ # Build exposure query with conditional exposure_identifier(s)+ exposure_query = self._b._get_exposure_query()+ if num_source_info.kind == "datawarehouse" or denom_source_info.kind == "datawarehouse":+ # Add exposure_identifier fields for data warehouse joins+ # Support different join keys for numerator and denominator+ if num_source_info.kind == "datawarehouse":+ num_source = cast(ExperimentDataWarehouseNode, self._b.metric.numerator)+ num_join_key_parts = cast(list[str | int], num_source.events_join_key.split("."))++ # Use argMin to pick one exposure_identifier per entity_id (from first exposure)+ # This prevents fan-out when a user has multiple exposures with different join key values+ exposure_query.select.append(+ ast.Alias(+ alias="exposure_identifier_num",+ expr=ast.Call(+ name="argMin",+ args=[ast.Field(chain=num_join_key_parts), ast.Field(chain=["timestamp"])],+ ),+ )+ )+ # Do NOT add to GROUP BY - that would cause fan-out when join key varies across exposures++ if denom_source_info.kind == "datawarehouse":+ denom_source = cast(ExperimentDataWarehouseNode, self._b.metric.denominator)+ denom_join_key_parts = cast(list[str | int], denom_source.events_join_key.split("."))++ # Use argMin to pick one exposure_identifier per entity_id (from first exposure)+ # This prevents fan-out when a user has multiple exposures with different join key values+ exposure_query.select.append(+ ast.Alias(+ alias="exposure_identifier_denom",+ expr=ast.Call(+ name="argMin",+ args=[ast.Field(chain=denom_join_key_parts), ast.Field(chain=["timestamp"])],+ ),+ )+ )+ # Do NOT add to GROUP BY - that would cause fan-out when join key varies across exposures++ # Build join conditions for pre-aggregation CTEs based on DW scenario+ if num_source_info.kind == "datawarehouse":+ num_preagg_join = "toString(exposures.exposure_identifier_num) = toString(numerator_events.entity_id)"+ else:+ num_preagg_join = "exposures.entity_id = numerator_events.entity_id"++ if denom_source_info.kind == "datawarehouse":+ denom_preagg_join = "toString(exposures.exposure_identifier_denom) = toString(denominator_events.entity_id)"+ else:+ denom_preagg_join = "exposures.entity_id = denominator_events.entity_id"++ # Pre-aggregation approach: aggregate events per entity_id FIRST, then join+ # This dramatically reduces memory usage by avoiding large intermediate result sets+ # Memory impact: 471M rows → ~2M rows in joins+ 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}}+ ),++ 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}}+ ),++ numerator_agg AS (+ SELECT+ exposures.entity_id AS entity_id,+ {{numerator_agg}} AS value+ FROM numerator_events+ JOIN exposures ON {num_preagg_join}+ WHERE {{numerator_conversion_window}}+ GROUP BY exposures.entity_id+ ),++ denominator_agg AS (+ SELECT+ exposures.entity_id AS entity_id,+ {{denominator_agg}} AS value+ FROM denominator_events+ JOIN exposures ON {denom_preagg_join}+ WHERE {{denominator_conversion_window}}+ GROUP BY exposures.entity_id+ ),++ entity_metrics AS (+ SELECT+ exposures.variant AS variant,+ exposures.entity_id AS entity_id,+ any(coalesce(numerator_agg.value, 0)) AS numerator_value,+ any(coalesce(denominator_agg.value, 0)) AS denominator_value+ -- breakdown columns added programmatically below+ FROM exposures+ LEFT JOIN numerator_agg ON exposures.entity_id = numerator_agg.entity_id+ LEFT JOIN denominator_agg ON exposures.entity_id = denominator_agg.entity_id+ GROUP BY exposures.variant, exposures.entity_id+ -- breakdown columns added programmatically below+ )+ """++ placeholders: dict[str, ast.Expr] = {+ "exposure_select_query": exposure_query,+ "num_entity_key": num_entity_field,+ "denom_entity_key": denom_entity_field,+ "num_timestamp_field": ast.Field(chain=[num_timestamp_field]),+ "num_table": ast.Field(chain=[num_table]),+ "denom_timestamp_field": ast.Field(chain=[denom_timestamp_field]),+ "denom_table": ast.Field(chain=[denom_table]),+ "numerator_predicate": self._b._build_metric_predicate(+ source=self._b.metric.numerator, table_alias=num_table+ ),+ "numerator_value_expr": self._b._build_value_expr(source=self._b.metric.numerator),+ "numerator_agg": self._b._build_value_aggregation_expr(+ source=self._b.metric.numerator, events_alias="numerator_events", column_name="value"+ ),+ "numerator_conversion_window": self._b._build_conversion_window_predicate_for_events("numerator_events"),+ "denominator_predicate": self._b._build_metric_predicate(+ source=self._b.metric.denominator, table_alias=denom_table+ ),+ "denominator_value_expr": self._b._build_value_expr(source=self._b.metric.denominator),+ "denominator_agg": self._b._build_value_aggregation_expr(+ source=self._b.metric.denominator, events_alias="denominator_events", column_name="value"+ ),+ "denominator_conversion_window": self._b._build_conversion_window_predicate_for_events(+ "denominator_events"+ ),+ }++ return common_ctes, placeholders