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.

feat(hogql): add HogQL expression breakdowns to retention (#60853)

Christiaan Hendriksen816a6d73ff02
diff --git a/frontend/src/scenes/insights/filters/BreakdownFilter/TaxonomicBreakdownPopover.tsx b/frontend/src/scenes/insights/filters/BreakdownFilter/TaxonomicBreakdownPopover.tsx
index 65ec1545dbe9..f288cd71d641 100644
--- a/frontend/src/scenes/insights/filters/BreakdownFilter/TaxonomicBreakdownPopover.tsx
+++ b/frontend/src/scenes/insights/filters/BreakdownFilter/TaxonomicBreakdownPopover.tsx
@@ -50,6 +50,7 @@ export const TaxonomicBreakdownPopover = ({
TaxonomicFilterGroupType.EventFeatureFlags,
...groupsTaxonomicTypes,
TaxonomicFilterGroupType.CohortsWithAllUsers,
+ TaxonomicFilterGroupType.HogQLExpression,
TaxonomicFilterGroupType.DataWarehousePersonProperties,
]
} else {
diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py b/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py
index 2aaa8ad5694d..f3df9547ea96 100644
--- a/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py
+++ b/posthog/hogql_queries/insights/retention/test/test_retention_query_runner.py
@@ -19,6 +19,7 @@ from unittest.mock import MagicMock, patch
from django.test import override_settings
+from parameterized import parameterized
from rest_framework.exceptions import ValidationError
from posthog.schema import HogQLQueryModifiers, InCohortVia, RetentionQuery
@@ -4001,6 +4002,69 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixi
),
)
+ @parameterized.expand(
+ [
+ ("plain", "upper(properties.browser)"),
+ # The `AS` clause exercises strip_user_aliases: it must be dropped, not break the query.
+ ("with_alias", "upper(properties.browser) AS browser_upper"),
+ ]
+ )
+ def test_retention_with_breakdown_hogql_expression(self, _name: str, breakdown: str):
+ # upper(...) makes the buckets uppercased, which only happens if the expression
+ # is evaluated as SQL rather than treated as a property name.
+ _create_person(team_id=self.team.pk, distinct_ids=["person1"])
+ _create_person(team_id=self.team.pk, distinct_ids=["person2"])
+ _create_person(team_id=self.team.pk, distinct_ids=["person3"])
+ _create_person(team_id=self.team.pk, distinct_ids=["person4"])
+
+ _create_events(
+ self.team,
+ [
+ # Chrome cohort
+ ("person1", _date(0), {"browser": "Chrome"}), # Day 0
+ ("person1", _date(1), {"browser": "Chrome"}), # Day 1
+ ("person1", _date(3), {"browser": "Chrome"}), # Day 3
+ ("person3", _date(0), {"browser": "Chrome"}), # Day 0
+ ("person3", _date(2), {"browser": "Chrome"}), # Day 2
+ # Safari cohort
+ ("person2", _date(0), {"browser": "Safari"}), # Day 0
+ ("person2", _date(1), {"browser": "Safari"}), # Day 1
+ ("person2", _date(4), {"browser": "Safari"}), # Day 4
+ # Firefox cohort
+ ("person4", _date(0), {"browser": "Firefox"}), # Day 0
+ ("person4", _date(5), {"browser": "Firefox"}), # Day 5
+ ],
+ )
+
+ result = self.run_query(
+ query={
+ "dateRange": {"date_to": _date(5, hour=0)},
+ "retentionFilter": {
+ "totalIntervals": 6,
+ "period": "Day",
+ },
+ "breakdownFilter": {"breakdown": breakdown, "breakdown_type": "hogql"},
+ }
+ )
+
+ breakdown_values = {c.get("breakdown_value") for c in result}
+ self.assertEqual(breakdown_values, {"CHROME", "SAFARI", "FIREFOX"})
+
+ chrome_cohorts = pluck([c for c in result if c.get("breakdown_value") == "CHROME"], "values", "count")
+ self.assertEqual(
+ chrome_cohorts,
+ pad(
+ [
+ [2, 1, 1, 1, 0, 0],
+ [1, 0, 1, 0, 0, 0],
+ [1, 0, 0, 0, 0, 0],
+ [1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ ]
+ ),
+ )
+
def test_retention_with_breakdown_event_properties_and_minimum_occurrences(self):
"""Test retention with breakdown by event properties"""
_create_person(team_id=self.team.pk, distinct_ids=["person1"])
diff --git a/posthog/hogql_queries/insights/retention/utils.py b/posthog/hogql_queries/insights/retention/utils.py
index 38ac6b95c43f..f4e8e34a4447 100644
--- a/posthog/hogql_queries/insights/retention/utils.py
+++ b/posthog/hogql_queries/insights/retention/utils.py
@@ -1,6 +1,10 @@
from typing import cast
from posthog.hogql import ast
+from posthog.hogql.parser import parse_expr
+
+from posthog.clickhouse.query_tagging import tag_contains_user_hogql
+from posthog.hogql_queries.insights.utils.breakdowns import strip_user_aliases
def breakdown_extract_expr(property_name: str, breakdown_type: str, group_type_index: int | None = None) -> ast.Expr:
@@ -9,27 +13,35 @@ def breakdown_extract_expr(property_name: str, breakdown_type: str, group_type_i
# so we just return the cohort ID as a constant
return ast.Constant(value=str(property_name))
- if breakdown_type == "person":
- if property_name.startswith("$virt_"):
- # Virtual properties exist as expression fields on the persons table
- properties_chain = ["person", property_name]
- else:
- properties_chain = ["person", "properties", property_name]
- elif breakdown_type == "data_warehouse_person_property":
- properties_chain = ["person", *property_name.split(".")]
- elif breakdown_type == "group":
- if property_name.startswith("$virt_"):
- # Virtual properties exist as expression fields on the groups table
- properties_chain = [f"groups_{group_type_index}", property_name]
- else:
- properties_chain = [f"groups_{group_type_index}", "properties", property_name]
+ if breakdown_type == "hogql":
+ # The value is a raw HogQL expression, not a property name. Parse it and
+ # strip any display-only `AS` aliases the user added, which would otherwise
+ # break the surrounding toString()/argMinIf() wrapping.
+ tag_contains_user_hogql()
+ property_field: ast.Expr = strip_user_aliases(parse_expr(property_name))
else:
- # Default to event properties
- properties_chain = ["events", "properties", property_name]
+ if breakdown_type == "person":
+ if property_name.startswith("$virt_"):
+ # Virtual properties exist as expression fields on the persons table
+ properties_chain = ["person", property_name]
+ else:
+ properties_chain = ["person", "properties", property_name]
+ elif breakdown_type == "data_warehouse_person_property":
+ properties_chain = ["person", *property_name.split(".")]
+ elif breakdown_type == "group":
+ if property_name.startswith("$virt_"):
+ # Virtual properties exist as expression fields on the groups table
+ properties_chain = [f"groups_{group_type_index}", property_name]
+ else:
+ properties_chain = [f"groups_{group_type_index}", "properties", property_name]
+ else:
+ # Default to event properties
+ properties_chain = ["events", "properties", property_name]
+
+ property_field = ast.Field(chain=cast(list[str | int], properties_chain))
# Convert the property to String first, then handle NULLs.
# This avoids potential type mismatches (e.g., mixing Float64 and String for NULLs).
- property_field = ast.Field(chain=cast(list[str | int], properties_chain))
to_string_expr = ast.Call(name="toString", args=[property_field])
# Replace NULL with empty string ''
return ast.Call(name="ifNull", args=[to_string_expr, ast.Constant(value="")])