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(retention): close breakdown parity gap in DWH variant (#64530)

Thomas Obermüller7fbd16bed610
diff --git a/posthog/hogql_queries/insights/retention/retention_base_query_builder.py b/posthog/hogql_queries/insights/retention/retention_base_query_builder.py
index 4b2d424e2342..fd834220599d 100644
--- a/posthog/hogql_queries/insights/retention/retention_base_query_builder.py
+++ b/posthog/hogql_queries/insights/retention/retention_base_query_builder.py
@@ -148,25 +148,27 @@ class RetentionBaseQueryBuilder(ABC):
sample_value=ast.RatioExpr(left=ast.Constant(value=self.query.samplingFactor))
)
- def apply_breakdown(self, base_query: ast.SelectQuery) -> None:
+ def breakdown_extract_expr_for_query(self) -> ast.Expr | None:
if not self.query.breakdownFilter:
- return
-
- breakdown_expr = None
+ return None
if self.query.breakdownFilter.breakdowns:
# supporting only single breakdowns for now
breakdown = self.query.breakdownFilter.breakdowns[0]
- breakdown_expr = breakdown_extract_expr(
+ return breakdown_extract_expr(
str(breakdown.property), cast(str, breakdown.type), breakdown.group_type_index
)
- elif self.query.breakdownFilter.breakdown is not None:
- breakdown_expr = breakdown_extract_expr(
+ if self.query.breakdownFilter.breakdown is not None:
+ return breakdown_extract_expr(
cast(str, self.query.breakdownFilter.breakdown),
cast(str, self.query.breakdownFilter.breakdown_type),
self.query.breakdownFilter.breakdown_group_type_index,
)
+ return None
+
+ def apply_breakdown(self, base_query: ast.SelectQuery) -> None:
+ breakdown_expr = self.breakdown_extract_expr_for_query()
if breakdown_expr is None:
return
diff --git a/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py b/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py
index e4da41cc0021..9177b035ac89 100644
--- a/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py
+++ b/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py
@@ -9,7 +9,7 @@ from posthog.hogql.parser import parse_expr
from posthog.hogql.property import property_to_expr
from posthog.hogql_queries.insights.retention.retention_base_query_builder import RetentionBaseQueryBuilder
-from posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID
+from posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID, has_breakdown_filter
if TYPE_CHECKING:
from posthog.models import Team
@@ -79,6 +79,71 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
super().apply_sampling(base_query)
+ def apply_breakdown(self, base_query: ast.SelectQuery) -> None:
+ select_from = base_query.select_from
+ if select_from is not None and isinstance(select_from.table, ast.SelectSetQuery):
+ # Variant path: breakdown_value is resolved inside each UNION ALL arm and
+ # surfaced by build_base_query_dwh. The parent implementation appends
+ # events.*-referencing exprs to this outer query, where only the
+ # retention_events union is in scope, so it must not run here.
+ return
+
+ super().apply_breakdown(base_query)
+
+ def _breakdown_extract_targets_events_table(self) -> bool:
+ # event / event_metadata breakdowns hardcode events.properties.* and cannot be
+ # resolved against a data-warehouse-table arm. person / group / cohort /
+ # data_warehouse_person_property go via joins or a constant, and hogql is
+ # user-authored (it may legitimately reference the DWH table's own columns), so
+ # those are left to resolve normally.
+ breakdown_filter = self.query.breakdownFilter
+ if breakdown_filter is None:
+ return False
+ breakdown_type = (
+ breakdown_filter.breakdowns[0].type if breakdown_filter.breakdowns else breakdown_filter.breakdown_type
+ )
+ return breakdown_type in ("event", "event_metadata", None)
+
+ def _dwh_breakdown_value_arm_expr(
+ self,
+ entity: RetentionEntity,
+ breakdown_extract: ast.Expr,
+ timestamp_field: ast.Expr,
+ query_kind: Literal["start", "return"],
+ ) -> ast.Expr:
+ # An events-table-rooted extract can't be resolved against a data-warehouse-table
+ # arm; fall back to the empty bucket so the query still prints. The events arm (if
+ # any) supplies the real value, surfaced by the outer max().
+ if entity.type == EntityType.DATA_WAREHOUSE and self._breakdown_extract_targets_events_table():
+ return ast.Constant(value="")
+
+ if self.is_first_ever_occurrence:
+ # First-ever buckets each actor by the breakdown value on their earliest START
+ # event, resolved here via argMinIf(..., start_entity_expr_no_props). The events
+ # return arm can only do that when it shares the events source with the start
+ # entity. When the start entity is a DWH table, start_entity_expr_no_props
+ # collapses to a truthy constant, so on the events return arm argMinIf would
+ # instead read the actor's earliest RETURN event's value. Degrade to the empty
+ # bucket — the start (DWH) arm already emits "", so the outer max() yields "".
+ if (
+ query_kind == "return"
+ and self.start_event.type == EntityType.DATA_WAREHOUSE
+ and self._breakdown_extract_targets_events_table()
+ ):
+ return ast.Constant(value="")
+ # Bucket each actor by the breakdown value on their earliest start event.
+ return parse_expr(
+ "argMinIf({breakdown}, {timestamp}, {entity})",
+ {
+ "breakdown": breakdown_extract,
+ "timestamp": timestamp_field,
+ "entity": self.start_entity_expr_no_props,
+ },
+ )
+
+ # Recurring / first-time-matching: per-row value; the arm groups by it.
+ return breakdown_extract
+
# Nested fixed-interval query with data warehouse support.
# Intended as a drop-in replacement for the legacy query while we verify
# parity in production.
@@ -190,10 +255,23 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
if retention_value_expr:
select_fields.append(ast.Alias(alias="retention_value", expr=retention_value_expr))
+ group_by_fields: list[ast.Expr] = [ast.Field(chain=["actor_id"])]
+ if has_breakdown_filter(self.query.breakdownFilter):
+ if self.is_first_ever_occurrence:
+ # Each arm resolves the same single per-actor value; max() collapses the
+ # UNION rows deterministically and lets a real value win over the
+ # empty-bucket fallback on a data-warehouse-mixed series.
+ select_fields.append(ast.Alias(alias="breakdown_value", expr=parse_expr("max(breakdown_value)")))
+ else:
+ # Per-value rows from the arms; carry the value as a grouping key so the
+ # per-value cohort partitioning survives the outer aggregation.
+ select_fields.append(ast.Alias(alias="breakdown_value", expr=ast.Field(chain=["breakdown_value"])))
+ group_by_fields.append(ast.Field(chain=["breakdown_value"]))
+
base_query = ast.SelectQuery(
select=select_fields,
select_from=ast.JoinExpr(table=retention_events, alias="retention_events"),
- group_by=[ast.Field(chain=["actor_id"])],
+ group_by=group_by_fields,
having=ast.And(
exprs=[
(
@@ -319,11 +397,28 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
]
)
+ group_by_fields: list[ast.Expr] = [ast.Field(chain=["actor_id"])]
+
+ breakdown_extract = self.breakdown_extract_expr_for_query()
+ if breakdown_extract is not None:
+ select_fields.append(
+ ast.Alias(
+ alias="breakdown_value",
+ expr=self._dwh_breakdown_value_arm_expr(entity, breakdown_extract, timestamp_field, query_kind),
+ )
+ )
+ # Recurring / first-time-matching mirrors the legacy per-value cohort
+ # semantics: grouping each arm by breakdown_value filters its start and
+ # return aggregations to events carrying that value. First-ever resolves a
+ # single per-actor value (argMinIf), so it stays grouped by actor_id only.
+ if not self.is_first_ever_occurrence:
+ group_by_fields.append(ast.Field(chain=["breakdown_value"]))
+
return ast.SelectQuery(
select=select_fields,
select_from=ast.JoinExpr(table=ast.Field(chain=[table_name])),
where=where_expr,
- group_by=[ast.Field(chain=["actor_id"])],
+ group_by=group_by_fields,
)
def _first_time_start_event_timestamps_expr(self, entity: RetentionEntity) -> ast.Expr:
diff --git a/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_data_warehouse.ambr b/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_data_warehouse.ambr
index ffa51478df31..00bbb6f7a648 100644
--- a/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_data_warehouse.ambr
+++ b/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_data_warehouse.ambr
@@ -51,6 +51,59 @@
use_hive_partitioning=0
'''
# ---
+# name: TestRetentionDataWarehouse.test_retention_data_warehouse_breakdown_by_warehouse_column
+ '''
+ SELECT actor_activity.start_interval_index AS start_event_matching_interval,
+ actor_activity.intervals_from_base AS intervals_from_base,
+ actor_activity.breakdown_value AS breakdown_value,
+ count(DISTINCT actor_activity.actor_id) AS count
+ FROM
+ (SELECT retention_events.actor_id AS actor_id,
+ arrayFlatten(groupArray(retention_events.start_event_timestamps)) AS start_event_timestamps,
+ arrayFlatten(groupArray(retention_events.return_event_timestamps)) AS return_event_timestamps,
+ arrayMap(x -> plus(toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(x)), range(0, 5)) AS date_range,
+ arrayJoin(arrayFilter(x -> ifNull(greater(x, -1), 0), arrayMap((interval_index, interval_date, _start_event_timestamps) -> if(has(_start_event_timestamps, interval_date), minus(interval_index, 1), -1), arrayEnumerate(date_range), date_range, arrayResize([start_event_timestamps], length(date_range), start_event_timestamps)))) AS start_interval_index,
+ arrayJoin(arrayConcat(if(has(start_event_timestamps, date_range[plus(start_interval_index, 1)]), [0], []), arrayFilter(x -> ifNull(greater(x, 0), 0), arrayMap(_timestamp -> minus(indexOf(arraySlice(date_range, plus(start_interval_index, 1), 4), _timestamp), 1), return_event_timestamps)))) AS intervals_from_base,
+ retention_events.breakdown_value AS breakdown_value
+ FROM
+ (SELECT posthog_test_warehouse_activity_breakdown.person_id AS actor_id,
+ arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC')), and(equals(posthog_test_warehouse_activity_breakdown.activity_type, 'signed_up'), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC'), toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC')))))) AS start_event_timestamps,
+ [] AS return_event_timestamps,
+ ifNull(toString(posthog_test_warehouse_activity_breakdown.plan), '') AS breakdown_value
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse/posthog_test_warehouse_activity_breakdown/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `activity_type` String, `plan` String, `occurred_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_activity_breakdown
+ GROUP BY actor_id,
+ breakdown_value
+ UNION ALL SELECT posthog_test_warehouse_activity_breakdown.person_id AS actor_id,
+ [] AS start_event_timestamps,
+ arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC')), and(equals(posthog_test_warehouse_activity_breakdown.activity_type, 'renewed'), and(greaterOrEquals(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(posthog_test_warehouse_activity_breakdown.occurred_at, 'UTC'), toDateTime64('2025-01-06 00:00:00.000000', 6, 'UTC')))))) AS return_event_timestamps,
+ ifNull(toString(posthog_test_warehouse_activity_breakdown.plan), '') AS breakdown_value
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse/posthog_test_warehouse_activity_breakdown/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` Int64, `person_id` UUID, `activity_type` String, `plan` String, `occurred_at` DateTime64(3, \'UTC\')') AS posthog_test_warehouse_activity_breakdown
+ GROUP BY actor_id,
+ breakdown_value) AS retention_events
+ GROUP BY actor_id,
+ breakdown_value
+ HAVING 1) AS actor_activity
+ GROUP BY start_event_matching_interval,
+ intervals_from_base,
+ breakdown_value
+ ORDER BY breakdown_value ASC,
+ start_event_matching_interval ASC,
+ intervals_from_base ASC
+ LIMIT 100000 SETTINGS format_csv_allow_double_quotes=1,
+ readonly=2,
+ max_execution_time=600,
+ 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,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
# name: TestRetentionDataWarehouse.test_retention_data_warehouse_different_tables
'''
SELECT actor_activity.start_interval_index AS start_event_matching_interval,
diff --git a/posthog/hogql_queries/insights/retention/test/retention_base_query_variant.py b/posthog/hogql_queries/insights/retention/test/retention_base_query_variant.py
index 2218388c600b..307e263aa774 100644
--- a/posthog/hogql_queries/insights/retention/test/retention_base_query_variant.py
+++ b/posthog/hogql_queries/insights/retention/test/retention_base_query_variant.py
@@ -31,7 +31,7 @@ class RetentionBaseQueryVariantComparisonMixin:
with patch(RETENTION_BASE_QUERY_VARIANT_PATCH_PATH, return_value=False):
legacy_result = calculate(legacy_query)
- if not self.should_compare_retention_base_query_variants(query):
+ if not self.should_compare_retention_base_query_variants():
return legacy_result
dwh_variant_query = deepcopy(query)
@@ -41,7 +41,7 @@ class RetentionBaseQueryVariantComparisonMixin:
cast(Any, self).assertEqual(dwh_variant_result, legacy_result)
return legacy_result
- def should_compare_retention_base_query_variants(self, query: dict[str, Any]) -> bool:
+ def should_compare_retention_base_query_variants(self) -> bool:
test_method_name = getattr(self, "_testMethodName", "")
if test_method_name in self.retention_base_query_variant_comparison_excluded_tests:
return False
@@ -50,10 +50,4 @@ class RetentionBaseQueryVariantComparisonMixin:
if getattr(test_method, SKIP_RETENTION_BASE_QUERY_VARIANT_COMPARISON_ATTR, False):
return False
- return not self._query_uses_known_retention_base_query_variant_gap(query)
-
- def _query_uses_known_retention_base_query_variant_gap(self, query: dict[str, Any]) -> bool:
- if query.get("breakdownFilter"):
- return True
-
- return False
+ return True
diff --git a/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse.py b/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse.py
index bc3b40297c94..32e740ef3753 100644
--- a/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse.py
+++ b/posthog/hogql_queries/insights/retention/test/test_retention_data_warehouse.py
@@ -20,6 +20,8 @@ from posthog.hogql_queries.insights.retention.test.utils import pad, pluck
from posthog.models.group.util import create_group
from posthog.test.test_utils import create_group_type_mapping_without_created_at
+from products.cohorts.backend.models.cohort import Cohort
+from products.data_tools.backend.models.join import DataWarehouseJoin
from products.data_warehouse.backend.test.utils import create_data_warehouse_table_from_csv
TEST_BUCKET = "test_storage_bucket-posthog.hogql_queries.insights.retention.data_warehouse"
@@ -208,6 +210,214 @@ class TestRetentionDataWarehouse(ClickhouseTestMixin, APIBaseTest):
),
)
+ def _activity_breakdown_table(self) -> tuple[str, dict[str, str]]:
+ person_ids = self._create_people()
+ table = self._create_data_warehouse_table(
+ filename="warehouse_activity_breakdown.csv",
+ table_name="warehouse_activity_breakdown",
+ header=["id", "person_id", "activity_type", "plan", "occurred_at"],
+ rows=[
+ [1, person_ids["user-1"], "signed_up", "pro", "2025-01-01 09:00:00"],
+ [2, person_ids["user-2"], "signed_up", "free", "2025-01-01 10:00:00"],
+ [3, person_ids["user-1"], "renewed", "pro", "2025-01-02 12:00:00"],
+ [4, person_ids["user-2"], "renewed", "free", "2025-01-03 12:00:00"],
+ ],
+ table_columns={
+ "id": "Int64",
+ "person_id": "UUID",
+ "activity_type": "String",
+ "plan": "String",
+ "occurred_at": "DateTime64(3, 'UTC')",
+ },
+ )
+ return table, person_ids
+
+ def _activity_retention_filter(self, table: str) -> dict[str, Any]:
+ def entity(activity: str) -> dict[str, Any]:
+ return {
+ "id": table,
+ "name": table,
+ "type": "data_warehouse",
+ "table_name": table,
+ "aggregation_target_field": "person_id",
+ "timestamp_field": "occurred_at",
+ "properties": [
+ {"key": "activity_type", "value": activity, "operator": "exact", "type": "data_warehouse"}
+ ],
+ }
+
+ return {
+ "period": "Day",
+ "totalIntervals": 4,
+ "targetEntity": entity("signed_up"),
+ "returningEntity": entity("renewed"),
+ }
+
+ @snapshot_clickhouse_queries
+ def test_retention_data_warehouse_breakdown_by_warehouse_column(self):
+ table, _person_ids = self._activity_breakdown_table()
+
+ result = self.run_query(
+ query={
+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},
+ "retentionFilter": self._activity_retention_filter(table),
+ "breakdownFilter": {"breakdown": "plan", "breakdown_type": "hogql"},
+ }
+ )
+
+ self.assertEqual({c.get("breakdown_value") for c in result}, {"pro", "free"})
+ pro = pluck([c for c in result if c.get("breakdown_value") == "pro"], "values", "count")
+ free = pluck([c for c in result if c.get("breakdown_value") == "free"], "values", "count")
+ self.assertEqual(pro[0][:2], [1, 1]) # user-1 day 0, renewed day 1
+ self.assertEqual(free[0][:3], [1, 0, 1]) # user-2 day 0, renewed day 2
+
+ def test_retention_data_warehouse_breakdown_by_cohort(self):
+ table, person_ids = self._activity_breakdown_table()
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name="pro_users",
+ groups=[{"properties": [{"key": "id", "value": [person_ids["user-1"]], "type": "person"}]}],
+ )
+ cohort.calculate_people_ch(pending_version=0)
+
+ result = self.run_query(
+ query={
+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},
+ "retentionFilter": self._activity_retention_filter(table),
+ "breakdownFilter": {"breakdown_type": "cohort", "breakdown": [cohort.pk]},
+ }
+ )
+
+ self.assertEqual({c.get("breakdown_value") for c in result}, {str(cohort.pk)})
+
+ def test_retention_data_warehouse_breakdown_by_person_property(self):
+ # Person-property breakdown on a DWH series resolves through a configured
+ # DWH-table -> persons join; the variant passes the person.* extract through
+ # unchanged, so it composes once that join exists.
+ person_ids = {
+ "user-1": "00000000-0000-0000-0000-000000000001",
+ "user-2": "00000000-0000-0000-0000-000000000002",
+ }
+ _create_person(team=self.team, distinct_ids=["user-1"], uuid=person_ids["user-1"], properties={"plan": "pro"})
+ _create_person(team=self.team, distinct_ids=["user-2"], uuid=person_ids["user-2"], properties={"plan": "free"})
+ flush_persons_and_events()
+
+ table = self._create_data_warehouse_table(
+ filename="warehouse_activity_person_bd.csv",
+ table_name="warehouse_activity_person_bd",
+ header=["id", "person_id", "activity_type", "occurred_at"],
+ rows=[
+ [1, person_ids["user-1"], "signed_up", "2025-01-01 09:00:00"],
+ [2, person_ids["user-2"], "signed_up", "2025-01-01 10:00:00"],
+ [3, person_ids["user-1"], "renewed", "2025-01-02 12:00:00"],
+ [4, person_ids["user-2"], "renewed", "2025-01-03 12:00:00"],
+ ],
+ table_columns={
+ "id": "Int64",
+ "person_id": "UUID",
+ "activity_type": "String",
+ "occurred_at": "DateTime64(3, 'UTC')",
+ },
+ )
+ DataWarehouseJoin.objects.create(
+ team=self.team,
+ source_table_name=table,
+ source_table_key="person_id",
+ joining_table_name="persons",
+ joining_table_key="id",
+ field_name="person",
+ )
+
+ result = self.run_query(
+ query={
+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},
+ "retentionFilter": self._activity_retention_filter(table),
+ "breakdownFilter": {"breakdowns": [{"property": "plan", "type": "person"}]},
+ }
+ )
+
+ self.assertEqual({c.get("breakdown_value") for c in result}, {"pro", "free"})
+
+ def test_retention_data_warehouse_event_property_breakdown_degrades_to_empty_bucket(self):
+ table, _person_ids = self._activity_breakdown_table()
+
+ result = self.run_query(
+ query={
+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},
+ "retentionFilter": self._activity_retention_filter(table),
+ "breakdownFilter": {"breakdowns": [{"property": "category", "type": "event"}]},
+ }
+ )
+
+ # Event-property extracts can't resolve against a data-warehouse-table arm, so the
+ # whole series degrades to the empty bucket rather than raising.
+ self.assertEqual({c.get("breakdown_value") for c in result}, {""})
+
+ def test_retention_first_ever_dwh_start_events_return_event_breakdown_degrades_to_empty_bucket(self):
+ # Cross-table first-ever retention: data warehouse start entity, events return entity,
+ # breakdown on an events-table property. The first-ever breakdown value must come from
+ # the actor's first START event, but the start event lives in the DWH table and carries
+ # no $browser. The return arm therefore must NOT fall back to the return event's $browser
+ # (which would happen because start_entity_expr_no_props collapses to a truthy constant
+ # for a DWH start); every actor degrades to the empty bucket instead.
+ person_ids = self._create_people()
+ signups_table_name = self._create_data_warehouse_table(
+ filename="warehouse_first_ever_breakdown_signups.csv",
+ table_name="warehouse_first_ever_breakdown_signups",
+ header=["id", "person_id", "signed_up_at"],
+ rows=[
+ [1, person_ids["user-1"], "2025-01-01 09:00:00"],
+ [2, person_ids["user-2"], "2025-01-01 10:00:00"],
+ ],
+ table_columns={
+ "id": "Int64",
+ "person_id": "UUID",
+ "signed_up_at": "DateTime64(3, 'UTC')",
+ },
+ )
+
+ for distinct_id, browser in [("user-1", "Chrome"), ("user-2", "Firefox")]:
+ _create_event(
+ team=self.team,
+ event="$pageview",
+ distinct_id=distinct_id,
+ timestamp="2025-01-02T12:00:00Z",
+ properties={"$browser": browser},
+ )
+ flush_persons_and_events()
+
+ result = self.run_query(
+ query={
+ "dateRange": {"date_from": "2025-01-01T00:00:00Z", "date_to": "2025-01-05T00:00:00Z"},
+ "retentionFilter": {
+ "period": "Day",
+ "totalIntervals": 4,
+ "retentionType": "retention_first_ever_occurrence",
+ "targetEntity": {
+ "id": signups_table_name,
+ "name": signups_table_name,
+ "type": "data_warehouse",
+ "table_name": signups_table_name,
+ "aggregation_target_field": "person_id",
+ "timestamp_field": "signed_up_at",
+ },
+ "returningEntity": {"id": "$pageview", "name": "$pageview", "type": "events"},
+ },
+ "breakdownFilter": {"breakdowns": [{"property": "$browser", "type": "event"}]},
+ }
+ )
+
+ # The breakdown value isn't available on the DWH start side, so both actors land in the
+ # empty bucket — never bucketed by the return event's $browser (Chrome / Firefox).
+ self.assertEqual({c.get("breakdown_value") for c in result}, {""})
+
+ # Sanity: both users cohort day 0 and return day 1 — they still retain in the empty bucket.
+ empty_bucket = [c for c in result if c.get("breakdown_value") == ""]
+ self.assertEqual(
+ pluck(empty_bucket, "values", "count"),
+ pad([[2, 2, 0, 0], [0, 0, 0], [0, 0], [0], [0]]),
+ )
+
@parameterized.expand([("person",), ("group",)])
def test_retention_data_warehouse_actor_query_maps_back_to_actors(self, actor_type: str) -> None:
actor_ids = self._create_people() if actor_type == "person" else self._create_groups()
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 f05ccea81864..340cb938fbd1 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
@@ -3830,6 +3830,114 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixi
),
)
+ def test_dwh_variant_breakdown_event_property_per_value_parity(self):
+ # Tracer bullet: the variant must mirror the legacy per-value cohort semantics
+ # for event-property breakdowns. person1 starts "clothing" then returns with a
+ # mismatched "electronics" purchase, which must not retain within the clothing
+ # bucket — identically on both the legacy and the DWH-variant paths.
+ _create_person(team_id=self.team.pk, distinct_ids=["person1"])
+ _create_person(team_id=self.team.pk, distinct_ids=["person2"])
+
+ _create_events(
+ self.team,
+ [
+ ("person1", _date(0), {"category": "clothing", "$event_type": "signup"}),
+ ("person2", _date(0), {"category": "electronics", "$event_type": "signup"}),
+ ],
+ event="signup",
+ )
+ _create_events(
+ self.team,
+ [
+ ("person1", _date(1), {"category": "clothing", "$event_type": "purchase"}),
+ ("person1", _date(2), {"category": "electronics", "$event_type": "purchase"}),
+ ("person2", _date(1), {"category": "electronics", "$event_type": "purchase"}),
+ ],
+ event="purchase",
+ )
+ flush_persons_and_events()
+
+ result = self.run_query(
+ query={
+ "dateRange": {"date_to": _date(5, hour=0)},
+ "retentionFilter": {
+ "totalIntervals": 6,
+ "period": "Day",
+ "targetEntity": {"id": "signup", "type": "events"},
+ "returningEntity": {"id": "purchase", "type": "events"},
+ },
+ "breakdownFilter": {"breakdowns": [{"property": "category", "type": "event"}]},
+ }
+ )
+
+ # Clothing cohort retains person1 on day 1 (matching purchase) but not day 2
+ # (the electronics purchase belongs to a different bucket).
+ clothing = pluck([c for c in result if c.get("breakdown_value") == "clothing"], "values", "count")
+ self.assertEqual(clothing[0][:3], [1, 1, 0])
+
+ def test_dwh_variant_breakdown_first_ever_parity(self):
+ # First-ever buckets each actor by the breakdown value on their absolute-first
+ # start event (argMinIf). old_user's first app_opened predates the flag, so they
+ # belong only to the empty bucket — never the later "control" one — on both paths.
+ _create_person(team_id=self.team.pk, distinct_ids=["old_user"])
+ _create_person(team_id=self.team.pk, distinct_ids=["new_user"])
+
+ _create_events(self.team, [("old_user", _date(0))], "app_opened")
+ _create_events(self.team, [("old_user", _date(2), {"$feature/x": "control"})], "app_opened")
+ _create_events(self.team, [("old_user", _date(3), {"$feature/x": "control"})], "insight_viewed")
+ _create_events(self.team, [("new_user", _date(2), {"$feature/x": "variant"})], "app_opened")
+ _create_events(self.team, [("new_user", _date(3), {"$feature/x": "variant"})], "insight_viewed")
+ flush_persons_and_events()
+
+ result = self.run_query(
+ query={
+ "dateRange": {"date_from": _date(0), "date_to": _date(4)},
+ "retentionFilter": {
+ "period": "Day",
+ "totalIntervals": 4,
+ "retentionType": RETENTION_FIRST_EVER_OCCURRENCE,
+ "targetEntity": {"id": "app_opened", "name": "app_opened", "type": TREND_FILTER_TYPE_EVENTS},
+ "returningEntity": {"id": "insight_viewed", "name": "insight_viewed", "type": "events"},
+ },
+ "breakdownFilter": {"breakdown": "$feature/x", "breakdown_type": "event"},
+ }
+ )
+ # old_user anchors on their flag-less first event, so "control" never appears.
+ self.assertNotIn("control", {c.get("breakdown_value") for c in result})
+
+ def test_dwh_variant_breakdown_cohort_union_of_unions_parity(self):
+ # Cohort breakdown composes as a UNION ALL of per-cohort base queries, each
+ # itself a UNION ALL inside the variant. Both paths must agree on that shape.
+ _create_person(team_id=self.team.pk, distinct_ids=["p1"], properties={"name": "p1"})
+ _create_person(team_id=self.team.pk, distinct_ids=["p2"], properties={"name": "p2"})
+ cohort1 = Cohort.objects.create(
+ team=self.team,
+ name="c1",
+ groups=[{"properties": [{"key": "name", "value": "p1", "type": "person"}]}],
+ )
+ cohort2 = Cohort.objects.create(
+ team=self.team,
+ name="c2",
+ groups=[{"properties": [{"key": "name", "value": "p2", "type": "person"}]}],
+ )
+ cohort1.calculate_people_ch(pending_version=0)
+ cohort2.calculate_people_ch(pending_version=0)
+
+ _create_events(
+ self.team,
+ [("p1", _date(0)), ("p1", _date(1)), ("p2", _date(0)), ("p2", _date(2))],
+ )
+ flush_persons_and_events()
+
+ result = self.run_query(
+ query={
+ "dateRange": {"date_to": _date(4, hour=0)},
+ "retentionFilter": {"totalIntervals": 5, "period": "Day"},
+ "breakdownFilter": {"breakdown_type": "cohort", "breakdown": [cohort1.pk, cohort2.pk]},
+ }
+ )
+ self.assertEqual({c.get("breakdown_value") for c in result}, {str(cohort1.pk), str(cohort2.pk)})
+
@override_settings(IN_UNIT_TESTING=True)
def test_retention_with_breakdown_with_data_warehouse_person_properties(self):
table_name = self.setup_data_warehouse_person_properties()