: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 path cleaning for event breakdowns (#61060)
Sam Penningtonf22f5d297a47
diff --git a/posthog/hogql_queries/insights/funnels/funnel_event_query.py b/posthog/hogql_queries/insights/funnels/funnel_event_query.pyindex e74aba1fe7e2..7ff59e602d95 100644--- a/posthog/hogql_queries/insights/funnels/funnel_event_query.py+++ b/posthog/hogql_queries/insights/funnels/funnel_event_query.py@@ -423,8 +423,13 @@ class FunnelEventQuery(DataWarehouseSchemaMixin):return get_breakdown_expr(breakdown, properties_column)elif breakdownType == "event":properties_column = "properties"- normalize_url = breakdownFilter.breakdown_normalize_url- return get_breakdown_expr(breakdown, properties_column, normalize_url=normalize_url)+ return get_breakdown_expr(+ breakdown,+ properties_column,+ normalize_url=breakdownFilter.breakdown_normalize_url,+ path_cleaning=breakdownFilter.breakdown_path_cleaning,+ team=self.context.team,+ )elif breakdownType == "cohort":if isinstance(breakdown, int):cohort_id = breakdowndiff --git a/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel_breakdowns_by_current_url.ambr b/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel_breakdowns_by_current_url.ambrindex a7b488871103..35e696fade95 100644--- a/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel_breakdowns_by_current_url.ambr+++ b/posthog/hogql_queries/insights/funnels/test/__snapshots__/test_funnel_breakdowns_by_current_url.ambr@@ -135,3 +135,139 @@use_hive_partitioning=0'''# ---+# name: TestFunnelBreakdownsByCurrentURL.test_breakdown_by_pathname_with_path_cleaning+ '''+ SELECT sum(step_1) AS step_1,+ sum(step_2) AS step_2,+ arrayMap(x -> if(isNaN(x), NULL, x), [avgArrayOrNull(step_1_conversion_times)])[1] AS step_1_average_conversion_time,+ arrayMap(x -> if(isNaN(x), NULL, x), [medianArrayOrNull(step_1_conversion_times)])[1] AS step_1_median_conversion_time,+ groupArray(row_number) AS row_number,+ final_prop AS final_prop+ FROM+ (SELECT countIf(ifNull(notEquals(bitAnd(steps_bitfield, 1), 0), 1)) AS step_1,+ countIf(ifNull(notEquals(bitAnd(steps_bitfield, 2), 0), 1)) AS step_2,+ groupArrayIf(timings[1], ifNull(greater(timings[1], 0), 0)) AS step_1_conversion_times,+ rowNumberInAllBlocks() AS row_number,+ if(ifNull(less(row_number, 100), 0), breakdown, ['Other']) AS final_prop+ FROM+ (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, arrayMap(x -> ifNull(x, ''), prop_basic), arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1)])))) AS events_array,+ argMinIf(prop_basic, timestamp, notEmpty(arrayFilter(x -> notEmpty(x), prop_basic))) AS prop,+ arrayJoin(aggregate_funnel_array(2, 1209600, 'first_touch', 'ordered', [if(empty(prop), [''], prop)], [], arrayFilter((x, x_before, x_after) -> not(and(ifNull(lessOrEquals(length(x.4), 1), 0), ifNull(equals(x.4, x_before.4), isNull(x.4)+ and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)+ and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)+ and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)+ and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,+ af_tuple.1 AS step_reached,+ plus(af_tuple.1, 1) AS steps,+ af_tuple.2 AS breakdown,+ af_tuple.3 AS timings,+ af_tuple.5 AS steps_bitfield,+ aggregation_target AS aggregation_target+ FROM+ (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,+ if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,+ e.uuid AS uuid,+ e.`$session_id` AS `$session_id`,+ e.`$window_id` AS `$window_id`,+ if(equals(e.event, 'watched movie'), 1, 0) AS step_0,+ if(equals(e.event, 'terminate funnel'), 1, 0) AS step_1,+ [if(empty(replaceRegexpOne(replaceRegexpAll(ifNull(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$pathname'), ''), 'null'), '^"|"$', '')), ''), '/home.*', '/cleaned-home'), '[\\/?#]*$', '')), '/', replaceRegexpOne(replaceRegexpAll(ifNull(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$pathname'), ''), 'null'), '^"|"$', '')), ''), '/home.*', '/cleaned-home'), '[\\/?#]*$', ''))] AS prop_basic,+ prop_basic AS prop+ FROM events AS e+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('terminate funnel', 'watched movie'))), or(ifNull(equals(step_0, 1), 0), ifNull(equals(step_1, 1), 0))))+ GROUP BY aggregation_target+ HAVING ifNull(greaterOrEquals(step_reached, 0), 0))+ GROUP BY breakdown+ ORDER BY step_2 DESC,+ step_1 DESC)+ GROUP BY final_prop+ ORDER BY step_2 DESC,+ step_1 DESC+ LIMIT 101 SETTINGS join_algorithm='auto',+ readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=23622320128,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---+# name: TestFunnelBreakdownsByCurrentURL.test_breakdown_by_pathname_with_path_cleaning_without_normalization+ '''+ SELECT sum(step_1) AS step_1,+ sum(step_2) AS step_2,+ arrayMap(x -> if(isNaN(x), NULL, x), [avgArrayOrNull(step_1_conversion_times)])[1] AS step_1_average_conversion_time,+ arrayMap(x -> if(isNaN(x), NULL, x), [medianArrayOrNull(step_1_conversion_times)])[1] AS step_1_median_conversion_time,+ groupArray(row_number) AS row_number,+ final_prop AS final_prop+ FROM+ (SELECT countIf(ifNull(notEquals(bitAnd(steps_bitfield, 1), 0), 1)) AS step_1,+ countIf(ifNull(notEquals(bitAnd(steps_bitfield, 2), 0), 1)) AS step_2,+ groupArrayIf(timings[1], ifNull(greater(timings[1], 0), 0)) AS step_1_conversion_times,+ rowNumberInAllBlocks() AS row_number,+ if(ifNull(less(row_number, 100), 0), breakdown, ['Other']) AS final_prop+ FROM+ (SELECT arraySort(t -> t.1, groupArray(tuple(accurateCastOrNull(timestamp, 'Float64'), uuid, arrayMap(x -> ifNull(x, ''), prop_basic), arrayFilter(x -> ifNull(notEquals(x, 0), 1), [multiply(1, step_0), multiply(2, step_1)])))) AS events_array,+ argMinIf(prop_basic, timestamp, notEmpty(arrayFilter(x -> notEmpty(x), prop_basic))) AS prop,+ arrayJoin(aggregate_funnel_array(2, 1209600, 'first_touch', 'ordered', [if(empty(prop), [''], prop)], [], arrayFilter((x, x_before, x_after) -> not(and(ifNull(lessOrEquals(length(x.4), 1), 0), ifNull(equals(x.4, x_before.4), isNull(x.4)+ and isNull(x_before.4)), ifNull(equals(x.4, x_after.4), isNull(x.4)+ and isNull(x_after.4)), ifNull(equals(x.3, x_before.3), isNull(x.3)+ and isNull(x_before.3)), ifNull(equals(x.3, x_after.3), isNull(x.3)+ and isNull(x_after.3)), ifNull(greater(x.1, x_before.1), 0), ifNull(less(x.1, x_after.1), 0))), events_array, arrayRotateRight(events_array, 1), arrayRotateLeft(events_array, 1)))) AS af_tuple,+ af_tuple.1 AS step_reached,+ plus(af_tuple.1, 1) AS steps,+ af_tuple.2 AS breakdown,+ af_tuple.3 AS timings,+ af_tuple.5 AS steps_bitfield,+ aggregation_target AS aggregation_target+ FROM+ (SELECT toTimeZone(e.timestamp, 'UTC') AS timestamp,+ if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id) AS aggregation_target,+ e.uuid AS uuid,+ e.`$session_id` AS `$session_id`,+ e.`$window_id` AS `$window_id`,+ if(equals(e.event, 'watched movie'), 1, 0) AS step_0,+ if(equals(e.event, 'terminate funnel'), 1, 0) AS step_1,+ [replaceRegexpAll(ifNull(toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, '$pathname'), ''), 'null'), '^"|"$', '')), ''), '/home.*', '/cleaned-home')] AS prop_basic,+ prop_basic AS prop+ FROM events AS e+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) AS person_id,+ person_distinct_id_overrides.distinct_id AS distinct_id+ FROM person_distinct_id_overrides+ WHERE equals(person_distinct_id_overrides.team_id, 99999)+ GROUP BY person_distinct_id_overrides.distinct_id+ HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('terminate funnel', 'watched movie'))), or(ifNull(equals(step_0, 1), 0), ifNull(equals(step_1, 1), 0))))+ GROUP BY aggregation_target+ HAVING ifNull(greaterOrEquals(step_reached, 0), 0))+ GROUP BY breakdown+ ORDER BY step_2 DESC,+ step_1 DESC)+ GROUP BY final_prop+ ORDER BY step_2 DESC,+ step_1 DESC+ LIMIT 101 SETTINGS join_algorithm='auto',+ readonly=2,+ max_execution_time=60,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=23622320128,+ transform_null_in=1,+ optimize_min_equality_disjunction_chain_length=4294967295,+ allow_experimental_join_condition=1,+ use_hive_partitioning=0+ '''+# ---diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_breakdowns_by_current_url.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_breakdowns_by_current_url.pyindex 71abb7cb2bb5..26053202f0ee 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel_breakdowns_by_current_url.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_breakdowns_by_current_url.py@@ -203,3 +203,103 @@ class TestFunnelBreakdownsByCurrentURL(ClickhouseTestMixin, APIBaseTest):],key=sk,)++ @snapshot_clickhouse_queries+ def test_breakdown_by_pathname_with_path_cleaning(self) -> None:+ self.team.path_cleaning_filters = [{"alias": "/cleaned-home", "regex": "/home.*"}]+ self.team.save()++ response = self._run(+ FunnelsQuery(+ series=[+ EventsNode(event="watched movie", name="watched movie"),+ EventsNode(event="terminate funnel", name="terminate funnel"),+ ],+ dateRange=DateRange(+ date_from="2020-01-02T00:00:00Z",+ date_to="2020-01-12T00:00:00Z",+ ),+ funnelsFilter=FunnelsFilter(),+ breakdownFilter=BreakdownFilter(+ breakdown="$pathname",+ breakdown_type="event",+ breakdown_normalize_url=True,+ breakdown_path_cleaning=True,+ breakdown_limit=100, # never have other+ ),+ )+ )++ actual = []+ for breakdown_value in response:+ for funnel_step in breakdown_value:+ actual.append(+ (+ funnel_step["name"],+ funnel_step["count"],+ funnel_step["breakdown"],+ )+ )++ sk = lambda x: (x[1], x[2][0], x[0])+ assert sorted(actual, key=sk) == sorted(+ [+ ("watched movie", 2, ["/"]),+ ("terminate funnel", 2, ["/"]),+ ("watched movie", 2, ["/cleaned-home"]),+ ("terminate funnel", 2, ["/cleaned-home"]),+ ],+ key=sk,+ )++ @snapshot_clickhouse_queries+ def test_breakdown_by_pathname_with_path_cleaning_without_normalization(self) -> None:+ # Path cleaning must apply on its own, not only when normalize_url is also enabled.+ self.team.path_cleaning_filters = [{"alias": "/cleaned-home", "regex": "/home.*"}]+ self.team.save()++ response = self._run(+ FunnelsQuery(+ series=[+ EventsNode(event="watched movie", name="watched movie"),+ EventsNode(event="terminate funnel", name="terminate funnel"),+ ],+ dateRange=DateRange(+ date_from="2020-01-02T00:00:00Z",+ date_to="2020-01-12T00:00:00Z",+ ),+ funnelsFilter=FunnelsFilter(),+ breakdownFilter=BreakdownFilter(+ breakdown="$pathname",+ breakdown_type="event",+ breakdown_normalize_url=False,+ breakdown_path_cleaning=True,+ breakdown_limit=100,+ ),+ )+ )++ actual = []+ for breakdown_value in response:+ for funnel_step in breakdown_value:+ actual.append(+ (+ funnel_step["name"],+ funnel_step["count"],+ funnel_step["breakdown"],+ )+ )++ sk = lambda x: (x[1], x[2][0], x[0])+ # The /home* variants collapse to /cleaned-home; the others keep their raw, un-normalized values.+ assert sorted(actual, key=sk) == sorted(+ [+ ("watched movie", 2, ["/cleaned-home"]),+ ("terminate funnel", 2, ["/cleaned-home"]),+ ("watched movie", 1, ["?"]),+ ("terminate funnel", 1, ["?"]),+ ("watched movie", 1, ["/"]),+ ("terminate funnel", 1, ["/"]),+ ],+ key=sk,+ )diff --git a/posthog/hogql_queries/insights/funnels/utils.py b/posthog/hogql_queries/insights/funnels/utils.pyindex a7558b4f8818..948de935342c 100644--- a/posthog/hogql_queries/insights/funnels/utils.py+++ b/posthog/hogql_queries/insights/funnels/utils.py@@ -12,8 +12,10 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.parser import parse_expr+from posthog.hogql.property import apply_path_cleaningfrom posthog.constants import FUNNEL_WINDOW_INTERVAL_TYPES+from posthog.models.team.team import Teamfrom posthog.types import FunnelEntityNode, FunnelExclusionEntityNode@@ -39,7 +41,11 @@ def funnel_window_interval_unit_to_sql(def get_breakdown_expr(- breakdowns: list[str | int] | str | int, properties_column: str | None, normalize_url: bool | None = False+ breakdowns: list[str | int] | str | int,+ properties_column: str | None,+ normalize_url: bool | None = False,+ path_cleaning: bool | None = False,+ team: Team | None = None,) -> ast.Expr:def make_field(breakdown: str | int) -> ast.Expr:if properties_column is None:@@ -48,6 +54,10 @@ def get_breakdown_expr(else:return ast.Field(chain=[*properties_column.split("."), breakdown])+ # Fail loudly rather than silently skipping cleaning if a caller forgets the team+ if path_cleaning and team is None:+ 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",@@ -66,6 +76,8 @@ def get_breakdown_expr(ast.Constant(value=""),],)+ if path_cleaning and team is not None:+ expr = apply_path_cleaning(expr, team)if normalize_url:regex = "[\\\\/?#]*$"expr = parse_expr(