Skip to content

: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.

fix(insights): fix funnel correlation join for HogQL aggregation (#58708)

Sam Pennington0aac75f671db
diff --git a/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.py b/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.py
index a59ab0d38069..328e2948bbb1 100644
--- a/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.py
+++ b/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.py
@@ -23,7 +23,7 @@ from posthog.schema import (
from posthog.hogql import ast
from posthog.hogql.constants import LimitContext
-from posthog.hogql.parser import parse_select
+from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.printer import to_printed_hogql
from posthog.hogql.property import property_to_expr
from posthog.hogql.query import execute_hogql_query
@@ -421,6 +421,7 @@ class FunnelCorrelationQueryRunner(AnalyticsQueryRunner[FunnelCorrelationRespons
"date_from": date_from,
"date_to": date_to,
"target_event": ast.Constant(value=target_event),
+ **self._aggregation_join_placeholders(),
},
)
assert isinstance(query, ast.SelectQuery)
@@ -552,6 +553,7 @@ class FunnelCorrelationQueryRunner(AnalyticsQueryRunner[FunnelCorrelationRespons
"date_to": date_to,
"exclude_event_names": exclude_event_names_ast,
"total_identifier": ast.Constant(value=self.TOTAL_IDENTIFIER),
+ **self._aggregation_join_placeholders(),
},
)
@@ -659,6 +661,7 @@ class FunnelCorrelationQueryRunner(AnalyticsQueryRunner[FunnelCorrelationRespons
if exclude_property_names
else {}
),
+ **self._aggregation_join_placeholders(),
},
)
@@ -830,11 +833,37 @@ class FunnelCorrelationQueryRunner(AnalyticsQueryRunner[FunnelCorrelationRespons
ON funnel_actors.actor_id = event.$group_{self.funnels_query.aggregation_group_type_index}
"""
- return (
- aggregation_group_join
- if self.funnels_query.aggregation_group_type_index is not None
- else aggregation_person_join
- )
+ if self.funnels_query.aggregation_group_type_index is not None:
+ return aggregation_group_join
+
+ # When the funnel aggregates by a custom HogQL expression, funnel_actors.actor_id
+ # holds that value — joining on event.person_id would mismatch types (UUID vs the
+ # expression's type). Join on the same expression instead, emitted as a placeholder
+ # parsed by _aggregation_join_placeholders so the user-controlled string can't
+ # inject query structure.
+ if self._hogql_aggregation_expr() is not None:
+ return """
+ JOIN funnel_actors
+ ON funnel_actors.actor_id = {aggregation_join_target}
+ """
+
+ return aggregation_person_join
+
+ def _hogql_aggregation_expr(self) -> ast.Expr | None:
+ """Parsed AST for funnelAggregateByHogQL when set and non-trivial, else None for
+ person/group aggregation. Parsing the user-controlled string into an AST keeps it a
+ single bounded expression — it cannot add joins or clauses to the query."""
+ if self.funnels_query.aggregation_group_type_index is not None:
+ return None
+ funnels_filter = self.funnels_query.funnelsFilter
+ aggregate_by_hogql = funnels_filter.funnelAggregateByHogQL if funnels_filter else None
+ if aggregate_by_hogql and aggregate_by_hogql != "person_id":
+ return parse_expr(aggregate_by_hogql)
+ return None
+
+ def _aggregation_join_placeholders(self) -> dict[str, ast.Expr]:
+ expr = self._hogql_aggregation_expr()
+ return {"aggregation_join_target": expr} if expr is not None else {}
def _get_aggregation_join_query(self):
if self.funnels_query.aggregation_group_type_index is None:
diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_correlation.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_correlation.py
index df9aa3f7fa92..daab3de0e433 100644
--- a/posthog/hogql_queries/insights/funnels/test/test_funnel_correlation.py
+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_correlation.py
@@ -105,6 +105,73 @@ class TestClickhouseFunnelCorrelation(ClickhouseTestMixin, APIBaseTest):
)
return [str(row[0]) for row in serialized_actors]
+ def test_funnel_correlation_with_events_and_hogql_aggregation(self):
+ # When the funnel aggregates by a custom HogQL expression, the correlation
+ # event join must use that expression — joining on event.person_id would
+ # mismatch types (UUID vs the string actor id) and fail the query.
+ query = FunnelsQuery(
+ series=[EventsNode(event="user signed up"), EventsNode(event="paid")],
+ dateRange=DateRange(date_from="2020-01-01", date_to="2020-01-14"),
+ funnelsFilter=FunnelsFilter(funnelAggregateByHogQL="properties.session_id"),
+ )
+
+ # Converting sessions (reach "paid") that also fire "positively_related".
+ for i in range(5):
+ _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)
+ _create_event(
+ team=self.team,
+ event="user signed up",
+ distinct_id=f"user_{i}",
+ timestamp="2020-01-02T14:00:00Z",
+ properties={"session_id": f"session_{i}"},
+ )
+ _create_event(
+ team=self.team,
+ event="positively_related",
+ distinct_id=f"user_{i}",
+ timestamp="2020-01-03T14:00:00Z",
+ properties={"session_id": f"session_{i}"},
+ )
+ _create_event(
+ team=self.team,
+ event="paid",
+ distinct_id=f"user_{i}",
+ timestamp="2020-01-04T14:00:00Z",
+ properties={"session_id": f"session_{i}"},
+ )
+
+ # Non-converting sessions (never reach "paid"), needed so odds ratios are
+ # computable rather than the totals being skewed to 100% conversion.
+ for i in range(5, 10):
+ _create_person(distinct_ids=[f"user_{i}"], team_id=self.team.pk)
+ _create_event(
+ team=self.team,
+ event="user signed up",
+ distinct_id=f"user_{i}",
+ timestamp="2020-01-02T14:00:00Z",
+ properties={"session_id": f"session_{i}"},
+ )
+
+ # Before the fix this raised TYPE_MISMATCH (joining event.person_id, a UUID,
+ # against the string actor id). The join must now run and actually match rows.
+ result, _ = self._get_events_for_query(query)
+ events = {item["event"]: item for item in result}
+ self.assertIn("positively_related", events)
+ self.assertEqual(events["positively_related"]["success_count"], 5)
+ self.assertEqual(events["positively_related"]["correlation_type"], "success")
+
+ def test_funnel_correlation_hogql_aggregation_rejects_injection(self):
+ # funnelAggregateByHogQL is user-controlled — a value that isn't a single
+ # bounded expression (e.g. an attempt to inject an extra JOIN) must be
+ # rejected by the parser, not interpolated into the query.
+ query = FunnelsQuery(
+ series=[EventsNode(event="user signed up"), EventsNode(event="paid")],
+ dateRange=DateRange(date_from="2020-01-01", date_to="2020-01-14"),
+ funnelsFilter=FunnelsFilter(funnelAggregateByHogQL="properties.session_id JOIN persons ON 1=1"),
+ )
+ with self.assertRaises(Exception):
+ self._get_events_for_query(query)
+
def test_basic_funnel_correlation_with_events(self):
query = FunnelsQuery(
series=[EventsNode(event="user signed up"), EventsNode(event="paid")],