: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): trim and correct comments in query runner code (#107210)
Anders3da174b397d2
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 5f09bc9a8b8e..3ca8380ba94f 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -122,7 +122,6 @@1 products/error_tracking/backend/hogql_queries/error_tracking_issue_correlation_query_runner.py1 products/error_tracking/backend/logic/symbol_sets.py1 products/error_tracking/backend/temporal/weekly_digest/test/test_weekly_digest_temporal.py-1 products/experiments/backend/hogql_queries/metric_source.py1 products/experiments/backend/running_time_calculator.py1 products/experiments/stats/frequentist/method.py1 products/experiments/stats/frequentist/tests.pydiff --git a/products/experiments/backend/hogql_queries/__init__.py b/products/experiments/backend/hogql_queries/__init__.pyindex 2a2ca64d59a4..5c761c28776e 100644--- a/products/experiments/backend/hogql_queries/__init__.py+++ b/products/experiments/backend/hogql_queries/__init__.py@@ -1,4 +1,3 @@-# The FF variant name for controlCONTROL_VARIANT_KEY = "control"@@ -16,15 +15,13 @@ def get_baseline_variant_key(stats_config: dict | None, variant_keys: list[str])return variant_keys[0]-# The FF variant name for multiple variants+# Variant key for an entity exposed to more than one variantMULTIPLE_VARIANT_KEY = "$multiple"-# controls minimum number of people to be exposed to a variant-# before the results are deemed significant+# Minimum number of people exposed to a variant before the results can be significantFF_DISTRIBUTION_THRESHOLD = 100-# If probability of a variant is below this threshold, it will be considered-# insignificant+# A variant with a win probability below this threshold is not significantMIN_PROBABILITY_FOR_SIGNIFICANCE = 0.9EXPECTED_LOSS_SIGNIFICANCE_LEVEL = 0.01diff --git a/products/experiments/backend/hogql_queries/base_query_utils.py b/products/experiments/backend/hogql_queries/base_query_utils.pyindex 90772f99ab18..e7e25cdd5422 100644--- a/products/experiments/backend/hogql_queries/base_query_utils.py+++ b/products/experiments/backend/hogql_queries/base_query_utils.py@@ -39,13 +39,11 @@ from products.product_analytics.backend.facade.queries import ALLOWED_SESSION_MAdef is_session_property_metric(source: Union[EventsNode, ActionsNode]) -> bool:"""- Check if the metric source uses session-level aggregation.+ Session properties need special handling:+ 1. They are read from session.X instead of properties.X.+ 2. They need deduplication per session, so that a session with many events counts once.- Session properties require special handling:- 1. They must be accessed via session.X instead of properties.X- 2. They need deduplication per session to avoid event multiplication-- Matches logic in trends/aggregation_operations.py:166-179+ Keep in sync with the session property checks in product_analytics trends/aggregation_operations.py."""if not hasattr(source, "math_property"):return False@@ -64,10 +62,7 @@ def is_session_property_metric(source: Union[EventsNode, ActionsNode]) -> bool:def validate_session_property(source: Union[EventsNode, ActionsNode]) -> str:"""- Validate and return the session property name.-- Raises ValueError for invalid properties.- Matches logic in trends/aggregation_operations.py:154-164+ Keep in sync with the session property checks in product_analytics trends/aggregation_operations.py."""math_property = getattr(source, "math_property", None)if not math_property:@@ -114,17 +109,14 @@ def is_threshold_supported_math(math_type: ExperimentMetricMathType | None) -> bdef get_source_value_expr(source: Union[EventsNode, ActionsNode, ExperimentDataWarehouseNode]) -> ast.Expr:"""- Returns the expression for extracting values from a given source (EventsNode, ActionsNode, or DataWarehouseNode).- For count metrics, returns 1. For property-based metrics, extracts the property value.+ Return the per-row value that the metric aggregates."""if isinstance(source, EventsNode) or isinstance(source, ActionsNode):- # Check if the source has a math type that indicates continuous valuesif hasattr(source, "math") and is_continuous(source.math):- # If the metric is a property math type, we need to extract the value from the event propertymetric_property = getattr(source, "math_property", None)if metric_property:- # Use the same property access pattern as trends to get property groups optimization+ # Access the property the same way as trends, so that the property groups optimization applies.return ast.Call(name="toFloat", args=[ast.Field(chain=["properties", metric_property])])elif hasattr(source, "math") and source.math == ExperimentMetricMathType.UNIQUE_SESSION:return ast.Field(chain=["$session_id"])@@ -141,7 +133,6 @@ def get_source_value_expr(source: Union[EventsNode, ActionsNode, ExperimentDataWand source.math == ExperimentMetricMathType.HOGQLand getattr(source, "math_hogql", None) is not None):- # Extract the inner expression from the HogQL expressionmath_hogql = source.math_hogqlif math_hogql:tag_contains_user_hogql()@@ -169,26 +160,22 @@ def get_source_value_expr(source: Union[EventsNode, ActionsNode, ExperimentDataW)return parsed- # Default to count - emit 1 so we can easily sum it up+ # Count metrics: each row contributes 1, so the sum is the event count.return ast.Constant(value=1)def event_or_action_to_filter(team: Team, entity_node: Union[EventsNode, ActionsNode, ExperimentEventExposureConfig]) -> ast.Expr:- """- Returns the filter for a single entity node.- """-if isinstance(entity_node, ActionsNode):try:action = Action.objects.get(pk=int(entity_node.id), team__project_id=team.project_id)event_filter = action_to_expr(action)except Action.DoesNotExist:- # If an action doesn't exist, we want to return no events+ # A missing action matches no events, so that the query still runs.event_filter = ast.Constant(value=False)else:- # If event is None, we want to match all events (no event name filter)+ # An event of None means "All events", so there is no event name filter.if entity_node.event is None:event_filter = ast.Constant(value=True)else:@@ -206,10 +193,6 @@ def event_or_action_to_filter(def data_warehouse_node_to_filter(team: Team, node: ExperimentDataWarehouseNode) -> ast.Expr:- """- Returns the filter for a data warehouse node, including all properties and fixedProperties.- """- # Collect all properties from both properties and fixedPropertiesall_properties = []if node.properties:@@ -218,12 +201,9 @@ def data_warehouse_node_to_filter(team: Team, node: ExperimentDataWarehouseNode)if node.fixedProperties:all_properties.extend(node.fixedProperties)- # If no properties, return True (no filtering)if not all_properties:return ast.Constant(value=True)- # Use property_to_expr to convert properties to HogQL expressions- # This follows the same pattern as TrendsQueryBuilder._events_filter()return property_to_expr(all_properties, team)@@ -255,17 +235,13 @@ def analysis_window_end(end_date: Optional[datetime], as_of: datetime) -> datetiFor an ordinary "current results" query the caller passes ``as_of = end_date or now``, so a stoppedexperiment resolves to ``end_date`` and a running one to ``now``. A recalc passes its frozen run- snapshot; a timeseries backfill passes each historical day — which is why an ``as_of`` *below*- ``end_date`` must win, so per-day points stay distinct instead of all collapsing onto ``end_date``.-- The historical "results keep growing after end_date" bug: the run snapshot (``now``, always at or- after a stopped experiment's ``end_date``) was used as the edge *instead of* ``end_date``, so the- window kept extending to now. Capping at ``end_date`` fixes it while preserving the sub-window.+ snapshot. A timeseries backfill passes each historical day, which is why an ``as_of`` *below*+ ``end_date`` must win: the per-day points stay distinct instead of all collapsing onto ``end_date``.- Value-based on purpose. A caller holding a serialized query whose result is cached under a key- hashed from that query (the exposure runner) must pass the query's ``end_date`` here, not live- model state — otherwise the key can describe a window the result wasn't computed for. Callers that- hold the model use the :func:`experiment_window_end` wrapper.+ The function takes values instead of the model on purpose. A caller holding a serialized query whose+ result is cached under a key hashed from that query (the exposure runner) must pass the query's+ ``end_date`` here, not live model state. Otherwise the key can describe a window the result wasn't+ computed for. Callers that hold the model use the :func:`experiment_window_end` wrapper.``as_of`` (and ``end_date`` when set) must be timezone-aware."""@@ -277,11 +253,11 @@ def analysis_window_end(end_date: Optional[datetime], as_of: datetime) -> datetidef analysis_window(start_date: Optional[datetime], end_date: Optional[datetime], team: Team, as_of: datetime) -> DateRange:- """Single source of truth for an experiment's analysis ``DateRange``, from raw start/end dates.+ """Build an experiment's analysis ``DateRange`` from raw start/end dates.- Replaces the scattered ``override_end_date or end_date or now`` derivations. The upper edge always- comes from :func:`analysis_window_end` (earlier of ``as_of`` and ``end_date``), so no call site can- extend the window past ``end_date``. A draft experiment (no ``start_date``) has no window.+ Derive every analysis window here. The upper edge always comes from :func:`analysis_window_end`+ (earlier of ``as_of`` and ``end_date``), so no call site can extend the window past ``end_date``.+ A draft experiment (no ``start_date``) has no window."""if start_date is None:return DateRange(date_from=None, date_to=None, explicitDate=True)@@ -314,18 +290,16 @@ def funnel_steps_to_filter(team: Team, funnel_steps: list[EventsNode | ActionsNode | ExperimentDataWarehouseNode]) -> ast.Expr:"""- Returns the OR expression for a list of funnel steps. Will match if any of the funnel steps are true.+ Match a row if it matches any funnel step.- Note: This function filters out ExperimentDataWarehouseNode entries since they cannot be- evaluated as boolean filters (they require separate UNION ALL query pattern).+ Data warehouse steps are skipped because they are not event filters. The funnel query+ reads them through a separate UNION ALL."""- # Filter out DW nodes - they require UNION ALL pattern, not boolean filtersevent_and_action_steps = [step for step in funnel_steps if not isinstance(step, ExperimentDataWarehouseNode)]- # Guard against empty list (all DW nodes case)if not event_and_action_steps:- # Return a constant false expression - this prevents empty ast.Or- # This case should be caught earlier by validation, but we guard defensively+ # Validation should reject a funnel with only data warehouse steps. Return False+ # if one gets through, because an empty ast.Or is not a valid expression.return ast.Constant(value=False)return ast.Or(exprs=[event_or_action_to_filter(team, funnel_step) for funnel_step in event_and_action_steps])@@ -335,11 +309,10 @@ def funnel_evaluation_expr(team: Team, funnel_metric: ExperimentFunnelMetric, events_alias: str, include_exposure: bool = False) -> ast.Expr:"""- Returns an expression using the aggregate_funnel_array UDF to evaluate the funnel.- Returns the highest step number (0-indexed) that the user reached.+ Evaluate the funnel with the aggregate_funnel_array UDF.- When events_alias is provided, assumes that step conditions have been pre-calculated- as step_0, step_1, etc. fields in the aliased table.+ The expression returns a tuple of (highest step reached, 0-indexed; uuid of that step's event).+ The `events_alias` table must have precomputed `step_0`, `step_1`, ... columns."""if funnel_metric.conversion_window is not None and funnel_metric.conversion_window_unit is not None:@@ -347,29 +320,25 @@ def funnel_evaluation_expr(funnel_metric.conversion_window, funnel_metric.conversion_window_unit)else:- # Default to include all events selected, so we just set a large value here (3 years)+ # Without a conversion window, all events count. 3 years is large enough to act as no limit.conversion_window_seconds = 3 * 365 * 24 * 60 * 60num_steps = len(funnel_metric.series)if include_exposure:num_steps += 1- # Create field references with proper alias supporttimestamp_field = f"{events_alias}.timestamp"uuid_field = f"{events_alias}.uuid"- # When using an alias, assume step conditions are pre-calculatedstep_conditions = [f"{i + 1} * {events_alias}.step_{i}" for i in range(num_steps)]step_conditions_str = ", ".join(step_conditions)- # Determine funnel order type - default to "ordered" for backward compatibility+ # Metrics saved without funnel_order_type use "ordered", the original behavior.funnel_order_type = funnel_metric.funnel_order_type or "ordered"- # Return tuple of (highest step reached, uuid of that step's event)- # aggregate_funnel_array returns an array of tuples where:- # result.1 is the step_reached (0-indexed)- # result.4 is an array of arrays of UUIDs for each step+ # aggregate_funnel_array returns an array of tuples. result.1 is the step reached (0-indexed),+ # and result.4 is an array of arrays of UUIDs for each step.expression = f"""arraySort(x -> -x.1,arrayMap(diff --git a/products/experiments/backend/hogql_queries/breakdown_injector.py b/products/experiments/backend/hogql_queries/breakdown_injector.pyindex ffb112b9b6c6..91c359654fd4 100644--- a/products/experiments/backend/hogql_queries/breakdown_injector.py+++ b/products/experiments/backend/hogql_queries/breakdown_injector.py@@ -1,9 +1,4 @@-"""-Breakdown column injection for experiment queries.--Handles injecting breakdown columns into various metric type queries (funnel, mean, ratio, retention).-Breakdown columns are used to segment experiment results by property values.-"""+"""Breakdown column injection for experiment metric queries (funnel, mean, ratio, retention)."""from typing import Union, cast@@ -27,10 +22,8 @@ from products.product_analytics.backend.facade.queries import get_properties_chaclass BreakdownInjector:"""- Handles injection of breakdown columns into experiment query AST.-- Breakdown columns are added to intermediate CTEs and final SELECT/GROUP BY clauses- to enable segmentation of experiment results by property values.+ Adds breakdown columns to the intermediate CTEs and the final SELECT/GROUP BY of an+ experiment query. Each entity takes its breakdown value from its first exposure."""def __init__(@@ -42,20 +35,15 @@ class BreakdownInjector:self.metric = metricdef _has_breakdown(self) -> bool:- """Returns True if any breakdowns are configured"""return len(self.breakdowns) > 0def _get_breakdown_aliases(self) -> list[str]:- """Returns list of breakdown aliases: ['breakdown_value_1', 'breakdown_value_2', ...]"""return [f"breakdown_value_{i + 1}" for i in range(len(self.breakdowns))]def build_breakdown_exprs(self, table_alias: str = "events") -> list[tuple[str, ast.Expr]]:"""- Returns list of (alias, expression) tuples for extracting breakdown properties from events.- Handles NULL values by replacing with BREAKDOWN_NULL_STRING_LABEL.- Returns empty list if no breakdowns configured.-- This is a public method used by exposure query building in ExperimentQueryBuilder.+ Returns (alias, expression) pairs that read each breakdown property, with NULL replaced+ by BREAKDOWN_NULL_STRING_LABEL. ExposureQueryBuilder also calls this."""if not self._has_breakdown():return []@@ -65,23 +53,20 @@ class BreakdownInjector:# Default to event type for backward compatibilitybreakdown_type = breakdown.type or cast(MultipleBreakdownType, "event")- # Convert property to string (it can be str | int in schema)+ # The schema allows an int property.breakdown_field = str(breakdown.property)- # Get the correct property chain based on typeproperties_chain = get_properties_chain(breakdown_type=breakdown_type,breakdown_field=breakdown_field,group_type_index=breakdown.group_type_index,)- # For event properties, prepend table_alias if provided- # For person/group/session, use chain as-is (they reference other tables)+ # Only event properties take the table alias. Person, group, and session chains+ # reference other tables.if table_alias and properties_chain[0] == "properties":- # Event property: prepend table aliasproperty_expr = ast.Field(chain=[table_alias, *properties_chain])else:- # Person/group/session property or no table alias: use chain directlyproperty_expr = ast.Field(chain=properties_chain)expr = parse_expr(@@ -97,40 +82,33 @@ class BreakdownInjector:return resultdef inject_funnel_breakdown_columns(self, query: ast.SelectQuery) -> None:- """- Injects breakdown columns into funnel query AST.- Modifies query in-place.- """if not self._has_breakdown():returnaliases = self._get_breakdown_aliases()breakdown_exprs = self.build_breakdown_exprs(table_alias="")- # Inject into metric_events CTE SELECTif query.ctes and "metric_events" in query.ctes:metric_events_cte = query.ctes["metric_events"]if isinstance(metric_events_cte, ast.CTE) and isinstance(metric_events_cte.expr, ast.SelectQuery):for alias, expr in breakdown_exprs:metric_events_cte.expr.select.append(ast.Alias(alias=alias, expr=expr))- # Inject into entity_metrics CTE SELECT (attribution - extract from exposure events only)if query.ctes and "entity_metrics" in query.ctes:entity_metrics_cte = query.ctes["entity_metrics"]if isinstance(entity_metrics_cte, ast.CTE) and isinstance(entity_metrics_cte.expr, ast.SelectQuery):- # Check if this is an unordered funnel (has exposures CTE with LEFT JOIN)- # In that case, breakdown comes from exposures, not metric_events+ # Only the unordered funnel has an exposures CTE, and the breakdown there is+ # already attributed. The ordered funnel attributes it from the first step_0+ # (exposure) row in metric_events.has_exposures = "exposures" in query.ctes if query.ctes else Falsefor alias in aliases:if has_exposures:- # Unordered funnel: get breakdown from exposures (already attributed)entity_metrics_cte.expr.select.append(ast.Alias(alias=alias, expr=ast.Field(chain=["exposures", alias])))else:- # Ordered funnel: use argMinIf to attribute from first exposure in metric_events- # Qualify the field reference to avoid ambiguity+ # Qualify the field with metric_events to avoid an ambiguous reference.entity_metrics_cte.expr.select.append(ast.Alias(alias=alias,@@ -149,46 +127,38 @@ class BreakdownInjector:))- # For unordered funnels, also add breakdown to entity_metrics GROUP BYif has_exposures:if entity_metrics_cte.expr.group_by is None:entity_metrics_cte.expr.group_by = []for alias in aliases:entity_metrics_cte.expr.group_by.append(ast.Field(chain=["exposures", alias]))- # Inject into final SELECT - breakdown columns must come right after variantfor i, alias in enumerate(aliases):query.select.insert(1 + i, # Position after variant column (index 0)ast.Alias(alias=alias, expr=ast.Field(chain=["entity_metrics", alias])),)- # Inject into final GROUP BYif query.group_by is None:query.group_by = []for alias in aliases:query.group_by.append(ast.Field(chain=["entity_metrics", alias]))def inject_funnel_breakdown_columns_optimized(self, query: ast.SelectQuery) -> None:- """- Injects breakdown columns into the optimized 2-CTE funnel query AST.- The optimized query has base_events and entity_metrics CTEs (no exposures CTE).- Modifies query in-place.- """+ """The optimized funnel query has base_events and entity_metrics CTEs, and no exposures CTE."""if not self._has_breakdown():returnaliases = self._get_breakdown_aliases()breakdown_exprs = self.build_breakdown_exprs(table_alias="")- # Inject into base_events CTE SELECTif query.ctes and "base_events" in query.ctes:base_events_cte = query.ctes["base_events"]if isinstance(base_events_cte, ast.CTE) and isinstance(base_events_cte.expr, ast.SelectQuery):for alias, expr in breakdown_exprs:base_events_cte.expr.select.append(ast.Alias(alias=alias, expr=expr))- # Inject into entity_metrics CTE SELECT using argMinIf attribution from first exposure+ # Attribute from the first step_0 (exposure) row.if query.ctes and "entity_metrics" in query.ctes:entity_metrics_cte = query.ctes["entity_metrics"]if isinstance(entity_metrics_cte, ast.CTE) and isinstance(entity_metrics_cte.expr, ast.SelectQuery):@@ -211,47 +181,35 @@ class BreakdownInjector:))- # Inject into final SELECT - breakdown columns must come right after variantfor i, alias in enumerate(aliases):query.select.insert(1 + i, # Position after variant column (index 0)ast.Alias(alias=alias, expr=ast.Field(chain=["entity_metrics", alias])),)- # Inject into final GROUP BYif query.group_by is None:query.group_by = []for alias in aliases:query.group_by.append(ast.Field(chain=["entity_metrics", alias]))def inject_mean_breakdown_columns(self, query: ast.SelectQuery, final_cte_name: str = "entity_metrics") -> None:- """- Injects breakdown columns into mean query AST.- Modifies query in-place.-- Args:- query: The parsed SelectQuery AST- final_cte_name: Name of the final CTE before main SELECT ('entity_metrics' or 'winsorized_entity_metrics')- """+ """final_cte_name is the CTE the main SELECT reads: 'entity_metrics' or 'winsorized_entity_metrics'."""if not self._has_breakdown():returnaliases = self._get_breakdown_aliases()- # Get table name for metric_events based on metric sourceassert isinstance(self.metric, ExperimentMeanMetric)is_dw = isinstance(self.metric.source, ExperimentDataWarehouseNode)breakdown_exprs = self.build_breakdown_exprs(table_alias="metric_events" if is_dw else "events")- # Inject into metric_events CTE SELECTif query.ctes and "metric_events" in query.ctes:metric_events_cte = query.ctes["metric_events"]if isinstance(metric_events_cte, ast.CTE) and isinstance(metric_events_cte.expr, ast.SelectQuery):for alias, expr in breakdown_exprs:metric_events_cte.expr.select.append(ast.Alias(alias=alias, expr=expr))- # Inject into entity_metrics CTE SELECT and GROUP BYif query.ctes and "entity_metrics" in query.ctes:entity_metrics_cte = query.ctes["entity_metrics"]if isinstance(entity_metrics_cte, ast.CTE) and isinstance(entity_metrics_cte.expr, ast.SelectQuery):@@ -259,43 +217,38 @@ class BreakdownInjector:entity_metrics_cte.expr.select.append(ast.Alias(alias=alias, expr=ast.Field(chain=["exposures", alias])))- # Also add to GROUP BYif entity_metrics_cte.expr.group_by is None:entity_metrics_cte.expr.group_by = []for alias in aliases:entity_metrics_cte.expr.group_by.append(ast.Field(chain=["exposures", alias]))- # Inject into percentiles CTE (only for winsorization queries)+ # Group the winsorization percentiles by breakdown, so that each breakdown group gets+ # its own thresholds.if query.ctes and "percentiles" in query.ctes:percentiles_cte = query.ctes["percentiles"]if isinstance(percentiles_cte, ast.CTE) and isinstance(percentiles_cte.expr, ast.SelectQuery):- # Add breakdown columns to SELECTfor alias in aliases:percentiles_cte.expr.select.append(ast.Alias(alias=alias, expr=ast.Field(chain=["entity_metrics", alias])))- # Initialize and populate GROUP BY for per-breakdown percentilesif percentiles_cte.expr.group_by is None:percentiles_cte.expr.group_by = []for alias in aliases:percentiles_cte.expr.group_by.append(ast.Field(chain=["entity_metrics", alias]))- # Inject into winsorized_entity_metrics CTE (only when final_cte_name is winsorized_entity_metrics)if query.ctes and final_cte_name == "winsorized_entity_metrics":winsorized_cte = query.ctes["winsorized_entity_metrics"]if isinstance(winsorized_cte, ast.CTE) and isinstance(winsorized_cte.expr, ast.SelectQuery):- # Add breakdown columns to SELECTfor alias in aliases:winsorized_cte.expr.select.append(ast.Alias(alias=alias, expr=ast.Field(chain=["entity_metrics", alias])))- # Convert CROSS JOIN to proper JOIN with breakdown conditions+ # Replace the CROSS JOIN to percentiles with a per-breakdown JOIN, so that each+ # entity is capped at the thresholds of its own breakdown group.if winsorized_cte.expr.select_from:join_expr = winsorized_cte.expr.select_from.next_joinif join_expr and isinstance(join_expr, ast.JoinExpr):- # Change from CROSS JOIN to INNER JOINjoin_expr.join_type = "JOIN"- # Build join condition: percentiles.bd1 = entity_metrics.bd1 AND ...join_conditions = []for alias in aliases:join_conditions.append(@@ -305,7 +258,6 @@ class BreakdownInjector:right=ast.Field(chain=["entity_metrics", alias]),))- # Combine conditions with ANDcondition_expr: ast.Exprif len(join_conditions) == 1:condition_expr = join_conditions[0]@@ -314,17 +266,14 @@ class BreakdownInjector:for condition in join_conditions[1:]:combined = ast.And(exprs=[combined, condition])condition_expr = combined- # Wrap in JoinConstraint with ON clausejoin_expr.constraint = ast.JoinConstraint(expr=condition_expr, constraint_type="ON")- # Inject into final SELECT - breakdown columns must come right after variantfor i, alias in enumerate(aliases):query.select.insert(1 + i, # Position after variant column (index 0)ast.Alias(alias=alias, expr=ast.Field(chain=[final_cte_name, alias])),)- # Inject into final GROUP BYif query.group_by is None:query.group_by = []for alias in aliases:@@ -332,13 +281,8 @@ class BreakdownInjector:def inject_ratio_breakdown_columns(self, query: ast.SelectQuery, winsorized: bool = False) -> None:"""- Injects breakdown columns into ratio query AST.- Modifies query in-place.-- With the pre-aggregation structure, breakdowns are simpler:- - Breakdowns are attributed from exposures (not from numerator/denominator events)- - entity_metrics gets breakdown columns directly from exposures- - No need for breakdown join conditions on the event joins+ Breakdowns come from exposures, not from numerator or denominator events. So+ entity_metrics reads them from exposures, and the event joins need no breakdown conditions.When ``winsorized`` is set the query has extra ``percentiles`` and``winsorized_entity_metrics`` CTEs: percentiles are computed per breakdown group@@ -351,7 +295,6 @@ class BreakdownInjector:aliases = self._get_breakdown_aliases()final_cte_name = "winsorized_entity_metrics" if winsorized else "entity_metrics"- # Inject into entity_metrics CTE SELECT and GROUP BY (from exposures)if query.ctes and "entity_metrics" in query.ctes:entity_metrics_cte = query.ctes["entity_metrics"]if isinstance(entity_metrics_cte, ast.CTE) and isinstance(entity_metrics_cte.expr, ast.SelectQuery):@@ -364,8 +307,8 @@ class BreakdownInjector:for alias in aliases:entity_metrics_cte.expr.group_by.append(ast.Field(chain=["exposures", alias]))- # Inject into percentiles CTE (only for winsorization queries) so each breakdown- # group gets its own thresholds, pooled across variations.+ # Group the winsorization percentiles by breakdown, so that each breakdown group gets its+ # own thresholds, pooled across variations.if winsorized and query.ctes and "percentiles" in query.ctes:percentiles_cte = query.ctes["percentiles"]if isinstance(percentiles_cte, ast.CTE) and isinstance(percentiles_cte.expr, ast.SelectQuery):@@ -378,8 +321,7 @@ class BreakdownInjector:for alias in aliases:percentiles_cte.expr.group_by.append(ast.Field(chain=["entity_metrics", alias]))- # Inject into winsorized_entity_metrics CTE: add breakdown columns and convert the- # CROSS JOIN to percentiles into a per-breakdown JOIN.+ # Replace the CROSS JOIN to percentiles with a per-breakdown JOIN.if winsorized and query.ctes and "winsorized_entity_metrics" in query.ctes:winsorized_cte = query.ctes["winsorized_entity_metrics"]if isinstance(winsorized_cte, ast.CTE) and isinstance(winsorized_cte.expr, ast.SelectQuery):@@ -410,59 +352,44 @@ class BreakdownInjector:condition_expr = combinedjoin_expr.constraint = ast.JoinConstraint(expr=condition_expr, constraint_type="ON")- # Inject into final SELECT - breakdown columns must come right after variantfor i, alias in enumerate(aliases):query.select.insert(1 + i, # Position after variant column (index 0)ast.Alias(alias=alias, expr=ast.Field(chain=[final_cte_name, alias])),)- # Inject into final GROUP BYif query.group_by is None:query.group_by = []for alias in aliases:query.group_by.append(ast.Field(chain=[final_cte_name, alias]))def inject_retention_breakdown_columns(self, query: ast.SelectQuery) -> None:- """- Injects breakdown columns into retention query AST.- Modifies query in-place.-- Retention breakdown injection is simpler than ratio because:- - Only entity_metrics CTE needs modification- - No JOIN conditions require breakdown columns- - Breakdowns come from exposures only- """+ """Breakdowns come from exposures, so only entity_metrics and the final SELECT need them."""if not self._has_breakdown():returnaliases = self._get_breakdown_aliases()- # Inject into entity_metrics CTE SELECT and GROUP BY (carry breakdown from exposures)if query.ctes and "entity_metrics" in query.ctes:entity_metrics_cte = query.ctes["entity_metrics"]if isinstance(entity_metrics_cte, ast.CTE) and isinstance(entity_metrics_cte.expr, ast.SelectQuery):- # Add breakdown columns to SELECT (after entity_id and variant)for i, alias in enumerate(aliases):entity_metrics_cte.expr.select.insert(2 + i, # After entity_id (0), variant (1)ast.Alias(alias=alias, expr=ast.Field(chain=["exposures", alias])),)- # Add breakdown columns to GROUP BYif entity_metrics_cte.expr.group_by is None:entity_metrics_cte.expr.group_by = []for alias in aliases:entity_metrics_cte.expr.group_by.append(ast.Field(chain=["exposures", alias]))- # Inject into final SELECT - breakdown columns must come right after variantfor i, alias in enumerate(aliases):query.select.insert(1 + i, # Position after variant column (index 0)ast.Alias(alias=alias, expr=ast.Field(chain=["entity_metrics", alias])),)- # Inject into final GROUP BYif query.group_by is None:query.group_by = []for alias in aliases:diff --git a/products/experiments/backend/hogql_queries/error_handling.py b/products/experiments/backend/hogql_queries/error_handling.pyindex 160171cbd4a6..d4b5c71cfb13 100644--- a/products/experiments/backend/hogql_queries/error_handling.py+++ b/products/experiments/backend/hogql_queries/error_handling.py@@ -36,7 +36,6 @@ if TYPE_CHECKING:from posthog.models.team import Teamfrom posthog.models.user import User-# Map error types to their error codes for the API responseERROR_TYPE_TO_CODE: dict[type, str] = {ClickHouseQueryMemoryLimitExceeded: "memory_limit_exceeded",}@@ -47,36 +46,28 @@ logger = structlog.get_logger(__name__)F = TypeVar("F", bound=Callable[..., Any])-# User-friendly error messages for specific error types-# Note: ValueError and generic Exception are intentionally excluded - they pass through unaltered-# so the original error message is visible for debugging+# ValueError and generic Exception are left out on purpose. They pass through unaltered, so that+# the original error message stays visible for debugging.ERROR_TYPE_MESSAGES: dict[type, str] = {- # Statistical calculation errorsStatisticError: "Unable to calculate experiment statistics. Please ensure your experiment has sufficient data and try again.",- # HogQL/Query errorsInternalHogQLError: "Unable to process your experiment query. Please check your metric configuration and try again.",ExposedCHQueryError: "Unable to retrieve experiment data. Please try refreshing the page.",- # ClickHouse resource errorsClickHouseQueryMemoryLimitExceeded: "This experiment query is using too much memory. Try viewing a shorter time period or contact support for help.",- # Python built-in errors that can occur during calculationZeroDivisionError: "Unable to calculate results due to insufficient data. Please wait for more experiment data.",}def get_user_friendly_message(error: Exception) -> str | None:- """Convert technical error messages to user-friendly ones based on error type.- Returns None if the error type is not in the mapping (should be re-raised as-is).- """+ """Return None when the error type has no mapping, so that the caller re-raises the error as-is."""error_type = type(error)- # If a ValidationError is raised, we can return the message directly+ # ValidationError messages are already user-facing.if error_type is ValidationError:validation_error = cast(ValidationError, error)if isinstance(validation_error.detail, list) and validation_error.detail:return str(validation_error.detail[0])elif isinstance(validation_error.detail, dict):- # For dict-style errors, get the first error messageif not validation_error.detail:return "Validation error occurred"first_key = next(iter(validation_error.detail))@@ -88,11 +79,9 @@ def get_user_friendly_message(error: Exception) -> str | None:else:return str(validation_error.detail)- # Look for exact type match firstif error_type in ERROR_TYPE_MESSAGES:return ERROR_TYPE_MESSAGES[error_type]- # Check if error is an instance of any of the registered typesfor registered_type, message in ERROR_TYPE_MESSAGES.items():if isinstance(error, registered_type):return message@@ -101,8 +90,8 @@ def get_user_friendly_message(error: Exception) -> str | None:def classify_experiment_query_error(error: Exception) -> str:- """Single failure taxonomy for the `experiment metric error` event, derived from the typed- exceptions `posthog/errors.py` already produces — never from message parsing or HTTP status.+ """Failure taxonomy for the `experiment metric error` event. It uses the typed exceptions+ from `posthog/errors.py`, never message parsing or HTTP status.Values: timeout · out_of_memory · byte_limit · rate_limited · insufficient_data ·validation_error · server_error (catch-all).@@ -120,8 +109,9 @@ def classify_experiment_query_error(error: Exception) -> str:if isinstance(error, ServerException):meta = look_up_clickhouse_error_code_meta(error)if meta.name == "NOT_AN_AGGREGATE":- # Only known producer in experiment queries is user-authored HogQL referencing a- # row-level column outside an aggregate — a metric-config error, not a platform one.+ # In experiment queries, only user-authored HogQL is known to produce this error, by+ # referencing a row-level column outside an aggregate. This is a metric configuration+ # error, not a platform error.return "validation_error"if meta.name in ("TIMEOUT_EXCEEDED", "SOCKET_TIMEOUT"):return "timeout"@@ -185,10 +175,10 @@ def capture_experiment_metric_error_event(def _emit_runner_terminal_error_event(runner: Any, error: Exception) -> None:"""Emit the terminal failure event for a query runner on the direct (in-request) path.- Gated on the runner's `error_event_context` ("ui"/"agent"; None = silent) AND `user_facing`- (internal callers — recalc, canary, warming — own their retries, so a runner-level emit there- would count non-terminal attempts). One runner execution is terminal on every direct path:- the frontend has no automatic retry loop and the async Celery task swallows failures+ Emits only when the runner has an `error_event_context` ("ui"/"agent"; None means silent) and is+ `user_facing`. Internal callers (recalc, canary, warming) own their retries, so an emit from the+ runner there would count non-terminal attempts. On every direct path one runner execution is+ terminal: the frontend has no automatic retry loop, and the async Celery task swallows failures(no retry passes back through the runner)."""if runner is None:@@ -230,17 +220,17 @@ def experiment_error_handler(method: F) -> F:try:return method(*args, **kwargs)except (ValidationError, ExposedHogQLError) as e:- # ValidationErrors and ExposedHogQLErrors are already user-facing, let them through.- # Still terminal user pain (the metric fails to load every time), so still counted.+ # These errors are already user-facing, so re-raise them unchanged. They still count+ # as terminal failures, because the metric fails to load on every attempt._emit_runner_terminal_error_event(args[0] if args else None, e)raiseexcept CHQueryErrorNotAnAggregate as e:- # Only known producer in experiment queries is user-authored HogQL (math_hogql /- # warehouse math_property) referencing a row-level column outside an aggregate —- # builder-generated SQL is snapshot-tested, and every tracked occurrence carried- # contains_user_hogql. A metric-config error: give an actionable message, keep it- # out of error tracking, and let classify_experiment_query_error's validation_error- # mapping make the recalculation worker fail it permanently instead of retrying.+ # In experiment queries, only user-authored HogQL (math_hogql or warehouse+ # math_property) is known to produce this error, because builder-generated SQL is+ # snapshot-tested. Treat it as a metric configuration error: give an actionable+ # message and keep it out of error tracking. The validation_error mapping in+ # classify_experiment_query_error makes the recalculation worker fail it permanently+ # instead of retrying.self = args[0] if args else Nonelogger.warning("Experiment metric HogQL references column outside aggregate",@@ -257,7 +247,6 @@ def experiment_error_handler(method: F) -> F:raiseraise user_error from eexcept Exception as e:- # Get context for loggingself = args[0] if args else Noneexperiment_id = getattr(self, "experiment_id", None)@@ -274,7 +263,6 @@ def experiment_error_handler(method: F) -> F:query_runner = type(self).__name__ if self is not None else None- # Log the technical error for engineerslogger.error("Experiment calculation error",experiment_id=experiment_id,@@ -286,7 +274,6 @@ def experiment_error_handler(method: F) -> F:exc_info=True,)- # Capture exception for error trackingcapture_exception(e,additional_properties={@@ -299,21 +286,19 @@ def experiment_error_handler(method: F) -> F:_emit_runner_terminal_error_event(self, e)- # If this is not user-facing, re-raise the original exception after logging/capturinguser_facing = Trueif self is not None:user_facing = getattr(self, "user_facing", True)if not user_facing:- # Preserve original exception for internal callers+ # Internal callers expect the original exception type.raise- # Convert to user-friendly error if we have a mapping, otherwise re-raise as-isuser_message = get_user_friendly_message(e)if user_message is None:raise- # Get error code if available. Chain the original explicitly: the query SLO- # classifier reads __cause__ to keep converted technical errors counted as failures.+ # Chain the original explicitly, because the query SLO classifier reads __cause__ to+ # keep converted technical errors counted as failures.error_code = ERROR_TYPE_TO_CODE.get(type(e))raise ValidationError(user_message, code=error_code) from ediff --git a/products/experiments/backend/hogql_queries/experiment_breakdown_attribution_query_builder.py b/products/experiments/backend/hogql_queries/experiment_breakdown_attribution_query_builder.pyindex 1704c6601008..9d3e39d47c90 100644--- a/products/experiments/backend/hogql_queries/experiment_breakdown_attribution_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_breakdown_attribution_query_builder.py@@ -6,7 +6,7 @@ that reads each breakdown property off the metric event, attributes it acrossfunnel steps with the context's resolved aggregation, and injects the breakdowncolumns into the funnel query CTEs.-Scope: funnel metrics only, for now.+Scope: funnel metrics only."""from typing import cast@@ -40,14 +40,13 @@ class ExperimentBreakdownAttributionQueryBuilder:events table and the warehouse tables. Those branches carry no breakdown column, so abreakdown attributed from ``metric_events`` would reference a column no branch produces.Attributing a breakdown off warehouse rows needs a design this builder does not have, so- the combination is rejected until integration adds it.+ the combination is rejected.A single-step funnel is degenerate for metric-event attribution. A user reaches a namedbucket only by emitting the step event, which is the same event the funnel counts as theconversion, so every named bucket is 100% converted and the per-bucket rate carries no- information. The multi-step case raises a wider statistics question (per-bucket buckets- condition on a post-exposure event) that the experiments team must settle before wiring;- the one-step case is unambiguous, so it is rejected now.+ information. A multi-step funnel has a related open question, because each bucket+ conditions on a post-exposure event."""if self.context.has_data_warehouse_step():raise NotImplementedError(@@ -151,7 +150,7 @@ class ExperimentBreakdownAttributionQueryBuilder:The step condition is a per-row flag with no ordering, so this aggregate can pick a stepoccurrence the walk skipped. This is sharpest for specific-step attribution: a step-2 eventthat fires before step_1, then again after, gives the funnel the second occurrence and this- aggregate the first. First and last touch now scan every metric step, which is near how+ aggregate the first. First and last touch scan every metric step, which is near howinsights treats them, but insights still restricts them to the events the aggregate walks.The fix routes per-event values through ``funnel_evaluation_expr`` (or reads them by theaggregate's matched-step UUIDs), which changes a shared helper this class does not own.@@ -180,9 +179,9 @@ class ExperimentBreakdownAttributionQueryBuilder:def _top_breakdowns_subquery(self, aliases: list[str]) -> ast.SelectQuery:"""Top-N breakdown tuples by entity (user) count, pooled across variants.- Selects from entity_metrics (one row per user) so the ranking measure is the- number of experiment units in each breakdown bucket — the funnel analog of- insights ranking by frequency.+ Selects from entity_metrics (one row per user), so the ranking measure is the number of+ experiment units in each breakdown bucket. This is the funnel equivalent of insights+ ranking by frequency.Only users who reach the result are ranked. Users with no variant are dropped by thefinal SELECT, and under "exclude" handling the runner drops multi-variant users after@@ -223,9 +222,9 @@ class ExperimentBreakdownAttributionQueryBuilder:Integration should measure the top-N read cost. The same membership subquery is inlinedonce per breakdown column, and ClickHouse re-evaluates an unmaterialized CTE at each- reference, so N breakdowns plus the outer read scan entity_metrics N+1 times (the runner- caps N at 3, so up to 4). On the optimized funnel path entity_metrics is the single events- scan that path exists to compute once. Two fixes, both needing a real experiment timing:+ reference, so N breakdowns plus the outer read scan entity_metrics N+1 times. On the+ optimized funnel path entity_metrics is the single events scan that path exists to+ compute once. Two fixes, both needing a real experiment timing:materialize entity_metrics (trades the repeated scan for holding one row per exposed user),or compute the membership flag once in a select that wraps the outer query. The wrap cannothappen here, because the funnel query builder keeps editing the final SELECT afterdiff --git a/products/experiments/backend/hogql_queries/experiment_breakdown_attribution_query_context.py b/products/experiments/backend/hogql_queries/experiment_breakdown_attribution_query_context.pyindex ec596a86c591..f51721def135 100644--- a/products/experiments/backend/hogql_queries/experiment_breakdown_attribution_query_context.py+++ b/products/experiments/backend/hogql_queries/experiment_breakdown_attribution_query_context.py@@ -10,8 +10,7 @@ Unlike ``BreakdownInjector`` (which attributes the breakdown from the exposureevent), this attributes the breakdown off the *metric* event, aligningexperiment funnel breakdowns with how insights funnels behave.-Scope: funnel metrics only, for now. The context and the builder replace the-old injector once every metric type migrates to metric-event breakdowns.+Scope: funnel metrics only. The other metric types use ``BreakdownInjector``."""from posthog.schema import (diff --git a/products/experiments/backend/hogql_queries/experiment_cuped_query_builder.py b/products/experiments/backend/hogql_queries/experiment_cuped_query_builder.pyindex e178075739c2..d29aeee48e34 100644--- a/products/experiments/backend/hogql_queries/experiment_cuped_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_cuped_query_builder.py@@ -22,9 +22,9 @@ class CupedQueryBuilder:--------------When CUPED is enabled, the query output includes:- - ``covariate_sum`` — sum of the per-entity covariate- - ``covariate_sum_squares``— sum of the squared per-entity covariate- - ``covariate_sum_product``— sum of (metric value x covariate) per entity+ - ``covariate_sum``: sum of the per-entity covariate+ - ``covariate_sum_squares``: sum of the squared per-entity covariate+ - ``covariate_sum_product``: sum of (metric value x covariate) per entityThese three sums are consumed by ``cuped_adjust`` downstream. For meanmetrics the covariate is the pre-window metric value; for funnel metrics it@@ -38,10 +38,6 @@ class CupedQueryBuilder:``date_from`` rolls back by ``lookback_days`` (see``extend_date_from_for_funnel_cuped`` for the funnel case; mean metrics widenvia ``build_metric_predicate``'s ``cuped_lookback_days`` argument).-- To keep the move behavior-preserving, this class holds a reference to the- owning ``ExperimentQueryBuilder`` and reaches through it for the CUPED- config."""def __init__(self, builder: "ExperimentQueryBuilder"):@@ -82,9 +78,9 @@ class CupedQueryBuilder:Per-entity binary covariate for funnel CUPED: 1 if the entity fired thefunnel's last step inside the pre-exposure window, else 0.- The covariate has to be binary to keep the same Bernoulli scale as the- post-window proportion metric, and aligns with the example pattern of- treating the conversion event as both the metric and the covariate.+ The covariate is binary so that it has the same Bernoulli scale as the+ post-window proportion metric. The conversion event is both the metric+ and the covariate."""return parse_expr(f"coalesce(maxIf(1, {events_alias}.step_{last_step_index} = 1 AND {{pre_window}}), 0)",@@ -120,10 +116,10 @@ class CupedQueryBuilder:aliases (`covariate_sum`, `covariate_sum_squares`, `covariate_sum_product`)to the outer SELECT.- Asserts the expected `entity_metrics` CTE shape: this method is called- right after the funnel SELECT is parsed in the funnel builder, so the- shape is an invariant — a violation means the SQL above changed without- updating CUPED, and we want a loud failure rather than zeroed covariates.+ Asserts the expected `entity_metrics` CTE shape. The funnel builder calls+ this method right after it parses the funnel SELECT, so the shape is an+ invariant. A violation means the funnel SQL changed without an update to+ CUPED, and a loud failure is better than zeroed covariates."""assert query.ctes is not None and "entity_metrics" in query.ctesentity_metrics_cte = query.ctes["entity_metrics"]@@ -144,7 +140,6 @@ class CupedQueryBuilder:"""Roll the funnel's `date_from` back by `lookback_days` when CUPED isenabled, so the same scan also feeds the CUPED pre-exposure window.- Returns the input unchanged when CUPED is off."""if not self._b.cuped_config.enabled:return date_fromdiff --git a/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.py b/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.pyindex 5ee540ec8bae..b6816e4b51bd 100644--- a/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.py@@ -18,8 +18,8 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (def _optimize_and_chain(expr: ast.Expr) -> ast.Expr:"""- Remove True constants from AND chains to preserve ClickHouse index optimizations.- Keeps SQL templates readable while avoiding unnecessary conditions.+ Drops True constants from an AND chain. The SQL templates use True as a no-op filter, and+ removing it preserves ClickHouse index optimizations."""if not isinstance(expr, ast.And):return expr@@ -78,15 +78,7 @@ class ExposureQueryBuilder:return self.maturity_having_builder(timestamp_expr)def timeseries_query(self) -> ast.SelectQuery:- """- Returns a query for exposure timeseries data.-- Generates daily exposure counts per variant, counting each entity- only once on their first exposure day.-- Returns:- SelectQuery with columns: day, variant, exposed_count- """+ """Daily exposure counts per variant. Each entity counts once, on its first exposure day."""query = parse_select("""WITH first_exposures AS ({first_exposures_select})@@ -164,10 +156,7 @@ class ExposureQueryBuilder:)def daily_exposures_from_precomputed(self, job_ids: list[str]) -> ast.SelectQuery:- """- Reads from the precomputed table and aggregates into day/variant/count.- Used by the Exposures tab in the experiment UI.- """+ """Same output as timeseries_query, read from the precomputed exposures table."""entity_id_expr = self._build_precomputed_entity_id_expr()variant_expr = self._build_precomputed_variant_expr()@@ -221,11 +210,8 @@ class ExposureQueryBuilder:return ast.Constant(value=True)def build_variant_property(self) -> ast.Field:- """Derive which event property that should be used for variants"""-- # $feature_flag_called events are special as we can use the $feature_flag_response.- # $experiment_exposure is an ingestion-side duplicate of $feature_flag_called and- # carries the same properties, so it gets the same treatment.+ # $feature_flag_called carries the variant in $feature_flag_response. $experiment_exposure+ # is an ingestion-side duplicate of $feature_flag_called with the same properties.if isinstance(self.context.exposure_config, ExperimentEventExposureConfig) and self.context.exposure_config.event in (DEFAULT_EXPOSURE_EVENT, EXPERIMENT_EXPOSURE_EVENT):@@ -234,21 +220,11 @@ class ExposureQueryBuilder:return ast.Field(chain=["properties", f"$feature/{self.context.feature_flag_key}"])def build_exposure_event_predicate(self) -> ast.Expr:- """- Builds the event predicate for exposure filtering (without timestamp conditions).-- This handles:- - Custom exposure events via event_or_action_to_filter- - Special $feature_flag_called filtering (matching the flag key)-- Used by both _build_exposure_predicate() and get_exposure_query_for_precomputation().- """+ """Event-level exposure predicate, without date, variant, or test-account conditions."""event_predicate = event_or_action_to_filter(self.context.team, self.context.exposure_config)- # $feature_flag_called events are special. We need to check that the property- # $feature_flag matches the flag. The same goes for $experiment_exposure, which- # duplicates flag events: without this filter, exposures of other experiments- # would count too.+ # $feature_flag_called and $experiment_exposure are not specific to one flag, so without the+ # flag key filter, exposures of other experiments would count too.if isinstance(self.context.exposure_config, ExperimentEventExposureConfig) and self.context.exposure_config.event in (DEFAULT_EXPOSURE_EVENT, EXPERIMENT_EXPOSURE_EVENT):@@ -281,9 +257,6 @@ class ExposureQueryBuilder:return ast.Call(name="notEmpty", args=[ast.Field(chain=[self.context.entity_key])])def build_exposure_predicate(self) -> ast.Expr:- """- Builds the exposure predicate as an AST expression.- """return _optimize_and_chain(parse_expr("""@@ -401,14 +374,13 @@ class ExposureQueryBuilder:max(timestamp) AS last_exposure_time,argMin(uuid, timestamp) AS exposure_event_uuid,argMin(`$session_id`, timestamp) AS exposure_session_id- -- breakdown columns added programmatically below+ -- _finalize_exposure_select appends the breakdown columnsFROM eventsINNER JOIN ({flag_exposures}) AS flag_exposuresON {entity_key} = flag_exposures.entity_idWHERE {activation_predicate}AND timestamp >= flag_exposures.first_flag_exposure_timeGROUP BY entity_id- -- breakdown columns added programmatically below""",placeholders={"entity_key": parse_expr(self.context.entity_key),@@ -429,11 +401,10 @@ class ExposureQueryBuilder:max(timestamp) AS last_exposure_time,argMin(uuid, timestamp) AS exposure_event_uuid,argMin(`$session_id`, timestamp) AS exposure_session_id- -- breakdown columns added programmatically below+ -- _finalize_exposure_select appends the breakdown columnsFROM eventsWHERE {exposure_predicate}GROUP BY entity_id- -- breakdown columns added programmatically below""",placeholders={"entity_key": parse_expr(self.context.entity_key),@@ -445,17 +416,12 @@ class ExposureQueryBuilder:return self._finalize_exposure_select(exposure_query)def _finalize_exposure_select(self, exposure_query: ast.SelectQuery) -> ast.SelectQuery:- # Inject breakdown columns into the exposure query if neededif self.breakdown_injector:breakdown_exprs = self.breakdown_injector.build_breakdown_exprs(table_alias="")- # Add breakdown columns to SELECT using argMin attribution- # This ensures each user is attributed to exactly one breakdown value- # (from their first exposure), preventing duplicate counting when users- # have multiple exposures with different breakdown property values+ # argMin attributes each entity to the breakdown value of its first exposure. An entity+ # whose exposures carry different values is then counted in one breakdown only.for alias, expr in breakdown_exprs:- # Use argMin to attribute breakdown value from first exposure- # This matches the variant attribution logicbreakdown_attributed = parse_expr("argMin({expr}, timestamp)", placeholders={"expr": expr})exposure_query.select.append(ast.Alias(alias=alias, expr=breakdown_attributed))@@ -471,14 +437,12 @@ class ExposureQueryBuilder:def precomputed_select_query(self, job_ids: list[str]) -> ast.SelectQuery:"""- Builds the exposure CTE by reading from the lazy-computed table instead of scanning events.-- Re-aggregates across jobs since the same user can appear in multiple time-window jobs.- Returns the same column shape as _build_exposure_select_query().+ Builds the exposure CTE from the lazy-computed table instead of scanning events. Returns+ the same column shape as _build_exposure_select_query().- Important: Jobs can cover broader time ranges than the experiment (for reusability),- so we must filter by experiment start/end dates to avoid including exposures outside- the experiment window.+ Re-aggregates across jobs, because the same user can appear in several time-window jobs.+ A job can cover a wider time range than the experiment (so that it can be reused), so the+ query also filters on the experiment start and end dates."""# The lazy-computed table stores entity_id as String, but person_id is UUID in events.# Cast back to match the type expected by downstream JOINs.@@ -525,25 +489,19 @@ class ExposureQueryBuilder:def precomputation_query(self) -> tuple[str, dict[str, ast.Expr]]:"""- Returns the exposure query and placeholders for lazy computation.+ Returns (query_string, placeholders) for lazy computation.- The query string uses {time_window_min} and {time_window_max} placeholders- which are filled in by the lazy computation system for each daily bucket.- Other placeholders are returned in the dict and should be passed to- ensure_precomputed().-- Returns:- Tuple of (query_string, placeholders_dict)+ The lazy computation system fills the {time_window_min} and {time_window_max}+ placeholders for each daily bucket. Pass the returned placeholders to ensure_precomputed()."""if self.context.activation_config is not None:# Callers gate on has_activation_config before precomputing; a cache built from# this per-day query would count flag exposures alone and poison later reads.raise ValueError("Activation-mode exposures cannot be precomputed per day")- # Query template with placeholders- # Note: uses < for time_window_max (exclusive end for bucket boundaries)- # vs <= in normal query (inclusive end for experiment boundary)- # Keep in sync with _build_exposure_select_query+ # Keep in sync with _build_exposure_select_query. This query uses < for time_window_max+ # (exclusive end for bucket boundaries), where the normal query uses <= (inclusive end for+ # the experiment boundary).## The time_window_min/max placeholders define the job's cache window# (UTC-day-aligned). The experiment_date_from/to placeholders tighten@@ -584,9 +542,9 @@ class ExposureQueryBuilder:def build_variant_expr_for_mean(self) -> ast.Expr:"""- Builds the variant selection expression for mean metrics based on multiple variant handling.+ Per-entity variant: the first-seen variant under FIRST_SEEN handling. Otherwise+ MULTIPLE_VARIANT_KEY when the entity saw more than one variant."""-if self.context.multiple_variant_handling == MultipleVariantHandling.FIRST_SEEN:return parse_expr("argMin({variant_property}, timestamp)",diff --git a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.pyindex 40c47617636e..62bd8851df80 100644--- a/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_exposures_query_runner.py@@ -46,7 +46,7 @@ from products.experiments.backend.models.team_experiments_config import TeamExpelogger = structlog.get_logger(__name__)-QUERY_ROW_LIMIT = 5000 # Should be sufficient for all experiments (days * variants)+QUERY_ROW_LIMIT = 5000 # The result has one row per (day, variant) pairSRM_MINIMUM_SAMPLE_SIZE = 100 # Minimum total exposures required for SRM calculation@@ -56,7 +56,7 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):def __init__(self, *args, error_event_context: str | None = "ui", **kwargs):super().__init__(*args, **kwargs)- # See ExperimentQueryRunner.__init__ — tags the terminal error event; None = silent.+ # Same contract as ExperimentQueryRunner.__init__: tags the terminal error event, and None keeps it silent.self.error_event_context = error_event_contextif not self.query.experiment_id:@@ -72,16 +72,17 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):except Experiment.DoesNotExist:raise ValidationError(f"Experiment with id {self.query.experiment_id} not found")self.feature_flag_key: str = self.experiment.feature_flag.key_without_tombstone()- # From the DB flag, not the query dict — callers vary in the feature_flag shape they- # pass (full flag object vs bare filters), and a missed group index would bypass the- # group-aggregation precompute gate below. Mirrors feature_flag_key above.+ # Read from the DB flag, not the query dict, because callers pass different feature_flag+ # shapes (full flag object or bare filters). A missed group index would bypass the+ # group-aggregation precompute gate below.self.group_type_index = (self.experiment.feature_flag.filters or {}).get("aggregation_group_type_index")- # The analysis window comes from the query, not live model state: this runner's result is- # cached under a key hashed from self.query (see get_cache_payload), so the window it computes- # must match the window the query declares — otherwise the key can describe a window the result- # wasn't computed for. A running experiment serializes end_date=None; expand that to now() here- # (lazily, so the moving instant stays out of the cache key and the 24h TTL governs refresh).+ # The analysis window comes from the query, not live model state. The result is cached under+ # a key hashed from self.query (see get_cache_payload), so the computed window must match the+ # window the query declares. Otherwise the key can describe a window the result was not+ # computed for. A running experiment serializes end_date=None, which expands to now() here.+ # The expansion does not change self.query, so the moving instant stays out of the cache key+ # and the cache TTL governs refresh.self.window_start = datetime.fromisoformat(self.query.start_date) if self.query.start_date else Noneself.window_end_date = datetime.fromisoformat(self.query.end_date) if self.query.end_date else Noneself.as_of = self.window_end_date or datetime.now(UTC)@@ -96,11 +97,10 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):for variant in multivariate_data.get("variants", [])if variant.get("key") not in self.excluded_variants]- # No variants means the exposure SQL (`variant IN {variants}`) matches nothing.- # For a running experiment that's a broken flag (variants stripped out from under- # it) — surface it rather than render an empty chart that reads as "no exposures".- # Stopped/draft experiments may legitimately keep a flag that was later simplified- # to boolean, so they fall through and degrade to an empty result instead.+ # No variants means the exposure SQL (`variant IN {variants}`) matches nothing. For a+ # running experiment that is a broken flag, so raise instead of rendering an empty chart+ # that reads as "no exposures". A stopped or draft experiment can legitimately keep a flag+ # that was later changed to boolean, so it falls through to an empty result.if not multivariate_data.get("variants") and self.experiment.is_running:raise ValidationError("This experiment's feature flag has no variants. Restore the flag's variants to see exposure data."@@ -115,7 +115,6 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):)def _get_date_range(self) -> DateRange:- """The experiment's analysis DateRange, derived from the query (see analysis_window)."""return analysis_window(self.window_start, self.window_end_date, self.team, self.as_of)def _ensure_exposures_precomputed(self, builder: ExperimentQueryBuilder) -> LazyComputationResult:@@ -146,13 +145,11 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):activation_config=exposure_params.activation_config,)- # TODO: Add query-level precomputation_mode override for ExperimentExposureQuery.- # Until then, the duration gate here is unconditional — the main runner- # lets PrecomputationMode.PRECOMPUTED bypass the gate, but this path has- # no equivalent escape hatch yet, so callers cannot force precomputation- # on a sub-12h experiment for the exposures view.- # group_type_index gate: mirrors the main runner — group builds always fail- # (the INSERT can't resolve the materialized $group_N column on sharded_events).+ # TODO: Add a query-level precomputation_mode override for ExperimentExposureQuery. The main+ # runner lets PrecomputationMode.PRECOMPUTED bypass the duration gate. This path has no such+ # override, so callers cannot force precomputation for an experiment below the minimum duration.+ # The group_type_index check mirrors the main runner: group builds always fail, because the+ # INSERT cannot resolve the materialized $group_N column on sharded_events.if (self.group_type_index is Noneand team_precompute_skip_reason(@@ -179,11 +176,8 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):return builder.get_exposure_timeseries_query()def _calculate_srm(self, total_exposures: dict[str, int]) -> SampleRatioMismatch | None:- """- Calculate Sample Ratio Mismatch using chi-squared goodness-of-fit test.- Compares observed variant distribution against expected (from rollout percentages).- Returns None if insufficient data.- """+ """Chi-squared goodness-of-fit test of the observed variant counts against the rollout+ percentages. Returns None when there is too little data."""multivariate_data = (self.query.feature_flag.get("filters") or {}).get("multivariate") or {}variants_config = multivariate_data.get("variants", [])@@ -198,7 +192,7 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):rollout_percentages[key] = pct# Holdout reduces the share available to the exposed variants. Rescale- # the variant rollouts to reflect what's expected AMONG EXPOSED users+ # the variant rollouts to reflect what's expected among exposed users# (which is what total_exposures measures). The holdout itself is dropped:# it never appears in total_exposures (the exposure query excludes it from# the WHERE IN clause), so including it in the chi-square would compare@@ -215,24 +209,21 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):scale = (100 - holdout_pct) / 100rollout_percentages = {k: v * scale for k, v in rollout_percentages.items()}- # excluded_variants are not in the exposure chart, so they must not enter- # the chi-square. Drop them from rollout_percentages.+ # excluded_variants are not in the exposure chart, so they must not enter the chi-square.rollout_percentages = {k: v for k, v in rollout_percentages.items() if k not in self.excluded_variants}- # Get all variant keys with non-zero rollout percentage- # We must iterate over these (not total_exposures) to ensure sum(observed) == sum(expected)+ # Iterate over the variants with rollout, not total_exposures, so that a variant with 0+ # exposures still enters the chi-square and sum(observed) == sum(expected).variants_with_rollout = {key for key, pct in rollout_percentages.items() if pct > 0}- # Calculate total observed for variants with non-zero rollout- # Use .get(key, 0) to handle variants that may be missing from total_exposurestotal_observed = sum(total_exposures.get(key, 0) for key in variants_with_rollout if key != MULTIPLE_VARIANT_KEY)if total_observed < SRM_MINIMUM_SAMPLE_SIZE:return None- # After dropping holdout/excluded variants the remaining percentages may not sum to 100.- # Normalise so chi-square expected counts sum to total_observed.+ # After dropping holdout and excluded variants, the remaining percentages may not sum to 100.+ # Normalize so that the chi-square expected counts sum to total_observed.total_rollout = sum(rollout_percentages[k] for k in variants_with_rollout if k != MULTIPLE_VARIANT_KEY)if total_rollout <= 0:return None@@ -241,8 +232,6 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):expected: list[float] = []expected_counts: dict[str, float] = {}- # Iterate over all variants with non-zero rollout (not just those in total_exposures)- # This ensures variants with 0 exposures are still included in the chi-square calculationfor variant_key in variants_with_rollout:if variant_key == MULTIPLE_VARIANT_KEY:continue@@ -267,9 +256,10 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):def _evaluate_bias_risk(self, total_exposures: dict[str, int]) -> BiasRisk | None:# Shipping a variant rewrites the flag to 100/0, which would falsely trip the- # uneven-split check on data collected under the original split. The warning is- # also unactionable post-stop — both CTAs only help while running. Read end from the- # query (the cache key), so the running/stopped decision matches the cached window.+ # uneven-split check on data collected under the original split. The warning also has+ # no action after the experiment stops, because both of its CTAs only apply while it runs.+ # Read the end from the query (the cache key), so that the running/stopped decision+ # matches the cached window.if self.window_end_date is not None:return Nonemultivariate_data = (self.query.feature_flag.get("filters") or {}).get("multivariate") or {}@@ -285,8 +275,6 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):@experiment_error_handlerdef _calculate(self) -> ExperimentExposureQueryResponse:- # Adding experiment specific tags to the tag collection- # This will be available as labels in Prometheustag_queries(experiment_id=self.query.experiment_id,experiment_name=self.query.experiment_name,@@ -316,7 +304,6 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):response.results = self._fill_date_gaps(response.results)variant_series: dict[str, ExperimentExposureTimeSeries] = {}- # Organize results by variantvariant_data: dict[str, dict[str, int]] = {}for result in response.results:day, variant, count = result@@ -324,7 +311,6 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):variant_data[variant] = {}variant_data[variant][day.isoformat()] = count- # Create cumulative series for each variantfor variant, daily_counts in variant_data.items():sorted_days = sorted(daily_counts.keys())cumulative_counts = []@@ -338,10 +324,8 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):variant=variant, days=sorted_days, exposure_counts=cumulative_counts)- # Sort timeseries by original variant order, with MULTIPLE_VARIANT_KEY last+ # Keep the configured variant order, with MULTIPLE_VARIANT_KEY lastordered_timeseries = []-- # Add variants in original orderfor variant in self.variants:if variant in variant_series:ordered_timeseries.append(variant_series[variant])@@ -349,7 +333,6 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):if MULTIPLE_VARIANT_KEY in variant_series:ordered_timeseries.append(variant_series[MULTIPLE_VARIANT_KEY])- # Calculate total exposures, excluding MULTIPLE_VARIANT_KEY for FIRST_SEEN handlingtotal_exposures = {}for variant, series in variant_series.items():total_exposures[variant] = int(series.exposure_counts[-1]) if series.exposure_counts else 0@@ -370,15 +353,13 @@ class ExperimentExposuresQueryRunner(ExperimentResultsCacheMixin, QueryRunner):def _fill_date_gaps(self, results):"""- Ensures the exposure data includes all dates within the experiment's date range- and an entry for every configured variant — even variants that had zero- exposures across the whole window. This lets the response carry an empty- timeseries for those variants (days filled with the date range, counts all 0)- instead of omitting them entirely.+ Fills in every date of the analysis range for every configured variant, including a+ variant with zero exposures in the whole window. The response then carries an empty+ timeseries (all counts 0) for that variant instead of omitting it."""date_range = self._get_date_range()- # for draft experiments, return an empty result+ # A draft experiment has no start date, so it has no exposures.if not date_range.date_from:return []diff --git a/products/experiments/backend/hogql_queries/experiment_funnel_actors_query_builder.py b/products/experiments/backend/hogql_queries/experiment_funnel_actors_query_builder.pyindex 3b94489022b7..515476c20396 100644--- a/products/experiments/backend/hogql_queries/experiment_funnel_actors_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_funnel_actors_query_builder.py@@ -14,12 +14,11 @@ from products.experiments.backend.hogql_queries.experiment_query_builder importclass ExperimentFunnelActorsQueryBuilder:"""- Builds actors query for experiment funnels with exposure filtering.+ Builds the actors query for experiment funnels with exposure filtering.- Composes the extracted exposure and funnel fragment builders to reuse- exposure filtering and funnel step logic while adding actor-specific- selection and filtering. The actors query has a different output contract- from aggregate experiment results, so that selection/filtering lives here.+ Reuses the exposure and funnel fragment builders for exposure filtering and funnel+ steps. The actors query has a different output contract from the aggregate experiment+ results, so the actor selection and filtering live here.Query structure:1. exposures CTE: First exposure per entity (same as main query)@@ -52,10 +51,8 @@ class ExperimentFunnelActorsQueryBuilder:self.funnel_step_breakdown = funnel_step_breakdownself.include_recordings = include_recordings- # Compose an ExperimentQueryBuilder to source the shared exposure and- # funnel fragment builders. The funnel fragment builder reaches through- # an ExperimentQueryBuilder for shared metric/exposure state, so we keep- # one here rather than re-deriving that state.+ # The funnel fragment builder reads shared metric and exposure state through an+ # ExperimentQueryBuilder, so keep one here instead of re-deriving that state.self._query_builder = ExperimentQueryBuilder(team=team,feature_flag_key=feature_flag_key,@@ -71,21 +68,16 @@ class ExperimentFunnelActorsQueryBuilder:def build_actors_query(self) -> ast.SelectQuery:"""- Build the complete actors query with exposure filtering.-Returns persons who:- Were exposed to the specified variant- Completed the specified funnel step (or dropped off at that step)- Only considers events that occurred AFTER their first exposure"""- # Build the base query structure with CTEsquery = self._build_base_query_with_ctes()-- # Add actors-specific SELECT and WHEREquery = self._add_actors_selection(query)query = self._add_actors_where_clause(query)- # Add ORDER BY for consistent results+ # Order by entity_id so that results are deterministic.query.order_by = [ast.OrderExpr(expr=ast.Field(chain=["entity_id"]))]return query@@ -137,16 +129,10 @@ class ExperimentFunnelActorsQueryBuilder:This mirrors the main experiment query structure but focuses onindividual users rather than aggregate statistics."""- # Build exposure CTE from the shared exposure fragment builderexposure_select_query = self._query_builder._exposure_query_builder().select_query()-- # Build metric events CTEmetric_events_cte = self._build_metric_events_cte()-- # Build entity metrics CTE with funnel evaluationentity_metrics_cte = self._build_entity_metrics_cte()- # Construct the query with CTEsquery = cast(ast.SelectQuery,parse_select(@@ -174,20 +160,13 @@ class ExperimentFunnelActorsQueryBuilder:Includes step_0 (exposure), step_1, step_2, ... (metric events)"""- # Ensure metric is ExperimentFunnelMetric (guaranteed by the constructor signature)assert isinstance(self.metric, ExperimentFunnelMetric), "metric must be ExperimentFunnelMetric"- # Get date range predicatesdate_from = self.date_range_query.date_from_as_hogql()date_to = self.date_range_query.date_to_as_hogql()-- # Build funnel steps filterfunnel_steps_filter = funnel_steps_to_filter(self.team, self.metric.series)-- # Build exposure predicate from the shared exposure fragment builderexposure_predicate = self._query_builder._exposure_query_builder().build_exposure_step_event_predicate()- # Parse base query without step columnsquery = cast(ast.SelectQuery,parse_select(@@ -213,11 +192,9 @@ class ExperimentFunnelActorsQueryBuilder:),)- # Add step columns dynamically using the shared funnel fragment builder- # build_funnel_step_columns() returns [step_0, step_1, step_2, ...]- # We skip step_0 (exposure) since it's not needed in metric_events CTE+ # The SELECT above already defines step_0, so take only the metric step columns.all_step_columns = self._query_builder._funnel_query_builder().build_funnel_step_columns()- step_columns = all_step_columns[1:] # Skip step_0, keep step_1, step_2, ...+ step_columns = all_step_columns[1:]query.select.extend(step_columns)return query@@ -229,10 +206,9 @@ class ExperimentFunnelActorsQueryBuilder:Uses aggregate_funnel_array UDF with exposure as step 0.Includes matched_events_array for recording support."""- # Ensure metric is ExperimentFunnelMetric (guaranteed by the constructor signature)assert isinstance(self.metric, ExperimentFunnelMetric), "metric must be ExperimentFunnelMetric"- # Determine if unordered funnel (needs temporal filter). Activation mode needs it for+ # An unordered funnel needs the temporal filter. Activation mode needs it for# ordered funnels too, matching the main funnel query: step_0 rows are plain# activation-event matches, so events before the qualifying activation must be excluded.is_unordered = self.metric.funnel_order_type == "unordered"@@ -241,7 +217,6 @@ class ExperimentFunnelActorsQueryBuilder:"AND metric_events.timestamp >= exposures.first_exposure_time" if is_unordered or is_activation_mode else "")- # Build conversion windowif self.metric.conversion_window is not None and self.metric.conversion_window_unit is not None:from products.experiments.backend.hogql_queries.base_query_utils import conversion_window_to_seconds@@ -249,17 +224,15 @@ class ExperimentFunnelActorsQueryBuilder:self.metric.conversion_window, self.metric.conversion_window_unit)else:- # Default to 3 years+ # Without a conversion window, all events count. 3 years is large enough to act as no limit.conversion_window_seconds = 3 * 365 * 24 * 60 * 60num_steps = len(self.metric.series) + 1 # +1 for exposurefunnel_order_type = self.metric.funnel_order_type or "ordered"- # Build step conditions for aggregate_funnel_arraystep_conditions = [f"{i + 1} * metric_events.step_{i}" for i in range(num_steps)]step_conditions_str = ", ".join(step_conditions)- # Build recordings support fields if requestedif self.include_recordings:recordings_fields = """groupArray(tuple(metric_events.timestamp, metric_events.uuid, metric_events.session_id, '')) as user_events,@@ -290,7 +263,6 @@ class ExperimentFunnelActorsQueryBuilder:step_conditions_str=step_conditions_str,)else:- # Without recordings, just compute step_reached using funnel_evaluation_exprfrom products.experiments.backend.hogql_queries.base_query_utils import funnel_evaluation_exprfunnel_agg_expr = funnel_evaluation_expr(@@ -299,14 +271,10 @@ class ExperimentFunnelActorsQueryBuilder:events_alias="metric_events",include_exposure=True,)- # Extract step_reached from the funnel evaluation result- # The result is arraySort with tuple(step_reached, uuid_string)- # We want the .1 element which is step_reachedrecordings_fields = ""- # Build the complete SELECT query- # Note: recordings_fields and temporal_filter are internally computed safe strings- # covered by semgrep exception (see .semgrep/rules/security/hogql-no-fstring.yaml line 114)+ # recordings_fields and temporal_filter are built internally from validated values. The+ # semgrep rule in .semgrep/rules/security/hogql-no-fstring.yaml exempts them.query = cast(ast.SelectQuery,parse_select(@@ -328,7 +296,7 @@ class ExperimentFunnelActorsQueryBuilder:),)- # If not including recordings, add step_reached using funnel_evaluation_expr+ # funnel_evaluation_expr returns tuple(step_reached, ...), so element 1 is step_reached.if not self.include_recordings:query.select.append(ast.Alias(@@ -340,20 +308,15 @@ class ExperimentFunnelActorsQueryBuilder:return querydef _add_actors_selection(self, query: ast.SelectQuery) -> ast.SelectQuery:- """- Add actor-specific SELECT columns.-- Returns entity_id, variant, and optionally matching_events for recordings support.- """+ """Selects actor_id, variant, and matching_events when recordings are requested."""select_exprs: list[ast.Expr] = [ast.Alias(alias="actor_id", expr=ast.Field(chain=["entity_id"])),ast.Alias(alias="variant", expr=ast.Field(chain=["variant"])),]- # Add matching_events field only when recordings are requestedif self.include_recordings:- # For conversions and drop-offs, select events from the reached step- # step_reached is 0-indexed, so we add 1 to get the array index+ # For conversions and drop-offs, select the events of the reached step.+ # step_reached is 0-indexed and HogQL arrays are 1-indexed.select_exprs.append(ast.Alias(alias="matching_events",@@ -366,26 +329,21 @@ class ExperimentFunnelActorsQueryBuilder:def _add_actors_where_clause(self, query: ast.SelectQuery) -> ast.SelectQuery:"""- Add WHERE clause to filter to specific step and variant.-- Mirrors the step filtering logic from FunnelBase._get_funnel_person_step_condition+ Filters to the requested step and variant. Mirrors the step filtering in+ FunnelUDF._get_funnel_person_step_condition."""conditions: list[ast.Expr] = []- # Filter by step- # NOTE: step_reached is 0-indexed and includes exposure as step 0+ # step_reached is 0-indexed and counts the exposure as step 0:# - step_reached = 0: completed exposure only# - step_reached = 1: completed exposure + first metric# - step_reached = 2: completed exposure + first + second metric- # funnelStep is 1-indexed for metric steps (exposure is not counted):+ # funnelStep is 1-indexed for metric steps and does not count the exposure:# - funnelStep = 1: first metric step# - funnelStep = 2: second metric stepif self.funnel_step >= 0:- # Conversion: user reached this step- # funnelStep=1 (first metric) requires step_reached >= 1 (exposure + first metric)- # funnelStep=2 (second metric) requires step_reached >= 2 (exposure + first + second metric)- # Formula: step_reached >= funnel_step+ # Conversion: the user reached this step, so step_reached >= funnel_step.conditions.append(ast.CompareOperation(op=ast.CompareOperationOp.GtEq,@@ -394,10 +352,8 @@ class ExperimentFunnelActorsQueryBuilder:))else:- # Drop-off: user reached prior step but NOT this step- # funnelStep=-2 means dropped at step 2: completed step 1 (first metric) but NOT step 2 (second metric)- # In step_reached terms: step_reached >= 1 AND step_reached < 2- # Formula for funnelStep=-N: step_reached >= (N-1) AND step_reached < N+ # Drop-off: the user reached the prior step but not this one. For funnelStep=-N,+ # that is step_reached >= N-1 AND step_reached < N.target_step = abs(self.funnel_step)conditions.append(@@ -415,7 +371,6 @@ class ExperimentFunnelActorsQueryBuilder:))- # Filter by variant (skip if empty string or None)variant_filter = self._build_variant_filter()if variant_filter is not None:conditions.append(variant_filter)diff --git a/products/experiments/backend/hogql_queries/experiment_funnel_query_builder.py b/products/experiments/backend/hogql_queries/experiment_funnel_query_builder.pyindex a287db63e129..010d8bf58f40 100644--- a/products/experiments/backend/hogql_queries/experiment_funnel_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_funnel_query_builder.py@@ -35,40 +35,27 @@ class FunnelQueryBuilder:Builds funnel-metric queries (aggregate results and the metric-eventsprecomputation write query).- Funnel construction is deeply coupled to the rest of the experiment query- builder: it reads the metric and CUPED config, calls shared exposure and- metric-value helpers, and the CUPED and maturity helpers call back into the- funnel helpers. To keep the move behavior-preserving, this class holds a- reference to the owning ``ExperimentQueryBuilder`` and reaches through it for- that shared state and those cross-cluster helpers. The optimized- (single-scan) and legacy (double-scan) paths intentionally live side by side- here without being merged.+ Funnel construction is coupled to the rest of the experiment query builder:+ it reads the metric and CUPED config, calls shared exposure and metric-value+ helpers, and the CUPED and maturity helpers call back into the funnel helpers.+ So this class holds a reference to the owning ``ExperimentQueryBuilder`` and+ reads that shared state and those helpers through it."""def __init__(self, builder: "ExperimentQueryBuilder"):self._b = builderdef build_funnel_query(self) -> ast.SelectQuery:- """- Builds query for funnel metrics.- Dispatches to optimized (single-scan) or legacy (double-scan) path.- """if self.should_use_optimized_funnel_query():return self.build_funnel_query_optimized()return self.build_funnel_query_legacy()def should_use_optimized_funnel_query(self) -> bool:- """- Returns True when the optimized single-scan funnel query should be used.- The legacy path is kept for precomputed exposures, where the exposures CTE- reads from a cheap preaggregated table (no double-scan penalty).-- Also routes to legacy path for DW funnels, which use UNION ALL pattern- only implemented in the legacy path.- """+ # With precomputed exposures, the exposures CTE of the legacy path reads from a+ # cheap preaggregated table, so its second scan costs little.if self._b.preaggregation_job_ids and not self._b.breakdowns:return False- # Route DW funnels to legacy path which supports UNION ALL+ # Only the legacy path implements the UNION ALL pattern for DW funnels.if isinstance(self._b.metric, ExperimentFunnelMetric) and self.has_datawarehouse_steps():return False# Activation-mode exposure is a join against flag exposures, not a single-event@@ -81,9 +68,9 @@ class FunnelQueryBuilder:def build_funnel_query_legacy(self) -> ast.SelectQuery:"""3-CTE funnel query: exposures, metric_events, entity_metrics.- Called "legacy" because it predates the single-scan optimized path,- but this is the primary path for precomputed queries — both exposures- and metric_events CTEs can read from precomputed tables here.+ The name "legacy" comes from before the single-scan optimized path existed.+ It is still the primary path for precomputed queries, because both the+ exposures and the metric_events CTEs can read from precomputed tables here.Supports two patterns:1. Events-only: Single query with boolean step columns@@ -91,20 +78,17 @@ class FunnelQueryBuilder:"""assert isinstance(self._b.metric, ExperimentFunnelMetric)- # Validate DW funnel configuration before building queryFunnelDWValidator.validate_funnel_metric(self._b.metric)- num_steps = len(self._b.metric.series) + 1 # +1 as we are including exposure criteria+ num_steps = len(self._b.metric.series) + 1 # +1 for step_0, the exposure step- # Determine which query pattern to usehas_dw_steps = self.has_datawarehouse_steps()- # Track whether step columns need to be injected after parsing.- # Precomputed metric events already have steps extracted from the array.+ # Precomputed metric events already extract the step columns from the steps+ # array, so the step column injection below is skipped for them.inject_step_columns = Trueif self._b.metric_events_preaggregation_job_ids and not has_dw_steps:- # Read from precomputed table instead of scanning eventsinject_step_columns = Falsestep_extracts = ", ".join(f"arrayElement(t.steps, {i + 1}) AS step_{i}" for i in range(num_steps))entity_id_cast = "toUUID(t.entity_id)" if self._b.entity_key == "person_id" else "t.entity_id"@@ -134,8 +118,6 @@ class FunnelQueryBuilder:)"""elif has_dw_steps:- # UNION ALL pattern for heterogeneous sources- # We'll inject the UNION query directly as AST after building the main querymetric_events_cte_str = """metric_events AS (SELECT 1 AS placeholder@@ -158,18 +140,12 @@ class FunnelQueryBuilder:is_unordered_funnel = self._b.metric.funnel_order_type == StepOrderValue.UNORDERED- # Use separate exposures CTE to leverage precomputed exposure cache when available.- # The exposures query automatically falls back to scanning events if precomputation- # isn't enabled for the team.- #- # Unordered funnels need temporal filtering (metric_events.timestamp >= first_exposure_time)- # because the funnel UDF doesn't filter out events before the exposure.- # Ordered funnels don't need this - the UDF handles temporal ordering internally.-- # Build the JOIN clause with conditional temporal filter. Activation mode needs it- # for ordered funnels too: step_0 rows are plain activation-event matches, and the- # UDF's ordering cannot express "at/after the first flag exposure", so events before- # the qualifying activation must be excluded here.+ # Unordered funnels need the temporal filter because the funnel UDF does not drop+ # events before the exposure. Ordered funnels do not need it, because the UDF+ # enforces the step order. Activation mode needs it for ordered funnels too:+ # step_0 rows are plain activation-event matches, and the UDF's ordering cannot+ # express "at or after the first flag exposure", so the join must exclude events+ # before the qualifying activation.is_activation_mode = self._b.context.activation_config is not Nonetemporal_filter = ("AND metric_events.timestamp >= exposures.first_exposure_time"@@ -201,22 +177,21 @@ class FunnelQueryBuilder:FROM exposuresLEFT JOIN metric_events{entity_id_join}- {temporal_filter} -- Only for unordered: filters out events before exposure+ {temporal_filter}GROUP BYexposures.entity_id,exposures.variant)"""- # Build exposure query, adding exposure_identifier for DW funnelsexposure_query = self._b._get_exposure_query()if has_dw_steps:- # All DW steps are validated to use the same events_join_key+ # FunnelDWValidator guarantees that all DW steps use the same events_join_keyfirst_dw_step = next(s for s in self._b.metric.series if isinstance(s, ExperimentDataWarehouseNode))events_join_key_parts = cast(list[str | int], first_dw_step.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+ # argMin takes the join key value from the first exposure. This prevents fan-out+ # when the exposures of one entity have different join key values.exposure_query.select.append(ast.Alias(alias="exposure_identifier",@@ -253,9 +228,8 @@ class FunnelQueryBuilder:SELECTentity_metrics.variant AS variant,count(entity_metrics.entity_id) AS num_users,- -- The return value from the funnel eval is zero indexed. So reaching first step means- -- it return 0, and so on. So reaching the last step means it will return- -- num_steps - 1+ -- The funnel UDF returns a zero-indexed step, so an entity that reaches the+ -- last step returns num_steps - 1countIf(entity_metrics.value.1 = {{num_steps_minus_1}}) AS total_sum,countIf(entity_metrics.value.1 = {{num_steps_minus_1}}) AS total_sum_of_squares-- CUPED aggregation columns added programmatically below@@ -279,26 +253,21 @@ class FunnelQueryBuilder:exposure_alias="exposures",)- # Inject breakdown columns into the query ASTif self._b.breakdown_injector:self._b.breakdown_injector.inject_funnel_breakdown_columns(query)- # Inject or replace the metric_events CTE based on whether DW steps are presentif query.ctes and "metric_events" in query.ctes:if has_dw_steps:- # Replace with UNION ALL query for DW funnelsunion_query = self.build_funnel_metric_events_union_query()query.ctes["metric_events"] = ast.CTE(name="metric_events", expr=union_query, cte_type="subquery")else:- # Inject step columns into the metric_events CTE (skip when precomputed — already extracted)if inject_step_columns:metric_events_cte = query.ctes["metric_events"]if isinstance(metric_events_cte, ast.CTE) and isinstance(metric_events_cte.expr, ast.SelectQuery):step_columns = self.build_funnel_step_columns()metric_events_cte.expr.select.extend(step_columns)- # Inject the additional selects we do for getting the data we need to render the funnel chart- # Add step counts - how many users reached each step+ # step_counts feeds the funnel chart: the number of entities that reached each stepstep_count_exprs = []for i in range(1, num_steps):step_count_exprs.append(f"countIf(entity_metrics.value.1 >= {i})")@@ -322,9 +291,8 @@ class FunnelQueryBuilder:"""assert isinstance(self._b.metric, ExperimentFunnelMetric)- num_steps = len(self._b.metric.series) + 1 # +1 as we are including exposure criteria+ num_steps = len(self._b.metric.series) + 1 # +1 for step_0, the exposure step- # CTE 1: base_events - single scan of events table# WHERE admits both exposure and conversion events. Exclusion filters are# embedded in step_0 only, not the WHERE clause, so conversion events from# internal users pass through (they only matter if the user has a valid exposure).@@ -343,7 +311,6 @@ class FunnelQueryBuilder:is_unordered_funnel = self._b.metric.funnel_order_type == StepOrderValue.UNORDERED- # CTE 2: entity_metrics - GROUP BY entity_id, no JOINtemporal_setup = self.build_funnel_optimized_temporal_setup(is_unordered_funnel)ctes_sql = f"""@@ -379,9 +346,8 @@ class FunnelQueryBuilder:SELECTentity_metrics.variant AS variant,count(entity_metrics.entity_id) AS num_users,- -- The return value from the funnel eval is zero indexed. So reaching first step means- -- it return 0, and so on. So reaching the last step means it will return- -- num_steps - 1+ -- The funnel UDF returns a zero-indexed step, so an entity that reaches the+ -- last step returns num_steps - 1countIf(entity_metrics.value.1 = {{num_steps_minus_1}}) AS total_sum,countIf(entity_metrics.value.1 = {{num_steps_minus_1}}) AS total_sum_of_squares-- CUPED aggregation columns added programmatically below@@ -405,19 +371,15 @@ class FunnelQueryBuilder:exposure_alias="first_exposures",)- # Inject breakdown columns into the query ASTif self._b.breakdown_injector:self._b.breakdown_injector.inject_funnel_breakdown_columns_optimized(query)- # Inject step columns into the base_events CTEif query.ctes and "base_events" in query.ctes:base_events_cte = query.ctes["base_events"]if isinstance(base_events_cte, ast.CTE) and isinstance(base_events_cte.expr, ast.SelectQuery):step_columns = self.build_funnel_step_columns()base_events_cte.expr.select.extend(step_columns)- # Inject maturity HAVING clause into entity_metrics CTE- # Use maxIf to only consider exposure events for maturitymaturity_having = self.build_maturity_having_clause_optimized()if maturity_having is not None:if query.ctes and "entity_metrics" in query.ctes:@@ -430,7 +392,7 @@ class FunnelQueryBuilder:exprs=[entity_metrics_cte.expr.having, maturity_having])- # Add step counts - how many users reached each step+ # step_counts feeds the funnel chart: the number of entities that reached each stepstep_count_exprs = []for i in range(1, num_steps):step_count_exprs.append(f"countIf(entity_metrics.value.1 >= {i})")@@ -442,10 +404,8 @@ class FunnelQueryBuilder:def build_funnel_optimized_temporal_setup(self, is_unordered_funnel: bool) -> FunnelTemporalSetup:"""- Returns the FunnelTemporalSetup (first exposures CTE, temporal join,- having clause) for the optimized funnel query.-- Three call sites collapse into one place:+ The first_exposures CTE, temporal join and HAVING clause of the optimized+ funnel query depend on three cases:- Unordered funnels need temporal filtering because the UDF doesn'tenforce that step_0 (exposure) precedes step_1..N. We exclude events@@ -493,10 +453,6 @@ class FunnelQueryBuilder:)def build_variant_expr_for_funnel(self) -> ast.Expr:- """- Builds the variant selection expression based on multiple variant handling.- """-if self._b.multiple_variant_handling == MultipleVariantHandling.FIRST_SEEN:return parse_expr("argMinIf(variant, timestamp, step_0 = 1)",@@ -513,14 +469,11 @@ class FunnelQueryBuilder:"""Returns the SELECT query that the lazy computation system wraps in anINSERT INTO experiment_metric_events_preaggregated. This is the write- path — it scans the events table and stores one row per matching event- with step indicators packed into an Array(UInt8).+ path: it scans the events table and stores one row per matching event,+ with the step indicators packed into an Array(UInt8).The query uses {time_window_min} and {time_window_max} placeholders filledby the lazy computation system for each daily bucket.-- Returns:- Tuple of (query_string, placeholders_dict)"""assert isinstance(self._b.metric, ExperimentFunnelMetric)@@ -578,12 +531,8 @@ class FunnelQueryBuilder:return query_string, placeholdersdef build_funnel_step_columns(self) -> list[ast.Alias]:- """- Builds list of step column AST expressions: step_0, step_1, etc.- """assert isinstance(self._b.metric, ExperimentFunnelMetric)- # Check if any step is a data warehouse nodehas_dw_nodes = any(isinstance(step, ExperimentDataWarehouseNode) for step in self._b.metric.series)if has_dw_nodes:@@ -592,7 +541,6 @@ class FunnelQueryBuilder:"Mixed-source UNION ALL query pattern needs to be implemented.")- # Use FunnelStepBuilder abstraction for boolean columnsstep_builder = FunnelStepBuilder(self._b.metric.series, self._b.team)exposure_filter = self._b._build_exposure_step_predicate()return step_builder.build_boolean_columns(exposure_filter)@@ -641,47 +589,32 @@ class FunnelQueryBuilder:return funnel_evaluation_expr(self._b.team, self._b.metric, events_alias="metric_events", include_exposure=True)def has_datawarehouse_steps(self) -> bool:- """- Check if funnel metric has any datawarehouse steps.-- Returns:- True if any step in the series is ExperimentDataWarehouseNode- """assert isinstance(self._b.metric, ExperimentFunnelMetric)return any(isinstance(step, ExperimentDataWarehouseNode) for step in self._b.metric.series)def build_funnel_metric_events_union_query(self) -> ast.SelectSetQuery:- """- Build metric_events UNION ALL query for funnels with DW steps.-- Uses MetricSourceInfo and FunnelStepBuilder abstractions.-- Returns:- SelectSetQuery with UNION ALL combining events and DW sources- """+ """metric_events as a UNION ALL of one events subquery and one subquery per DW step."""assert isinstance(self._b.metric, ExperimentFunnelMetric)step_builder = FunnelStepBuilder(self._b.metric.series, self._b.team)- # All DW steps are validated to use the same events_join_key+ # FunnelDWValidator guarantees that all DW steps use the same events_join_keyfirst_dw_step = next(s for s in self._b.metric.series if isinstance(s, ExperimentDataWarehouseNode))events_join_key = first_dw_step.events_join_key- # Build events subquery (always needed for exposure + event/action steps)+ # The events subquery is always present, because it carries the exposure stepevents_subquery = self.build_funnel_events_subquery_for_union(step_builder, events_join_key)- # Build DW subqueries (one per DW step)dw_subqueries = []for i, step in enumerate(self._b.metric.series):if isinstance(step, ExperimentDataWarehouseNode):dw_subquery = self.build_funnel_dw_step_subquery(step, i + 1, step_builder)dw_subqueries.append(dw_subquery)- # Combine with UNION ALLall_subqueries = [events_subquery, *dw_subqueries]result = ast.SelectSetQuery.create_from_queries(all_subqueries, "UNION ALL")- # create_from_queries returns SelectQuery if only one query, but we always have at least 2 (events + DW)+ # create_from_queries returns a SelectQuery for one query, but there are always at least two: events and DWassert isinstance(result, ast.SelectSetQuery)return result@@ -689,21 +622,10 @@ class FunnelQueryBuilder:self, step_builder: FunnelStepBuilder, events_join_key: str) -> ast.SelectQuery:"""- Build events subquery for UNION pattern.-- This subquery includes:- - Exposure events (step_0=1 when exposure, 0 otherwise)- - Event and action steps (step_N=1 when matches, 0 otherwise)- - DW steps (always step_N=0 in this subquery)-- Args:- step_builder: FunnelStepBuilder instance for step columns- events_join_key: The event property key used to join with DW tables- (e.g. "properties.$user_id"). Used as entity_id so it matches the- DW subquery's data_warehouse_join_key.-- Returns:- SELECT query for events table+ Events subquery for the UNION ALL pattern, with these step columns:+ - step_0: 1 for an exposure event, else 0+ - step_N for an event or action step: 1 when the event matches, else 0+ - step_N for a DW step: always 0, because the DW subqueries supply those rows"""assert isinstance(self._b.metric, ExperimentFunnelMetric)@@ -712,7 +634,6 @@ class FunnelQueryBuilder:events_join_key_parts = cast(list[str | int], events_join_key.split("."))entity_id_expr = ast.Call(name="toString", args=[ast.Field(chain=events_join_key_parts)])- # Build base SELECT fieldsselect_fields: list[ast.Expr] = [ast.Alias(alias="entity_id", expr=entity_id_expr),ast.Alias(alias="variant", expr=self._b._build_variant_property()),@@ -721,14 +642,8 @@ class FunnelQueryBuilder:ast.Alias(alias="session_id", expr=ast.Field(chain=["properties", "$session_id"])),]- # Build step columns- # - step_0 (exposure): if(exposure_predicate, 1, 0)- # - step_N (event/action): if(step_filter, 1, 0)- # - step_N (DW): 0 (always 0 in events subquery)-exposure_filter = self._b._build_exposure_step_predicate()- # step_0: exposurestep_0 = ast.Alias(alias="step_0",expr=ast.Call(@@ -744,18 +659,15 @@ class FunnelQueryBuilder:if not isinstance(step_source, ExperimentDataWarehouseNode):step_filters[i + 1] = step_builder._build_step_filter(step_source)- # step_1, step_2, ...: event/action steps or DW stepsfor i, step_source in enumerate(self._b.metric.series):step_index = i + 1 # +1 because step_0 is exposureif isinstance(step_source, ExperimentDataWarehouseNode):- # DW step: always 0 in events subquerystep_col = ast.Alias(alias=f"step_{step_index}",expr=ast.Constant(value=0),)else:- # Event or action step: if(step_filter, 1, 0)step_col = ast.Alias(alias=f"step_{step_index}",expr=ast.Call(@@ -766,11 +678,8 @@ class FunnelQueryBuilder:select_fields.append(step_col)- # Build WHERE clause - matches exposure OR any event/action step- # (DW steps will be queried separately)event_action_filters = list(step_filters.values())- # Build time window filter (experiment date range + conversion window)conversion_window_seconds = self._b._get_conversion_window_seconds()date_to_expr: ast.Exprif conversion_window_seconds > 0:@@ -802,16 +711,14 @@ class FunnelQueryBuilder:])- # Combine step matching with time rangewhere: ast.Exprif event_action_filters:step_match = ast.Or(exprs=[self._b._build_exposure_step_predicate(), ast.Or(exprs=event_action_filters)])where = ast.And(exprs=[time_range_filter, step_match])else:- # Only exposure events (all steps are DW)+ # All steps are DW steps, so this subquery only needs the exposure eventswhere = ast.And(exprs=[time_range_filter, self._b._build_exposure_step_predicate()])- # Build queryquery = ast.SelectQuery(select=select_fields,select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),@@ -826,36 +733,19 @@ class FunnelQueryBuilder:step_index: int,step_builder: FunnelStepBuilder,) -> ast.SelectQuery:- """- Build subquery for a single DW step.-- Uses MetricSourceInfo and FunnelStepBuilder abstractions for normalized output.-- Args:- step: The DW node configuration- step_index: The step number (1-indexed, after exposure step_0)- step_builder: FunnelStepBuilder instance for step columns-- Returns:- SELECT query for DW table- """+ """Subquery for one DW step. `step_index` is 1-based, because step_0 is the exposure step."""assert isinstance(self._b.metric, ExperimentFunnelMetric)- # Use MetricSourceInfo for normalized schemasource_info = MetricSourceInfo.from_source(step, entity_key=None)- # Build SELECT fields (entity_id, variant, timestamp, uuid, session_id)- # Cast to list[Expr] since Alias is a subclass of Expr+ # list is invariant, so list[Alias] needs a cast to list[Expr]select_fields: list[ast.Expr] = cast(list[ast.Expr], source_info.build_select_fields())- # Add step columns (step_0=0, ..., step_N=1, ...) using FunnelStepBuilderstep_columns = step_builder.build_constant_columns(active_step_index=step_index)select_fields.extend(step_columns)- # Build WHERE predicatewhere = self.build_dw_step_predicate(step, source_info)- # Build queryquery = ast.SelectQuery(select=select_fields,select_from=ast.JoinExpr(table=ast.Field(chain=[source_info.table_name])),@@ -870,32 +760,20 @@ class FunnelQueryBuilder:source_info: MetricSourceInfo,) -> ast.Expr:"""- Build WHERE predicate for DW step filtering.-- Filters by:- - Timestamp range (experiment dates + conversion window)- - DW node properties (custom filters)-- Args:- step: The DW node configuration- source_info: MetricSourceInfo for this DW source-- Returns:- Filter expression+ Filters the DW table on the experiment date range plus the conversion window,+ and on the DW node's property filters."""assert isinstance(self._b.metric, ExperimentFunnelMetric)conversion_window_seconds = self._b._get_conversion_window_seconds()- # Build timestamp filter- # Use unqualified field name for DW to avoid issues with dotted table names+ # Use the unqualified field name, because a qualified name breaks for dotted DW table namestimestamp_field = ast.Field(chain=[source_info.timestamp_field])# date_from <= timestamp < date_to + conversion_windowdate_from_expr = self._b.date_range_query.date_from_as_hogql()date_to_expr = self._b.date_range_query.date_to_as_hogql()- # Add conversion window to date_todate_to_with_window: ast.Exprif conversion_window_seconds > 0:date_to_with_window = ast.Call(@@ -926,14 +804,10 @@ class FunnelQueryBuilder:])- # Build property filter from DW nodedw_filter = data_warehouse_node_to_filter(self._b.team, step)- # Combine filtersreturn ast.And(exprs=[timestamp_filter, dw_filter])- # --- Optimized funnel query helpers ----def build_variant_expr_for_funnel_optimized(self) -> ast.Expr:"""Variant expression for the optimized funnel path.diff --git a/products/experiments/backend/hogql_queries/experiment_funnels_query_runner.py b/products/experiments/backend/hogql_queries/experiment_funnels_query_runner.pyindex 8ecfddf7a890..f3e83df1fb22 100644--- a/products/experiments/backend/hogql_queries/experiment_funnels_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_funnels_query_runner.py@@ -58,8 +58,6 @@ class ExperimentFunnelsQueryRunner(QueryRunner):)def _calculate(self) -> ExperimentFunnelsQueryResponse:- # Adding experiment specific tags to the tag collection- # This will be available as labels in Prometheustag_queries(query_type="ExperimentFunnelsQuery",experiment_id=self.experiment.id,@@ -72,12 +70,10 @@ class ExperimentFunnelsQueryRunner(QueryRunner):self._validate_event_variants(funnels_result)try:- # Filter results to only include valid variants in the first stepfunnels_result.results = [result for result in funnels_result.results if result[0]["breakdown_value"][0] in self.variants]- # Statistical analysiscontrol_variant, test_variants = self._get_variants_with_base_stats(funnels_result)probabilities = calculate_probabilities_v2(control_variant, test_variants)significance_code, loss = are_results_significant_v2(control_variant, test_variants, probabilities)@@ -103,17 +99,13 @@ class ExperimentFunnelsQueryRunner(QueryRunner):def _prepare_funnel_query(self) -> FunnelsQuery:"""- This method takes the raw funnel query and adapts it- for the needs of experiment analysis:+ Adapts the raw funnel query for experiment analysis:1. Set the date range to match the experiment's duration, using the project's timezone.- 2. Configure the breakdown to use the feature flag key, which allows us- to separate results for different experiment variants.+ 2. Break down by the feature flag key, to separate the results for each variant."""- # Clone the funnels queryprepared_funnels_query = FunnelsQuery(**self.query.funnels_query.model_dump())- # Set the date range to match the experiment's duration, using the project's timezoneif self.team.timezone:tz = ZoneInfo(self.team.timezone)start_date = self.experiment.start_date.astimezone(tz) if self.experiment.start_date else None@@ -128,13 +120,11 @@ class ExperimentFunnelsQueryRunner(QueryRunner):explicitDate=True,)- # Configure the breakdown to use the feature flag keyprepared_funnels_query.breakdownFilter = BreakdownFilter(breakdown=f"$feature/{self.feature_flag_key}",breakdown_type="event",)- # Set the layout to verticalif prepared_funnels_query.funnelsFilter is None:prepared_funnels_query.funnelsFilter = FunnelsFilter()prepared_funnels_query.funnelsFilter.layout = FunnelLayout.VERTICAL@@ -193,14 +183,12 @@ class ExperimentFunnelsQueryRunner(QueryRunner):if event_dict.get("order") == 0:eventsWithOrderZero.append(event_dict)- # Check if "control" is presentfor event in eventsWithOrderZero:event_variant = event.get("breakdown_value", [None])[0]if event_variant == "control":errors[ExperimentNoResultsErrorKeys.NO_CONTROL_VARIANT] = Falsebreak- # Check if at least one of the test variants is presenttest_variants = [variant for variant in self.variants if variant != "control"]for event in eventsWithOrderZero:event_variant = event.get("breakdown_value", [None])[0]@@ -215,7 +203,6 @@ class ExperimentFunnelsQueryRunner(QueryRunner):def to_query(self) -> ast.SelectQuery:raise ValueError(f"Cannot convert source query of type {self.query.funnels_query.kind} to query")- # Cache results for 24 hoursdef cache_target_age(self, last_refresh: Optional[datetime], lazy: bool = False) -> Optional[datetime]:if last_refresh is None:return Nonediff --git a/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py b/products/experiments/backend/hogql_queries/experiment_mean_query_builder.pyindex 111573cdd585..5e6eaa0af84c 100644--- a/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py@@ -27,12 +27,9 @@ class MeanQueryBuilder:Builds mean-metric queries (count, sum, avg, etc.), including thewinsorized 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.+ The class holds a reference to the owning ``ExperimentQueryBuilder`` and+ reads shared state (metric, entity key, CUPED config, breakdown injector)+ and the shared exposure, metric-value, and CUPED helpers through it."""def __init__(self, builder: "ExperimentQueryBuilder"):@@ -40,11 +37,9 @@ class MeanQueryBuilder: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+ A session property has one value per session, not per event. Without+ deduplication, every event in a session adds the full session value, so+ the result scales with the event count. Each session must contribute once.Pattern:1. metric_events_by_session: GROUP BY $session_id, get any(session.$property)@@ -61,8 +56,6 @@ class MeanQueryBuilder:{{exposure_select_query}}),- -- Layer 1: Deduplicate within sessions- -- Each session contributes exactly one value regardless of event countmetric_events_by_session AS (SELECT{{entity_key}} AS entity_id,@@ -76,7 +69,6 @@ class MeanQueryBuilder:GROUP BY {{entity_key}}, `$session_id`),- -- Layer 2: Join with exposures, filter by temporal orderingmetric_events AS (SELECTexposures.entity_id AS entity_id,@@ -90,7 +82,6 @@ class MeanQueryBuilder:AND {{session_conversion_window_predicate}}),- -- Layer 3: Aggregate across sessions per entityentity_metrics AS (SELECTentity_id,@@ -108,16 +99,13 @@ class MeanQueryBuilder:"""assert isinstance(self._b.metric, ExperimentMeanMetric)- # Check if this is a session property metric - use special CTE structureif 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 metadatasource_info = MetricSourceInfo.from_source(self._b.metric.source, entity_key=self._b.entity_key)- # Determine join condition based on source typeif source_info.kind == "datawarehouse":join_condition = "{join_condition}"else:@@ -138,7 +126,7 @@ class MeanQueryBuilder:# 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 reusability, so we must filter on read. The upper+ # 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@@ -209,7 +197,6 @@ class MeanQueryBuilder:"""assert isinstance(self._b.metric, ExperimentMeanMetric)- # Check if this is a session property metric - use different placeholdersis_session_property = isinstance(self._b.metric.source, (ActionsNode, EventsNode)) and is_session_property_metric(self._b.metric.source)@@ -217,17 +204,16 @@ class MeanQueryBuilder:if is_session_property:return self.get_session_property_placeholders()- # Use MetricSourceInfo abstraction for source metadatasource_info = MetricSourceInfo.from_source(self._b.metric.source, entity_key=self._b.entity_key)- # Build exposure query with exposure_identifier for data warehouseexposure_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+ # argMin takes the join key from the first exposure, so each entity_id gets one+ # exposure_identifier. Do not add the join key to GROUP BY: a user with exposures+ # that carry different join key values would then fan out into several rows.exposure_query.select.append(ast.Alias(alias="exposure_identifier",@@ -237,7 +223,6 @@ class MeanQueryBuilder:),))- # Do NOT add to GROUP BY - that would cause fan-out when join key varies across exposuresmetric_predicate = self._b._build_metric_predicate(table_alias=source_info.table_name,@@ -276,7 +261,6 @@ class MeanQueryBuilder:value=self._b._get_conversion_window_seconds())- # Add join condition for data warehouseif source_info.kind == "datawarehouse":placeholders["join_condition"] = parse_expr("toString(exposures.exposure_identifier) = toString(metric_events.entity_id)"@@ -285,10 +269,7 @@ class MeanQueryBuilder:return placeholdersdef get_session_property_placeholders(self) -> dict:- """- Returns placeholders specific to session property metrics.- Session properties use a different CTE structure with deduplication per session.- """+ """Placeholders for the CTEs from get_session_property_ctes()."""assert isinstance(self._b.metric, ExperimentMeanMetric)exposure_query = self._b._get_exposure_query()@@ -305,7 +286,7 @@ class MeanQueryBuilder:"""Returns the SELECT query that the lazy computation system wraps in anINSERT INTO experiment_metric_events_preaggregated. This is the write- path — it scans the events table and stores one row per matching metric+ path. It scans the events table and stores one row per matching metricevent with its per-event value in numeric_value. For numeric math thevalue is already coalesced to a non-null float by _build_value_expr(),so storing it in the non-nullable numeric_value column is lossless.@@ -318,11 +299,8 @@ class MeanQueryBuilder:by the lazy computation system for each daily bucket. The experiment datebounds must stay named placeholders (the caller declares experiment_date_toa sentinel) rather than reusing _build_metric_predicate(), which bakes the- resolved dates into the AST — a running experiment's moving window end- would then change the job hash and defeat cache reuse.-- Returns:- Tuple of (query_string, placeholders_dict)+ 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."""assert isinstance(self._b.metric, ExperimentMeanMetric)source = self._b.metric.source@@ -367,12 +345,8 @@ class MeanQueryBuilder:return query_string, placeholdersdef 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)@@ -424,7 +398,6 @@ class MeanQueryBuilder:assert isinstance(query, ast.SelectQuery)- # Inject breakdown columns into the query ASTif self._b.breakdown_injector:self._b.breakdown_injector.inject_mean_breakdown_columns(query, final_cte_name="entity_metrics")@@ -432,12 +405,11 @@ class MeanQueryBuilder: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.+ Clamps each entity's value to percentile-based bounds to limit the+ effect of outliers."""assert isinstance(self._b.metric, ExperimentMeanMetric)- # Build lower bound expressionif self._b.metric.lower_bound_percentile is not None:lower_bound_expr = parse_expr("quantileExact({level})(entity_metrics.value)",@@ -446,9 +418,7 @@ class MeanQueryBuilder:else:lower_bound_expr = parse_expr("min(entity_metrics.value)")- # Build upper bound expressionif self._b.metric.upper_bound_percentile is not None:- # Handle ignore_zeros flag for upper bound calculationif getattr(self._b.metric, "ignore_zeros", False):upper_bound_expr = parse_expr("quantileExact({level})(if(entity_metrics.value != 0, entity_metrics.value, null))",@@ -479,7 +449,6 @@ class MeanQueryBuilder:else "")- # Add winsorization-specific placeholdersplaceholders["lower_bound"] = lower_bound_exprplaceholders["upper_bound"] = upper_bound_expr@@ -522,7 +491,6 @@ class MeanQueryBuilder:assert isinstance(query, ast.SelectQuery)- # Inject breakdown columns into the query ASTif self._b.breakdown_injector:self._b.breakdown_injector.inject_mean_breakdown_columns(query, final_cte_name="winsorized_entity_metrics")diff --git a/products/experiments/backend/hogql_queries/experiment_metric_fingerprint.py b/products/experiments/backend/hogql_queries/experiment_metric_fingerprint.pyindex cf8c4ae672d9..0040be2cd08a 100644--- a/products/experiments/backend/hogql_queries/experiment_metric_fingerprint.py+++ b/products/experiments/backend/hogql_queries/experiment_metric_fingerprint.py@@ -1,6 +1,4 @@"""-Experiment metric fingerprinting-Generates fingerprints for experiment metrics to detect when metric definitionsor the experiment itself have changed in ways that would affect calculation results.Used to invalidate cached timeseries data when metrics are modified.@@ -51,28 +49,12 @@ def compute_metric_fingerprint(only_count_matured_users: bool = False,excluded_variants: list[str] | None = None,) -> str:- """- Compute fingerprint for a metric.-- Args:- metric: The metric definition- start_date: Experiment start date- stats_method- exposure_criteria- only_count_matured_users- excluded_variants: Variant keys excluded from analysis — changing the set- invalidates cached results since it alters which data is computed-- Returns:- SHA256 hash string representing the metric fingerprint- """clean_metric = deepcopy(metric)for field in METRIC_FIELDS_TO_IGNORE:clean_metric.pop(field, None)_strip_empty_breakdowns(clean_metric)- # Convert datetime to ISO string for JSON serialization- # Always use UTC to ensure consistent fingerprints regardless of user timezone+ # Normalize to UTC so that the same instant gives the same fingerprint in every timezoneif isinstance(start_date, datetime):start_date_str = start_date.astimezone(ZoneInfo("UTC")).isoformat()else:@@ -96,7 +78,6 @@ def compute_metric_fingerprint(if excluded_variants:fingerprint_data["excluded_variants"] = sorted(set(excluded_variants))- # Create deterministic JSON string with sorted keys at all levelsjson_str = json.dumps(fingerprint_data, sort_keys=True, separators=(",", ":"))hash_result = hashlib.sha256(json_str.encode("utf-8")).hexdigest()diff --git a/products/experiments/backend/hogql_queries/experiment_metric_values.py b/products/experiments/backend/hogql_queries/experiment_metric_values.pyindex 4ef8f3737567..88c38c706b9c 100644--- a/products/experiments/backend/hogql_queries/experiment_metric_values.py+++ b/products/experiments/backend/hogql_queries/experiment_metric_values.py@@ -34,10 +34,7 @@ MetricSource = Union[EventsNode, ActionsNode, ExperimentDataWarehouseNode]def get_conversion_window_seconds(metric: ExperimentMetric) -> int:- """- Returns the conversion window in seconds for the current metric.- Returns 0 if no conversion window is configured.- """+ """Returns 0 when the metric has no conversion window."""if metric.conversion_window and metric.conversion_window_unit:return conversion_window_to_seconds(metric.conversion_window,@@ -47,18 +44,10 @@ def get_conversion_window_seconds(metric: ExperimentMetric) -> int:def build_conversion_window_predicate(conversion_window_seconds: int) -> ast.Expr:- """- Build the predicate for limiting metric events to the conversion window for the user.- Uses "metric_events" as the events alias.- """return build_conversion_window_predicate_for_events("metric_events", conversion_window_seconds)def build_session_conversion_window_predicate(conversion_window_seconds: int) -> ast.Expr:- """- Build the predicate for limiting session metric events to the conversion window.- Uses first_event_timestamp from metric_events_by_session for temporal filtering.- """if conversion_window_seconds > 0:return parse_expr("""@@ -70,16 +59,12 @@ def build_session_conversion_window_predicate(conversion_window_seconds: int) ->},)else:- # No conversion window limit - just return true since temporal filtering- # is already handled by the >= first_exposure_timestamp condition in the join+ # Without a conversion window there is no upper bound. The join already+ # requires first_event_timestamp >= first_exposure_time.return ast.Constant(value=True)def build_conversion_window_predicate_for_events(events_alias: str, conversion_window_seconds: int) -> ast.Expr:- """- Build the predicate for limiting metric events to the conversion window for the user.- Parameterized to support different event table aliases (for ratio metrics).- """if conversion_window_seconds > 0:return parse_expr(f"""@@ -105,11 +90,9 @@ def build_metric_predicate(cuped_lookback_days: int | None = None,) -> ast.Expr:"""- Builds the metric predicate as an AST expression.For ratio metrics, pass the specific source (numerator or denominator) and table_alias.- For mean metrics, pass the resolved metric source explicitly with "events" alias.+ For mean metrics, pass the resolved metric source explicitly with the "events" alias."""- # Data warehouse sources use different table and predicate logictimestamp_field_chain: list[str | int]if isinstance(source, ExperimentDataWarehouseNode):# For DW tables, don't prefix with table name since:@@ -150,20 +133,13 @@ def build_metric_predicate(def build_value_expr(source: MetricSource, apply_coalesce: bool = True) -> ast.Expr:"""- Extracts the value expression from the metric source configuration.For ratio metrics, pass the specific source (numerator or denominator).For mean metrics, pass the resolved metric source explicitly.- Args:- source: The metric source configuration- apply_coalesce: If True, wrap numeric values with coalesce(..., 0) so that- NULL property values are treated as 0. This should be True- for event CTEs (metric_events, numerator_events, denominator_events)- so that downstream aggregations don't need to distinguish between- metric types.-- Note: For count distinct math types (UNIQUE_SESSION, DAU, UNIQUE_GROUP), coalesce- is not applied since the value is an ID, not a numeric value.+ apply_coalesce wraps numeric values in coalesce(..., 0), so a NULL property+ value counts as 0. Event CTEs (metric_events, numerator_events,+ denominator_events) need it, so that downstream aggregations do not have to+ distinguish between metric types."""base_expr = get_source_value_expr(source)@@ -180,10 +156,8 @@ def build_value_expr(source: MetricSource, apply_coalesce: bool = True) -> ast.E]:return base_expr- # Wrap numeric values with coalesce so NULL property values become 0- # We need toFloat to ensure type consistency - base_expr could be String (HOGQL),- # Float64 (continuous), or UInt8 (count). Coalesce requires matching types.- # Skip wrapping with toFloat if base_expr is already a toFloat call (e.g., continuous metrics)+ # coalesce() needs matching argument types, and base_expr can be Float64+ # (continuous) or UInt8 (count), so cast it to Float before the coalesce.if isinstance(base_expr, ast.Call) and base_expr.name == "toFloat":float_expr = base_exprelse:@@ -198,19 +172,14 @@ def build_value_aggregation_expr(value_expr: ast.Expr | None = None,) -> ast.Expr:"""- Returns the value aggregation expression based on math type.For ratio metrics, pass the specific source (numerator or denominator) and events_alias.- For mean metrics, pass the resolved metric source explicitly with "metric_events" alias.-- Args:- source: The metric source configuration- events_alias: The table/CTE alias to use (e.g., "metric_events", "combined_events")- column_name: The column name containing the value (e.g., "value", "numerator_value")+ For mean metrics, pass the resolved metric source explicitly with the "metric_events" alias.+ value_expr, when set, replaces the {events_alias}.{column_name} column.- Note: NULL handling (coalesce) is applied upstream in _build_value_expr() when building- the event CTEs. This method does not need to handle NULLs - aggregation functions will- naturally ignore NULLs from combined_events (ratio metrics), while NULL property values- have already been coalesced to 0 at the source.+ build_value_expr() already coalesces NULL property values to 0 in the event CTEs.+ The aggregated rows can still hold NULL: the LEFT JOIN from exposures gives NULL+ for an entity without events, and a CUPED value_expr is NULL outside its window.+ Each branch below returns 0, not NULL, for an entity with only NULL values."""math_type = getattr(source, "math", ExperimentMetricMathType.TOTAL)column_ref = f"{events_alias}.{column_name}"@@ -280,14 +249,12 @@ def build_value_aggregation_expr(if not aggregation_needs_numeric_input(aggregation_function):agg_call = ast.Call(name="toFloat", args=[agg_call])return ast.Call(name="coalesce", args=[agg_call, ast.Constant(value=0)])- # Fallback to SUM+ # A math_hogql without a known aggregation function falls back to sum.if value_expr is not None:return parse_expr("sum(coalesce(toFloat({value_expr}), 0))", placeholders={"value_expr": value_expr})return parse_expr(f"sum(coalesce(toFloat({column_ref}), 0))")else:- # SUM (default) - coalesce is needed here because sum(NULL) returns NULL.- # For ratio metrics with combined_events, when there are no events of one type,- # all values for that type are NULL (from UNION ALL structure), and we want 0 not NULL.+ # SUM (default). sum() over only NULL values returns NULL, so coalesce each value.if value_expr is not None:return parse_expr("sum(coalesce(toFloat({value_expr}), 0))", placeholders={"value_expr": value_expr})return parse_expr(f"sum(coalesce(toFloat({column_ref}), 0))")diff --git a/products/experiments/backend/hogql_queries/experiment_query_builder.py b/products/experiments/backend/hogql_queries/experiment_query_builder.pyindex f46f871ef416..6ab30406059d 100644--- a/products/experiments/backend/hogql_queries/experiment_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_query_builder.py@@ -77,7 +77,6 @@ def get_exposure_config_params_for_builder(team: Team,start_date: Optional[datetime],) -> ExposureQueryParams:- """Returns exposure-related parameters required by the query builder."""criteria = normalize_to_exposure_criteria(exposure_criteria)exposure_config: ExperimentEventExposureConfig | ActionsNodeactivation_config: ExperimentEventExposureConfig | ActionsNode | None = None@@ -160,9 +159,9 @@ class ExperimentQueryBuilder:if activation_config is not None and isinstance(metric, ExperimentFunnelMetric):self.cuped_config = CupedQueryConfig(enabled=False, lookback_days=self.cuped_config.lookback_days)- # Experiment-level invariants, gathered into a single frozen context for- # later extracted modules to consume. Additive: every self.* attribute- # above remains the source of truth for existing internal methods.+ # Frozen snapshot for builders that take a context instead of this builder,+ # such as ExposureQueryBuilder. Methods on this class read the self.* attributes,+ # so a later change to one of them does not reach the context.self.context = ExperimentQueryContext(team=self.team,feature_flag_key=self.feature_flag_key,@@ -179,19 +178,17 @@ class ExperimentQueryBuilder:)# Experiment queries group by (variant, breakdown_values), so the row count is- # bounded by num_variants × num_breakdown_values. The HogQL executor injects+ # bounded by num_variants × num_breakdown_values. The HogQL executor injects# LIMIT 100 when no explicit limit is set, which silently truncates results for- # high-cardinality breakdowns. Set a generous explicit limit to prevent this.+ # high-cardinality breakdowns.QUERY_RESULT_LIMIT = MAX_SELECT_RETURNED_ROWSdef build_query(self, precomputation_context: ExperimentPrecomputationContext | None = None) -> ast.SelectQuery:"""- Main entry point. Returns complete query built from HogQL with placeholders.-- When ``precomputation_context`` is supplied, the precomputed job IDs are- applied here so every internal method that reads ``self.*`` stays- unchanged. Job IDs can only be supplied at build time because the builder- itself generates the precompute queries before any job IDs exist.+ ``precomputation_context`` carries the precomputed job IDs. They arrive here+ and not in __init__, because the same builder generates the precompute+ queries before any job IDs exist. The IDs are stored on self so the+ metric builders read them like any other builder state."""if precomputation_context is not None:self.preaggregation_job_ids = precomputation_context.exposure_job_ids@@ -216,11 +213,7 @@ class ExperimentQueryBuilder:return querydef _exposure_query_builder(self) -> ExposureQueryBuilder:- """Construct an ExposureQueryBuilder from the current builder state.-- Built fresh per call so it picks up the current ``preaggregation_job_ids``- (only known at build time).- """+ """Built per call so it picks up the ``preaggregation_job_ids`` that build_query() sets."""return ExposureQueryBuilder(context=self.context,breakdown_injector=self.breakdown_injector,@@ -229,38 +222,24 @@ class ExperimentQueryBuilder:)def _funnel_query_builder(self) -> FunnelQueryBuilder:- """Construct a FunnelQueryBuilder backed by the current builder state.-- Built fresh per call so it picks up the current precomputation job IDs- (only known at build time).- """return FunnelQueryBuilder(self)def _retention_query_builder(self) -> RetentionQueryBuilder:- """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 _cuped_query_builder(self) -> CupedQueryBuilder:- """Construct a CupedQueryBuilder backed by the current builder state."""return CupedQueryBuilder(self)def get_exposure_timeseries_query(self) -> ast.SelectQuery:"""- Returns a query for exposure timeseries data.-- Generates daily exposure counts per variant, counting each entity- only once on their first exposure day.-- Returns:- SelectQuery with columns: day, variant, exposed_count+ Daily exposure counts per variant. Each entity counts once, on the day of+ its first exposure. Columns: day, variant, exposed_count."""return self._exposure_query_builder().timeseries_query()@@ -272,18 +251,15 @@ class ExperimentQueryBuilder:return self._exposure_query_builder().daily_exposures_from_precomputed(job_ids)def _get_conversion_window_seconds(self) -> int:- """- Returns the conversion window in seconds for the current metric.- Returns 0 if no conversion window is configured.- """+ """Returns 0 when the metric has no conversion window."""assert self.metric is not None, "metric is required for _get_conversion_window_seconds()"return get_conversion_window_seconds(self.metric)def _get_maturity_window_seconds(self) -> int:"""- Returns the maturity window in seconds for non-retention metrics.- Retention metrics use _get_retention_maturity_seconds and apply maturity- in the start_events CTE, anchored on start_event timestamp.+ Non-retention metrics only. Retention uses+ RetentionQueryBuilder.get_retention_maturity_seconds() and applies maturity+ in its start_events CTE, anchored on the start_event timestamp."""return self._get_conversion_window_seconds()@@ -297,8 +273,8 @@ class ExperimentQueryBuilder:window for flags re-evaluated repeatedly (e.g. backend flags), so active userswould never mature. Callers pass an exposure-only timestamp expression.- Retention metrics handle maturity separately in their own start_events CTE- via _build_retention_maturity_having_clause; this function intentionally+ Retention metrics apply maturity in their own start_events CTE through+ RetentionQueryBuilder.build_retention_maturity_having_clause(), so thisreturns None for them."""if self.metric is None:@@ -322,46 +298,23 @@ class ExperimentQueryBuilder:)def _build_funnel_query(self) -> ast.SelectQuery:- """- Builds query for funnel metrics.- Dispatches to optimized (single-scan) or legacy (double-scan) path.- """return self._funnel_query_builder().build_funnel_query()def _build_mean_query(self) -> ast.SelectQuery:- """- Builds query for mean metrics (count, sum, avg, etc.)- """return self._mean_query_builder().build_mean_query()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.- """return self._ratio_query_builder().build_ratio_query()def _build_conversion_window_predicate(self) -> ast.Expr:- """- Build the predicate for limiting metric events to the conversion window for the user.- Uses "metric_events" as the events alias.- """+ """Uses "metric_events" as the events alias."""return build_conversion_window_predicate(self._get_conversion_window_seconds())def _build_session_conversion_window_predicate(self) -> ast.Expr:- """- Build the predicate for limiting session metric events to the conversion window.- Uses first_event_timestamp from metric_events_by_session for temporal filtering.- """+ """Uses first_event_timestamp from metric_events_by_session as the event time."""return build_session_conversion_window_predicate(self._get_conversion_window_seconds())def _build_conversion_window_predicate_for_events(self, events_alias: str) -> ast.Expr:- """- Build the predicate for limiting metric events to the conversion window for the user.- Parameterized to support different event table aliases (for ratio metrics).- """return build_conversion_window_predicate_for_events(events_alias, self._get_conversion_window_seconds())def _build_cuped_pre_window_predicate(@@ -401,9 +354,8 @@ class ExperimentQueryBuilder:cuped_lookback_days: int | None = None,) -> ast.Expr:"""- Builds the metric predicate as an AST expression.For ratio metrics, pass the specific source (numerator or denominator) and table_alias.- For mean metrics, uses self.metric.source by default with "events" alias.+ For mean metrics, the default is self.metric.source with the "events" alias."""if source is None:assert isinstance(self.metric, ExperimentMeanMetric)@@ -420,20 +372,10 @@ class ExperimentQueryBuilder:def _build_value_expr(self, source=None, apply_coalesce: bool = True) -> ast.Expr:"""- Extracts the value expression from the metric source configuration.For ratio metrics, pass the specific source (numerator or denominator).- For mean metrics, uses self.metric.source by default.-- Args:- source: The metric source configuration- apply_coalesce: If True, wrap numeric values with coalesce(..., 0) so that- NULL property values are treated as 0. This should be True- for event CTEs (metric_events, numerator_events, denominator_events)- so that downstream aggregations don't need to distinguish between- metric types.-- Note: For count distinct math types (UNIQUE_SESSION, DAU, UNIQUE_GROUP), coalesce- is not applied since the value is an ID, not a numeric value.+ For mean metrics, the default is self.metric.source.++ See build_value_expr() for apply_coalesce."""if source is None:assert isinstance(self.metric, ExperimentMeanMetric)@@ -449,19 +391,10 @@ class ExperimentQueryBuilder:value_expr: ast.Expr | None = None,) -> ast.Expr:"""- Returns the value aggregation expression based on math type.For ratio metrics, pass the specific source (numerator or denominator) and events_alias.- For mean metrics, uses self.metric.source by default with "metric_events" alias.-- Args:- source: The metric source configuration- events_alias: The table/CTE alias to use (e.g., "metric_events", "combined_events")- column_name: The column name containing the value (e.g., "value", "numerator_value")+ For mean metrics, the default is self.metric.source with the "metric_events" alias.- Note: NULL handling (coalesce) is applied upstream in _build_value_expr() when building- the event CTEs. This method does not need to handle NULLs - aggregation functions will- naturally ignore NULLs from combined_events (ratio metrics), while NULL property values- have already been coalesced to 0 at the source.+ value_expr, when set, replaces the {events_alias}.{column_name} column."""if source is None:assert isinstance(self.metric, ExperimentMeanMetric)@@ -475,13 +408,9 @@ class ExperimentQueryBuilder:)def _build_variant_property(self) -> ast.Field:- """Derive which event property that should be used for variants"""return self._exposure_query_builder().build_variant_property()def _build_exposure_predicate(self) -> ast.Expr:- """- Builds the exposure predicate as an AST expression.- """return self._exposure_query_builder().build_exposure_predicate()def _build_exposure_step_predicate(self) -> ast.Expr:@@ -496,15 +425,9 @@ class ExperimentQueryBuilder:def get_exposure_query_for_precomputation(self) -> tuple[str, dict[str, ast.Expr]]:"""- Returns the exposure query and placeholders for lazy computation.-The query string uses {time_window_min} and {time_window_max} placeholders- which are filled in by the lazy computation system for each daily bucket.- Other placeholders are returned in the dict and should be passed to- ensure_precomputed().-- Returns:- Tuple of (query_string, placeholders_dict)+ that the lazy computation system fills for each daily bucket. Pass the+ returned placeholders dict to ensure_precomputed()."""return self._exposure_query_builder().precomputation_query()@@ -512,15 +435,12 @@ class ExperimentQueryBuilder:"""Returns the SELECT query that the lazy computation system wraps in anINSERT INTO experiment_metric_events_preaggregated, dispatched by metric- type. This is the write path — it scans the events table and stores one- row per matching event: funnel metrics pack step indicators into an- Array(UInt8), mean metrics store the per-event value in numeric_value.+ 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.The query uses {time_window_min} and {time_window_max} placeholders filledby the lazy computation system for each daily bucket.-- Returns:- Tuple of (query_string, placeholders_dict)"""match self.metric:case ExperimentFunnelMetric():@@ -543,40 +463,4 @@ class ExperimentQueryBuilder:return self._get_conversion_window_seconds()def _build_retention_query(self) -> ast.SelectQuery:- """- Builds query for retention metrics.-- Retention measures the proportion of users who performed a "completion event"- within a specified time window after performing a "start event".-- Statistical Treatment:- This metric is treated as a ratio metric using RatioStatistic. Each entity has:- - Numerator value: 1 if completed within retention window, 0 otherwise- - Denominator value: 1 (they performed the start event)-- Unlike standard proportion tests (where sample size is fixed), retention metrics- have a random denominator (count of users who started). This makes retention a- ratio of two random variables, requiring delta method variance.-- Returns 7 fields for RatioStatistic:- - Standard: num_users, total_sum, total_sum_of_squares- - Ratio-specific: denominator_sum, denominator_sum_squares, numerator_denominator_sum_product-- The collected statistics are processed using RatioStatistic (not ProportionStatistic)- for both frequentist and Bayesian analysis.-- Structure:- - exposures: all exposures with variant assignment- - start_events: when each entity performed the start_event (with start_handling logic)- - completion_events: when each entity performed the completion_event- - entity_metrics: join exposures + start_events + completion_events- Calculate retention per entity (1 if retained, 0 if not)- - Final SELECT: aggregated statistics per variant-- Key Design Decision:- Uses INNER JOIN between exposures and start_events, meaning only users who- performed the start event are included in the retention calculation. This- measures "Of users who did X, how many came back to do Y?" rather than- "Of all exposed users, how many did X and then Y?"- """return self._retention_query_builder().build_retention_query()diff --git a/products/experiments/backend/hogql_queries/experiment_query_context.py b/products/experiments/backend/hogql_queries/experiment_query_context.pyindex 2549f3269700..2c10b53972cd 100644--- a/products/experiments/backend/hogql_queries/experiment_query_context.py+++ b/products/experiments/backend/hogql_queries/experiment_query_context.py@@ -12,10 +12,8 @@ from products.experiments.backend.hogql_queries.cuped_config import CupedQueryCoclass ExperimentQueryContext:"""Experiment-level invariants shared across query construction.- This is a transitional and organizational object: it carries the- experiment-scoped parameters that the builder receives at construction- time so future extracted modules can take a single, stable input- instead of threading each parameter individually.+ The query builder and the modules it delegates to, such as the exposure+ query builder, take this one object instead of each parameter."""team: Team@@ -36,12 +34,10 @@ class ExperimentQueryContext:@dataclass(frozen=True)class ExperimentPrecomputationContext:- """Explicit precomputation inputs supplied at build time.+ """Precomputation inputs supplied at build time, not at construction.- Replaces post-construction mutation of the builder's job-id attributes.- The builder is needed to generate the precompute queries before any job- IDs exist (chicken-and-egg), so job IDs can only be supplied once they- are known, at the build call.+ The builder generates the precompute queries before any job IDs exist,+ so the caller can supply the job IDs only at the build call."""exposure_job_ids: list[str] | None = Nonediff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.pyindex 0eaabb3398bf..8fa30ed46449 100644--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py@@ -122,7 +122,6 @@ METRIC_EVENTS_MAX_WINDOW_EXTENSION_SECONDS = 90 * 24 * 60 * 60 # 90 daysdef experiment_precompute_ttl_schedule(team_timezone: str) -> TtlSchedule:- """The experiment TTL schedule with job width capped at PRECOMPUTE_MAX_WINDOW_DAYS."""return parse_ttl_schedule(DEFAULT_EXPOSURE_TTL_SECONDS,team_timezone,@@ -139,11 +138,11 @@ def experiment_precompute_ttl_schedule(team_timezone: str) -> TtlSchedule:# (frozen) windows. Bypassed by an explicit PrecomputationMode.PRECOMPUTED# query override.#-# Why 12h: covers the workday in which users launch experiments — that's-# when they refresh the results page most often and the 15-min cache lag-# would be most noticeable. Past that, refreshes drop off and the cost-# saving from precomputation matters more than the freshness gap. Short-# enough that experiments still hit the precomputed (fast) path on day two.+# Why 12h: it covers the workday in which users launch experiments. Users+# refresh the results page most often then, so the 15-min cache lag is most+# noticeable. After that, refreshes drop off and the cost saving from+# precomputation matters more than the freshness gap. 12h is also short enough+# that experiments hit the precomputed (fast) path on day two.MIN_PRECOMPUTATION_DURATION_SECONDS = 12 * 60 * 60 # 12 hoursMAX_EXECUTION_TIME = 600@@ -162,11 +161,11 @@ def experiment_has_min_runtime_for_precomputation(used. A future end_date (planned end) is ignored so we don't creditruntime that hasn't happened yet.- Note: this is elapsed *runtime*, a different concept from the analysis- window. It deliberately clamps to min(now, end_date) — the opposite of- experiment_window_end, which lets a future end_date win for the query- window (no events exist beyond now anyway). Keep the two rules separate;- do not fold this into the window primitive.+ This is elapsed *runtime*, which is a different concept from the analysis+ window. It clamps to min(now, end_date), which is the opposite of+ experiment_window_end: there a future end_date wins for the query window,+ because no events exist after now. Keep the two rules separate, and do not+ fold this into the window primitive."""if start_date is None:return False@@ -198,12 +197,12 @@ def has_uncalculated_cohorts(team: Team, *filter_sources: Any) -> bool:"""True when any cohort referenced in the given filter structures hasn't finished itsfirst materialization (dynamic: no completed version; static: initial population running).- Queries against such a cohort read its partially-inserted membership — they load fine- but undercount, and with a skew determined by insertion order. A precompute build in- that window freezes the torn snapshot for the frozen-band TTL (60 days), so precompute- must be skipped until the first calculation lands. Cohorts with a completed version are- safe even mid-recalculation: reads pin the last complete version, and cohorts recalculate- every ~15 minutes, so gating on is_calculating would disable precompute permanently.+ A query against such a cohort reads its partially-inserted membership. The query succeeds+ but undercounts, with a skew that depends on insertion order. A precompute build in that+ state freezes the torn snapshot for the frozen-band TTL, so precompute must wait until the+ first calculation lands. A cohort with a completed version is safe even mid-recalculation,+ because reads pin the last complete version. Cohorts recalculate frequently, so a gate on+ is_calculating would disable precompute almost permanently."""ids: set[int] = set()for source in filter_sources:@@ -262,7 +261,6 @@ def ensure_exposures_precomputed(time_range_start: datetime,time_range_end: datetime,) -> LazyComputationResult:- """Ensure lazy-computed exposure data exists for the window, and return its job_ids."""query_string, placeholders = builder.get_exposure_query_for_precomputation()return ensure_precomputed(@@ -331,8 +329,8 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):# Evaluation point for the analysis window; experiment_window_end caps it at end_date. An# explicit as_of is a recalc's frozen run snapshot or a timeseries backfill's per-day point.- # The default — end_date for a stopped experiment, else now — makes a plain results query- # cover the full [start, end_date] window (or [start, now] while running).+ # The default is end_date for a stopped experiment, else now, so that a plain results query+ # covers the full [start, end_date] window, or [start, now] while the experiment runs.self.as_of = as_of if as_of is not None else (self.experiment.end_date or datetime.now(UTC))self.feature_flag = self.experiment.feature_flagself.feature_flag_key = self.feature_flag.key_without_tombstone()@@ -358,21 +356,17 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):interval=IntervalType.DAY,now=datetime.now(),)- # Check if this is a data warehouse queryif isinstance(self.query.metric, ExperimentMeanMetric):self.is_data_warehouse_query = self.query.metric.source.kind == "ExperimentDataWarehouseNode"elif isinstance(self.query.metric, ExperimentFunnelMetric):- # For funnel metrics, check if any step uses data warehouseself.is_data_warehouse_query = any(isinstance(step, ExperimentDataWarehouseNode) for step in self.query.metric.series)elif isinstance(self.query.metric, ExperimentRatioMetric):- # For ratio metrics, check if either numerator or denominator uses data warehousenumerator_is_dw = isinstance(self.query.metric.numerator, ExperimentDataWarehouseNode)denominator_is_dw = isinstance(self.query.metric.denominator, ExperimentDataWarehouseNode)self.is_data_warehouse_query = numerator_is_dw or denominator_is_dwelif isinstance(self.query.metric, ExperimentRetentionMetric):- # For retention metrics, check if either start_event or completion_event uses data warehousestart_is_dw = isinstance(self.query.metric.start_event, ExperimentDataWarehouseNode)completion_is_dw = isinstance(self.query.metric.completion_event, ExperimentDataWarehouseNode)self.is_data_warehouse_query = start_is_dw or completion_is_dw@@ -383,7 +377,6 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):self.experiment.exposure_criteria)- # Just to simplify accessself.metric = self.query.metricself.cuped_config = get_cuped_config(self.experiment.stats_config,@@ -398,7 +391,6 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):self._metric_events_precomputed: bool = Falsedef _get_breakdowns_for_builder(self) -> list | None:- """Extract and validate breakdowns from metric configuration."""breakdown_filter = getattr(self.metric, "breakdownFilter", None)if not breakdown_filter:return None@@ -438,10 +430,10 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):date_from = self.experiment.start_datedate_to = experiment_window_end(self.experiment, self.as_of)- # Extend time range past experiment end — metric events can occur after it: within- # the conversion window, plus for retention the retention window (a completion can- # land up to retention_window_end after a start event that itself lands up to- # conversion_window after the last exposure).+ # Extend the time range past the experiment end, because metric events can occur after+ # it: within the conversion window, and for retention also within the retention window+ # (a completion can land up to retention_window_end after a start event, which itself+ # can land up to conversion_window after the last exposure).extension_seconds = builder.get_metric_events_window_extension_seconds()if extension_seconds > 0:date_to = date_to + timedelta(seconds=extension_seconds)@@ -464,7 +456,6 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):return get_or_create_team_extension(self.team, TeamExperimentsConfig)def _should_precompute(self) -> bool:- """Resolve whether to use precomputation: query-level override > team-level default + duration gate."""return self._precompute_skip_reason() not in BLOCKING_PRECOMPUTE_SKIP_REASONSdef _precompute_skip_reason(self) -> Optional[PrecomputeSkipReason]:@@ -497,6 +488,8 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):unique sessions), and retention metrics, in all cases withoutbreakdowns, CUPED, or data warehouse sources."""+ # CUPED extends the metric scan back by lookback_days for the pre-exposure covariate,+ # but the precomputed metric_events table covers only the experiment window.if self._get_breakdowns_for_builder() or self.cuped_config.enabled or self.is_data_warehouse_query:return Falseif isinstance(self.metric, ExperimentFunnelMetric):@@ -555,15 +548,11 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):return "precomputed" if self._metric_events_precomputed else "direct_scan"def _get_experiment_query(self) -> ast.SelectQuery:- """- Returns the main experiment query.- """assert isinstance(self.metric,ExperimentFunnelMetric | ExperimentMeanMetric | ExperimentRatioMetric | ExperimentRetentionMetric,)- # Get the "missing" (not directly accessible) parameters required for the builderexposure_params = get_exposure_config_params_for_builder(self.experiment.exposure_criteria, self.team, self.experiment.start_date)@@ -616,11 +605,6 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):},)- # Precompute metric events for eligible metrics (ordered funnels, count/sum- # means). CUPED extends the metric scan back by `lookback_days` to source the- # pre-exposure covariate; the precomputed metric_events table only covers the- # experiment window, so skip precomputation here and let the builder issue a- # fresh scan.if self._metric_events_precompute_applicable():try:with tags_context(@@ -653,8 +637,6 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):def _evaluate_experiment_query(self,) -> tuple[list[tuple], list[str]]:- # Adding experiment specific tags to the tag collection- # This will be available as labels in Prometheusmetric_name = self.metric.name or get_default_metric_title(self.metric.model_dump())tag_queries(product=Product.EXPERIMENTS,@@ -729,7 +711,6 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):workload=self.workload,)- # Remove the $multiple variant only when using exclude handlingif self.multiple_variant_handling == MultipleVariantHandling.EXCLUDE:response.results = [result for result in response.results if result[0] != MULTIPLE_VARIANT_KEY]@@ -739,20 +720,16 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):@experiment_error_handlerdef _calculate(self) -> ExperimentQueryResponse:- # Prepare variant datavariant_results = self._prepare_variant_results()- # Process breakdowns or extract variantsif self._has_breakdown(variant_results):breakdown_results, variants = self._process_breakdown_results(variant_results)else:breakdown_results = Nonevariants = [v for _, v in variant_results]- # Calculate final statisticsresult = self._calculate_statistics_for_variants(variants)- # Attach breakdown data if presentif breakdown_results is not None:result.breakdown_results = breakdown_results@@ -763,17 +740,14 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):return resultdef _prepare_variant_results(self) -> list[tuple[tuple[str, ...] | None, ExperimentStatsBase]]:- """Fetch and prepare variant results with missing variants added."""sorted_results, columns = self._evaluate_experiment_query()variant_results = get_variant_results(sorted_results, columns)return self._add_missing_variants(variant_results)def _has_breakdown(self, variant_results: list[tuple[tuple[str, ...] | None, ExperimentStatsBase]]) -> bool:- """Check if results contain breakdown data."""return any(bv is not None for bv, _ in variant_results)def _calculate_statistics_for_variants(self, variants: list[ExperimentStatsBase]) -> ExperimentQueryResponse:- """Calculate statistical analysis results for a set of variants."""control_variant, test_variants = split_baseline_and_test_variants(variants, self.baseline_variant_key)if self.stats_method == "frequentist":@@ -798,7 +772,6 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):def _process_breakdown_results(self, variant_results: list[tuple[tuple[str, ...] | None, ExperimentStatsBase]]) -> tuple[list[ExperimentBreakdownResult], list[ExperimentStatsBase]]:- """Compute per-breakdown statistics and aggregate across breakdowns."""breakdown_tuples = sorted({bv for bv, _ in variant_results if bv is not None})breakdown_results = [@@ -814,15 +787,14 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):breakdown_tuple: tuple[str, ...],variant_results: list[tuple[tuple[str, ...] | None, ExperimentStatsBase]],) -> ExperimentBreakdownResult:- """Compute statistics for a single breakdown combination."""breakdown_variants = [v for bv, v in variant_results if bv == breakdown_tuple]- # Ensure all expected variants are present in this breakdown group- # Some breakdown groups may not have data for all variants (e.g., no control users with specific browser)+ # A breakdown group can lack a variant, for example when no control user has a specific+ # browser. The statistics fail without a control variant, so add the missing variants+ # with zero stats.variants_present = {v.key for v in breakdown_variants}for expected_variant in self.variants:if expected_variant not in variants_present:- # Add missing variant with zero stats to avoid "No control variant found" errorbreakdown_variants.append(ExperimentStatsBase(key=expected_variant,@@ -843,27 +815,20 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):def _add_missing_variants(self, variants: list[tuple[tuple[str, ...] | None, ExperimentStatsBase]]) -> list[tuple[tuple[str, ...] | None, ExperimentStatsBase]]:- """- Check if the variants configured in the experiment is seen in the collected data.- If not, add them to the result set with values set to 0.- Preserves the tuple structure with breakdown values.- """+ """Adds a zero-stats row for each configured variant that is missing from the results."""variants_seen = [v.key for _, v in variants]# Fan out over the breakdown combinations actually present in the results, not over the# metric's breakdown config: a metric can declare breakdowns and still come back with no- # rows at all (no data yet), and there is then nothing to fan out over — fall back to the- # single breakdown-less zero row so the baseline variant still exists.+ # rows at all (no data yet), and there is then nothing to fan out over. In that case, fall+ # back to the single breakdown-less zero row, so that the baseline variant still exists.breakdown_tuples = {bv for bv, _ in variants if bv is not None}- # Type annotation required for empty list so mypy knows the expected element type:- # list of tuples containing (breakdown_values, stats) where breakdown_values can be Nonevariants_missing: list[tuple[tuple[str, ...] | None, ExperimentStatsBase]] = []for key in self.variants:if key not in variants_seen:if breakdown_tuples:- # Use extend to add MULTIPLE tuples - one for each breakdown combination- # Each missing variant needs to appear across ALL breakdown values to maintain consistency+ # A missing variant needs a zero row in every breakdown combinationvariants_missing.extend([(bv, ExperimentStatsBase(key=key, number_of_samples=0, sum=0, sum_squares=0))@@ -871,8 +836,6 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):])else:- # Use append to add a SINGLE tuple with None as the breakdown value- # Without breakdowns, we only need one entry per missing variantvariants_missing.append((None, ExperimentStatsBase(key=key, number_of_samples=0, sum=0, sum_squares=0)))@@ -881,31 +844,17 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):def to_actors_query(self) -> ast.SelectQuery:"""- Generate actors query for experiment funnels with exposure filtering.-- This method builds an actors query that applies the SAME temporal filtering- as the main experiment query by including exposure as step 0.-- Key differences from main query:- - Returns individual users instead of aggregate statistics- - Filters to specific step and variant- - Includes matched recordings when requested-- The query structure mirrors the main experiment query:- - Step 0: Exposure event (filters events to only those AFTER exposure)- - Step 1-N: Metric events from funnel.series-- This ensures counts match between funnel visualization and PersonModal.+ Actors query for a funnel metric. It includes exposure as step 0, so it applies+ the same temporal filtering as the main experiment query, and its counts match+ the funnel chart. It returns the individual users for one step and variant,+ optionally with matched recordings, instead of aggregate statistics."""- # Ensure actors_query is setif self.actors_query is None:raise ValidationError("actors_query must be set before calling to_actors_query()")- # Only support funnel metrics for nowif not isinstance(self.metric, ExperimentFunnelMetric):raise ValidationError("Actors query only supported for funnel experiment metrics")- # Validate funnelStepfunnel_step = self.actors_query.funnelStepif funnel_step is None:raise ValidationError("funnelStep is required for experiment actors query")@@ -914,7 +863,7 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):# funnelStep=-1 is a valid drop-off: "exposed but never reached the first metric step".# step_reached is 0-indexed with exposure as step 0, so the WHERE clause resolves it to- # step_reached == 0 — the exposed users who did not validly enter the funnel.+ # step_reached == 0, which selects the exposed users who did not validly enter the funnel.if funnel_step < 0:max_drop_off = -(num_metric_steps + 1)if funnel_step < max_drop_off:@@ -929,8 +878,6 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):f"Valid conversion steps: 0 (exposure step) to {num_metric_steps}.")- # Extract exposure configuration from actors query- # Fall back to experiment exposure_criteria if not providedfrom posthog.schema import ActionsNode, ExperimentEventExposureConfigexposure_config: ExperimentEventExposureConfig | ActionsNode@@ -949,13 +896,11 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):exposure_config = exposure_params.exposure_configactivation_config = exposure_params.activation_config- # Get multiple variant handlingif self.actors_query.multipleVariantHandling is not None:multiple_variant_handling = self.actors_query.multipleVariantHandlingelse:multiple_variant_handling = self.multiple_variant_handling- # Get feature flag keyif self.actors_query.featureFlagKey:feature_flag_key = self.actors_query.featureFlagKeyelse:@@ -966,17 +911,14 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):ExperimentFunnelActorsQueryBuilder,)- # Extract funnel_step_breakdown and ensure it's a simple typefunnel_step_breakdown_raw = self.actors_query.funnelStepBreakdownif funnel_step_breakdown_raw is None:funnel_step_breakdown: str | int | float = ""elif isinstance(funnel_step_breakdown_raw, list):- # If it's a list, take the first elementfunnel_step_breakdown = funnel_step_breakdown_raw[0] if funnel_step_breakdown_raw else ""else:funnel_step_breakdown = funnel_step_breakdown_raw- # Add experiment-specific tags for monitoring and alertingmetric_name = self.metric.name or get_default_metric_title(self.metric.model_dump())tag_queries(product=Product.EXPERIMENTS,@@ -995,7 +937,6 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):experiment_actors_query_includes_recordings=self.actors_query.includeRecordings or False,)- # Build the actors query using the same infrastructure as main querybuilder = ExperimentFunnelActorsQueryBuilder(team=self.team,feature_flag_key=feature_flag_key,diff --git a/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.py b/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.pyindex 8c194478d510..5f92fb1e78a7 100644--- a/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.py@@ -15,23 +15,15 @@ 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.+ The class holds a reference to the owning ``ExperimentQueryBuilder`` and+ reads shared state (metric, entity key, breakdown injector) and the shared+ exposure and metric-value helpers through it."""def __init__(self, builder: "ExperimentQueryBuilder"):self._b = builderdef 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():@@ -61,7 +53,6 @@ class RatioQueryBuilder:assert isinstance(query, ast.SelectQuery)- # Inject breakdown columns into the query ASTif self._b.breakdown_injector:self._b.breakdown_injector.inject_ratio_breakdown_columns(query)@@ -91,8 +82,8 @@ class RatioQueryBuilder:When a bound is not configured the threshold falls back to min()/max() so theleast(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.+ and denominator be capped independently. A binomial denominator leaves its outlier+ handling unset, so it is never clamped.value_field is an internal column name (numerator_value / denominator_value), neveruser input, so interpolating it into the expression string is safe.@@ -127,8 +118,6 @@ class RatioQueryBuilder: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 ownmean metric: percentile thresholds are computed separately for each component (pooledacross all variations) and the per-entity numerator and denominator values are clamped@@ -197,7 +186,6 @@ class RatioQueryBuilder:assert isinstance(query, ast.SelectQuery)- # Inject breakdown columns into the query ASTif self._b.breakdown_injector:self._b.breakdown_injector.inject_ratio_breakdown_columns(query, winsorized=True)@@ -207,42 +195,38 @@ class RatioQueryBuilder:"""Builds the shared CTE chain and placeholders for ratio metric queries.- Optimized structure using pre-aggregation to reduce join operations:+ Structure:- 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.+ Each component collapses to one row per entity before entity_metrics joins+ the two. A direct join of the raw numerator and denominator events would fan+ out to (numerator rows × denominator rows) per entity and use much more memory."""assert isinstance(self._b.metric, ExperimentRatioMetric)- # Use MetricSourceInfo abstraction for both numerator and denominatornum_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 numeratornum_table = num_source_info.table_namenum_entity_field = num_source_info.entity_keynum_timestamp_field = num_source_info.timestamp_field- # Extract field names for denominatordenom_table = denom_source_info.table_namedenom_entity_field = denom_source_info.entity_keydenom_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+ # argMin takes each join key from the first exposure, so each entity_id gets one+ # identifier per component. Do not add the join keys to GROUP BY: a user with+ # exposures that carry different join key values would then fan out into several rows.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 valuesexposure_query.select.append(ast.Alias(alias="exposure_identifier_num",@@ -252,14 +236,11 @@ class RatioQueryBuilder:),))- # Do NOT add to GROUP BY - that would cause fan-out when join key varies across exposuresif 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 valuesexposure_query.select.append(ast.Alias(alias="exposure_identifier_denom",@@ -269,9 +250,7 @@ class RatioQueryBuilder:),))- # 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 scenarioif num_source_info.kind == "datawarehouse":num_preagg_join = "toString(exposures.exposure_identifier_num) = toString(numerator_events.entity_id)"else:@@ -282,9 +261,6 @@ class RatioQueryBuilder: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 joinscommon_ctes = f"""exposures AS ({{exposure_select_query}}diff --git a/products/experiments/backend/hogql_queries/experiment_retention_query_builder.py b/products/experiments/backend/hogql_queries/experiment_retention_query_builder.pyindex 1c09f75d91f5..d3783041640d 100644--- a/products/experiments/backend/hogql_queries/experiment_retention_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_retention_query_builder.py@@ -31,13 +31,11 @@ class RetentionQueryBuilder:"""Builds retention-metric queries.- Retention reuses the shared exposure and conversion-window helpers already- extracted from the experiment query builder, but has its own maturity- semantics anchored on the start_event. To keep the move behavior-preserving,- this class holds a reference to the owning ``ExperimentQueryBuilder`` and- reaches through it for shared state (the metric, team, date range, entity- key, breakdown injector) and the cross-cluster exposure and- conversion-window helpers.+ Retention shares the exposure and conversion-window helpers with the other+ metric types, but anchors maturity on the start_event. The class holds a+ reference to the owning ``ExperimentQueryBuilder`` and reads shared state+ (metric, team, date range, entity key, breakdown injector) and helpers+ through it."""def __init__(self, builder: "ExperimentQueryBuilder"):@@ -45,9 +43,8 @@ class RetentionQueryBuilder:def get_retention_maturity_seconds(self) -> int:"""- Returns the maturity window in seconds for retention metrics.- Equals retention_window_end converted to seconds; conversion_window does- not contribute because retention maturity is anchored on start_event.+ Retention maturity is anchored on start_event, so conversion_window does+ not contribute. Only retention_window_end counts."""assert isinstance(self._b.metric, ExperimentRetentionMetric)return conversion_window_to_seconds(@@ -60,8 +57,8 @@ class RetentionQueryBuilder:How far past the experiment end date the metric-events scan must extend.A completion event can land up to retention_window_end after a start eventthat itself lands up to conversion_window after the last exposure, so the- extension is the sum — unlike funnel/mean, where the conversion window alone- bounds it.+ extension is the sum of both. For funnel and mean metrics, the conversion+ window alone bounds it."""assert isinstance(self._b.metric, ExperimentRetentionMetric)return self._b._get_conversion_window_seconds() + conversion_window_to_seconds(@@ -73,7 +70,7 @@ class RetentionQueryBuilder:"""Returns the SELECT query that the lazy computation system wraps in anINSERT INTO experiment_metric_events_preaggregated. This is the write- path — it stores one row per event matching the start predicate or the+ path. It stores one row per event matching the start predicate or thecompletion predicate, flagged via the steps array (steps[1] = matchedstart_event, steps[2] = matched completion_event; an event can matchboth). Start anchoring (FIRST_SEEN/LAST_SEEN), the per-user retention@@ -84,13 +81,10 @@ class RetentionQueryBuilder:by the lazy computation system for each daily bucket. The experiment datebounds must stay named placeholders (the caller declares experiment_date_toa sentinel) rather than reusing the direct-scan predicates, which bake the- resolved dates into the AST — a running experiment's moving window end- would then change the job hash and defeat cache reuse. The window extension- stays a placeholder too, but as a hashed constant: it derives from+ 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 window+ extension stays a placeholder too, but as a hashed constant: it derives fromretention_window_end, so changing the window must invalidate jobs.-- Returns:- Tuple of (query_string, placeholders_dict)"""assert isinstance(self._b.metric, ExperimentRetentionMetric)start_event = self._b.metric.start_event@@ -184,8 +178,6 @@ class RetentionQueryBuilder:def build_retention_query(self) -> ast.SelectQuery:"""- Builds query for retention metrics.-Retention measures the proportion of users who performed a "completion event"within a specified time window after performing a "start event".@@ -198,13 +190,11 @@ class RetentionQueryBuilder:have a random denominator (count of users who started). This makes retention aratio of two random variables, requiring delta method variance.- Returns 7 fields for RatioStatistic:+ Returns 7 fields for RatioStatistic, which both the frequentist and the+ Bayesian analysis use:- Standard: num_users, total_sum, total_sum_of_squares- Ratio-specific: denominator_sum, denominator_sum_squares, numerator_denominator_sum_product- The collected statistics are processed using RatioStatistic (not ProportionStatistic)- for both frequentist and Bayesian analysis.-Structure:- exposures: all exposures with variant assignment- start_events: when each entity performed the start_event (with start_handling logic)@@ -225,9 +215,9 @@ class RetentionQueryBuilder:# Read start/completion events from the precomputed table instead of scanning# events; the event predicates were applied at build time and survive as the# steps flags (steps[1] = matched start_event, steps[2] = matched completion_event).- # Time bounds must mirror the direct-scan predicates exactly — jobs can cover- # broader ranges than the experiment for cache reusability — so start events are- # bounded by the exposure window + conversion window and completions additionally+ # Time bounds must mirror the direct-scan predicates exactly, because jobs can+ # cover broader ranges than the experiment for cache reuse. Start events are+ # bounded by the exposure window + conversion window, and completions additionally# by retention_window_end. Everything downstream (start anchoring, window# arithmetic, maturity, same-event exclusion) is read-time and stays unchanged.# No dedup of replayed build rows is needed: min/max/argMin/argMax and the@@ -294,7 +284,6 @@ class RetentionQueryBuilder:GROUP BY exposures.entity_id)"""- # Build the CTEscommon_ctes = (f"""exposures AS (@@ -412,18 +401,12 @@ class RetentionQueryBuilder:else:start_events_cte.expr.having = ast.And(exprs=[start_events_cte.expr.having, retention_maturity])- # Inject breakdown columns if breakdown filter is presentif self._b.breakdown_injector:self._b.breakdown_injector.inject_retention_breakdown_columns(query)return querydef build_start_event_timestamp_expr(self) -> ast.Expr:- """- Returns expression to get start event timestamp based on start_handling.- FIRST_SEEN: Use the first occurrence of start event- LAST_SEEN: Use the last occurrence of start event- """assert isinstance(self._b.metric, ExperimentRetentionMetric)if self._b.metric.start_handling == StartHandling.FIRST_SEEN:@@ -446,18 +429,12 @@ class RetentionQueryBuilder:def get_retention_window_truncation_expr(self, timestamp_expr: ast.Expr) -> ast.Expr:"""- Returns truncated timestamp expression for retention window comparisons.-- For DAY: returns toStartOfDay(timestamp)- For HOUR: returns toStartOfHour(timestamp)- For other units: returns timestamp unchanged-- This ensures [7,7] day window means "any time on day 7" rather than- "exactly 7*24 hours after start event to the second".+ Truncates DAY and HOUR windows to the start of the interval, so a [7, 7]+ day window means "any time on day 7" rather than exactly 7*24 hours after+ the start event. Other units compare exact timestamps."""assert isinstance(self._b.metric, ExperimentRetentionMetric)- # Only truncate DAY and HOUR units for intuitive behaviorunit_to_interval_name = {FunnelConversionWindowTimeUnit.DAY: "day",FunnelConversionWindowTimeUnit.HOUR: "hour",@@ -470,9 +447,6 @@ class RetentionQueryBuilder:return get_start_of_interval_hogql(interval=interval_name, team=self._b.team, source=timestamp_expr)def build_retention_window_interval(self, window_value: int) -> ast.Expr:- """- Converts retention window value to ClickHouse interval expression.- """assert isinstance(self._b.metric, ExperimentRetentionMetric)unit_map = {@@ -490,9 +464,6 @@ class RetentionQueryBuilder:)def build_start_event_predicate(self) -> ast.Expr:- """- Builds the predicate for filtering start events.- """assert isinstance(self._b.metric, ExperimentRetentionMetric)start_event = self._b.metric.start_event@@ -521,9 +492,6 @@ class RetentionQueryBuilder:)def build_completion_event_predicate(self) -> ast.Expr:- """- Builds the predicate for filtering completion events.- """assert isinstance(self._b.metric, ExperimentRetentionMetric)if isinstance(self._b.metric.completion_event, ExperimentDataWarehouseNode):@@ -531,8 +499,8 @@ class RetentionQueryBuilder:else:event_filter = event_or_action_to_filter(self._b.team, self._b.metric.completion_event)- # Completion events can occur within the retention window after the start event- # The retention window end could extend beyond the experiment end date+ # A start event can land up to conversion_window after date_to, and its+ # completion up to retention_window_end after that, so the scan extends by both.conversion_window_seconds = self._b._get_conversion_window_seconds()retention_window_end_seconds = conversion_window_to_seconds(self._b.metric.retention_window_end,@@ -555,9 +523,8 @@ class RetentionQueryBuilder:def build_start_after_exposure_predicate(self) -> ast.Expr:"""- Builds the predicate for filtering start events to only those after exposure.- Applied inside the start_events CTE (pre-aggregation) so that min/max only- considers events after the user's first exposure.+ Applied inside the start_events CTE, before aggregation, so that min/max+ only considers start events after the user's first exposure."""conversion_window_seconds = self._b._get_conversion_window_seconds()if conversion_window_seconds > 0:@@ -575,15 +542,13 @@ class RetentionQueryBuilder:def build_completion_retention_window_predicate(self) -> ast.Expr:"""- Builds the predicate for the join condition ensuring completion events- are within a reasonable timeframe relative to start events.-- This is a performance optimization - we'll do the exact retention window- calculation in the entity_metrics CTE.+ Coarse join condition that limits which completion events join to each+ start event. It is only a performance filter, because entity_metrics+ applies the exact retention window.- For DAY/HOUR units that use timestamp truncation, we add a buffer to account- for the truncation window. This ensures that same-period retention (e.g., [0,0])- captures all events within that period, not just events at the exact same second.+ DAY and HOUR windows compare truncated timestamps, so the bound adds one+ unit of buffer. Without it, a same-period window such as [0, 0] would miss+ completions later in the same day or hour."""assert isinstance(self._b.metric, ExperimentRetentionMetric)@@ -592,17 +557,12 @@ class RetentionQueryBuilder:self._b.metric.retention_window_unit,)- # For DAY/HOUR units, add a buffer to account for truncation- # This ensures same-period retention windows work correctlytruncation_buffer = 0if self._b.metric.retention_window_unit == FunnelConversionWindowTimeUnit.DAY:- # For DAY units, allow completions within the same day (24 hours)truncation_buffer = 86400 # 1 day in secondselif self._b.metric.retention_window_unit == FunnelConversionWindowTimeUnit.HOUR:- # For HOUR units, allow completions within the same hourtruncation_buffer = 3600 # 1 hour in seconds- # Add buffer to retention window endbuffered_window_end_seconds = retention_window_end_seconds + truncation_bufferreturn parse_expr(diff --git a/products/experiments/backend/hogql_queries/experiment_trends_query_runner.py b/products/experiments/backend/hogql_queries/experiment_trends_query_runner.pyindex acf347491869..b9a675ed0705 100644--- a/products/experiments/backend/hogql_queries/experiment_trends_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_trends_query_runner.py@@ -85,7 +85,7 @@ class ExperimentTrendsQueryRunner(QueryRunner):def _uses_math_aggregation_by_user_or_property_value(self, query: TrendsQuery):math_keys = ALL_SUPPORTED_MATH_FUNCTIONS- # "sum" doesn't need special handling, we *can* have custom exposure for sum filters+ # "sum" works with a custom exposure query, so it needs no special handling.if "sum" in math_keys:math_keys.remove("sum")return any(entity.math in math_keys for entity in query.series)@@ -99,10 +99,6 @@ class ExperimentTrendsQueryRunner(QueryRunner):self.query.count_query.series[0].math = PropertyMathType.SUMdef _get_date_range(self) -> DateRange:- """- Returns an DateRange object based on the experiment's start and end dates,- adjusted for the team's timezone if applicable.- """if self.team.timezone:tz = ZoneInfo(self.team.timezone)start_date = self.experiment.start_date.astimezone(tz) if self.experiment.start_date else None@@ -130,7 +126,6 @@ class ExperimentTrendsQueryRunner(QueryRunner):)def _get_metric_type(self) -> ExperimentMetricType:- # Currently, we rely on the math type to determine the metric typematch self.query.count_query.series[0].math:case PropertyMathType.SUM | "hogql":return ExperimentMetricType.CONTINUOUS@@ -139,13 +134,8 @@ class ExperimentTrendsQueryRunner(QueryRunner):def _prepare_count_query(self) -> TrendsQuery:"""- This method takes the raw trend query and adapts it- for the needs of experiment analysis:-- 1. Set the trend display type based on whether math aggregation is used- 2. Set the date range to match the experiment's duration, using the project's timezone.- 3. Configure the breakdown to use the feature flag key, which allows us- to separate results for different experiment variants.+ Adapt the raw trends query for experiment analysis. The date range matches the experiment's+ duration, and the breakdown on the feature flag property splits the results by variant."""prepared_count_query = TrendsQuery(**self.query.count_query.model_dump())@@ -182,17 +172,15 @@ class ExperimentTrendsQueryRunner(QueryRunner):def _prepare_exposure_query(self) -> TrendsQuery:"""- Exposure is the count of users who have seen the experiment. This is necessary to calculate the statistical- significance of the experiment.+ Exposure is the count of users who saw the experiment, which the significance calculation needs.- There are 2 possible cases for the exposure query:- 1. Otherwise, if an exposure query is provided, we use it as is, adapting it to the experiment's duration and breakdown- 2. Otherwise, we construct a default exposure query (the count of $feature_flag_called events)+ A custom exposure query is used as is, with the experiment's date range and breakdown applied.+ Otherwise, and always for data warehouse metrics, the default query counts unique users with a+ $feature_flag_called event."""prepared_count_query = TrendsQuery(**self.query.count_query.model_dump())- # 1. If an exposure query is provided, we use it as is, adapting it to the experiment's duration and breakdownif self.query.exposure_query and not self._is_data_warehouse_query(prepared_count_query):prepared_exposure_query = TrendsQuery(**self.query.exposure_query.model_dump())prepared_exposure_query.dateRange = self._get_date_range()@@ -206,7 +194,6 @@ class ExperimentTrendsQueryRunner(QueryRunner):type="event",)]- # 2. Otherwise, we construct a default exposure query: unique users for the $feature_flag_called eventelse:prepared_exposure_query = TrendsQuery(dateRange=self._get_date_range(),@@ -241,8 +228,6 @@ class ExperimentTrendsQueryRunner(QueryRunner):return prepared_exposure_querydef _calculate(self) -> ExperimentTrendsQueryResponse:- # Adding experiment specific tags to the tag collection- # This will be available as labels in Prometheustag_queries(query_type="ExperimentTrendsQuery",experiment_id=str(self.experiment.id),@@ -271,7 +256,7 @@ class ExperimentTrendsQueryRunner(QueryRunner):if is_parallel:from django.db import connection- # This will only close the DB connection for the newly spawned thread and not the whole app+ # This closes only the DB connection of this thread, not the connections of the app.connection.close()# This exists so that we're not spawning threads during unit tests@@ -287,7 +272,6 @@ class ExperimentTrendsQueryRunner(QueryRunner):[j.start() for j in jobs] # type: ignore[j.join() for j in jobs] # type: ignore- # Raise any errors raised in a separate threadif errors:raise errors[0]@@ -298,7 +282,6 @@ class ExperimentTrendsQueryRunner(QueryRunner):self._validate_event_variants(count_result, exposure_result)- # Statistical analysiscontrol_variant, test_variants = self._get_variants_with_base_stats(count_result, exposure_result)match self._get_metric_type():case ExperimentMetricType.CONTINUOUS:@@ -394,13 +377,11 @@ class ExperimentTrendsQueryRunner(QueryRunner):if not count_result.results or not count_result.results[0]:raise ValidationError(code="no-results", detail=json.dumps(errors))- # Check if "control" is presentfor event in count_result.results:event_variant = event.get("breakdown_value")if event_variant == "control":errors[ExperimentNoResultsErrorKeys.NO_CONTROL_VARIANT] = Falsebreak- # Check if at least one of the test variants is presenttest_variants = [variant for variant in self.variants if variant != "control"]for event in count_result.results:@@ -419,7 +400,6 @@ class ExperimentTrendsQueryRunner(QueryRunner):def to_query(self) -> ast.SelectQuery:raise ValueError(f"Cannot convert source query of type {self.query.count_query.kind} to query")- # Cache results for 24 hoursdef cache_target_age(self, last_refresh: Optional[datetime], lazy: bool = False) -> Optional[datetime]:if last_refresh is None:return Nonediff --git a/products/experiments/backend/hogql_queries/exposure_query_logic.py b/products/experiments/backend/hogql_queries/exposure_query_logic.pyindex 9392a5038509..139da9abd25f 100644--- a/products/experiments/backend/hogql_queries/exposure_query_logic.py+++ b/products/experiments/backend/hogql_queries/exposure_query_logic.py@@ -1,9 +1,4 @@-"""-Shared exposure logic for experiment query runners.--This module contains common functions for handling experiment exposures,-including multiple variant handling and exposure filtering logic.-"""+"""Exposure criteria resolution and exposure filters shared by the experiment query runners."""import loggingfrom collections.abc import Collection@@ -28,11 +23,11 @@ from products.actions.backend.models.action import Actionlogger = logging.getLogger(__name__)-# The event an experiment counts exposures on when its criteria don't name one. If the default-# ever changes (e.g. to a dedicated exposure event), flip it here — consumers that resolve-# criteria through this module's helpers key off this constant. Note the variant-property-# pairing in `get_exposure_event_and_property` (and the handling of configs that explicitly-# name `$feature_flag_called`) must move with it.+# The event an experiment counts exposures on when its criteria don't name one and+# resolve_default_exposure_event does not move it to EXPERIMENT_EXPOSURE_EVENT. Consumers that+# resolve criteria through this module's helpers key off this constant. If it changes, update the+# variant-property pairing in `get_exposure_event_and_property` and the handling of configs that+# explicitly name `$feature_flag_called` too.DEFAULT_EXPOSURE_EVENT = "$feature_flag_called"# The dedicated exposure event that replaces $feature_flag_called as the default,@@ -40,8 +35,8 @@ DEFAULT_EXPOSURE_EVENT = "$feature_flag_called"EXPERIMENT_EXPOSURE_EVENT = "$experiment_exposure"EXPERIMENT_EXPOSURE_EVENT_FLAG = "experiment-exposure-event"-# When $experiment_exposure ingestion goes live. Experiments started before this timestamp ran-# (at least partly) without the new event, so they must keep counting exposures via+# The start of $experiment_exposure ingestion. Experiments started before this timestamp ran+# (at least partly) without $experiment_exposure, so they must keep counting exposures via# $feature_flag_called even where the two overlap. Only experiments whose start_date is at or# after the cutoff can rely on $experiment_exposure covering their whole exposure window.EXPERIMENT_EXPOSURE_EVENT_CUTOFF = datetime(2026, 9, 1, tzinfo=UTC)@@ -63,8 +58,8 @@ def resolve_default_exposure_event(team: Team, start_date: Optional[datetime]) -start_date = start_date.replace(tzinfo=UTC)if start_date < EXPERIMENT_EXPOSURE_EVENT_CUTOFF:return DEFAULT_EXPOSURE_EVENT- # only_evaluate_locally keeps this off the network - it runs on the query hot path, so an- # inconclusive or failed local evaluation must fall back to the pre-rollout default.+ # only_evaluate_locally keeps this off the network, because it runs on the query hot path. An+ # inconclusive or failed local evaluation falls back to the pre-rollout default.try:enabled = posthoganalytics.feature_enabled(EXPERIMENT_EXPOSURE_EVENT_FLAG,@@ -128,45 +123,27 @@ def resolve_flag_call_source_event(events_present: Collection[str]) -> str:rows carry decides and the flag does not.This is not `resolve_default_exposure_event`: that one answers what a new experiment would- count, which can differ from what the project's events carry today.+ count, which can differ from what the project's events carry."""return EXPERIMENT_EXPOSURE_EVENT if EXPERIMENT_EXPOSURE_EVENT in events_present else DEFAULT_EXPOSURE_EVENTdef _is_actions_node_dict(config: dict) -> bool:- """- Helper to determine if a dict represents an ActionsNode.- Checks for the 'kind' field first as the primary indicator.- """return config.get("kind") == "ActionsNode"def normalize_to_exposure_criteria(exposure_criteria: Union[ExperimentExposureCriteria, dict, None],) -> Optional[ExperimentExposureCriteria]:- """- Normalizes various input types to a properly typed ExperimentExposureCriteria object.-- This handles the conversion from:- - Django Experiment models (extracts exposure_criteria field)- - Plain dictionaries (from JSONFields)- - Already typed ExperimentExposureCriteria objects (passthrough)- - None values-- Returns:- ExperimentExposureCriteria object or None- """+ """Converts stored criteria (a JSONField dict) to ExperimentExposureCriteria. A typed object passes through."""if exposure_criteria is None:return None- # Already a typed object, return as-isif isinstance(exposure_criteria, ExperimentExposureCriteria):return exposure_criteria- # Convert dict to typed objectif isinstance(exposure_criteria, dict):criteria_copy = dict(exposure_criteria)- # Also normalize nested configs if presentfor config_key in ("exposure_config", "activation_config"):config = criteria_copy.get(config_key)if config and isinstance(config, dict):@@ -204,29 +181,17 @@ def has_activation_config(exposure_criteria: Union[ExperimentExposureCriteria, ddef get_multiple_variant_handling_from_experiment(exposure_criteria: Union[ExperimentExposureCriteria, dict, None],) -> MultipleVariantHandling:- """- Determines how to handle entities exposed to multiple variants based on experiment configuration.- """criteria = normalize_to_exposure_criteria(exposure_criteria)if criteria and criteria.multiple_variant_handling:return criteria.multiple_variant_handling- # Default to "exclude" if not specifiedreturn MultipleVariantHandling.EXCLUDEdef get_test_accounts_filter(team: Team, exposure_criteria: Union[ExperimentExposureCriteria, dict, None] = None) -> list[ast.Expr]:- """- Returns test account filters based on experiment configuration.-- Args:- team: The team object- exposure_criteria: Experiment exposure criteria configuration- """- # Normalize to typed objectcriteria = normalize_to_exposure_criteria(exposure_criteria)filter_test_accounts = criteria.filterTestAccounts if criteria else False@@ -243,29 +208,20 @@ def get_exposure_event_and_property(default_exposure_event: str,) -> tuple[Optional[str], str]:"""- Determines which event and feature flag variant property to use for exposures.-- Args:- feature_flag_key: The feature flag key- exposure_criteria: Experiment exposure criteria configuration- default_exposure_event: What the experiment's default exposure resolves to- (`resolve_default_exposure_event`). Required so every consumer makes the rollout- decision explicitly: resolve it for the experiment being served, or pass- DEFAULT_EXPOSURE_EVENT where staying on the legacy event is the deliberate choice.-- Returns:- Tuple of (event_name, feature_flag_variant_property)- event_name can be None for ActionsNode (actions can match multiple events)+ Returns (event_name, feature_flag_variant_property) for exposures. event_name is None for an+ ActionsNode config, because an action can match several events.++ `default_exposure_event` is what the experiment's default exposure resolves to+ (`resolve_default_exposure_event`). It is required so that every consumer makes the rollout+ decision explicitly: resolve it for the experiment being served, or pass+ DEFAULT_EXPOSURE_EVENT where staying on the legacy event is the deliberate choice."""- # Normalize to typed objectcriteria = normalize_to_exposure_criteria(exposure_criteria)exposure_config = criteria.exposure_config if criteria else None- # Handle ActionsNodeif isinstance(exposure_config, ActionsNode):- # For actions, we don't filter by event name (actions can match multiple events)- # The action filter will be applied in build_exposure_event_conditions+ # build_exposure_event_conditions applies the action filter.feature_flag_variant_property = f"$feature/{feature_flag_key}"event = Noneelif (@@ -274,8 +230,7 @@ def get_exposure_event_and_property(and exposure_config.eventand exposure_config.event not in (DEFAULT_EXPOSURE_EVENT, EXPERIMENT_EXPOSURE_EVENT)):- # For custom exposure events, we extract the event name from the exposure config- # and get the variant from the $feature/<key> property+ # A custom exposure event carries the variant in the $feature/<key> property.feature_flag_variant_property = f"$feature/{feature_flag_key}"event = exposure_config.eventelse:@@ -296,7 +251,6 @@ def _get_event_name_from_config(exposure_config: Optional[Union[ActionsNode, ExperimentEventExposureConfig]],default_exposure_event: str,) -> str:- """Extract event name from exposure config, defaulting to the resolved default exposure event."""if not exposure_config or not hasattr(exposure_config, "event"):return default_exposure_event@@ -324,12 +278,9 @@ def _build_event_filters(feature_flag_key: Optional[str],default_exposure_event: str,) -> list[ast.Expr]:- """Build event/action filters based on exposure config."""- # Handle action-based exposureif isinstance(exposure_config, ActionsNode):return [_build_action_filter(int(exposure_config.id), team)]- # Handle event-based exposureevent = _get_event_name_from_config(exposure_config, default_exposure_event)filters: list[ast.Expr] = [ast.CompareOperation(@@ -339,9 +290,8 @@ def _build_event_filters()]- # Add feature flag key filter for $feature_flag_called events. $experiment_exposure gets the- # same treatment: ingestion emits it for every experiment, so without this filter exposures- # of other experiments would count too.+ # $feature_flag_called and $experiment_exposure are not specific to one flag, so without the+ # flag key filter, exposures of other experiments would count too.if event in (DEFAULT_EXPOSURE_EVENT, EXPERIMENT_EXPOSURE_EVENT) and feature_flag_key:filters.append(ast.CompareOperation(@@ -357,7 +307,6 @@ def _build_event_filters(def _build_property_filters(exposure_config: Optional[Union[ActionsNode, ExperimentEventExposureConfig]], team: Team) -> list[ast.Expr]:- """Build property filters from exposure config."""if not exposure_config or exposure_config.kind != "ExperimentEventExposureConfig" or not exposure_config.properties:return []@@ -391,15 +340,6 @@ def build_exposure_event_conditions(def get_entity_key(group_type_index: Optional[int]) -> str:- """- Returns the appropriate entity key based on whether we're dealing with groups or persons.-- Args:- group_type_index: Group type index if using groups, None for persons-- Returns:- Entity key string (either "person_id" or "$group_{index}")- """if isinstance(group_type_index, int):return f"$group_{group_type_index}"return "person_id"diff --git a/products/experiments/backend/hogql_queries/funnel_step_builder.py b/products/experiments/backend/hogql_queries/funnel_step_builder.pyindex 352abe0f3dd6..c72db29b80fb 100644--- a/products/experiments/backend/hogql_queries/funnel_step_builder.py+++ b/products/experiments/backend/hogql_queries/funnel_step_builder.py@@ -1,11 +1,3 @@-"""-Funnel step column builder for experiment queries.--This module provides utilities for building step column expressions used in-funnel metric queries, supporting both boolean columns (for events-only queries)-and constant columns (for UNION ALL queries with datawarehouse sources).-"""-from typing import Unionfrom posthog.schema import ActionsNode, EventsNode, ExperimentDataWarehouseNode@@ -19,10 +11,7 @@ from products.experiments.backend.hogql_queries.base_query_utils import event_orclass FunnelStepBuilder:"""- Builds step column expressions for funnel queries.-- This class separates step column generation logic from query building,- supporting two distinct patterns:+ Builds step column expressions for funnel queries in one of two patterns:1. **Boolean columns**: For events-only funnels where all steps are evaluatedin a single query against the events table. Each step is a boolean expression.@@ -30,11 +19,6 @@ class FunnelStepBuilder:2. **Constant columns**: For UNION ALL queries with heterogeneous sources(events + datawarehouse). Each subquery represents one step, with theactive step set to 1 and all others set to 0.-- Attributes:- series: List of funnel step sources (EventsNode, ActionsNode, or ExperimentDataWarehouseNode)- team: Team context for filtering and entity resolution- num_steps: Total number of steps in the funnel (including exposure step_0)"""def __init__(@@ -42,45 +26,19 @@ class FunnelStepBuilder:series: list[Union[EventsNode, ActionsNode, ExperimentDataWarehouseNode]],team: Team,):- """- Initialize FunnelStepBuilder.-- Args:- series: List of funnel step sources- team: Team context- """self.series = seriesself.team = team- # num_steps includes step_0 (exposure) + all metric steps+ # +1 for step_0, the exposure stepself.num_steps = len(series) + 1def build_boolean_columns(self, exposure_filter: ast.Expr) -> list[ast.Alias]:"""- Build step columns as boolean expressions for events table queries.-- Used when all funnel steps come from the events table (no UNION needed).- Each row in the events table is evaluated against all step conditions,- producing boolean columns [step_0, step_1, ..., step_N].-- Args:- exposure_filter: AST expression for exposure condition (becomes step_0)-- Returns:- List of AST Alias nodes for step columns, each evaluating to 0 or 1-- Example:- >>> builder = FunnelStepBuilder([- ... EventsNode(event="pageview"),- ... EventsNode(event="purchase")- ... ], team)- >>> exposure_filter = parse_expr("event = '$feature_flag_called'")- >>> columns = builder.build_boolean_columns(exposure_filter)- >>> [col.alias for col in columns]- ['step_0', 'step_1', 'step_2']+ Step columns for a funnel where all steps come from the events table, so+ no UNION is necessary. Each event row gets the 0/1 columns+ [step_0, step_1, ..., step_N], with `exposure_filter` as step_0."""columns = []- # Step 0: Exposurecolumns.append(ast.Alias(alias="step_0",@@ -88,7 +46,6 @@ class FunnelStepBuilder:))- # Steps 1..N: Metric stepsfor step_index, step_source in enumerate(self.series, start=1):step_filter = self._build_step_filter(step_source)columns.append(@@ -102,29 +59,12 @@ class FunnelStepBuilder:def build_constant_columns(self, active_step_index: int) -> list[ast.Alias]:"""- Build step columns as constants for DW subquery.-- Used in UNION ALL queries where each subquery represents one step.- The active step has value 1, all other steps have value 0.-- This pattern is necessary when combining events and datawarehouse sources- because each source requires a separate subquery with different table- references and field structures.+ Step columns as constants for one subquery of a UNION ALL, where each+ subquery represents one step. The active step is 1 and all other steps are 0.- Args:- active_step_index: The step number that should be set to 1 (0-based)-- Returns:- List of AST Alias nodes for step columns as constants-- Raises:- ValueError: If active_step_index is out of bounds-- Example:- >>> builder = FunnelStepBuilder([...], team)- >>> # For DW step 2 subquery:- >>> columns = builder.build_constant_columns(active_step_index=2)- >>> # Results in: step_0=0, step_1=0, step_2=1+ A funnel that combines events and data warehouse sources needs this pattern,+ because each source needs its own subquery with different table references+ and fields."""if active_step_index < 0 or active_step_index >= self.num_steps:raise ValueError(@@ -146,29 +86,10 @@ class FunnelStepBuilder:return columnsdef _build_step_filter(self, step_source: Union[EventsNode, ActionsNode, ExperimentDataWarehouseNode]) -> ast.Expr:- """- Build boolean filter expression for a funnel step.-- For events-only queries, this generates the condition that determines- if a given event row matches the step criteria.-- Args:- step_source: The step source definition-- Returns:- AST expression evaluating to boolean (will be 0 or 1 in ClickHouse)-- Note:- Uses event_or_action_to_filter() for proper event/action handling.- For ExperimentDataWarehouseNode: Not used in boolean column context- """if isinstance(step_source, ExperimentDataWarehouseNode):- # ExperimentDataWarehouseNode - should not be used in boolean columns- # This is a programming error if reachedraise ValueError(f"Cannot build boolean filter for {type(step_source).__name__}. ""Use constant columns for UNION ALL queries with datawarehouse sources.")- # Use the standard event/action filter utilityreturn event_or_action_to_filter(self.team, step_source)diff --git a/products/experiments/backend/hogql_queries/funnel_validation.py b/products/experiments/backend/hogql_queries/funnel_validation.pyindex f8188534f13f..b97a6219855f 100644--- a/products/experiments/backend/hogql_queries/funnel_validation.py+++ b/products/experiments/backend/hogql_queries/funnel_validation.py@@ -1,11 +1,3 @@-"""-Datawarehouse funnel validation utilities.--This module provides validation for datawarehouse funnel configurations,-ensuring required fields are present, join keys are consistent, and-complexity limits are enforced before query execution.-"""-from typing import Anyfrom rest_framework.exceptions import ValidationError@@ -15,13 +7,9 @@ from posthog.schema import ExperimentDataWarehouseNode, ExperimentFunnelMetricclass FunnelDWValidator:"""- Validates datawarehouse funnel configuration.-- Provides clear, actionable error messages for common DW funnel- misconfigurations before expensive query execution.-- All methods are static as validation is stateless - operates only- on the provided metric configuration.+ Validates a data warehouse funnel configuration before the query runs, so that+ a misconfiguration gets an actionable error message instead of an expensive+ or failed query."""# Complexity limits to prevent expensive queries@@ -30,21 +18,7 @@ class FunnelDWValidator:@staticmethoddef validate_required_fields(node: ExperimentDataWarehouseNode, step_index: int) -> list[str]:- """- Validate DW node has all required fields.-- Args:- node: The datawarehouse node to validate- step_index: Step number in funnel (1-based for error messages)-- Returns:- List of error messages (empty if valid)-- Example:- >>> errors = FunnelDWValidator.validate_required_fields(node, 2)- >>> if errors:- ... raise ValidationError({"datawarehouse_configuration": errors})- """+ """`step_index` is 1-based because it appears in the error messages."""errors = []if not node.table_name:@@ -72,32 +46,14 @@ class FunnelDWValidator:@staticmethoddef validate_consistent_join_keys(metric: ExperimentFunnelMetric) -> dict[str, str] | None:- """- Validate all DW steps use the same events_join_key.-- This is a current limitation that simplifies the UNION ALL query pattern.- All DW steps must join to events using the same field.-- Args:- metric: The funnel metric to validate-- Returns:- Dictionary with error key and message if invalid, None if valid-- Example:- >>> error = FunnelDWValidator.validate_consistent_join_keys(metric)- >>> if error:- ... raise ValidationError(error)- """+ """All DW steps must use the same events_join_key, which keeps the UNION ALL query simple."""dw_steps = [(i + 1, step) for i, step in enumerate(metric.series) if isinstance(step, ExperimentDataWarehouseNode)]if len(dw_steps) <= 1:- # 0 or 1 DW steps - no consistency to checkreturn None- # Collect all unique events_join_keysjoin_keys: dict[str, list[int]] = {}for step_index, step in dw_steps:join_key = step.events_join_key@@ -106,7 +62,6 @@ class FunnelDWValidator:join_keys[join_key].append(step_index)if len(join_keys) > 1:- # Multiple different join keys - build helpful error messageerror_lines = ["All datawarehouse steps must use the same join key to events.\n"]for join_key, step_indices in join_keys.items():@@ -122,26 +77,11 @@ class FunnelDWValidator:@staticmethoddef validate_complexity_limits(metric: ExperimentFunnelMetric) -> dict[str, str] | None:"""- Enforce complexity limits to prevent expensive queries.-- Limits:- - Max 3 DW steps per funnel (reduces UNION ALL query size)- - Max 2 distinct DW tables per funnel (limits join complexity)-- Args:- metric: The funnel metric to validate-- Returns:- Dictionary with error key and message if limit exceeded, None if valid-- Example:- >>> error = FunnelDWValidator.validate_complexity_limits(metric)- >>> if error:- ... raise ValidationError(error)+ Each DW step adds a subquery to the UNION ALL, and each distinct DW table+ adds a join, so both counts have a limit."""dw_steps = [step for step in metric.series if isinstance(step, ExperimentDataWarehouseNode)]- # Check max DW stepsif len(dw_steps) > FunnelDWValidator.MAX_DW_STEPS:return {"complexity_limit": (@@ -153,7 +93,6 @@ class FunnelDWValidator:)}- # Check max distinct tablesdistinct_tables = {step.table_name for step in dw_steps}if len(distinct_tables) > FunnelDWValidator.MAX_DISTINCT_DW_TABLES:table_list = ", ".join(f"'{table}'" for table in sorted(distinct_tables))@@ -171,34 +110,14 @@ class FunnelDWValidator:@classmethoddef validate_funnel_metric(cls, metric: ExperimentFunnelMetric) -> None:- """- Run all validations on a funnel metric.-- This is the main entry point - call before building queries for DW funnels.-- Args:- metric: The funnel metric to validate-- Raises:- ValidationError: If any validation fails, with detailed error messages-- Example:- >>> try:- ... FunnelDWValidator.validate_funnel_metric(metric)- ... except ValidationError as e:- ... # Show error to user- ... return Response(e.detail, status=400)- """+ """Entry point to call before building the query. A funnel without DW steps always passes."""errors: dict[str, Any] = {}- # Check if there are any DW stepshas_dw_steps = any(isinstance(step, ExperimentDataWarehouseNode) for step in metric.series)- # If no DW steps, no validation neededif not has_dw_steps:return- # 1. Validate required fields for each DW stepfield_errors: list[str] = []for i, step in enumerate(metric.series):if isinstance(step, ExperimentDataWarehouseNode):@@ -208,19 +127,16 @@ class FunnelDWValidator:if field_errors:errors["datawarehouse_configuration"] = field_errorserrors["help"] = "All DW steps need table name, timestamp field, and join keys configured."- # Early return - downstream checks are unreliable with missing fields+ # Raise now, because the join key and complexity checks read these fieldsraise ValidationError(errors)- # 2. Validate join key consistencyjoin_key_error = cls.validate_consistent_join_keys(metric)if join_key_error:errors.update(join_key_error)- # 3. Validate complexity limitscomplexity_error = cls.validate_complexity_limits(metric)if complexity_error:errors.update(complexity_error)- # Raise if any errors foundif errors:raise ValidationError(errors)diff --git a/products/experiments/backend/hogql_queries/funnels_statistics_v2.py b/products/experiments/backend/hogql_queries/funnels_statistics_v2.pyindex 4dc95cff91ef..497f3a01d19a 100644--- a/products/experiments/backend/hogql_queries/funnels_statistics_v2.py+++ b/products/experiments/backend/hogql_queries/funnels_statistics_v2.py@@ -19,71 +19,35 @@ def calculate_probabilities_v2(control: ExperimentVariantFunnelsBaseStats, variants: list[ExperimentVariantFunnelsBaseStats]) -> list[float]:"""- Calculate the win probabilities for each variant in an experiment using Bayesian analysis- for funnel conversion rates.-- This function computes the probability that each variant is the best (i.e., has the highest- conversion rate) compared to all other variants, including the control. It uses a Beta- distribution as the "conjugate prior" for binomial (success/failure) data, and starts with- Beta(1,1) as a minimally informative prior distribution. The "conjugate prior" means that- the prior and posterior distributions are the same family, and the posterior is easy- to compute.-- Parameters:- ------------ control : ExperimentVariantFunnelsBaseStats- Statistics for the control group, containing success_count and failure_count- variants : list[ExperimentVariantFunnelsBaseStats]- List of statistics for test variants to compare against the control-- Returns:- --------- list[float]- A list of probabilities where each element represents:- - index 0: probability control beats the best test variant- - index i>0: probability test variant i-1 beats control-- Notes:- ------- - Uses a Bayesian approach with Beta distributions as conjugate prior for binomial data- - Uses Beta(1,1) as minimally informative prior (uniform over [0,1])- - Draws SAMPLE_SIZE (10,000) samples from each variant's posterior distribution- - Calculates win probability as frequency of samples where variant is maximum-- Example:- --------- >>> from posthog.schema import ExperimentVariantFunnelsBaseStats- >>> from products.experiments.backend.hogql_queries.funnels_statistics_v2 import calculate_probabilities_v2- >>> control = ExperimentVariantFunnelsBaseStats(key="control", success_count=100, failure_count=900)- >>> test = ExperimentVariantFunnelsBaseStats(key="test", success_count=150, failure_count=850)- >>> calculate_probabilities_v2(control, [test])- >>> # Returns: [0.001, 0.999] indicating the test variant is very likely to be best+ Monte Carlo win probabilities for funnel conversion rates.++ The Beta distribution is the conjugate prior for binomial (success/failure) data,+ so the posterior is also a Beta distribution and is easy to sample. The prior is+ Beta(1,1), which is uniform over [0, 1].++ Index 0 of the result is the probability that control beats the best test variant.+ Index i > 0 is the probability that test variant i-1 beats control."""all_variants = [control, *variants]- # Use Beta distribution for conversion ratessamples: list[np.ndarray] = []for variant in all_variants:- # Add prior to both successes and failures for Bayesian prioralpha = ALPHA_PRIOR + variant.success_countbeta = BETA_PRIOR + variant.failure_count- # Generate samples from Beta distributionvariant_samples = np.random.beta(alpha, beta, SAMPLE_SIZE)samples.append(variant_samples)samples_array = np.array(samples)probabilities = []- control_samples = samples_array[0] # Control is always first variant+ control_samples = samples_array[0]# Find the best test variant at each sample pointtest_variants_samples = samples_array[1:]best_variant_samples = np.max(test_variants_samples, axis=0)- # Control's probability is of being better than the best test variantcontrol_prob = np.mean(control_samples >= best_variant_samples)probabilities.append(float(control_prob))- # For each test variant, calculate probability of beating controlfor i in range(1, len(all_variants)):probability = np.mean(samples_array[i] > control_samples)probabilities.append(float(probability))@@ -95,32 +59,15 @@ def calculate_expected_loss_v2(target_variant: ExperimentVariantFunnelsBaseStats, variants: list[ExperimentVariantFunnelsBaseStats]) -> float:"""- Calculates expected loss in conversion rate using Beta-Binomial conjugate prior.-- This implementation uses a Bayesian approach with Beta-Binomial model- to estimate the expected loss when choosing the target variant over others.-- Parameters:- ------------ target_variant : ExperimentVariantFunnelsBaseStats- The variant being evaluated for loss- variants : list[ExperimentVariantFunnelsBaseStats]- List of other variants to compare against-- Returns:- --------- float- Expected loss in conversion rate if choosing the target variant+ Expected loss in conversion rate when the target variant is chosen over the best+ of the other variants, from Beta-Binomial posterior samples."""- # Calculate posterior parameters for target varianttarget_alpha = int(ALPHA_PRIOR + target_variant.success_count)target_beta = int(BETA_PRIOR + target_variant.failure_count)target_n = int(target_variant.success_count + target_variant.failure_count)- # Get samples from target variant's Beta-Binomialtarget_samples = betabinom.rvs(target_n, target_alpha, target_beta, size=SAMPLE_SIZE) / target_n- # Get samples from each comparison variantvariant_samples = []for variant in variants:n = int(variant.success_count + variant.failure_count)@@ -129,7 +76,6 @@ def calculate_expected_loss_v2(samples = betabinom.rvs(n, alpha, beta, size=SAMPLE_SIZE) / nvariant_samples.append(samples)- # Calculate lossvariant_max = np.maximum.reduce(variant_samples)losses = np.maximum(0, variant_max - target_samples)expected_loss = float(np.mean(losses))@@ -143,47 +89,17 @@ def are_results_significant_v2(probabilities: list[float],) -> tuple[ExperimentSignificanceCode, float]:"""- Determine if the experiment results are statistically significant using Bayesian analysis- for funnel conversion rates.-- This function evaluates whether there is strong evidence that any variant is better- than the others by considering both winning probabilities and expected loss. It checks- if the sample size is sufficient and evaluates the risk of choosing the winning variant.-- Parameters:- ------------ control : ExperimentVariantFunnelsBaseStats- Statistics for the control group, including success and failure counts- variants : list[ExperimentVariantFunnelsBaseStats]- List of statistics for test variants to compare against the control- probabilities : list[float]- List of probabilities from calculate_probabilities_v2-- Returns:- --------- tuple[ExperimentSignificanceCode, float]- A tuple containing:- - Significance code indicating the result (significant, not enough exposure, high loss, etc.)- - Expected loss value for significant results, 1.0 for non-significant results-- Notes:- ------- - Requires minimum exposure threshold per variant for reliable results- - Uses probability threshold from MIN_PROBABILITY_FOR_SIGNIFICANCE- - Calculates expected loss for the best-performing variant- - Returns HIGH_LOSS if expected loss exceeds significance threshold- - Returns NOT_ENOUGH_EXPOSURE if sample size requirements not met+ Returns the significance code and the expected loss of the variant with the+ highest conversion rate. The expected loss is 1.0 when a check fails before+ the loss calculation."""- # Check minimum exposureif control.success_count + control.failure_count < FF_DISTRIBUTION_THRESHOLD or any(v.success_count + v.failure_count < FF_DISTRIBUTION_THRESHOLD for v in variants):return ExperimentSignificanceCode.NOT_ENOUGH_EXPOSURE, 1.0- # Check if any variant has high enough probabilitymax_probability = max(probabilities)if max_probability >= MIN_PROBABILITY_FOR_SIGNIFICANCE:- # Find best performing variantall_variants = [control, *variants]conversion_rates = [v.success_count / (v.success_count + v.failure_count) for v in all_variants]best_idx = np.argmax(conversion_rates)@@ -200,53 +116,13 @@ def are_results_significant_v2(def calculate_credible_intervals_v2(variants: list[ExperimentVariantFunnelsBaseStats]) -> dict[str, list[float]]:- """- Calculate Bayesian credible intervals for conversion rates of each variant.-- This function computes the 95% credible intervals for the true conversion rate- of each variant using a Beta model. The interval represents the range where we- believe the true conversion rate lies with 95% probability.-- Parameters:- ------------ variants : list[ExperimentVariantFunnelsBaseStats]- List of all variants (including control), each containing success_count and failure_count-- Returns:- --------- dict[str, list[float]]- Dictionary mapping variant keys to [lower, upper] credible intervals, where:- - lower is the 2.5th percentile of the Beta posterior distribution- - upper is the 97.5th percentile of the Beta posterior distribution- - intervals represent conversion rates between 0 and 1-- Notes:- ------- - Uses Beta distribution as conjugate prior for binomial data- - Uses Beta(1,1) as minimally informative prior (uniform over [0,1])- - Computes 95% credible intervals (2.5th to 97.5th percentiles)- - Intervals become narrower with more data (larger success_count + failure_count)- - Returns empty dict if any calculations fail-- Example:- --------- >>> from posthog.schema import ExperimentVariantFunnelsBaseStats- >>> from products.experiments.backend.hogql_queries.funnels_statistics_v2 import calculate_credible_intervals_v2- >>> variants = [- ... ExperimentVariantFunnelsBaseStats(key="control", success_count=100, failure_count=900),- ... ExperimentVariantFunnelsBaseStats(key="test", success_count=150, failure_count=850)- ... ]- >>> calculate_credible_intervals_v2(variants)- >>> # Returns: {"control": [0.083, 0.120], "test": [0.129, 0.173]}- """+ """95% credible intervals for each variant's conversion rate, from the Beta posterior with a Beta(1,1) prior."""intervals = {}for variant in variants:- # Add 1 to both successes and failures for Bayesian prioralpha = ALPHA_PRIOR + variant.success_countbeta = BETA_PRIOR + variant.failure_count- # Calculate 95% credible intervallower, upper = stats.beta.ppf([0.025, 0.975], alpha, beta)intervals[variant.key] = [float(lower), float(upper)]diff --git a/products/experiments/backend/hogql_queries/hogql_aggregation_utils.py b/products/experiments/backend/hogql_queries/hogql_aggregation_utils.pyindex 78a3ea2ed6f5..8cd9681418ba 100644--- a/products/experiments/backend/hogql_queries/hogql_aggregation_utils.py+++ b/products/experiments/backend/hogql_queries/hogql_aggregation_utils.py@@ -7,16 +7,12 @@ from posthog.hogql.visitor import TraversingVisitordef is_aggregation_function(function_name: str) -> bool:- """Check if a function name is an aggregation function."""- # Normalize function name to lowercase for case-insensitive comparisonnormalized_name = function_name.lower()- # First check the dedicated HOGQL_AGGREGATIONS dictionarynormalized_hogql_aggregations = [func.lower() for func in HOGQL_AGGREGATIONS.keys()]if normalized_name in normalized_hogql_aggregations:return True- # Also check other function dictionaries for aggregate functionsfor functions_dict in [HOGQL_CLICKHOUSE_FUNCTIONS, HOGQL_POSTHOG_FUNCTIONS]:if normalized_name in functions_dict:func_meta = functions_dict[normalized_name]@@ -30,17 +26,8 @@ def extract_aggregation_and_inner_expr(hogql_expr: Union[str, ast.Expr],) -> tuple[Optional[str], ast.Expr, Optional[list[ast.Expr]], bool]:"""- Extract the aggregation function, inner expression, parameters, and distinct flag from a HogQL expression.-- Args:- hogql_expr: Either a HogQL expression string or an already parsed AST expression-- Returns:- A tuple of (aggregation_function_name, inner_expression, params, distinct)- - aggregation_function_name: The name of the aggregation function (e.g., "sum"), or None if not an aggregation- - inner_expression: The inner expression AST node- - params: List of parameter expressions for parametric aggregations (e.g., [0.90] for quantile), or None- - distinct: Whether the aggregation uses DISTINCT (e.g., count(distinct ...))+ Returns (aggregation_function_name, inner_expression, params, distinct). The+ function name is None when the top-level expression is not an aggregation.Examples:"sum(properties.revenue - properties.expense)" -> ("sum", <ArithmeticOperation node>, None, False)@@ -49,37 +36,30 @@ def extract_aggregation_and_inner_expr("properties.revenue" -> (None, <Field node>, None, False)"count()" -> ("count", <Constant value=1>, None, False)"""- # Parse the expression if it's a stringif isinstance(hogql_expr, str):expr = parse_expr(hogql_expr)else:expr = hogql_expr- # Check if the expression is a function callif isinstance(expr, ast.Call) and is_aggregation_function(expr.name):- # It's an aggregation functionaggregation_function = expr.name- # Get the inner expressionif expr.args and len(expr.args) > 0:- # Most aggregation functions take the expression as the first argumentinner_expression = expr.args[0]else:- # For functions like count() with no arguments, we emit 1+ # count() has no argument, so aggregate a constant 1 per row.inner_expression = ast.Constant(value=1)- # Extract parameters for parametric aggregations (e.g., quantile(0.90))params = expr.params if expr.params is not None else Nonedistinct = bool(expr.distinct)return aggregation_function, inner_expression, params, distinctelse:- # Not an aggregation function - return the whole expression as the inner partreturn None, expr, None, False-# Registered in HOGQL_AGGREGATIONS for their rewriting behavior but compile to scalar-# expressions — not real aggregates (md5 -> hex(MD5(...))).+# Registered in HOGQL_AGGREGATIONS for their rewriting behavior, but they compile to+# scalar expressions and are not real aggregates (md5 -> hex(MD5(...)))._SCALAR_REGISTRY_QUIRKS = frozenset({"md5"})@@ -118,7 +98,7 @@ _NON_NUMERIC_AGGREGATIONS = frozenset(def aggregation_needs_numeric_input(function_name: str) -> bool:- """Check if an aggregation function requires numeric input (i.e. needs toFloat wrapping)."""+ """Whether the aggregation needs a toFloat() around its input."""return function_name.lower() not in _NON_NUMERIC_AGGREGATIONS@@ -128,20 +108,4 @@ def build_aggregation_call(params: Optional[list[ast.Expr]] = None,distinct: bool = False,) -> ast.Call:- """- Build an aggregation function call AST node.-- Args:- aggregation_function: The aggregation function name (e.g., "sum", "quantile")- inner_expr: The inner expression to aggregate- params: Optional list of parameter expressions for parametric aggregations (e.g., [Constant(0.90)] for quantile)- distinct: Whether to use DISTINCT (for functions that support it)-- Returns:- An ast.Call node representing the aggregation-- Examples:- build_aggregation_call("sum", Field(...)) -> Call(name="sum", args=[...])- build_aggregation_call("quantile", Field(...), params=[Constant(0.90)]) -> Call(name="quantile", args=[...], params=[0.90])- """return ast.Call(name=aggregation_function, args=[inner_expr], params=params, distinct=distinct)diff --git a/products/experiments/backend/hogql_queries/metric_source.py b/products/experiments/backend/hogql_queries/metric_source.pyindex 9b6487e2d69d..d75b52d02c9c 100644--- a/products/experiments/backend/hogql_queries/metric_source.py+++ b/products/experiments/backend/hogql_queries/metric_source.py@@ -1,11 +1,3 @@-"""-Metric source abstraction for experiment queries.--This module provides a unified interface for handling different metric source types-(EventsNode, ActionsNode, ExperimentDataWarehouseNode) in experiment queries.-"""--from dataclasses import dataclassfrom typing import Unionfrom posthog.schema import ActionsNode, EventsNode, ExperimentDataWarehouseNode@@ -14,24 +6,15 @@ from posthog.hogql import astfrom posthog.hogql.parser import parse_exprfrom posthog.clickhouse.query_tagging import tag_contains_user_hogql+from posthog.dataclasses import frozen-@dataclass+@frozenclass MetricSourceInfo:"""- Encapsulates metadata about a metric source for query building.-- This abstraction allows experiment queries to handle heterogeneous sources- (events, actions, datawarehouse) uniformly, particularly important for- funnel queries that may combine multiple source types.-- Attributes:- kind: Source type - "events", "actions", or "datawarehouse"- table_name: Physical table name ("events" or DW table name)- entity_key: AST expression for extracting entity_id- timestamp_field: Field name containing timestamp- has_uuid: Whether source has UUID field (events/actions do, DW doesn't)- has_session_id: Whether source has session_id field (events/actions do, DW doesn't)+ Normalized metadata for an events, actions, or data warehouse metric source,+ so query builders can handle all three the same way. Funnel queries need this+ most, because one funnel can mix source types."""kind: str@@ -48,33 +31,11 @@ class MetricSourceInfo:entity_key: str | None = None,) -> "MetricSourceInfo":"""- Factory method to create MetricSourceInfo from any source type.-- This provides a uniform interface for working with different source types,- abstracting away the differences in their structure.-- Args:- source: The metric source (EventsNode, ActionsNode, or ExperimentDataWarehouseNode)- entity_key: Entity key from experiment context (e.g., "person_id" or "$group_0").- Required for events/actions sources to support group aggregation.- Ignored for datawarehouse sources (uses data_warehouse_join_key instead).-- Returns:- MetricSourceInfo with appropriate metadata for the source type-- Raises:- ValueError: If entity_key is not provided for events/actions sources-- Example:- >>> source = EventsNode(event="purchase")- >>> info = MetricSourceInfo.from_source(source, entity_key="person_id")- >>> info.kind- 'events'- >>> info.has_uuid- True+ entity_key is the experiment entity key, for example "person_id" or "$group_0".+ Events and actions sources require it and raise ValueError without it. Data+ warehouse sources ignore it and use their data_warehouse_join_key."""if isinstance(source, ExperimentDataWarehouseNode):- # Datawarehouse sources always use their own join key, ignore entity_key parameter# `data_warehouse_join_key` is the user-supplied HogQL parsed below.tag_contains_user_hogql()return cls(@@ -86,7 +47,6 @@ class MetricSourceInfo:has_session_id=False,)elif isinstance(source, ActionsNode):- # Events/actions sources require entity_key for group aggregation supportif entity_key is None:raise ValueError("entity_key is required for ActionsNode sources to support group aggregation")return cls(@@ -98,7 +58,6 @@ class MetricSourceInfo:has_session_id=True,)else: # EventsNode- # Events/actions sources require entity_key for group aggregation supportif entity_key is None:raise ValueError("entity_key is required for EventsNode sources to support group aggregation")return cls(@@ -112,27 +71,14 @@ class MetricSourceInfo:def build_select_fields(self) -> list[ast.Alias]:"""- Build normalized SELECT fields for UNION compatibility.-- All sources must return the same columns for UNION ALL:- - entity_id (String type for all sources)- - variant (empty string '' for DW sources)+ All sources in a UNION ALL must return the same columns:+ - entity_id (String for all sources)+ - variant (always empty, because the variant comes from the exposure join)- timestamp- - uuid (placeholder UUID for DW sources)- - session_id (empty string '' for DW sources)-- Returns:- List of aliased column expressions compatible across all source types-- Example:- >>> info = MetricSourceInfo.from_source(EventsNode(event="purchase"), entity_key="person_id")- >>> fields = info.build_select_fields()- >>> [f.alias for f in fields]- ['entity_id', 'variant', 'timestamp', 'uuid', 'session_id']+ - uuid (zero UUID for DW sources)+ - session_id (empty string for DW sources)"""- # All sources need these base fieldsfields = [- # entity_id: String type for consistencyast.Alias(alias="entity_id",expr=ast.Call(@@ -140,15 +86,12 @@ class MetricSourceInfo:args=[self.entity_key],),),- # variant: empty for DW (variant comes from exposure join)ast.Alias(alias="variant",expr=ast.Constant(value=""),),- # timestamp- # For DW sources, use unqualified field name to avoid issues with dotted table names- # (e.g., "schema.table" would become "schema.table.timestamp" if qualified).- # For events table, qualification is safe and conventional.+ # For DW sources, use the unqualified field name, because a dotted table name+ # such as "schema.table" would become "schema.table.timestamp" if qualified.ast.Alias(alias="timestamp",expr=ast.Field(@@ -159,12 +102,10 @@ class MetricSourceInfo:),]- # uuid: placeholder for DW sources (no UUID field)uuid_expr: ast.Exprif self.has_uuid:uuid_expr = ast.Field(chain=["uuid"])else:- # Placeholder UUID for DW: 00000000-0000-0000-0000-000000000000uuid_expr = ast.Call(name="toUUID",args=[ast.Constant(value="00000000-0000-0000-0000-000000000000")],@@ -172,12 +113,10 @@ class MetricSourceInfo:fields.append(ast.Alias(alias="uuid", expr=uuid_expr))- # session_id: placeholder for DW sources (no session_id field)session_id_expr: ast.Exprif self.has_session_id:session_id_expr = ast.Field(chain=["properties", "$session_id"])else:- # Empty string for DW sourcessession_id_expr = ast.Constant(value="")fields.append(ast.Alias(alias="session_id", expr=session_id_expr))diff --git a/products/experiments/backend/hogql_queries/retention_validation.py b/products/experiments/backend/hogql_queries/retention_validation.pyindex 31d9c79a4cc1..9c8f2e53d74e 100644--- a/products/experiments/backend/hogql_queries/retention_validation.py+++ b/products/experiments/backend/hogql_queries/retention_validation.py@@ -1,5 +1,3 @@-"""Validation for experiment retention metric configurations."""-from posthog.schema import ExperimentExposureNode, ExperimentRetentionMetric, StartHandlingdiff --git a/products/experiments/backend/hogql_queries/trends_statistics_v2_continuous.py b/products/experiments/backend/hogql_queries/trends_statistics_v2_continuous.pyindex 02943d579f84..c65daa6c08bf 100644--- a/products/experiments/backend/hogql_queries/trends_statistics_v2_continuous.py+++ b/products/experiments/backend/hogql_queries/trends_statistics_v2_continuous.py@@ -21,62 +21,22 @@ BETA_0 = 1.0 # Prior scale for varianceLOG_VARIANCE = 0.75SAMPLE_SIZE = 10000-EPSILON = 1e-10 # Small epsilon value to handle zeros+EPSILON = 1e-10 # Keeps log() finite when a mean is zerodef calculate_probabilities_v2_continuous(control_variant: ExperimentVariantTrendsBaseStats, test_variants: list[ExperimentVariantTrendsBaseStats]) -> list[float]:"""- Calculate the win probabilities for each variant in an experiment using Bayesian analysis- for continuous metrics (e.g., revenue) with log-normal distribution assumptions.-- This function computes the probability that each variant is the best by comparing its- posterior distribution against all other variants. It uses a Normal-Inverse-Gamma prior- and performs analysis in log-space to handle right-skewed distributions typical of- metrics like revenue.-- Parameters:- ------------ control_variant : ExperimentVariantTrendsBaseStats- Statistics for the control group, containing the mean value (in count field)- and exposure (number of users)- test_variants : list[ExperimentVariantTrendsBaseStats]- List of statistics for test variants to compare against the control-- Returns:- --------- list[float]- A list of probabilities where each element represents:- - index 0: probability control variant beats the best test variant- - index i>0: probability test variant i-1 beats control-- Notes:- ------- - Uses log-transformation of data to handle right-skewed distributions- - Employs a Normal-Inverse-Gamma prior with parameters:- MU_0=0.0, KAPPA_0=1.0, ALPHA_0=1.0, BETA_0=1.0- - Assumes constant variance in log-space (LOG_VARIANCE=0.75)- - Draws SAMPLE_SIZE=10000 samples from each posterior for probability estimation-- Example:- --------- >>> from posthog.schema import ExperimentVariantTrendsBaseStats- >>> from products.experiments.backend.hogql_queries.trends_statistics_v2_continuous import calculate_probabilities_v2_continuous- >>> control = ExperimentVariantTrendsBaseStats(- ... key="control",- ... count=50, # mean revenue per user- ... exposure=1.0, # exposure relative to control- ... absolute_exposure=500 # number of users- ... )- >>> test = ExperimentVariantTrendsBaseStats(- ... key="test",- ... count=60, # mean revenue per user- ... exposure=1, # exposure relative to control- ... absolute_exposure=500 # number of users- ... )- >>> calculate_probabilities_v2_continuous(control, [test])- >>> # Returns: [0.0004, 0.9996] indicating the test variant is very likely to be best+ Estimate win probabilities for a continuous metric (for example revenue) by sampling from+ each variant's posterior.++ `count` holds the metric total, so the per-user mean is count / absolute_exposure. The model+ works in log-space to handle right-skewed values, with a Normal-Inverse-Gamma prior and a+ fixed log-space variance (LOG_VARIANCE).++ Index 0 is the probability that control beats the best test variant.+ Index i > 0 is the probability that test variant i-1 beats control."""if len(test_variants) >= 10:raise ValidationError("Can't calculate experiment results for more than 10 variants", code="too_much_data")@@ -85,22 +45,18 @@ def calculate_probabilities_v2_continuous(mean_value_control = control_variant.count / control_variant.absolute_exposure- # Calculate posterior parameters for controllog_control_mean = np.log(mean_value_control + EPSILON)- # Update parameters for controlkappa_n_control = KAPPA_0 + control_variant.absolute_exposuremu_n_control = (KAPPA_0 * MU_0 + control_variant.absolute_exposure * log_control_mean) / kappa_n_controlalpha_n_control = ALPHA_0 + control_variant.absolute_exposure / 2beta_n_control = BETA_0 + 0.5 * control_variant.absolute_exposure * LOG_VARIANCE- # Draw samples from control posteriorcontrol_posterior = t(df=2 * alpha_n_control, loc=mu_n_control, scale=np.sqrt(beta_n_control / (kappa_n_control * alpha_n_control)))samples_control = control_posterior.rvs(SAMPLE_SIZE)- # Draw samples for each test varianttest_samples = []for test in test_variants:mean_value_test = test.count / test.absolute_exposure@@ -116,15 +72,12 @@ def calculate_probabilities_v2_continuous()test_samples.append(test_posterior.rvs(SAMPLE_SIZE))- # Calculate probabilitiesprobabilities = []- # Probability control wins (beats the best test variant)- best_test_samples = np.max(test_samples, axis=0) # Get best test variant at each sample point+ best_test_samples = np.max(test_samples, axis=0)control_wins = samples_control > best_test_samplesprobabilities.append(float(np.mean(control_wins)))- # Probability each test variant wins (beats control only)for test_sample in test_samples:variant_wins = test_sample > samples_controlprobabilities.append(float(np.mean(variant_wins)))@@ -138,25 +91,8 @@ def are_results_significant_v2_continuous(probabilities: list[float],) -> tuple[ExperimentSignificanceCode, float]:"""- Determines if experiment results are statistically significant using Bayesian analysis- for continuous metrics.-- Parameters:- ------------ control_variant : ExperimentVariantTrendsBaseStats- Statistics for the control group- test_variants : list[ExperimentVariantTrendsBaseStats]- List of statistics for test variants to compare against control- probabilities : list[float]- List of win probabilities for each variant-- Returns:- --------- tuple[ExperimentSignificanceCode, float]- - ExperimentSignificanceCode indicating the significance status- - Expected loss value for significant results, 1.0 for non-significant results+ Return (significance code, expected loss). The expected loss is 1.0 for any result that is not significant."""- # Check exposure thresholdsfor variant in test_variants:if variant.absolute_exposure < FF_DISTRIBUTION_THRESHOLD:return ExperimentSignificanceCode.NOT_ENOUGH_EXPOSURE, 1.0@@ -164,14 +100,11 @@ def are_results_significant_v2_continuous(if control_variant.absolute_exposure < FF_DISTRIBUTION_THRESHOLD:return ExperimentSignificanceCode.NOT_ENOUGH_EXPOSURE, 1.0- # Find highest probability among all variantsmax_probability = max(probabilities)- # Check if any variant has a high enough probability of being bestif max_probability >= MIN_PROBABILITY_FOR_SIGNIFICANCE:- # Find best performing variantall_variants = [control_variant, *test_variants]- means = [v.count for v in all_variants] # count field stores mean value+ means = [v.count for v in all_variants]best_idx = np.argmax(means)best_variant = all_variants[best_idx]other_variants = all_variants[:best_idx] + all_variants[best_idx + 1 :]@@ -188,90 +121,30 @@ def are_results_significant_v2_continuous(def calculate_credible_intervals_v2_continuous(variants, lower_bound=0.025, upper_bound=0.975):"""- Calculate Bayesian credible intervals for each variant's mean value using a log-normal model.-- This function computes credible intervals in log-space using a t-distribution posterior- derived from a Normal-Inverse-Gamma prior, then transforms the results back to the original- scale. This approach is particularly suitable for right-skewed metrics like revenue.-- Parameters:- ------------ variants : list[ExperimentVariantTrendsBaseStats]- List of variants where each variant contains:- - count: the mean value of the metric- - absolute_exposure: number of users/observations- - key: identifier for the variant- lower_bound : float, optional (default=0.025)- Lower percentile for the credible interval (2.5% for 95% CI)- upper_bound : float, optional (default=0.975)- Upper percentile for the credible interval (97.5% for 95% CI)-- Returns:- --------- dict[str, tuple[float, float]]- Dictionary mapping variant keys to their credible intervals where:- - Key: variant identifier- - Value: tuple of (lower_bound, upper_bound) in original scale- Returns empty dict if any calculation errors occur-- Notes:- ------- - Uses log-transformation to handle right-skewed distributions- - Employs Normal-Inverse-Gamma prior with parameters:- MU_0=0.0, KAPPA_0=1.0, ALPHA_0=1.0, BETA_0=1.0- - Assumes constant variance in log-space (LOG_VARIANCE=0.75)- - Results are transformed back to original scale and guaranteed non-negative- - Handles potential calculation errors gracefully by returning empty dict-- Example:- --------- >>> from posthog.schema import ExperimentVariantTrendsBaseStats- >>> from products.experiments.backend.hogql_queries.trends_statistics_v2_continuous import calculate_credible_intervals_v2_continuous- >>> variants = [- ... ExperimentVariantTrendsBaseStats(- ... key="control",- ... count=50.0, # mean revenue per user- ... exposure=1.0, # exposure relative to control- ... absolute_exposure=500 # number of users- ... ),- ... ExperimentVariantTrendsBaseStats(- ... key="test",- ... count=60.0, # mean revenue per user- ... exposure=1, # exposure relative to control- ... absolute_exposure=500 # number of users- ... )- ... ]- >>> calculate_credible_intervals_v2_continuous(variants)- >>> # Returns something like:- >>> # {- >>> # 'control': (45.98, 53.53), # 95% confident true mean is between $45.98-$53.53- >>> # 'test': (55.15, 64.22) # 95% confident true mean is between $55.15-$64.22- >>> # }+ Credible interval of each variant's per-user mean. The interval is computed in log-space and+ transformed back to the original scale.++ Returns an empty dict if the calculation fails for any variant."""intervals = {}for variant in variants:try:- # Log-transform the mean value, adding epsilon to handle zerosmean_value = variant.count / variant.absolute_exposurelog_mean = np.log(mean_value + EPSILON)- # Calculate posterior parameters using absolute_exposurekappa_n = KAPPA_0 + variant.absolute_exposuremu_n = (KAPPA_0 * MU_0 + variant.absolute_exposure * log_mean) / kappa_nalpha_n = ALPHA_0 + variant.absolute_exposure / 2beta_n = BETA_0 + 0.5 * variant.absolute_exposure * LOG_VARIANCE- # Create posterior distributionposterior = t(df=2 * alpha_n, loc=mu_n, scale=np.sqrt(beta_n / (kappa_n * alpha_n)))- # Calculate credible intervalscredible_interval = posterior.interval(upper_bound - lower_bound)- # Transform back from log space and subtract epsilonintervals[variant.key] = (- float(max(0, np.exp(credible_interval[0]) - EPSILON)), # Ensure non-negative- float(max(0, np.exp(credible_interval[1]) - EPSILON)), # Ensure non-negative+ float(max(0, np.exp(credible_interval[0]) - EPSILON)),+ float(max(0, np.exp(credible_interval[1]) - EPSILON)),)except Exception as e:capture_exception(@@ -287,41 +160,22 @@ def calculate_expected_loss_v2_continuous(target_variant: ExperimentVariantTrendsBaseStats, variants: list[ExperimentVariantTrendsBaseStats]) -> float:"""- Calculates expected loss in mean value using Normal-Inverse-Gamma conjugate prior.-- This implementation uses a Bayesian approach with Normal-Inverse-Gamma model- to estimate the expected loss when choosing the target variant over others.- The data is log-transformed to handle typical revenue/continuous metric distributions.-- Parameters:- ------------ target_variant : ExperimentVariantTrendsBaseStats- The variant being evaluated for loss- variants : list[ExperimentVariantTrendsBaseStats]- List of other variants to compare against-- Returns:- --------- float- Expected loss in mean value if choosing the target variant+ Expected loss in per-user mean from choosing the target variant: the mean of+ max(0, best alternative - target) over posterior samples, in the original scale."""- # Calculate posterior parameters for target varianttarget_mean = target_variant.count / target_variant.absolute_exposurelog_target_mean = np.log(target_mean + EPSILON)- # Update parameters for target variantkappa_n_target = KAPPA_0 + target_variant.absolute_exposuremu_n_target = (KAPPA_0 * MU_0 + target_variant.absolute_exposure * log_target_mean) / kappa_n_targetalpha_n_target = ALPHA_0 + target_variant.absolute_exposure / 2beta_n_target = BETA_0 + 0.5 * target_variant.absolute_exposure * LOG_VARIANCE- # Draw samples from target variant's posteriortarget_posterior = t(df=2 * alpha_n_target, loc=mu_n_target, scale=np.sqrt(beta_n_target / (kappa_n_target * alpha_n_target)))target_samples = target_posterior.rvs(SAMPLE_SIZE)- # Draw samples from each comparison variant's posteriorvariant_samples = []for variant in variants:variant_mean = variant.count / variant.absolute_exposure@@ -335,11 +189,9 @@ def calculate_expected_loss_v2_continuous(variant_posterior = t(df=2 * alpha_n, loc=mu_n, scale=np.sqrt(beta_n / (kappa_n * alpha_n)))variant_samples.append(variant_posterior.rvs(SAMPLE_SIZE))- # Transform samples back from log spacetarget_samples = np.exp(target_samples) - EPSILONvariant_samples = [np.exp(samples) - EPSILON for samples in variant_samples]- # Calculate lossvariant_max = np.maximum.reduce(variant_samples)losses = np.maximum(0, variant_max - target_samples)expected_loss = float(np.mean(losses))diff --git a/products/experiments/backend/hogql_queries/trends_statistics_v2_count.py b/products/experiments/backend/hogql_queries/trends_statistics_v2_count.pyindex 3e92d5cda86f..9a0f38f12007 100644--- a/products/experiments/backend/hogql_queries/trends_statistics_v2_count.py+++ b/products/experiments/backend/hogql_queries/trends_statistics_v2_count.py@@ -24,70 +24,34 @@ def calculate_probabilities_v2_count(control_variant: ExperimentVariantTrendsBaseStats, test_variants: list[ExperimentVariantTrendsBaseStats]) -> list[float]:"""- Calculate the win probabilities for each variant in an experiment using Bayesian analysis.-- This function computes the probability that each variant is the best (i.e., has the highest- rate) compared to all other variants, including the control. It uses a Gamma-Poisson model- where samples are drawn from the posterior Gamma distributions of each variant's rate.-- Parameters:- ------------ control_variant : ExperimentVariantTrendsBaseStats- Statistics for the control group, including count (events) and absolute_exposure- test_variants : list[ExperimentVariantTrendsBaseStats]- List of statistics for test variants to compare against the control-- Returns:- --------- list[float]- A list of probabilities where each element represents:- - index 0: probability control variant beats the best test variant- - index i>0: probability test variant i-1 beats control-- Notes:- ------- - Uses a Bayesian approach with a Gamma distribution as the posterior- - Assumes a minimally informative Gamma prior (alpha=1, beta=1)- - Draws samples from the posterior to estimate win probabilities- - Suitable for count/rate data following a Poisson distribution-- Example:- --------- >>> from posthog.schema import ExperimentVariantTrendsBaseStats- >>> from products.experiments.backend.hogql_queries.trends_statistics_v2_count import calculate_probabilities_v2_count- >>> control = ExperimentVariantTrendsBaseStats(key="control", count=100, exposure=1, absolute_exposure=1000)- >>> test = ExperimentVariantTrendsBaseStats(key="test", count=120, exposure=1, absolute_exposure=1000)- >>> calculate_probabilities_v2_count(control, [test])- >>> # Returns: [0.088, 0.920] indicating the test variant is more likely to be the best+ Estimate win probabilities by sampling from each variant's Gamma posterior+ (Gamma-Poisson model with a Gamma(1, 1) prior).++ Index 0 is the probability that control beats the best test variant.+ Index i > 0 is the probability that test variant i-1 beats control."""if len(test_variants) >= 10:raise ValidationError("Can't calculate experiment results for more than 10 variants", code="too_much_data")if len(test_variants) < 1:raise ValidationError("Can't calculate experiment results for less than 2 variants", code="no_data")- # Calculate posterior parameters for controlalpha_control = ALPHA_0 + control_variant.countbeta_control = BETA_0 + control_variant.absolute_exposure- # Draw samples from control posteriorsamples_control = gamma.rvs(alpha_control, scale=1 / beta_control, size=SAMPLE_SIZE)- # Draw samples for each test varianttest_samples = []for test in test_variants:alpha_test = ALPHA_0 + test.countbeta_test = BETA_0 + test.absolute_exposuretest_samples.append(gamma.rvs(alpha_test, scale=1 / beta_test, size=SAMPLE_SIZE))- # Calculate probabilitiesprobabilities = []- # Probability control wins (beats the best test variant)best_test_samples = np.max(test_samples, axis=0)control_wins = samples_control > best_test_samplesprobabilities.append(float(np.mean(control_wins)))- # Probability each test variant wins (beats control only)for test_sample in test_samples:variant_wins = test_sample > samples_controlprobabilities.append(float(np.mean(variant_wins)))@@ -101,40 +65,8 @@ def are_results_significant_v2_count(probabilities: list[Probability],) -> tuple[ExperimentSignificanceCode, Probability]:"""- Determines if experiment results are statistically significant.-- This function evaluates whether any variant can be confidently declared as best by:- 1. Checking if variants have sufficient exposure (minimum threshold)- 2. Evaluating if the highest win probability exceeds the significance threshold- 3. For the variant with highest rate, calculating expected loss compared to alternatives-- Parameters:- ------------ control_variant : ExperimentVariantTrendsBaseStats- Statistics for the control group, including count and absolute_exposure- test_variants : list[ExperimentVariantTrendsBaseStats]- List of statistics for test variants to compare against control- probabilities : list[Probability]- Win probabilities for each variant (must sum to 1), as calculated by calculate_probabilities_v2_count-- Returns:- --------- tuple[ExperimentSignificanceCode, Probability]- - ExperimentSignificanceCode indicating result status:- * NOT_ENOUGH_EXPOSURE: if any variant has exposure below threshold- * LOW_WIN_PROBABILITY: if no variant exceeds probability threshold- * HIGH_LOSS: if expected loss is too high for best variant- * SIGNIFICANT: if a variant is confidently best- - Expected loss value (between 0 and 1) for significant results, 1.0 for non-significant results-- Notes:- ------- - Uses FF_DISTRIBUTION_THRESHOLD for minimum exposure check- - Uses MIN_PROBABILITY_FOR_SIGNIFICANCE (default 0.9) for win probability threshold- - Uses EXPECTED_LOSS_SIGNIFICANCE_LEVEL for maximum acceptable expected loss- - Expected loss represents the expected rate difference between chosen variant and potential better alternatives+ Return (significance code, expected loss). The expected loss is 1.0 for any result that is not significant."""- # Check exposure thresholdsfor variant in test_variants:if variant.absolute_exposure < FF_DISTRIBUTION_THRESHOLD:return ExperimentSignificanceCode.NOT_ENOUGH_EXPOSURE, 1.0@@ -142,12 +74,9 @@ def are_results_significant_v2_count(if control_variant.absolute_exposure < FF_DISTRIBUTION_THRESHOLD:return ExperimentSignificanceCode.NOT_ENOUGH_EXPOSURE, 1.0- # Find highest probability among all variantsmax_probability = max(probabilities)- # Check if any variant has a high enough probability of being bestif max_probability >= MIN_PROBABILITY_FOR_SIGNIFICANCE:- # Find best performing variantall_variants = [control_variant, *test_variants]rates = [v.count / v.absolute_exposure for v in all_variants]best_idx = np.argmax(rates)@@ -166,55 +95,17 @@ def are_results_significant_v2_count(def calculate_credible_intervals_v2_count(variants, lower_bound=0.025, upper_bound=0.975):"""- Calculate Bayesian credible intervals for each variant's rate using a Gamma-Poisson model.-- Credible intervals represent the range where we believe the true rate lies- with a specified probability (default 95%). These intervals have a direct probabilistic- interpretation: "There is a 95% probability that the true rate lies within this interval."-- Parameters:- ------------ variants : list[ExperimentVariantTrendsBaseStats]- List of variants containing count (number of events) and absolute_exposure data- lower_bound : float, optional (default=0.025)- Lower percentile for the credible interval (2.5% for 95% CI)- upper_bound : float, optional (default=0.975)- Upper percentile for the credible interval (97.5% for 95% CI)-- Returns:- --------- dict[str, tuple[float, float]]- Dictionary mapping variant keys to their credible intervals- Each interval is a tuple of (lower_bound, upper_bound) representing rates-- Notes:- ------- - Uses a Gamma distribution as the posterior for the rate parameter- - Assumes a minimally informative Gamma prior (alpha=1, beta=1)- - Suitable for count/rate data following a Poisson distribution- - Returns empty dict if any calculations fail- - Intervals represent rates (events per exposure)-- Example:- --------- >>> from posthog.schema import ExperimentVariantTrendsBaseStats- >>> from products.experiments.backend.hogql_queries.trends_statistics_v2_count import calculate_credible_intervals_v2_count- >>> variants = [- ... ExperimentVariantTrendsBaseStats(key="control", count=100, exposure=1, absolute_exposure=1000),- ... ExperimentVariantTrendsBaseStats(key="test", count=150, exposure=1, absolute_exposure=1000)- ... ]- >>> calculate_credible_intervals_v2_count(variants)- >>> # Returns: {"control": (0.082, 0.122), "test": (0.128, 0.176)}+ Credible interval of each variant's rate (events per exposure), from its Gamma posterior.++ Returns an empty dict if the calculation fails for any variant."""intervals = {}for variant in variants:try:- # Calculate posterior parameters using absolute_exposurealpha_posterior = ALPHA_0 + variant.countbeta_posterior = BETA_0 + variant.absolute_exposure- # Calculate credible intervals using the posterior distributioncredible_interval = gamma.ppf([lower_bound, upper_bound], alpha_posterior, scale=1 / beta_posterior)intervals[variant.key] = (float(credible_interval[0]), float(credible_interval[1]))@@ -232,50 +123,17 @@ def calculate_expected_loss_v2_count(target_variant: ExperimentVariantTrendsBaseStats, variants: list[ExperimentVariantTrendsBaseStats]) -> float:"""- Calculates expected loss in count/rate using Gamma-Poisson conjugate prior.-- This implementation uses a Bayesian approach with Gamma-Poisson model to estimate- the expected loss when choosing the target variant over others. The Gamma-Poisson- model is used because:- 1. Count data follows a Poisson distribution (discrete events over time/exposure)- 2. The Gamma distribution is the conjugate prior for the Poisson rate parameter- 3. This combination allows for analytical posterior updates and handles rate uncertainty-- The model assumes:- - Events occur independently at a constant rate- - The number of events in any interval follows a Poisson distribution- - The rate parameter has a Gamma prior distribution- - The posterior distribution of the rate is also Gamma-- Parameters:- ------------ target_variant : ExperimentVariantTrendsBaseStats- The variant being evaluated for loss, containing count and exposure data- variants : list[ExperimentVariantTrendsBaseStats]- List of other variants to compare against-- Returns:- --------- float- Expected loss in rate if choosing the target variant. This represents- the expected difference in rate between the target variant and the best- performing alternative.-- Notes:- ------- - Uses minimally informative prior: Gamma(1,1)- - Posterior parameters: alpha = prior_alpha + count, beta = prior_beta + exposure- - Samples are drawn from posterior distributions to estimate expected loss- - Loss is calculated as max(0, best_alternative - target) for each sample+ Expected loss in rate from choosing the target variant: the mean of+ max(0, best alternative - target) over posterior samples.++ Gamma is the conjugate prior of the Poisson rate, so each posterior is+ Gamma(ALPHA_0 + count, BETA_0 + absolute_exposure)."""- # Calculate posterior parameters for target varianttarget_alpha = ALPHA_0 + target_variant.counttarget_beta = BETA_0 + target_variant.absolute_exposure- # Draw samples from target variant's Gamma posteriortarget_samples = gamma.rvs(target_alpha, scale=1 / target_beta, size=SAMPLE_SIZE)- # Draw samples from each comparison variant's Gamma posteriorvariant_samples = []for variant in variants:alpha = ALPHA_0 + variant.count@@ -283,7 +141,6 @@ def calculate_expected_loss_v2_count(samples = gamma.rvs(alpha, scale=1 / beta, size=SAMPLE_SIZE)variant_samples.append(samples)- # Calculate lossvariant_max = np.maximum.reduce(variant_samples)losses = np.maximum(0, variant_max - target_samples)expected_loss = float(np.mean(losses))diff --git a/products/experiments/backend/hogql_queries/types.py b/products/experiments/backend/hogql_queries/types.pyindex 4e4f4d6cab0b..8fb0deba754d 100644--- a/products/experiments/backend/hogql_queries/types.py+++ b/products/experiments/backend/hogql_queries/types.py@@ -10,7 +10,7 @@ class ExperimentMetricType(Enum):class PrecomputeSkipReason(StrEnum):"""Why a metric read never attempted precompute. Tagged on the query as`experiment_precompute_skip_reason` and counted per reason by the- `precompute_overview` staff endpoint, which iterates this enum — a reason+ `precompute_overview` staff endpoint, which iterates this enum. A reasonmissing here is invisible in the staff tooling."""OVERRIDE_DIRECT = "override_direct"diff --git a/products/experiments/backend/hogql_queries/utils.py b/products/experiments/backend/hogql_queries/utils.pyindex 909aaf56a669..108a3dd3170a 100644--- a/products/experiments/backend/hogql_queries/utils.py+++ b/products/experiments/backend/hogql_queries/utils.py@@ -59,10 +59,10 @@ def get_experiment_query_debug(bypass_warehouse_access_control: bool = False,) -> tuple[str, str]:"""- Generate both HogQL and ClickHouse SQL for debugging from experiment query AST.- Returns (hogql, clickhouse_sql) tuple.+ Return (hogql, clickhouse_sql) for debugging.- user/bypass must match the execution step, since resolving here also applies warehouse access control.+ `user` and `bypass_warehouse_access_control` must match the execution step, because+ resolving the query here also applies warehouse access control."""executor = HogQLQueryExecutor(query=experiment_query_ast,@@ -78,13 +78,6 @@ def get_experiment_query_debug(def _parse_enum_config(value: Any, enum_class: type[Enum], default: Any) -> Any:- """- Parse config value into enum with fallback to default.-- Handles string values (converts via enum_class[value]),- existing enum instances (passes through),- and invalid values (returns default).- """try:if isinstance(value, str):return enum_class[value]@@ -96,9 +89,6 @@ def _parse_enum_config(value: Any, enum_class: type[Enum], default: Any) -> Any:def _validate_numeric_range(value: Any, min_val: float, max_val: float, default: float) -> float:- """- Validate numeric value is within range, return default if invalid.- """try:float_value = float(value)if min_val <= float_value <= max_val:@@ -112,10 +102,10 @@ def sanitize_non_finite(value: Any) -> Any:"""Replace non-finite floats (inf/-inf/nan) with None, recursively.Stats can overflow to infinity (e.g. delta-method variance with a near-zero- denominator), json.dumps emits those as the nonstandard `Infinity`/`NaN`- tokens, and Postgres rejects them in jsonb columns — apply this to result- dicts at the storage boundary. None matches the schema: the affected fields- (confidence intervals etc.) are already nullable.+ denominator). json.dumps emits those as the nonstandard `Infinity`/`NaN`+ tokens, and Postgres rejects them in jsonb columns, so apply this to result+ dicts at the storage boundary. None matches the schema because the affected+ fields (confidence intervals etc.) are already nullable."""if isinstance(value, float) and not math.isfinite(value):return None@@ -142,8 +132,8 @@ def split_baseline_and_test_variants() -> tuple[V, list[V]]:control_variants = [variant for variant in variants if variant.key == baseline_key]if not control_variants:- # Expected while an experiment has no exposures for its baseline yet — a- # user-facing validation error, not a server error.+ # The baseline has no exposures early in an experiment. Raise a validation+ # error so that the user sees a message instead of a server error.raise ValidationError(f"No exposures for the '{baseline_key}' variant yet. Results can be calculated once it has data.",code="no_data",@@ -156,9 +146,9 @@ def split_baseline_and_test_variants(return control_variant, test_variants-# Maps SQL aliases produced by experiment_query_builder.py SELECT clauses to-# ExperimentStatsBase field names. Aliases not registered here are ignored —-# adding a new SELECT column without updating this map is a silent no-op.+# Maps the SELECT aliases of the experiment query builders to+# ExperimentStatsBase field names. Aliases not registered here are ignored, so+# a new SELECT column without an entry in this map is silently dropped._ALIAS_TO_STATS_FIELD: dict[str, str] = {"variant": "key","num_users": "number_of_samples",@@ -179,17 +169,11 @@ def get_variant_result(columns: list[str],) -> tuple[tuple[str, ...] | None, ExperimentStatsBase]:"""- Parse a single result row into (breakdown_tuple, ExperimentStatsBase).-- The contract between the SQL builder and this parser is the column aliases- declared in each SELECT (`count(...) AS num_users`, `sum(...) AS covariate_sum`,- `breakdown_value_1`, …). Field presence is driven by which aliases appear in- `columns`, so adding or reordering SELECT columns propagates here automatically- without any positional offsets to maintain.+ Parse one result row into (breakdown_tuple, stats).- Breakdown columns (`breakdown_value_1`, `breakdown_value_2`, …) are collected- in numeric order into the returned tuple. If none are present, the breakdown- tuple is None.+ Fields are matched by the column aliases declared in each SELECT+ (`count(...) AS num_users`, `breakdown_value_1`, ...), not by position.+ The breakdown tuple is None when the row has no `breakdown_value_N` columns."""row_dict = dict(zip(columns, row))@@ -217,20 +201,7 @@ def aggregate_variants_across_breakdowns(variants: list[tuple[tuple[str, ...] | None, ExperimentStatsBase]],) -> list[ExperimentStatsBase]:"""- Aggregates variant results across all breakdown combinations to compute global metrics.-- Takes list of (breakdown_tuple, ExperimentStatsBase) tuples and aggregates by variant key.- The breakdown_tuple contains all breakdown values (e.g., ("MacOS", "Chrome") for multiple- breakdowns, ("Chrome",) for single breakdown, or None for no breakdown).-- For each variant key (control, test, etc.), sums up:- - number_of_samples- - sum- - sum_squares- - For funnel metrics: step_counts (element-wise)- - For ratio metrics: denominator_sum, denominator_sum_squares, numerator_denominator_sum_product-- Returns a list of aggregated variants (without breakdown values).+ Sum each variant's stats over all breakdown combinations to get the overall stats per variant."""from collections import defaultdict@@ -314,17 +285,14 @@ def validate_variant_result(validation_failures=validation_failures,)- # Include funnel-specific fields if presentif hasattr(variant_result, "step_counts") and variant_result.step_counts is not None:validated_result.step_counts = variant_result.step_counts- # Include ratio-specific fields if presentif hasattr(variant_result, "denominator_sum") and variant_result.denominator_sum is not None:validated_result.denominator_sum = variant_result.denominator_sumvalidated_result.denominator_sum_squares = variant_result.denominator_sum_squaresvalidated_result.numerator_denominator_sum_product = variant_result.numerator_denominator_sum_product- # Include CUPED-specific fields if presentif hasattr(variant_result, "covariate_sum") and variant_result.covariate_sum is not None:validated_result.covariate_sum = variant_result.covariate_sumvalidated_result.covariate_sum_squares = variant_result.covariate_sum_squares@@ -352,8 +320,6 @@ def metric_variant_to_statistic(sum_squares=variant.sum_squares,)elif isinstance(metric, ExperimentRatioMetric):- # For ratio metrics, create statistics for both numerator and denominator- # and combine them using RatioStatisticnumerator_stat = SampleMeanStatistic(n=variant.number_of_samples,sum=variant.sum,@@ -371,15 +337,15 @@ def metric_variant_to_statistic(m_d_sum_of_products=variant.numerator_denominator_sum_product or 0.0,)elif isinstance(metric, ExperimentRetentionMetric):- # Retention metrics use ratio statistic to properly account for- # uncertainty in both numerator and denominator- # Numerator: count of users who completed (binary: 0 or 1 per user)+ # Model retention as a ratio so that the variance includes the uncertainty+ # in both the numerator and the denominator.+ # Numerator: users who completed (0 or 1 per user).numerator_stat = SampleMeanStatistic(n=variant.number_of_samples,sum=variant.sum,sum_squares=variant.sum_squares,)- # Denominator: each user who started contributes 1+ # Denominator: each user who started contributes 1.denominator_stat = SampleMeanStatistic(n=variant.number_of_samples,sum=variant.denominator_sum or 0.0,@@ -544,7 +510,6 @@ def get_frequentist_experiment_result(variants: list[ExperimentVariantResultFrequentist] = []for test_variant_validated in test_variants_validated:- # Add fields we should always returnexperiment_variant_result = ExperimentVariantResultFrequentist(key=test_variant_validated.key,number_of_samples=test_variant_validated.number_of_samples,@@ -554,7 +519,6 @@ def get_frequentist_experiment_result(validation_failures=test_variant_validated.validation_failures,)- # Include ratio-specific fields if presentif hasattr(test_variant_validated, "denominator_sum") and test_variant_validated.denominator_sum is not None:experiment_variant_result.denominator_sum = test_variant_validated.denominator_sumexperiment_variant_result.denominator_sum_squares = test_variant_validated.denominator_sum_squares@@ -563,7 +527,6 @@ def get_frequentist_experiment_result()_copy_cuped_fields(experiment_variant_result, test_variant_validated)- # Check if we can perform statistical analysisif control_stat and not test_variant_validated.validation_failures:try:test_stat = metric_variant_to_statistic(metric, test_variant_validated)@@ -587,7 +550,6 @@ def get_frequentist_experiment_result(confidence_interval = [result.confidence_interval[0], result.confidence_interval[1]]- # Set statistical analysis fieldsexperiment_variant_result.p_value = result.p_valueexperiment_variant_result.confidence_interval = confidence_intervalexperiment_variant_result.significant = result.is_significant@@ -614,9 +576,6 @@ def get_bayesian_experiment_result(stats_config: dict | None = None,cuped_config: CupedQueryConfig | None = None,) -> ExperimentQueryResponse:- """- Get experiment results using the new Bayesian method with the new format- """bayesian_config = stats_config.get("bayesian", {}) if stats_config else {}resolved_cuped_config = cuped_config or get_cuped_config(stats_config, metric)@@ -646,7 +605,6 @@ def get_bayesian_experiment_result(variants: list[ExperimentVariantResultBayesian] = []for test_variant_validated in test_variants_validated:- # Add fields we should always returnexperiment_variant_result = ExperimentVariantResultBayesian(key=test_variant_validated.key,number_of_samples=test_variant_validated.number_of_samples,@@ -656,7 +614,6 @@ def get_bayesian_experiment_result(validation_failures=test_variant_validated.validation_failures,)- # Include ratio-specific fields if presentif hasattr(test_variant_validated, "denominator_sum") and test_variant_validated.denominator_sum is not None:experiment_variant_result.denominator_sum = test_variant_validated.denominator_sumexperiment_variant_result.denominator_sum_squares = test_variant_validated.denominator_sum_squares@@ -665,7 +622,6 @@ def get_bayesian_experiment_result()_copy_cuped_fields(experiment_variant_result, test_variant_validated)- # Check if we can perform statistical analysisif control_stat and not test_variant_validated.validation_failures:try:test_stat = metric_variant_to_statistic(metric, test_variant_validated)@@ -687,13 +643,11 @@ def get_bayesian_experiment_result(unadjusted_mean=cuped_adjustment.control_unadjusted_mean,)- # Convert credible interval to percentagecredible_interval = [result.credible_interval[0], result.credible_interval[1]]- # Set statistical analysis fieldsexperiment_variant_result.chance_to_win = result.chance_to_winexperiment_variant_result.credible_interval = credible_interval- experiment_variant_result.significant = result.is_decisive # Use is_decisive for significance+ experiment_variant_result.significant = result.is_decisiveexcept StatisticError as e:logger.info("experiment_statistics_skipped",