: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): stop correlation analysis from crashing on funnel insights (#67432)
posthog[bot]465f79f0f82c
diff --git a/frontend/src/scenes/funnels/funnelCorrelationLogic.ts b/frontend/src/scenes/funnels/funnelCorrelationLogic.tsindex 6293808e7e54..f5cb97f23310 100644--- a/frontend/src/scenes/funnels/funnelCorrelationLogic.ts+++ b/frontend/src/scenes/funnels/funnelCorrelationLogic.ts@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'import { lemonToast } from '@posthog/lemon-ui'-import api from 'lib/api'+import api, { ApiError } from 'lib/api'import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'import { teamLogic } from 'scenes/teamLogic'@@ -70,8 +70,11 @@ export const funnelCorrelationLogic = kea<funnelCorrelationLogicType>([result_type: FunnelCorrelationResultsType.Events,})) as FunnelCorrelation[],}- } catch {- lemonToast.error('Failed to load correlation results', { toastId: 'funnel-correlation-error' })+ } catch (error) {+ const detail = error instanceof ApiError ? error.detail : null+ lemonToast.error(detail || 'Failed to load correlation results', {+ toastId: 'funnel-correlation-error',+ })return { events: [] }}},diff --git a/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.py b/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.pyindex f16392937a25..0e0478039f5e 100644--- a/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.py+++ b/posthog/hogql_queries/insights/funnels/funnel_correlation_query_runner.py@@ -16,6 +16,7 @@ from posthog.schema import (FunnelCorrelationResult,FunnelCorrelationResultsType,FunnelsActorsQuery,+ FunnelsDataWarehouseNode,FunnelsQuery,HogQLQueryModifiers,HogQLQueryResponse,@@ -206,6 +207,16 @@ class FunnelCorrelationQueryRunner(AnalyticsQueryRunner[FunnelCorrelationResponsresults=FunnelCorrelationResult(events=[], skewed=False), modifiers=self.modifiers)+ if self._uses_data_warehouse_series():+ # Correlation joins the events table onto the funnel actors on person_id, but a+ # data-warehouse funnel aggregates actors by a warehouse column (coerced to a+ # string id), so there is nothing on the events table to correlate against and+ # the join would fail on a UUID/String type mismatch. Return empty rather than+ # raising — correlation is a secondary panel and shouldn't crash the insight.+ return FunnelCorrelationResponse(+ results=FunnelCorrelationResult(events=[], skewed=False), modifiers=self.modifiers+ )+events, skewed_totals, hogql, response = self._calculate_internal()return FunnelCorrelationResponse(@@ -237,13 +248,23 @@ class FunnelCorrelationQueryRunner(AnalyticsQueryRunner[FunnelCorrelationResponsmodifiers=self.modifiers,limit_context=self.limit_context,)- assert response.results+ if not response.results:+ # An empty funnel yields no rows for the property/event-property correlation+ # queries. Nothing to correlate — return empty rather than raising.+ return [], True, hogql, response# Get the total success/failure counts from the resultsresults = [result for result in response.results if result[0] != self.TOTAL_IDENTIFIER]- _, success_total, failure_total = next(- result for result in response.results if result[0] == self.TOTAL_IDENTIFIER+ totals_row = next(+ (result for result in response.results if result[0] == self.TOTAL_IDENTIFIER),+ None,)+ if totals_row is None:+ # No totals row means the funnel matched no actors — the property and+ # event-property correlation queries arrayJoin over the actors CTE, so an empty+ # funnel produces no rows at all (including no totals). Nothing to correlate.+ return [], True, hogql, response+ _, success_total, failure_total = totals_row# Add a little structure, and keep it close to the query definition so it's# obvious what's going on with result indices.@@ -873,6 +894,14 @@ class FunnelCorrelationQueryRunner(AnalyticsQueryRunner[FunnelCorrelationResponsdef _get_aggregation_join_query(self):if self.funnels_query.aggregation_group_type_index is None:+ # When the funnel aggregates by a custom HogQL expression, funnel_actors.actor_id+ # holds that value rather than a person UUID, so joining persons.id (UUID) against+ # it mismatches types and fails with "no supertype for types UUID, String". Coerce+ # both sides to string so the join runs — it simply won't match persons, which is+ # expected for a non-person aggregation (the events-side join is coerced the same+ # way in _get_aggregation_target_join_query).+ if self._hogql_aggregation_expr() is not None:+ return "JOIN (SELECT id, properties as person_props FROM persons) persons ON toString(persons.id) = toString(funnel_actors.actor_id)"return f"JOIN (SELECT id, properties as person_props FROM persons) persons ON persons.id = funnel_actors.actor_id"else:group_type_index = self.funnels_query.aggregation_group_type_index@@ -936,6 +965,9 @@ class FunnelCorrelationQueryRunner(AnalyticsQueryRunner[FunnelCorrelationResponsreturn ast.Alias(alias="prop", expr=ast.Call(name="arrayJoin", args=[prop_array]))+ def _uses_data_warehouse_series(self) -> bool:+ return any(isinstance(entity, FunnelsDataWarehouseNode) for entity in self.funnels_query.series)+def _get_funnel_step_names(self) -> list[str]:events: set[str] = set()for entity in self.funnels_query.series:diff --git a/posthog/hogql_queries/insights/funnels/test/test_funnel_correlation.py b/posthog/hogql_queries/insights/funnels/test/test_funnel_correlation.pyindex e7ff7f5ebe28..34a39de15955 100644--- a/posthog/hogql_queries/insights/funnels/test/test_funnel_correlation.py+++ b/posthog/hogql_queries/insights/funnels/test/test_funnel_correlation.py@@ -13,6 +13,7 @@ from posthog.test.base import ()from unittest import skip+from parameterized import parameterizedfrom rest_framework.exceptions import ValidationErrorfrom posthog.schema import (@@ -24,6 +25,7 @@ from posthog.schema import (FunnelCorrelationQuery,FunnelCorrelationResultsType,FunnelsActorsQuery,+ FunnelsDataWarehouseNode,FunnelsFilter,FunnelsQuery,GroupPropertyFilter,@@ -172,6 +174,93 @@ class TestClickhouseFunnelCorrelation(ClickhouseTestMixin, APIBaseTest):with self.assertRaises(Exception):self._get_events_for_query(query)+ def test_funnel_correlation_with_properties_and_hogql_aggregation(self):+ # Property correlation joins funnel_actors onto the persons table on actor_id. When+ # the funnel aggregates by a HogQL expression, actor_id holds that value (a string)+ # rather than a person UUID, so the join used to fail with "no supertype for types+ # UUID, String". It must now run without raising rather than crashing the panel.+ # Every actor converts here, so failure_total is 0 and the runner short-circuits to [].+ 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"),+ )++ for i in range(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}"},+ )+ _create_event(+ team=self.team,+ event="paid",+ distinct_id=f"user_{i}",+ timestamp="2020-01-04T14:00:00Z",+ properties={"session_id": f"session_{i}"},+ )+ flush_persons_and_events()++ result, _ = self._get_events_for_query(+ query,+ funnelCorrelationType=FunnelCorrelationResultsType.PROPERTIES,+ funnelCorrelationNames=["$browser"],+ )+ self.assertEqual(result, [])++ @parameterized.expand(+ [+ ("properties", FunnelCorrelationResultsType.PROPERTIES, {"funnelCorrelationNames": ["$browser"]}),+ (+ "event_with_properties",+ FunnelCorrelationResultsType.EVENT_WITH_PROPERTIES,+ {"funnelCorrelationEventNames": ["rick"]},+ ),+ ]+ )+ def test_correlation_on_empty_funnel_returns_empty(self, _name, correlation_type, kwargs):+ # A funnel matching no actors produces zero rows for the property and event-property+ # correlation queries (they arrayJoin over the actors CTE), so there's no totals row.+ # This used to raise StopIteration / AssertionError; it should return empty instead.+ query = FunnelsQuery(+ series=[EventsNode(event="user signed up"), EventsNode(event="paid")],+ dateRange=DateRange(date_from="2020-01-01", date_to="2020-01-14"),+ )+ flush_persons_and_events()++ result, _ = self._get_events_for_query(query, funnelCorrelationType=correlation_type, **kwargs)+ self.assertEqual(result, [])++ def test_correlation_on_data_warehouse_funnel_returns_empty(self):+ # Correlation joins the events table onto the funnel actors on person_id, but a+ # data-warehouse funnel aggregates actors by a warehouse column (a string id), so+ # there's nothing to correlate against — it used to raise ValidationError ("Data+ # warehouse nodes are not supported here") or a UUID/String join error. It should+ # now return empty gracefully rather than crashing the panel.+ funnels_query = FunnelsQuery(+ series=[+ FunnelsDataWarehouseNode(+ id="stripe.invoices",+ id_field="id",+ table_name="stripe.invoices",+ timestamp_field="created_at",+ aggregation_target_field="customer_id",+ ),+ EventsNode(event="paid"),+ ],+ dateRange=DateRange(date_from="2020-01-01", date_to="2020-01-14"),+ )+ correlation_query = FunnelCorrelationQuery(+ source=FunnelsActorsQuery(source=funnels_query),+ funnelCorrelationType=FunnelCorrelationResultsType.EVENTS,+ )++ response = FunnelCorrelationQueryRunner(query=correlation_query, team=self.team)._calculate()+ self.assertEqual(response.results.events, [])+def test_basic_funnel_correlation_with_events(self):query = FunnelsQuery(series=[EventsNode(event="user signed up"), EventsNode(event="paid")],