: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
fix(funnels): apply the breakdown limit to every non-cohort breakdown (#103589)
Thomas Obermüller53eb4293f7a6
diff --git a/products/product_analytics/backend/hogql_queries/funnels/funnel.py b/products/product_analytics/backend/hogql_queries/funnels/funnel.pyindex 81c4faeb2ca9..f630b651e46c 100644--- a/products/product_analytics/backend/hogql_queries/funnels/funnel.py+++ b/products/product_analytics/backend/hogql_queries/funnels/funnel.py@@ -241,11 +241,8 @@ class FunnelUDF(FunnelUDFMixin, FunnelBase):other_aggregation = "['Other']" if self._query_has_array_breakdown() else "'Other'"- use_breakdown_limit = self.context.breakdown and self.context.breakdownType in [- BreakdownType.PERSON,- BreakdownType.EVENT,- BreakdownType.GROUP,- ]+ # Cohort values stay integer cohort ids, which have no supertype with the string `Other`.+ use_breakdown_limit = bool(self.context.breakdown) and self.context.breakdownType != BreakdownType.COHORTfinal_prop = (f"if(row_number < {self.get_breakdown_limit()}, breakdown, {other_aggregation})"diff --git a/products/product_analytics/backend/hogql_queries/funnels/funnel_event_query.py b/products/product_analytics/backend/hogql_queries/funnels/funnel_event_query.pyindex 56eb3413a8bc..46f314df0caf 100644--- a/products/product_analytics/backend/hogql_queries/funnels/funnel_event_query.py+++ b/products/product_analytics/backend/hogql_queries/funnels/funnel_event_query.py@@ -47,6 +47,7 @@ from products.product_analytics.backend.hogql_queries.funnels.utils import (data_warehouse_config_key,entity_config_mismatch,get_breakdown_expr,+ to_breakdown_string,)@@ -437,6 +438,11 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):return ast.Or(exprs=step_conditions)def _get_breakdown_expr(self) -> ast.Expr:+ """Build the per-event breakdown value.++ Every branch except cohort must return string-typed values, because the step query+ replaces values past the breakdown limit with the string `Other`.+ """breakdown, breakdownType, breakdownFilter = (self.context.breakdown,self.context.breakdownType,@@ -478,14 +484,16 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):return get_breakdown_expr(breakdown, "session")elif breakdownType == "element":values = breakdown if isinstance(breakdown, list) else [breakdown]- return ast.Array(exprs=[element_property_key_to_breakdown_expr(str(value)) for value in values])+ return ast.Array(+ exprs=[to_breakdown_string(element_property_key_to_breakdown_expr(str(value))) for value in values]+ )elif breakdownType == "hogql" or breakdownType == "event_metadata":assert isinstance(breakdown, list)- exprs = [strip_user_aliases(parse_expr(str(value))) for value in breakdown]+ exprs = [to_breakdown_string(strip_user_aliases(parse_expr(str(value)))) for value in breakdown]return ast.Alias(alias="value", expr=ast.Array(exprs=exprs))elif breakdownType == "data_warehouse_person_property":assert isinstance(breakdown, str)- return ast.Field(chain=["person", *breakdown.split(".")])+ return to_breakdown_string(ast.Field(chain=["person", *breakdown.split(".")]))elif breakdownType == "data_warehouse":return get_breakdown_expr(breakdown, None)else:diff --git a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel.py b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel.pyindex 8a5a94df4360..67c991d059cc 100644--- a/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel.py+++ b/products/product_analytics/backend/hogql_queries/funnels/test/test_funnel.py@@ -4320,6 +4320,41 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):with self.assertRaises(QueryError):FunnelsQueryRunner(query=query, team=self.team).calculate()+ def test_element_breakdown_buckets_values_past_the_limit_as_other(self) -> None:+ for text, user_count in [("Continue", 5), ("Details", 4), ("Back", 2), ("Close", 1)]:+ for index in range(user_count):+ distinct_id = f"{text}-user-{index}"+ _create_person(team=self.team, distinct_ids=[distinct_id])+ _create_event(+ team=self.team,+ event="$autocapture",+ distinct_id=distinct_id,+ timestamp="2024-03-22T12:00:00Z",+ elements_chain=f'button:nth-child="1"nth-of-type="1"text="{text}"',+ )+ _create_event(+ team=self.team,+ event="completed",+ distinct_id=distinct_id,+ timestamp="2024-03-22T12:01:00Z",+ )++ query = FunnelsQuery(+ series=[EventsNode(event="$autocapture"), EventsNode(event="completed")],+ dateRange=DateRange(date_from="2024-03-22", date_to="2024-03-22"),+ breakdownFilter=BreakdownFilter(+ breakdown="text",+ breakdown_type=BreakdownType.ELEMENT,+ breakdown_limit=2,+ ),+ )+ results = FunnelsQueryRunner(query=query, team=self.team).calculate().results++ self.assertEqual(+ {steps[0]["breakdown_value"][0]: [step["count"] for step in steps] for steps in results},+ {"Continue": [5, 5], "Details": [4, 4], "Other": [3, 3]},+ )+def test_funnel_query_with_event_metadata_breakdown(self):_create_person(distinct_ids=[f"user_1"],diff --git a/products/product_analytics/backend/hogql_queries/funnels/utils.py b/products/product_analytics/backend/hogql_queries/funnels/utils.pyindex 452dde521667..d83c73cfb702 100644--- a/products/product_analytics/backend/hogql_queries/funnels/utils.py+++ b/products/product_analytics/backend/hogql_queries/funnels/utils.py@@ -65,6 +65,18 @@ def funnel_window_interval_unit_to_sql(raise ValidationError(f"{funnelWindowIntervalUnit} not supported")+def to_breakdown_string(expr: ast.Expr) -> ast.Expr:+ """Coerce a breakdown value to a non-null string.++ The funnel step query replaces values past the breakdown limit with the string `Other`, which+ has no supertype with a number, a UUID, or an enum.+ """+ return ast.Call(+ name="ifNull",+ args=[ast.Call(name="toString", args=[expr]), ast.Constant(value="")],+ )++def get_breakdown_expr(breakdowns: list[str | int] | str | int,properties_column: str | None,@@ -92,23 +104,11 @@ def get_breakdown_expr(raise ValueError("get_breakdown_expr: path_cleaning=True requires a team")if isinstance(breakdowns, str) or isinstance(breakdowns, int) or breakdowns is None:- return ast.Call(- name="ifNull",- args=[- ast.Call(name="toString", args=[make_field(breakdowns)]),- ast.Constant(value=""),- ],- )+ return to_breakdown_string(make_field(breakdowns))else:exprs = []for breakdown in breakdowns:- expr: ast.Expr = ast.Call(- name="ifNull",- args=[- ast.Call(name="toString", args=[make_field(breakdown)]),- ast.Constant(value=""),- ],- )+ expr: ast.Expr = to_breakdown_string(make_field(breakdown))if path_cleaning and team is not None:expr = apply_path_cleaning(expr, team)if normalize_url: