: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
feat(experiments): add breakdown attribution query builder and context (#94844)
Rodrigo Iloro7020af36a4ac
diff --git a/products/experiments/backend/hogql_queries/experiment_breakdown_attribution_query_builder.py b/products/experiments/backend/hogql_queries/experiment_breakdown_attribution_query_builder.pynew file mode 100644index 000000000000..0a5f0d1dd776--- /dev/null+++ b/products/experiments/backend/hogql_queries/experiment_breakdown_attribution_query_builder.py@@ -0,0 +1,316 @@+"""+Builder for experiment breakdown attribution on metric events.++Takes an ``ExperimentBreakdownAttributionContext`` and constructs the HogQL AST+that reads each breakdown property off the metric event, attributes it across+funnel steps with the context's resolved aggregation, and injects the breakdown+columns into the funnel query CTEs.++Scope: funnel metrics only, for now.+"""++from typing import cast++from posthog.schema import MultipleBreakdownType++from posthog.hogql import ast+from posthog.hogql.parser import parse_expr++from posthog.hogql_queries.insights.trends.utils import get_properties_chain+from posthog.hogql_queries.utils.breakdowns import BREAKDOWN_NULL_STRING_LABEL, BREAKDOWN_OTHER_STRING_LABEL++from products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEY+from products.experiments.backend.hogql_queries.experiment_breakdown_attribution_query_context import (+ ExperimentBreakdownAttributionContext,+)+++class ExperimentBreakdownAttributionQueryBuilder:+ def __init__(self, context: ExperimentBreakdownAttributionContext):+ self.context = context++ def attributes_from_exposure(self) -> bool:+ """This builder attributes from the metric event, so the exposure query stays breakdown-free."""+ return False++ def _reject_unsupported_combinations(self) -> None:+ """Reject metric shapes this builder cannot attribute correctly yet.++ A data-warehouse funnel step replaces the ``metric_events`` CTE with a UNION over the+ events table and the warehouse tables. Those branches carry no breakdown column, so a+ breakdown 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.++ A single-step funnel is degenerate for metric-event attribution. A user reaches a named+ bucket only by emitting the step event, which is the same event the funnel counts as the+ conversion, 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.+ """+ if self.context.has_data_warehouse_step():+ raise NotImplementedError(+ "breakdowns on data-warehouse funnel steps are not yet supported for experiment funnels"+ )+ if self.context.is_single_step():+ raise NotImplementedError(+ "breakdowns on single-step funnel metrics are not supported: every named bucket would "+ "be 100% converted by construction"+ )++ def build_breakdown_exprs(self, table_alias: str = "events") -> list[tuple[str, ast.Expr]]:+ """Returns (alias, expression) tuples reading each breakdown property off the metric event.++ A missing property and a property set to an empty string both become+ BREAKDOWN_NULL_STRING_LABEL. The UI labels both as "None", so keeping them apart would+ show two identical rows, each with its own samples and statistics. Empty list if no+ breakdowns.+ """+ if not self.context.has_breakdown():+ return []++ result = []+ for i, breakdown in enumerate(self.context.breakdowns):+ breakdown_type = breakdown.type or cast(MultipleBreakdownType, "event")+ breakdown_field = str(breakdown.property)++ properties_chain = get_properties_chain(+ breakdown_type=breakdown_type,+ breakdown_field=breakdown_field,+ group_type_index=breakdown.group_type_index,+ )++ if table_alias and properties_chain[0] == "properties":+ property_expr: ast.Expr = ast.Field(chain=[table_alias, *properties_chain])+ else:+ property_expr = ast.Field(chain=properties_chain)++ expr = parse_expr(+ "coalesce(nullIf(toString({property_expr}), ''), {null_label})",+ placeholders={+ "property_expr": property_expr,+ "null_label": ast.Constant(value=BREAKDOWN_NULL_STRING_LABEL),+ },+ )+ result.append((f"breakdown_value_{i + 1}", expr))++ return result++ def _attribution_condition(self, step_indexes: list[int]) -> ast.Expr:+ """Match a metric event at any of the attribution step columns (``step_i = 1``)."""+ comparisons: list[ast.Expr] = [+ ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=[f"step_{index}"]),+ right=ast.Constant(value=1),+ )+ for index in step_indexes+ ]+ return comparisons[0] if len(comparisons) == 1 else ast.Or(exprs=comparisons)++ def _value_present_condition(self, breakdown_fields: list[ast.Expr]) -> ast.Expr:+ """Match a row that carries at least one breakdown value.++ The property is coalesced to the null label before attribution, so a row with no value+ would otherwise be an equal candidate and win on timestamp alone, hiding a later event+ that carries a real one.+ """+ comparisons: list[ast.Expr] = [+ ast.CompareOperation(+ op=ast.CompareOperationOp.NotEq,+ left=field,+ right=ast.Constant(value=BREAKDOWN_NULL_STRING_LABEL),+ )+ for field in breakdown_fields+ ]+ return comparisons[0] if len(comparisons) == 1 else ast.Or(exprs=comparisons)++ def _attribution_expr(self, breakdown_field: ast.Expr, breakdown_fields: list[ast.Expr]) -> ast.Expr:+ """Attributed breakdown value at the configured step(s).++ A candidate row must match an attribution step and carry a breakdown value. Every alias+ shares that one condition, and orders by (timestamp, uuid) rather than timestamp alone, so+ all breakdown values of a user come from the same event. With ties on timestamp each alias+ would otherwise pick its own row, forming a value tuple the user never had.++ argMinIf/argMaxIf over zero matching rows returns ClickHouse's empty string. The UI labels+ that as "None" too, but it is a different value from the null label, so it would form a+ second no-value bucket and steal a top-N slot. Users with no attributable metric event get+ the null label instead.++ Integration must add an exposure-time bound here. An ordered funnel keeps pre-exposure+ metric events in the CTE, because the funnel aggregate anchors on the exposure step while+ this aggregate reads any row at a metric step. So a user who fired a metric event before+ exposure can be filed under that earlier value. The 3-CTE path already has+ ``exposures.first_exposure_time`` to gate on; the optimized ordered path has no+ exposure-time column yet (its first-exposures CTE is built for unordered and CUPED only),+ so gating both paths together is deferred to the caller that wires this class in.++ Integration should also align attribution with the occurrence the funnel walk matched.+ The step condition is a per-row flag with no ordering, so this aggregate can pick a step+ occurrence the walk skipped. This is sharpest for specific-step attribution: a step-2 event+ that 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+ insights 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 the+ aggregate's matched-step UUIDs), which changes a shared helper this class does not own.+ """+ resolution = self.context.resolve_attribution()+ condition: ast.Expr = ast.And(+ exprs=[+ self._attribution_condition(resolution.step_indexes),+ self._value_present_condition(breakdown_fields),+ ]+ )+ ordering_key = ast.Tuple(exprs=[ast.Field(chain=["timestamp"]), ast.Field(chain=["uuid"])])+ attributed = ast.Call(+ name=resolution.aggregation_fn,+ args=[breakdown_field, ordering_key, condition],+ )+ return parse_expr(+ "if({has_match} = 0, {null_label}, {attributed})",+ placeholders={+ "has_match": ast.Call(name="countIf", args=[condition]),+ "null_label": ast.Constant(value=BREAKDOWN_NULL_STRING_LABEL),+ "attributed": attributed,+ },+ )++ 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.++ Only users who reach the result are ranked. Users with no variant are dropped by the+ final SELECT, and under "exclude" handling the runner drops multi-variant users after+ the query, so counting either here would let a bucket take a top-N slot and then show+ no row.+ """+ # Project a scalar for a single breakdown, or a tuple for multiple, so the+ # membership test on the outer query matches shapes.+ if len(aliases) == 1:+ projection: ast.Expr = ast.Field(chain=["entity_metrics", aliases[0]])+ else:+ projection = ast.Tuple(exprs=[ast.Field(chain=["entity_metrics", alias]) for alias in aliases])+ subquery = ast.SelectQuery(+ select=[projection],+ select_from=ast.JoinExpr(table=ast.Field(chain=["entity_metrics"])),+ where=parse_expr(+ "notEmpty(entity_metrics.variant) and entity_metrics.variant != {multiple_variant_key}",+ placeholders={"multiple_variant_key": ast.Constant(value=MULTIPLE_VARIANT_KEY)},+ ),+ group_by=[ast.Field(chain=["entity_metrics", alias]) for alias in aliases],+ # Tie-break by breakdown value so the cutoff at the limit is deterministic+ # across executions; count() alone lets ClickHouse pick tied tuples arbitrarily.+ order_by=[+ ast.OrderExpr(expr=ast.Call(name="count", args=[]), order="DESC"),+ *[ast.OrderExpr(expr=ast.Field(chain=["entity_metrics", alias]), order="ASC") for alias in aliases],+ ],+ limit=ast.Constant(value=self.context.breakdown_limit()),+ )+ return subquery++ def _inject_final_breakdown_columns(self, query: ast.SelectQuery, aliases: list[str]) -> None:+ """Surface breakdown columns in the outer SELECT (after variant) and GROUP BY.++ Applies the top-N + "Other" limit: breakdown tuples beyond the limit (ranked by+ user count) are relabeled to BREAKDOWN_OTHER_STRING_LABEL before the final GROUP BY,+ capping output cardinality. The relabel collapses the whole tuple together so all+ breakdown columns of an "Other" row carry the Other label.++ Integration should measure the top-N read cost. The same membership subquery is inlined+ once 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:+ 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 cannot+ happen here, because the funnel query builder keeps editing the final SELECT after+ injection (step counts, maturity HAVING), so it belongs in the caller that wires this in.+ """+ # Membership test against the top-N set. Single breakdown compares the scalar value+ # directly; multiple breakdowns compare the value tuple element-wise.+ if len(aliases) == 1:+ left: ast.Expr = ast.Field(chain=["entity_metrics", aliases[0]])+ else:+ left = ast.Tuple(exprs=[ast.Field(chain=["entity_metrics", alias]) for alias in aliases])+ in_top = ast.CompareOperation(+ op=ast.CompareOperationOp.In,+ left=left,+ right=self._top_breakdowns_subquery(aliases),+ )++ for i, alias in enumerate(aliases):+ limited_expr = parse_expr(+ "if({in_top}, {value}, {other})",+ placeholders={+ "in_top": in_top,+ "value": ast.Field(chain=["entity_metrics", alias]),+ "other": ast.Constant(value=BREAKDOWN_OTHER_STRING_LABEL),+ },+ )+ query.select.insert(1 + i, ast.Alias(alias=alias, expr=limited_expr))++ if query.group_by is None:+ query.group_by = []+ for alias in aliases:+ query.group_by.append(ast.Field(chain=[alias]))++ def inject_funnel_breakdown_columns(self, query: ast.SelectQuery) -> None:+ """Legacy 3-CTE path: exposures + metric_events + entity_metrics.++ The breakdown is always attributed from the metric event (never carried+ from exposures), so attribution is uniform regardless of funnel order.+ """+ if not self.context.has_breakdown():+ return+ self._reject_unsupported_combinations()++ aliases = self.context.breakdown_aliases()+ breakdown_exprs = self.build_breakdown_exprs(table_alias="")++ if 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))++ 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):+ breakdown_fields: list[ast.Expr] = [ast.Field(chain=["metric_events", alias]) for alias in aliases]+ for alias, field in zip(aliases, breakdown_fields):+ entity_metrics_cte.expr.select.append(+ ast.Alias(alias=alias, expr=self._attribution_expr(field, breakdown_fields))+ )++ self._inject_final_breakdown_columns(query, aliases)++ def inject_funnel_breakdown_columns_optimized(self, query: ast.SelectQuery) -> None:+ """Optimized 2-CTE path: base_events + entity_metrics (no exposures CTE)."""+ if not self.context.has_breakdown():+ return+ self._reject_unsupported_combinations()++ aliases = self.context.breakdown_aliases()+ breakdown_exprs = self.build_breakdown_exprs(table_alias="")++ if 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))++ 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):+ breakdown_fields: list[ast.Expr] = [ast.Field(chain=[alias]) for alias in aliases]+ for alias, field in zip(aliases, breakdown_fields):+ entity_metrics_cte.expr.select.append(+ ast.Alias(alias=alias, expr=self._attribution_expr(field, breakdown_fields))+ )++ self._inject_final_breakdown_columns(query, aliases)diff --git a/products/experiments/backend/hogql_queries/experiment_breakdown_attribution_query_context.py b/products/experiments/backend/hogql_queries/experiment_breakdown_attribution_query_context.pynew file mode 100644index 000000000000..ec596a86c591--- /dev/null+++ b/products/experiments/backend/hogql_queries/experiment_breakdown_attribution_query_context.py@@ -0,0 +1,112 @@+"""+Context for experiment breakdown attribution on metric events.++This carries the breakdown configuration for a metric and resolves the pure,+AST-free decisions that attribution needs: the aggregation function and step+columns for the configured ``breakdownAttributionType``, the breakdown value+aliases, and the top-N limit.++Unlike ``BreakdownInjector`` (which attributes the breakdown from the exposure+event), this attributes the breakdown off the *metric* event, aligning+experiment 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.+"""++from posthog.schema import (+ Breakdown,+ BreakdownAttributionType,+ ExperimentDataWarehouseNode,+ ExperimentFunnelMetric,+ StepOrderValue,+)++from posthog.hogql.constants import BREAKDOWN_VALUES_LIMIT++from posthog.dataclasses import frozen+++@frozen+class AttributionResolution:+ """The aggregation function and step columns that attribution reads from.++ ``aggregation_fn`` is a ClickHouse conditional aggregate (``argMinIf`` or+ ``argMaxIf``). ``step_indexes`` are 1-based funnel step columns (``step_1``+ is the first metric step; ``step_0`` is the exposure step and is never an+ attribution target).+ """++ aggregation_fn: str+ step_indexes: list[int]+++@frozen+class ExperimentBreakdownAttributionContext:+ """Breakdown configuration and pure attribution resolution for a metric.++ Holds no AST. The builder takes this context and constructs the query.+ """++ breakdowns: tuple[Breakdown, ...]+ metric: ExperimentFunnelMetric++ def has_breakdown(self) -> bool:+ return len(self.breakdowns) > 0++ def has_data_warehouse_step(self) -> bool:+ return any(isinstance(step, ExperimentDataWarehouseNode) for step in self.metric.series)++ def is_single_step(self) -> bool:+ return len(self.metric.series) == 1++ def breakdown_aliases(self) -> list[str]:+ return [f"breakdown_value_{i + 1}" for i in range(len(self.breakdowns))]++ def breakdown_limit(self) -> int:+ """Top-N cap on breakdown values; mirrors insights' default of BREAKDOWN_VALUES_LIMIT."""+ breakdown_filter = self.metric.breakdownFilter+ limit = breakdown_filter.breakdown_limit if breakdown_filter else None+ return limit or BREAKDOWN_VALUES_LIMIT++ def resolve_attribution(self) -> AttributionResolution:+ """Resolve the aggregation function and step columns for the attribution mode.++ In experiment funnels ``step_0`` is the exposure event and the metric series+ events are ``step_1 .. step_N`` (N = len(series)). The breakdown is read off+ the metric events, so attribution targets those steps, never the exposure step.++ - first_touch: argMinIf across all metric steps (step_1..step_N), so the value comes+ from the user's earliest metric event, whichever step it matched.+ - last_touch: argMaxIf across all metric steps, so a user who drops off before the last+ step still gets the value from their latest metric event.+ - step (ordered): argMinIf from ``breakdownAttributionValue`` (0-indexed into the+ series, mapped to the corresponding step column step_{value + 1}).+ - step (unordered, "Any step"): argMinIf across all metric step columns, since an+ unordered funnel has no fixed step position and any matching step attributes.++ all_events is not a single-value attribution: it buckets a unit under every distinct+ breakdown value it emitted, so it needs a group-array fan-out this resolver cannot+ express. It is rejected until the builder supports that fan-out.+ """+ attribution = self.metric.breakdownAttributionType or BreakdownAttributionType.FIRST_TOUCH+ num_metric_steps = len(self.metric.series)+ is_unordered = self.metric.funnel_order_type == StepOrderValue.UNORDERED+ all_metric_steps = list(range(1, num_metric_steps + 1))++ if attribution == BreakdownAttributionType.ALL_EVENTS:+ raise NotImplementedError("all-events breakdown attribution is not yet supported for experiment funnels")+ if attribution == BreakdownAttributionType.LAST_TOUCH:+ return AttributionResolution(aggregation_fn="argMaxIf", step_indexes=all_metric_steps)+ if attribution == BreakdownAttributionType.STEP:+ if is_unordered:+ # "Any step": the stored index is ignored, attribute from the earliest matching step.+ return AttributionResolution(aggregation_fn="argMinIf", step_indexes=all_metric_steps)+ series_index = self.metric.breakdownAttributionValue+ if series_index is None or series_index < 0 or series_index >= num_metric_steps:+ raise ValueError(+ f"breakdownAttributionValue must be in [0, {num_metric_steps - 1}] for step attribution, "+ f"got {series_index}"+ )+ return AttributionResolution(aggregation_fn="argMinIf", step_indexes=[series_index + 1])+ return AttributionResolution(aggregation_fn="argMinIf", step_indexes=all_metric_steps)diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_breakdown_attribution_query_builder.py b/products/experiments/backend/hogql_queries/test/test_experiment_breakdown_attribution_query_builder.pynew file mode 100644index 000000000000..14b5132978a7--- /dev/null+++ b/products/experiments/backend/hogql_queries/test/test_experiment_breakdown_attribution_query_builder.py@@ -0,0 +1,312 @@+from parameterized import parameterized++from posthog.schema import (+ Breakdown,+ BreakdownAttributionType,+ BreakdownFilter,+ EventsNode,+ ExperimentDataWarehouseNode,+ ExperimentFunnelMetric,+ StepOrderValue,+)++from posthog.hogql import ast+from posthog.hogql.parser import parse_select++from posthog.hogql_queries.utils.breakdowns import BREAKDOWN_NULL_STRING_LABEL++from products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEY+from products.experiments.backend.hogql_queries.experiment_breakdown_attribution_query_builder import (+ ExperimentBreakdownAttributionQueryBuilder,+)+from products.experiments.backend.hogql_queries.experiment_breakdown_attribution_query_context import (+ ExperimentBreakdownAttributionContext,+)+++def _funnel_metric(+ attribution: BreakdownAttributionType | None = None,+ attribution_value: int | None = None,+ num_steps: int = 2,+ funnel_order_type: StepOrderValue | None = None,+ properties: tuple[str, ...] = ("$browser",),+ breakdown_limit: int | None = None,+) -> ExperimentFunnelMetric:+ return ExperimentFunnelMetric(+ series=[EventsNode(event=f"step_{i}") for i in range(num_steps)],+ breakdownFilter=BreakdownFilter(+ breakdowns=[Breakdown(property=p) for p in properties], breakdown_limit=breakdown_limit+ ),+ breakdownAttributionType=attribution,+ breakdownAttributionValue=attribution_value,+ funnel_order_type=funnel_order_type,+ )+++def _builder(metric: ExperimentFunnelMetric) -> ExperimentBreakdownAttributionQueryBuilder:+ assert metric.breakdownFilter is not None and metric.breakdownFilter.breakdowns is not None+ context = ExperimentBreakdownAttributionContext(+ breakdowns=tuple(metric.breakdownFilter.breakdowns),+ metric=metric,+ )+ return ExperimentBreakdownAttributionQueryBuilder(context)+++def _unwrap_attribution(expr: ast.Expr) -> ast.Call:+ """Users with no attribution event get the null label, so the attribution agg is nested in an+ ``if(countIf(cond) = 0, null_label, agg(...))``. Return the inner argMin/argMax call."""+ assert isinstance(expr, ast.Call) and expr.name == "if"+ attributed = expr.args[2]+ assert isinstance(attributed, ast.Call)+ return attributed+++def _split_condition(condition: ast.Expr) -> tuple[ast.Expr, ast.Expr]:+ """Attribution matches a step AND requires a breakdown value. Return both halves."""+ assert isinstance(condition, ast.And) and len(condition.exprs) == 2+ return condition.exprs[0], condition.exprs[1]+++def _compared_fields(condition: ast.Expr) -> set[str]:+ """Field names on the left of a comparison, or of an OR of comparisons."""+ comparisons = condition.exprs if isinstance(condition, ast.Or) else [condition]+ return {+ c.left.chain[0]+ for c in comparisons+ if isinstance(c, ast.CompareOperation) and isinstance(c.left, ast.Field) and isinstance(c.left.chain[0], str)+ }+++def _optimized_query() -> ast.SelectQuery:+ query = parse_select("SELECT variant FROM base_events AS entity_metrics")+ assert isinstance(query, ast.SelectQuery)+ base = parse_select("SELECT variant, entity_id, timestamp, step_0, step_1, step_2 FROM events")+ em = parse_select("SELECT variant FROM base_events GROUP BY variant")+ assert isinstance(base, ast.SelectQuery) and isinstance(em, ast.SelectQuery)+ query.ctes = {+ "base_events": ast.CTE(name="base_events", expr=base, cte_type="subquery"),+ "entity_metrics": ast.CTE(name="entity_metrics", expr=em, cte_type="subquery"),+ }+ return query+++def _entity_metrics_aliases(query: ast.SelectQuery) -> dict[str, ast.Expr]:+ assert query.ctes is not None+ cte = query.ctes["entity_metrics"]+ assert isinstance(cte, ast.CTE) and isinstance(cte.expr, ast.SelectQuery)+ return {c.alias: c.expr for c in cte.expr.select if isinstance(c, ast.Alias)}+++class TestExperimentBreakdownAttributionQueryBuilder:+ # step_0 is the exposure step; metric series events are step_1..step_N. First and last touch+ # read across every metric step, so a user who never reached the last step still gets the value+ # from their earliest or latest metric event instead of falling into the null bucket.+ @parameterized.expand(+ [+ ("first_touch", BreakdownAttributionType.FIRST_TOUCH, None, "argMinIf", {"step_1", "step_2"}),+ ("last_touch", BreakdownAttributionType.LAST_TOUCH, None, "argMaxIf", {"step_1", "step_2"}),+ ("step_series_0", BreakdownAttributionType.STEP, 0, "argMinIf", {"step_1"}),+ ("step_series_1", BreakdownAttributionType.STEP, 1, "argMinIf", {"step_2"}),+ ("default_none", None, None, "argMinIf", {"step_1", "step_2"}),+ ]+ )+ def test_optimized_attribution_modes(self, _name, attribution, value, expected_agg, expected_steps):+ metric = _funnel_metric(attribution=attribution, attribution_value=value, num_steps=2)+ builder = _builder(metric)+ query = _optimized_query()++ builder.inject_funnel_breakdown_columns_optimized(query)++ expr = _unwrap_attribution(_entity_metrics_aliases(query)["breakdown_value_1"])+ assert expr.name == expected_agg+ # Ordering on timestamp alone lets tied events be picked per column, so a user's breakdown+ # values could come from different rows. The uuid makes the pick the same for every column.+ assert expr.args[1] == ast.Tuple(exprs=[ast.Field(chain=["timestamp"]), ast.Field(chain=["uuid"])])+ steps, _ = _split_condition(expr.args[2])+ assert _compared_fields(steps) == expected_steps++ def test_unattributed_users_get_null_label_not_empty_string(self):+ # argMinIf over zero matching rows returns "", which the UI labels "None" like the null+ # label but counts as its own bucket, so it must map to the null label instead.+ metric = _funnel_metric(attribution=BreakdownAttributionType.FIRST_TOUCH, num_steps=2)+ builder = _builder(metric)+ query = _optimized_query()++ builder.inject_funnel_breakdown_columns_optimized(query)++ expr = _entity_metrics_aliases(query)["breakdown_value_1"]+ assert isinstance(expr, ast.Call) and expr.name == "if"+ null_label = expr.args[1]+ assert isinstance(null_label, ast.Constant) and null_label.value == BREAKDOWN_NULL_STRING_LABEL++ def test_unordered_any_step_attributes_across_all_steps(self):+ # For unordered funnels "Any step" (step attribution) must match a metric event at any step,+ # not just step_1, or a user who completed through a later series event lands unattributed.+ metric = _funnel_metric(+ attribution=BreakdownAttributionType.STEP,+ attribution_value=0,+ num_steps=2,+ funnel_order_type=StepOrderValue.UNORDERED,+ )+ builder = _builder(metric)+ query = _optimized_query()++ builder.inject_funnel_breakdown_columns_optimized(query)++ steps, _ = _split_condition(_unwrap_attribution(_entity_metrics_aliases(query)["breakdown_value_1"]).args[2])+ assert _compared_fields(steps) == {"step_1", "step_2"}++ @parameterized.expand([("one_breakdown", ("$browser",)), ("two_breakdowns", ("$browser", "$os"))])+ def test_attribution_skips_events_without_a_breakdown_value(self, _name, properties):+ # The property is coalesced to the null label before attribution, so without this filter an+ # event missing the property would win on timestamp and hide a later event with a real+ # value. All aliases share one condition, so a user's values come from the same event.+ metric = _funnel_metric(attribution=BreakdownAttributionType.FIRST_TOUCH, properties=properties)+ builder = _builder(metric)+ query = _optimized_query()++ builder.inject_funnel_breakdown_columns_optimized(query)++ aliases = _entity_metrics_aliases(query)+ conditions = [+ _split_condition(_unwrap_attribution(aliases[f"breakdown_value_{i + 1}"]).args[2])[1]+ for i in range(len(properties))+ ]+ assert all(c == conditions[0] for c in conditions)+ shared = conditions[0]+ assert _compared_fields(shared) == {f"breakdown_value_{i + 1}" for i in range(len(properties))}+ comparisons = shared.exprs if isinstance(shared, ast.Or) else [shared]+ assert all(+ isinstance(c, ast.CompareOperation)+ and c.op == ast.CompareOperationOp.NotEq+ and isinstance(c.right, ast.Constant)+ and c.right.value == BREAKDOWN_NULL_STRING_LABEL+ for c in comparisons+ )++ def test_breakdown_read_from_metric_event_in_base_events(self):+ metric = _funnel_metric(attribution=BreakdownAttributionType.FIRST_TOUCH)+ builder = _builder(metric)+ query = _optimized_query()++ builder.inject_funnel_breakdown_columns_optimized(query)++ assert query.ctes is not None+ base_cte = query.ctes["base_events"]+ assert isinstance(base_cte, ast.CTE) and isinstance(base_cte.expr, ast.SelectQuery)+ base_columns = {c.alias: c.expr for c in base_cte.expr.select if isinstance(c, ast.Alias)}+ assert "breakdown_value_1" in base_columns+ # A property set to "" reads as no value: the UI labels it "None" like a missing property,+ # so leaving it distinct would split the no-value users across two identical rows.+ read = base_columns["breakdown_value_1"]+ assert isinstance(read, ast.Call) and read.name == "coalesce"+ assert isinstance(read.args[0], ast.Call) and read.args[0].name == "nullIf"+ empty, fallback = read.args[0].args[1], read.args[1]+ assert isinstance(empty, ast.Constant) and empty.value == ""+ assert isinstance(fallback, ast.Constant) and fallback.value == BREAKDOWN_NULL_STRING_LABEL++ def test_breakdown_added_to_final_select_and_group_by(self):+ metric = _funnel_metric()+ builder = _builder(metric)+ query = _optimized_query()++ builder.inject_funnel_breakdown_columns_optimized(query)++ select_aliases = [c.alias for c in query.select if isinstance(c, ast.Alias)]+ assert "breakdown_value_1" in select_aliases+ # The limit relabel groups by the output alias (the relabeled column), not the raw+ # entity_metrics column, so "Other" rows merge.+ assert query.group_by is not None+ assert ast.Field(chain=["breakdown_value_1"]) in query.group_by++ def test_final_breakdown_column_applies_top_n_other_relabel(self):+ metric = _funnel_metric(breakdown_limit=3)+ builder = _builder(metric)+ query = _optimized_query()++ builder.inject_funnel_breakdown_columns_optimized(query)++ final_alias = next(c for c in query.select if isinstance(c, ast.Alias) and c.alias == "breakdown_value_1")+ # if(<in top-N>, value, 'Other')+ assert isinstance(final_alias.expr, ast.Call)+ assert final_alias.expr.name == "if"+ in_top = final_alias.expr.args[0]+ assert isinstance(in_top, ast.CompareOperation)+ assert in_top.op == ast.CompareOperationOp.In+ assert isinstance(in_top.right, ast.SelectQuery)+ assert isinstance(in_top.right.limit, ast.Constant)+ assert in_top.right.limit.value == 3+ # count() DESC plus a breakdown-value tiebreak keeps the cutoff deterministic on ties+ assert in_top.right.order_by is not None+ assert [o.order for o in in_top.right.order_by] == ["DESC", "ASC"]+ # Rank only users who reach the result: a bucket of users the final SELECT or the runner+ # drops would otherwise take a top-N slot and then contribute no row.+ assert isinstance(in_top.right.where, ast.And)+ variant_present, not_multiple = in_top.right.where.exprs+ assert isinstance(variant_present, ast.Call) and variant_present.name == "notEmpty"+ assert isinstance(not_multiple, ast.CompareOperation)+ assert not_multiple.op == ast.CompareOperationOp.NotEq+ assert isinstance(not_multiple.right, ast.Constant) and not_multiple.right.value == MULTIPLE_VARIANT_KEY+ other = final_alias.expr.args[2]+ assert isinstance(other, ast.Constant)+ assert other.value == "$$_posthog_breakdown_other_$$"++ def test_step_attribution_out_of_range_raises(self):+ metric = _funnel_metric(attribution=BreakdownAttributionType.STEP, attribution_value=5, num_steps=2)+ builder = _builder(metric)+ query = _optimized_query()++ try:+ builder.inject_funnel_breakdown_columns_optimized(query)+ raise AssertionError("expected ValueError")+ except ValueError:+ pass++ def test_all_events_attribution_is_rejected(self):+ # all-events buckets a unit under every distinct breakdown value it emitted, so it needs a+ # group-array fan-out this resolver cannot express. Mapping it to first-touch would silently+ # collapse those buckets and report wrong conversion counts, so it must raise until supported.+ metric = _funnel_metric(attribution=BreakdownAttributionType.ALL_EVENTS, num_steps=2)+ builder = _builder(metric)+ query = _optimized_query()++ try:+ builder.inject_funnel_breakdown_columns_optimized(query)+ raise AssertionError("expected NotImplementedError")+ except NotImplementedError:+ pass++ def test_data_warehouse_step_with_breakdown_is_rejected(self):+ # A data-warehouse funnel step replaces the metric_events CTE with a UNION whose branches+ # carry no breakdown column, so a breakdown attributed from metric_events would reference a+ # column no branch produces and ClickHouse would fail on an unknown column. It must raise+ # until integration adds a real design for breakdowns on warehouse rows.+ metric = _funnel_metric(num_steps=2)+ metric.series[1] = ExperimentDataWarehouseNode(+ table_name="revenue_table",+ timestamp_field="purchase_date",+ data_warehouse_join_key="user_id",+ events_join_key="properties.$user_id",+ )+ builder = _builder(metric)+ query = _optimized_query()++ try:+ builder.inject_funnel_breakdown_columns(query)+ raise AssertionError("expected NotImplementedError")+ except NotImplementedError:+ pass++ def test_single_step_funnel_with_breakdown_is_rejected(self):+ # A user reaches a named bucket only by emitting the one step event, which is the same event+ # the funnel counts as the conversion, so every named bucket is 100% converted by+ # construction and the per-bucket rate carries no information. It must raise.+ metric = _funnel_metric(num_steps=1)+ builder = _builder(metric)+ query = _optimized_query()++ try:+ builder.inject_funnel_breakdown_columns_optimized(query)+ raise AssertionError("expected NotImplementedError")+ except NotImplementedError:+ pass