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(phai): label funnel counts by their aggregation (#115203)

posthog[bot]d4e18db8174a
diff --git a/ee/hogai/context/insight/format/funnel.py b/ee/hogai/context/insight/format/funnel.py
index 92da32875899..80c163318fe3 100644
--- a/ee/hogai/context/insight/format/funnel.py
+++ b/ee/hogai/context/insight/format/funnel.py
@@ -1,4 +1,6 @@
+import re
from datetime import datetime
+from enum import Enum
from typing import Any, cast
from posthog.schema import (
@@ -9,11 +11,13 @@ from posthog.schema import (
DateRange,
EventsNode,
FunnelsDataWarehouseNode,
+ FunnelsFilter,
FunnelsQuery,
FunnelStepReference,
FunnelVizType,
)
+from posthog.dataclasses import frozen
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.models import Team
@@ -28,6 +32,18 @@ from .utils import (
strip_datetime_seconds,
)
+SESSION_ID_EXPRESSIONS = {"properties.$session_id", "$session_id"}
+# Only a short property path goes into the LLM context, so a saved expression cannot carry free-form text.
+DISPLAYABLE_EXPRESSION_RE = re.compile(r"[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*")
+DISPLAYABLE_EXPRESSION_MAX_LENGTH = 100
+
+
+@frozen
+class FunnelAggregation:
+ count_label: str
+ distribution_label: str
+ unit: str
+
class FunnelResultsFormatter:
"""
@@ -101,9 +117,10 @@ class FunnelResultsFormatter:
else:
matrixes.append(self._format_steps_series(cast(list[dict], results)))
- conversion_type_hint = 'Conversion and drop-off rates are calculated in overall. For example, "Conversion rate: 9%" means that 9% of users from the first step completed the funnel.'
+ unit = self._aggregation.unit
+ conversion_type_hint = f'Conversion and drop-off rates are calculated in overall. For example, "Conversion rate: 9%" means that 9% of {unit} from the first step completed the funnel.'
if self._step_reference == FunnelStepReference.PREVIOUS:
- conversion_type_hint = "Conversion and drop-off rates are relative to the previous steps. For example, 'Conversion rate: 90%' means that 90% of users from the previous step completed the funnel."
+ conversion_type_hint = f"Conversion and drop-off rates are relative to the previous steps. For example, 'Conversion rate: 90%' means that 90% of {unit} from the previous step completed the funnel."
joined_matrixes = "\n\n".join(matrixes)
return f"{self._format_time_range()}\n\n{joined_matrixes}\n\n{conversion_type_hint}"
@@ -113,13 +130,14 @@ class FunnelResultsFormatter:
if not isinstance(results, dict) or len(results) == 0:
return "No data recorded for this time period."
+ aggregation = self._aggregation
matrix: list[list[Any]] = [
- ["Average time to convert", "User distribution"],
+ ["Average time to convert", aggregation.distribution_label],
]
for series in results.get("bins") or []:
matrix.append([format_duration(series[0]), format_percentage(series[1])])
- hint = "The user distribution is the percentage of users who completed the funnel in the given period."
+ hint = f"The {aggregation.distribution_label.lower()} is the percentage of {aggregation.unit} who completed the funnel in the given period."
return f"{self._format_time_range()}\n\nEvents: {self._format_filter_series_label()}\n{format_matrix(matrix)}\n\n{hint}"
def _format_trends(self) -> str:
@@ -144,10 +162,50 @@ class FunnelResultsFormatter:
viz_type = self._query.funnelsFilter.funnelVizType
return viz_type
+ @property
+ def _aggregation(self) -> FunnelAggregation:
+ funnels_filter = self._query.funnelsFilter
+ if isinstance(funnels_filter, FunnelsFilter) and funnels_filter.customAggregationTarget:
+ # Data warehouse steps count rows by each node's aggregation_target_field, not by person.
+ return FunnelAggregation(
+ count_label="Total entity count", distribution_label="Entity distribution", unit="entities"
+ )
+ # Group aggregation takes precedence over a HogQL expression, the same as in the funnel query runner.
+ if self._query.aggregation_group_type_index is not None:
+ return FunnelAggregation(
+ count_label=f"Total group count (group type index {self._query.aggregation_group_type_index})",
+ distribution_label="Group distribution",
+ unit="groups",
+ )
+ hogql = self._query.funnelsFilter.funnelAggregateByHogQL if self._query.funnelsFilter else None
+ if isinstance(hogql, Enum):
+ hogql = hogql.value
+ if not hogql or hogql == "person_id":
+ return FunnelAggregation(
+ count_label="Total person count", distribution_label="User distribution", unit="users"
+ )
+ if hogql in SESSION_ID_EXPRESSIONS:
+ return FunnelAggregation(
+ count_label=f"Total session count (aggregated by {hogql})",
+ distribution_label="Session distribution",
+ unit="sessions",
+ )
+ if len(hogql) <= DISPLAYABLE_EXPRESSION_MAX_LENGTH and DISPLAYABLE_EXPRESSION_RE.fullmatch(hogql):
+ return FunnelAggregation(
+ count_label=f"Total unique value count (aggregated by {hogql})",
+ distribution_label="Value distribution",
+ unit=f"unique values of {hogql}",
+ )
+ return FunnelAggregation(
+ count_label="Total unique value count (aggregated by a custom HogQL expression)",
+ distribution_label="Value distribution",
+ unit="unique values of the custom HogQL expression",
+ )
+
def _format_steps_series(self, results: list[dict[str, Any]]) -> str:
matrix: list[list[Any]] = [
["Metric"],
- ["Total person count"],
+ [self._aggregation.count_label],
["Conversion rate"],
["Dropoff rate"],
["Average conversion time"],
diff --git a/ee/hogai/context/insight/format/test/test_funnel.py b/ee/hogai/context/insight/format/test/test_funnel.py
index 3be13e25dc60..02df85fc16ff 100644
--- a/ee/hogai/context/insight/format/test/test_funnel.py
+++ b/ee/hogai/context/insight/format/test/test_funnel.py
@@ -11,6 +11,11 @@ from posthog.schema import (
AssistantFunnelsEventsNode,
AssistantFunnelsFilter,
AssistantFunnelsQuery,
+ EventsNode,
+ FunnelAggregateByHogQL,
+ FunnelsDataWarehouseNode,
+ FunnelsFilter,
+ FunnelsQuery,
FunnelStepReference,
FunnelVizType,
)
@@ -219,6 +224,92 @@ class TestFunnelResultsFormatter(BaseTest):
'Date range: 2025-01-31 00:00:00 to 2025-02-07 23:59:59 (UTC)\n\n---au\nMetric|$pageview|signup\nTotal person count|5|2\nConversion rate|100%|40%\nDropoff rate|0%|60%\nAverage conversion time|-|10s\nMedian conversion time|-|11s\n\n---us\nMetric|$pageview|signup\nTotal person count|5|2\nConversion rate|100%|40%\nDropoff rate|0%|60%\nAverage conversion time|-|10s\nMedian conversion time|-|11s\n\nConversion and drop-off rates are calculated in overall. For example, "Conversion rate: 9%" means that 9% of users from the first step completed the funnel.',
)
+ @parameterized.expand(
+ [
+ ("person_default", None, None, "Total person count", "users"),
+ ("person_id_expression", "person_id", None, "Total person count", "users"),
+ (
+ "session_expression",
+ "properties.$session_id",
+ None,
+ "Total session count (aggregated by properties.$session_id)",
+ "sessions",
+ ),
+ ("group", None, 1, "Total group count (group type index 1)", "groups"),
+ (
+ "group_wins_over_expression",
+ "properties.$session_id",
+ 0,
+ "Total group count (group type index 0)",
+ "groups",
+ ),
+ (
+ "custom_expression",
+ "properties.account_id",
+ None,
+ "Total unique value count (aggregated by properties.account_id)",
+ "unique values of properties.account_id",
+ ),
+ (
+ "custom_expression_not_a_property_path",
+ "concat(a,\n'x')||b",
+ None,
+ "Total unique value count (aggregated by a custom HogQL expression)",
+ "unique values of the custom HogQL expression",
+ ),
+ ]
+ )
+ def test_funnel_steps_count_label_follows_aggregation(
+ self, _name: str, hogql: str | None, group_type_index: int | None, count_label: str, unit: str
+ ):
+ query = FunnelsQuery(
+ series=[EventsNode(event="$pageview"), EventsNode(event="signup")],
+ aggregation_group_type_index=group_type_index,
+ funnelsFilter=FunnelsFilter(funnelAggregateByHogQL=hogql),
+ )
+ results = [
+ {"name": "$pageview", "count": 5, "average_conversion_time": None, "median_conversion_time": None},
+ {"name": "signup", "count": 2, "average_conversion_time": 10, "median_conversion_time": 11},
+ ]
+ output = FunnelResultsFormatter(query, results, self.team, datetime.now()).format()
+ self.assertIn(f"\n{count_label}|5|2\n", output)
+ self.assertIn(f"means that 9% of {unit} from the first step completed the funnel.", output)
+
+ def test_funnel_steps_count_label_for_custom_data_warehouse_target(self):
+ warehouse_step = {
+ "table_name": "opportunities",
+ "id_field": "id",
+ "timestamp_field": "created_at",
+ "aggregation_target_field": "account_id",
+ }
+ query = FunnelsQuery(
+ series=[
+ FunnelsDataWarehouseNode(id="opportunities", name="created", **warehouse_step),
+ FunnelsDataWarehouseNode(id="opportunities", name="won", **warehouse_step),
+ ],
+ funnelsFilter=FunnelsFilter(customAggregationTarget=True),
+ )
+ results = [
+ {"name": "created", "count": 5, "average_conversion_time": None, "median_conversion_time": None},
+ {"name": "won", "count": 2, "average_conversion_time": 10, "median_conversion_time": 11},
+ ]
+ output = FunnelResultsFormatter(query, results, self.team, datetime.now()).format()
+ self.assertIn("\nTotal entity count|5|2\n", output)
+ self.assertIn("means that 9% of entities from the first step completed the funnel.", output)
+
+ def test_assistant_funnel_session_aggregation(self):
+ query = AssistantFunnelsQuery(
+ series=[AssistantFunnelsEventsNode(event="$pageview"), AssistantFunnelsEventsNode(event="signup")],
+ funnelsFilter=AssistantFunnelsFilter(
+ funnelAggregateByHogQL=FunnelAggregateByHogQL.PROPERTIES__SESSION_ID,
+ funnelVizType=FunnelVizType.TIME_TO_CONVERT,
+ ),
+ )
+ results = {"average_conversion_time": 600, "bins": [[600, 1]]}
+ output = FunnelResultsFormatter(query, results, self.team, datetime.now()).format()
+ self.assertIn("Average time to convert|Session distribution\n10m|100%", output)
+ self.assertIn("The session distribution is the percentage of sessions who completed the funnel", output)
+
def test_funnels_time_to_convert(self):
query = AssistantFunnelsQuery(
series=[
diff --git a/ee/hogai/context/insight/prompts.py b/ee/hogai/context/insight/prompts.py
index 282dcdb3e4e1..074265d50a36 100644
--- a/ee/hogai/context/insight/prompts.py
+++ b/ee/hogai/context/insight/prompts.py
@@ -76,7 +76,7 @@ Here is the generated HogQL (a PostHog's subset of ClickHouse SQL) query used to
""".strip()
FUNNEL_STEPS_EXAMPLE_PROMPT = """
-You are given a table with the results of a funnel query. Values are separated by the pipe character "|" and rows are separated by newlines. The first column is the metric name, and the rest are the values for each metric. The first row is the header row with series names received from the query. Rows can be separated by a line with "---", indicating a series with a breakdown. For example, `---control` indicates that the series is for the value `control`.
+You are given a table with the results of a funnel query. Values are separated by the pipe character "|" and rows are separated by newlines. The first column is the metric name, and the rest are the values for each metric. The first row is the header row with series names received from the query. Rows can be separated by a line with "---", indicating a series with a breakdown. For example, `---control` indicates that the series is for the value `control`. The count row names what the funnel counts: persons, groups, sessions, or unique values of a custom HogQL expression.
Example:
```