: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(funnels): support element property breakdowns (#103431)
Paul D'Ambra667f7f8a7a54
diff --git a/docs/internal/taxonomic-filter-search.md b/docs/internal/taxonomic-filter-search.mdindex fa62d7d759af..f3b6afd74766 100644--- a/docs/internal/taxonomic-filter-search.md+++ b/docs/internal/taxonomic-filter-search.md@@ -27,6 +27,14 @@ Opening an event picker that offers Actions loads the list; later opens reuse thWhen an insight series picker opens on Suggested series, the current selection is the first and selected item. All events follows it.The classic popover unmounts after its close transition and starts with a fresh search when reopened.+## Element breakdowns++Trends and funnels offer element text, tag name, and href in the Elements category and suggested filters.+These breakdowns use values from the autocapture element chain.+Text and tag name use the first matching value in the chain. Href uses the first href.+CSS selectors remain available as property filters, but not as breakdowns.+Other insight types exclude element breakdown suggestions.+## Typing and renderingThe legacy picker debounces API searches for 500 ms after the last keystroke, including while the initial response is loading.diff --git a/frontend/src/scenes/insights/filters/BreakdownFilter/TaxonomicBreakdownPopover.tsx b/frontend/src/scenes/insights/filters/BreakdownFilter/TaxonomicBreakdownPopover.tsxindex dd0a53095ba5..69e94ddd149c 100644--- a/frontend/src/scenes/insights/filters/BreakdownFilter/TaxonomicBreakdownPopover.tsx+++ b/frontend/src/scenes/insights/filters/BreakdownFilter/TaxonomicBreakdownPopover.tsx@@ -40,6 +40,7 @@ export const TaxonomicBreakdownPopover = ({hasOnlyDataWarehouseSeries,dataWarehouseSeriesTableNames,isTrends,+ isFunnels,} = useValues(insightVizDataLogic(insightProps))useMountedLogic(actionsModel({@@ -94,9 +95,7 @@ export const TaxonomicBreakdownPopover = ({TaxonomicFilterGroupType.PersonProperties,TaxonomicFilterGroupType.EventFeatureFlags,TaxonomicFilterGroupType.EventMetadata,- // Element breakdowns read the autocapture elements chain, which only trends knows- // how to break down. Funnels raise for breakdown types outside their own list.- ...(isTrends ? [TaxonomicFilterGroupType.Elements] : []),+ ...(isTrends || isFunnels ? [TaxonomicFilterGroupType.Elements] : []),...groupsTaxonomicTypes,TaxonomicFilterGroupType.CohortsWithAllUsers,...(includeSessions ? [TaxonomicFilterGroupType.SessionProperties] : []),@@ -108,11 +107,10 @@ export const TaxonomicBreakdownPopover = ({// A selector filter is a regex over the whole elements chain, so no per-event breakdown// value can agree with it. Hide it in breakdowns only; property filters still offer it.- // Outside trends, element breakdowns are not supported at all, so hide every element- // property, including the suggested rows, or the click applies a breakdown the backend- // then rejects.+ // Hide element suggestions for insight types that cannot use element breakdowns.const excludedElementBreakdownProperties = {- [TaxonomicFilterGroupType.Elements]: isTrends ? ['selector'] : ['selector', 'text', 'href', 'tag_name'],+ [TaxonomicFilterGroupType.Elements]:+ isTrends || isFunnels ? ['selector'] : ['selector', 'text', 'href', 'tag_name'],}return (diff --git a/frontend/src/scenes/insights/filters/BreakdownFilter/taxonomicBreakdownFilterLogic.test.ts b/frontend/src/scenes/insights/filters/BreakdownFilter/taxonomicBreakdownFilterLogic.test.tsindex bbbd89e7133a..822f9b71f7d7 100644--- a/frontend/src/scenes/insights/filters/BreakdownFilter/taxonomicBreakdownFilterLogic.test.ts+++ b/frontend/src/scenes/insights/filters/BreakdownFilter/taxonomicBreakdownFilterLogic.test.ts@@ -69,8 +69,8 @@ describe('taxonomicBreakdownFilterLogic', () => {})})- it('sets breakdown for autocapture elements', async () => {- logic = taxonomicBreakdownFilterLogic(makeProps({ breakdownFilter: {} }))+ it.each([true, false])('sets breakdown for autocapture elements with isTrends=%s', async (isTrends) => {+ logic = taxonomicBreakdownFilterLogic(makeProps({ breakdownFilter: {}, isTrends, isFunnels: !isTrends }))logic.mount()propertyDefinitionsModel.actions.updatePropertyDefinitions({'event/text': {@@ -87,14 +87,11 @@ describe('taxonomicBreakdownFilterLogic', () => {logic.actions.addBreakdown('text', group)}).toFinishListeners()- expect(updateBreakdownFilter).toHaveBeenCalledWith({- breakdowns: [- {- property: 'text',- type: 'element',- },- ],- })+ expect(updateBreakdownFilter).toHaveBeenCalledWith(+ isTrends+ ? { breakdowns: [{ property: 'text', type: 'element' }] }+ : { breakdown: 'text', breakdown_type: 'element' }+ )})it('sets breakdown for cohorts', async () => {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 f153605640be..56eb3413a8bc 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@@ -25,7 +25,7 @@ from posthog.hogql.database.models import (UUIDDatabaseField,)from posthog.hogql.parser import parse_expr-from posthog.hogql.property import action_to_expr, property_to_expr+from posthog.hogql.property import action_to_expr, element_property_key_to_breakdown_expr, property_to_exprfrom posthog.clickhouse.materialized_columns import ColumnNamefrom posthog.clickhouse.query_tagging import tag_contains_user_hogql@@ -476,6 +476,9 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):return get_breakdown_expr(breakdown, properties_column)elif breakdownType == "session":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])elif breakdownType == "hogql" or breakdownType == "event_metadata":assert isinstance(breakdown, list)exprs = [strip_user_aliases(parse_expr(str(value))) for value in breakdown]diff --git a/products/product_analytics/backend/hogql_queries/funnels/funnel_query_context.py b/products/product_analytics/backend/hogql_queries/funnels/funnel_query_context.pyindex 049e7d33a41c..59c0bfea0367 100644--- a/products/product_analytics/backend/hogql_queries/funnels/funnel_query_context.py+++ b/products/product_analytics/backend/hogql_queries/funnels/funnel_query_context.py@@ -85,6 +85,7 @@ class FunnelQueryContext(QueryContext):"person","event","event_metadata",+ "element","hogql","session",None,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 e69a72e152f4..8a5a94df4360 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@@ -49,6 +49,7 @@ from posthog.schema import ()from posthog.hogql.database.database import Database+from posthog.hogql.errors import QueryErrorfrom posthog.hogql.modifiers import create_default_modifiers_for_teamfrom posthog.api.instance_settings import get_instance_setting@@ -4258,6 +4259,67 @@ class TestFOSSFunnelUDF(ClickhouseTestMixin, APIBaseTest):self.assertEqual(results[0][1]["breakdown_value"], ["test'123"])self.assertEqual(results[0][1]["count"], 1)+ @parameterized.expand(+ [+ ("text", {"Continue": [2, 1], "Details": [1, 1], "": [2, 1]}),+ ("tag_name", {"button": [2, 1], "a": [1, 1], "div": [1, 1], "": [1, 0]}),+ ("href", {"/details": [1, 1], "": [4, 2]}),+ ]+ )+ def test_breakdown_by_element_property(self, breakdown: str, expected: dict[str, list[int]]) -> None:+ button_chain = 'button:nth-child="1"nth-of-type="1"text="Continue";div:text="Container"'+ link_chain = 'a:href="/details"nth-child="2"nth-of-type="1"text="Details";div:text="Container"'+ for index, (elements_chain, converts) in enumerate(+ [+ (button_chain, True),+ (button_chain, False),+ (link_chain, True),+ ('div:nth-child="0"nth-of-type="0"', True),+ ("", False),+ ]+ ):+ distinct_id = f"element-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=elements_chain,+ )+ if converts:+ _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=breakdown, breakdown_type=BreakdownType.ELEMENT),+ )+ results = FunnelsQueryRunner(query=query, team=self.team).calculate().results++ self.assertEqual(+ {+ steps[0]["breakdown_value"][0] if steps[0]["breakdown_value"] else "": [step["count"] for step in steps]+ for steps in results+ },+ expected,+ )++ def test_element_breakdown_with_integer_value_raises_query_error(self) -> None:+ query = FunnelsQuery(+ series=[EventsNode(event="$autocapture"), EventsNode(event="completed")],+ dateRange=DateRange(date_from="2024-03-22", date_to="2024-03-22"),+ breakdownFilter=BreakdownFilter(breakdown=5, breakdown_type=BreakdownType.ELEMENT),+ )++ with self.assertRaises(QueryError):+ FunnelsQueryRunner(query=query, team=self.team).calculate()+def test_funnel_query_with_event_metadata_breakdown(self):_create_person(distinct_ids=[f"user_1"],