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(retention): scope dwh variant scans to each arm's own entity (#74218)

Thomas Obermüller7b4fefa4aef5
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 6f3ce9ae9d27..ecf32347a9d2 100644
--- a/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py
+++ b/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py
@@ -119,17 +119,12 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
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()
- ):
+ # event, resolved via argMinIf(..., start_entity_expr_no_props). Only the start
+ # arm sees the start entity's rows (its WHERE is scoped to that entity), so the
+ # return arm always degrades to the empty bucket and the outer max() lets the
+ # start arm's value win: '' is the floor because breakdown_extract_expr wraps
+ # every value in ifNull(toString(...), '').
+ if query_kind == "return":
return ast.Constant(value="")
# Bucket each actor by the breakdown value on their earliest start event.
return parse_expr(
@@ -299,11 +294,39 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
actor_field = ast.Field(chain=[self.aggregation_target_events_column])
start_of_interval_sql = self.query_date_range.get_start_of_interval_hogql(source=timestamp_field)
- start_event_timestamps_expr = self._single_scan_start_event_timestamps_expr(
- timestamp_field, self.start_entity_expr
- )
+ two_arm = self._first_time_two_arm_scan()
+ if two_arm:
+ # The same lean two-arm shape build_base_query_legacy uses: each arm carries its own
+ # entity's filters (start unbounded for the anchor, return bounded to the window) and
+ # projects only actor/timestamp/tags, so granules the unbounded start arm matches never
+ # read the other entity's columns. The aggregates below swap entity matchers for the
+ # arms' role tags.
+ select_from = ast.JoinExpr(
+ table=ast.SelectSetQuery.create_from_queries(
+ [
+ self._first_time_scan_arm(self.start_event, "start"),
+ self._first_time_scan_arm(self.return_event, "return"),
+ ],
+ "UNION ALL",
+ ),
+ alias="events",
+ )
+ where: ast.Expr | None = None
+ return_condition: ast.Expr = parse_expr("events.is_return = 1")
+ else:
+ select_from = ast.JoinExpr(table=ast.Field(chain=["events"]))
+ where = ast.And(exprs=self._single_scan_filters())
+ return_condition = self.return_entity_expr
+
if self.is_first_occurrence_matching_filters or self.is_first_ever_occurrence:
- start_event_timestamps_expr = self._first_time_start_event_timestamps_expr(self.start_event)
+ anchor_expr = (
+ self._first_time_two_arm_anchor_expr() if two_arm else self.get_first_time_anchor_expr(self.start_event)
+ )
+ start_event_timestamps_expr = self._anchored_start_event_timestamps_expr(anchor_expr)
+ else:
+ start_event_timestamps_expr = self._single_scan_start_event_timestamps_expr(
+ timestamp_field, self.start_entity_expr
+ )
select_fields: list[ast.Expr] = [
ast.Alias(alias="actor_id", expr=actor_field),
@@ -318,7 +341,7 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
with_dupes_expr=self._get_dwh_return_timestamps_expr(
minimum_occurrences=self.minimum_occurrences,
start_of_interval_sql=start_of_interval_sql,
- return_entity_expr=self.return_entity_expr,
+ return_entity_expr=return_condition,
timestamp_field=timestamp_field,
),
)
@@ -328,7 +351,7 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
return_event_timestamps_expr = self._get_dwh_return_timestamps_expr(
minimum_occurrences=1,
start_of_interval_sql=start_of_interval_sql,
- return_entity_expr=self.return_entity_expr,
+ return_entity_expr=return_condition,
timestamp_field=timestamp_field,
)
@@ -348,8 +371,8 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
return ast.SelectQuery(
select=select_fields,
- select_from=ast.JoinExpr(table=ast.Field(chain=["events"])),
- where=ast.And(exprs=self._event_filters()),
+ select_from=select_from,
+ where=where,
group_by=[ast.Field(chain=["actor_id"])],
having=ast.And(
exprs=[
@@ -375,6 +398,53 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
),
)
+ def _single_scan_filters(self) -> list[ast.Expr]:
+ if not (self.is_first_occurrence_matching_filters or self.is_first_ever_occurrence):
+ return self._event_filters()
+
+ start_branch = self._first_time_role_branch(self.start_event, "start")
+ if start_branch is None:
+ # The start entity can't be narrowed (matches all events), so a per-role split can't
+ # shrink the scan below "everything since the beginning" anyway.
+ return self._event_filters()
+
+ # First-time modes can't bound the whole scan to the query window because the cohorting
+ # anchor needs the start entity's full history. But only the START side needs that: every
+ # return-side aggregate is window-conditioned. Filtering per role keeps the start entity
+ # unbounded while cutting the return entity to the window, instead of reading BOTH
+ # entities' full history (with an all-events return entity that was the entire events
+ # table). Shapes the two-arm scan can serve never get here; this covers the remainder the
+ # tag arms can't carry, chiefly breakdowns, which read event properties in the outer query.
+ filters = self.runner.events_where_clause(
+ self.is_first_occurrence_matching_filters, self.is_first_ever_occurrence, entities=[]
+ )
+ if self.runner.group_type_index is not None:
+ filters.append(self.runner._group_actor_filter())
+ filters.extend(self._cohort_breakdown_filters())
+
+ return_branch = self._first_time_role_branch(self.return_event, "return") or self.events_timestamp_filter()
+ filters.append(ast.Or(exprs=[start_branch, return_branch]))
+ return filters
+
+ def _first_time_role_branch(
+ self, entity: RetentionEntity, query_kind: Literal["start", "return"]
+ ) -> ast.Expr | None:
+ """Row filter for one role of the first-time single scan: the entity's own rows, bounded to
+ the query window on the return side. None when the entity matches all events and the branch
+ has no predicate to narrow by."""
+ exprs: list[ast.Expr] = []
+ event_name_filter = self.runner.event_name_filter([entity])
+ if event_name_filter is not None:
+ exprs.append(event_name_filter)
+ predicate = self._arm_scan_predicate(entity, query_kind)
+ if not (isinstance(predicate, ast.Constant) and predicate.value is True):
+ exprs.append(predicate)
+ if not exprs:
+ return None
+ if query_kind == "return":
+ exprs.append(self.events_timestamp_filter())
+ return ast.And(exprs=exprs) if len(exprs) > 1 else exprs[0]
+
def _single_scan_start_event_timestamps_expr(self, timestamp_field: ast.Expr, entity_expr: ast.Expr) -> ast.Expr:
# The recurring within-window set of start-interval timestamps, one pass over the source. Mirrors the
# inline aggregate the legacy path and the DWH start arm both build.
@@ -497,7 +567,7 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
table_name = entity.table_name if entity_is_dwh else "events"
assert table_name
- where_expr = None if entity_is_dwh else ast.And(exprs=self._event_filters())
+ where_expr = None if entity_is_dwh else ast.And(exprs=self._arm_where_filters(entity, query_kind))
select_fields: list[ast.Expr] = [
ast.Alias(alias="actor_id", expr=actor_field),
@@ -538,14 +608,17 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
)
def _first_time_start_event_timestamps_expr(self, entity: RetentionEntity) -> ast.Expr:
- # The variant subquery is already GROUP BY actor_id, so the polymorphic first-time anchor (a minIf)
- # resolves to one cohorting timestamp per actor. Emit that single bucketed interval when the anchor falls
+ return self._anchored_start_event_timestamps_expr(self.get_first_time_anchor_expr(entity))
+
+ def _anchored_start_event_timestamps_expr(self, anchor_expr: ast.Expr) -> ast.Expr:
+ # The variant subquery is already GROUP BY actor_id, so the first-time anchor (a minIf over
+ # entity matchers, or over the two-arm role tags) resolves to one cohorting timestamp per actor.
+ # Emit that single bucketed interval when the anchor falls
# inside the query window, otherwise nothing. This mirrors the legacy
# if(has(_start_event_timestamps, min_timestamp), _start_event_timestamps, []) wrapping: in first-time
# mode the only element ever read is start_event_timestamps[1] (the minimum), so a single-element array is
# equivalent. A null anchor (first-ever occurrence not matching filters) or an out-of-window anchor both
# fail the window check and yield an empty array, excluding the actor.
- anchor_expr = self.get_first_time_anchor_expr(entity)
return parse_expr(
"if({within_window}, [{bucketed_anchor}], [])",
{
@@ -610,15 +683,15 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
source=ast.Field(chain=["events", "timestamp"])
)
- two_arm = self._legacy_first_time_two_arm_scan()
+ two_arm = self._first_time_two_arm_scan()
if two_arm:
# Aliasing the UNION as `events` keeps every aggregate expression below identical;
# only the entity conditions swap to the arms' role tags.
select_from = ast.JoinExpr(
table=ast.SelectSetQuery.create_from_queries(
[
- self._legacy_scan_arm(self.start_event, "start"),
- self._legacy_scan_arm(self.return_event, "return"),
+ self._first_time_scan_arm(self.start_event, "start"),
+ self._first_time_scan_arm(self.return_event, "return"),
],
"UNION ALL",
),
@@ -711,7 +784,7 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
if self.is_first_occurrence_matching_filters or self.is_first_ever_occurrence:
min_timestamp_inner_expr = (
- self._legacy_two_arm_anchor_expr() if two_arm else self.get_first_time_anchor_expr(self.start_event)
+ self._first_time_two_arm_anchor_expr() if two_arm else self.get_first_time_anchor_expr(self.start_event)
)
start_event_timestamps = parse_expr(
@@ -829,7 +902,7 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
return inner_query
- def _legacy_first_time_two_arm_scan(self) -> bool:
+ def _first_time_two_arm_scan(self) -> bool:
# The tag-column arms carry no event properties, so any per-row property read in the
# outer query (value breakdowns, property aggregation) keeps the single scan.
return (
@@ -845,7 +918,7 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
return False
return None not in self.runner.get_events_for_entity(self.start_event)
- def _legacy_scan_arm(self, entity: RetentionEntity, query_kind: Literal["start", "return"]) -> ast.SelectQuery:
+ def _first_time_scan_arm(self, entity: RetentionEntity, query_kind: Literal["start", "return"]) -> ast.SelectQuery:
filters = [*self.runner.arm_event_filters(entity, query_kind)]
if query_kind == "start":
# The first-ever anchor needs the no-props stream, so property matching moves into
@@ -881,7 +954,7 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
where=ast.And(exprs=filters) if filters else None,
)
- def _legacy_two_arm_anchor_expr(self) -> ast.Expr:
+ def _first_time_two_arm_anchor_expr(self) -> ast.Expr:
# Mirrors get_first_time_anchor_expr with the arms' tags standing in for the entity matchers.
if self.is_first_ever_occurrence:
return parse_expr(
@@ -1003,7 +1076,9 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
)
def _event_filters(self) -> list[ast.Expr]:
- event_filters = self.global_event_filters.copy()
+ return [*self.global_event_filters, *self._cohort_breakdown_filters()]
+
+ def _cohort_breakdown_filters(self) -> list[ast.Expr]:
if (
self.query.breakdownFilter
and self.query.breakdownFilter.breakdowns
@@ -1013,15 +1088,36 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
cohort_id = self.query.breakdownFilter.breakdowns[0].property
# Don't add cohort filter for "all users" (cohort_id = 0)
if int(cohort_id) != ALL_USERS_COHORT_ID:
- event_filters.append(
+ return [
ast.CompareOperation(
op=ast.CompareOperationOp.InCohort,
left=ast.Field(chain=["person_id"]),
right=ast.Constant(value=int(cohort_id)),
)
- )
+ ]
- return event_filters
+ return []
+
+ def _arm_scan_predicate(self, entity: RetentionEntity, query_kind: Literal["start", "return"]) -> ast.Expr:
+ # First-ever anchors the start side against the property-stripped stream (its minIf pair needs
+ # rows that match the entity but not necessarily its property filters); every other role only
+ # ever aggregates rows matching the full entity.
+ if query_kind == "start" and self.is_first_ever_occurrence:
+ return self.entity_expr_no_props(entity)
+ return self.entity_expr_with_props(entity)
+
+ def _arm_where_filters(self, entity: RetentionEntity, query_kind: Literal["start", "return"]) -> list[ast.Expr]:
+ """WHERE for one events arm of the UNION variant, scoped to that arm's entity only: the
+ per-arm equivalent of _event_filters(), mirroring the legacy two-arm scan. Every aggregate an
+ arm computes conditions on its own entity (first-ever breakdown resolution lives on the start
+ arm only, see _dwh_breakdown_value_arm_expr), so the other entity's rows can never contribute
+ and scanning them would only inflate read bytes and GROUP BY state."""
+ filters = self.runner.arm_event_filters(entity, query_kind)
+ filters.extend(self._cohort_breakdown_filters())
+ predicate = self._arm_scan_predicate(entity, query_kind)
+ if not (isinstance(predicate, ast.Constant) and predicate.value is True):
+ filters.append(predicate)
+ return filters
def _is_valid_start_interval_expr(self, start_event_timestamps_field: str = "start_event_timestamps") -> ast.Expr:
start_event_timestamps = ast.Field(chain=[start_event_timestamps_field])
diff --git a/posthog/hogql_queries/insights/retention/retention_query_runner.py b/posthog/hogql_queries/insights/retention/retention_query_runner.py
index 09f889079dfc..4786f9a23d95 100644
--- a/posthog/hogql_queries/insights/retention/retention_query_runner.py
+++ b/posthog/hogql_queries/insights/retention/retention_query_runner.py
@@ -401,21 +401,26 @@ class RetentionQueryRunner(AnalyticsQueryRunner[RetentionQueryResponse]):
# Pre-filter by event name
if entities is None:
entities = [self.start_event, self.return_event]
- events = [event for entity in entities for event in self.get_events_for_entity(entity)]
- unique_events = set(events)
- # Don't pre-filter if any of them is "All events" or the entity has no events at all
- if unique_events and None not in unique_events:
- events_where.append(
- ast.CompareOperation(
- left=ast.Field(chain=["event"]),
- # Sorting for consistent snapshots in tests
- right=ast.Tuple(exprs=[ast.Constant(value=event) for event in sorted(unique_events)]), # type: ignore
- op=ast.CompareOperationOp.In,
- )
- )
+ event_name_filter = self.event_name_filter(entities)
+ if event_name_filter is not None:
+ events_where.append(event_name_filter)
return events_where
+ def event_name_filter(self, entities: list[RetentionEntity]) -> ast.Expr | None:
+ """`event IN (...)` pre-filter for the given entities, or None when any of them is "All events"
+ (or an action with no concrete events), in which case no name filter can narrow the scan."""
+ events = [event for entity in entities for event in self.get_events_for_entity(entity)]
+ unique_events = set(events)
+ if not unique_events or None in unique_events:
+ return None
+ return ast.CompareOperation(
+ left=ast.Field(chain=["event"]),
+ # Sorting for consistent snapshots in tests
+ right=ast.Tuple(exprs=[ast.Constant(value=event) for event in sorted(unique_events)]), # type: ignore
+ op=ast.CompareOperationOp.In,
+ )
+
def _refresh_frequency(self):
date_to = self.query_date_range.date_to()
date_from = self.query_date_range.date_from()
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 4326c44400f7..ddce309c8586 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
@@ -28,7 +28,7 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(events.event, tuple('paid', 'posthog_test_warehouse_event_mix_signups')), or(equals(events.event, 'posthog_test_warehouse_event_mix_signups'), equals(events.event, 'paid')))
+ WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2025-01-01 00:00:00', 'UTC')), toIntervalDay(1))), less(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(events.event, tuple('paid')), equals(events.event, 'paid'))
GROUP BY actor_id) AS retention_events
GROUP BY actor_id
HAVING 1) AS actor_activity
diff --git a/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_query_runner.ambr b/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_query_runner.ambr
index d42d3773291b..88e472595aae 100644
--- a/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_query_runner.ambr
+++ b/posthog/hogql_queries/insights/retention/test/__snapshots__/test_retention_query_runner.ambr
@@ -745,23 +745,43 @@
actor_activity.intervals_from_base AS intervals_from_base,
count(DISTINCT actor_activity.actor_id) AS count
FROM
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS actor_id,
- if(and(greaterOrEquals(minIf(toTimeZone(events.timestamp, 'UTC'), and(equals(events.event, 'target_event'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'prop'), ''), 'null'), '^"|"$', ''), 'correct'), 0))), toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(minIf(toTimeZone(events.timestamp, 'UTC'), and(equals(events.event, 'target_event'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'prop'), ''), 'null'), '^"|"$', ''), 'correct'), 0))), toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), [toStartOfInterval(minIf(toTimeZone(events.timestamp, 'UTC'), and(equals(events.event, 'target_event'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'prop'), ''), 'null'), '^"|"$', ''), 'correct'), 0))), toIntervalDay(1))], []) AS start_event_timestamps,
+ (SELECT events.person_id AS actor_id,
+ if(and(greaterOrEquals(minIf(events.timestamp, equals(events.matches_start, 1)), toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(minIf(events.timestamp, equals(events.matches_start, 1)), toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), [toStartOfInterval(minIf(events.timestamp, equals(events.matches_start, 1)), toIntervalDay(1))], []) AS start_event_timestamps,
arrayMap(x -> plus(toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(x)), range(0, 6)) AS date_range,
- arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(events.timestamp, 'UTC')), and(equals(events.event, 'returning_event'), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(events.timestamp, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))))) AS return_event_timestamps,
+ arraySort(groupUniqArrayIf(toStartOfDay(events.timestamp), and(equals(events.is_return, 1), and(greaterOrEquals(events.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))))) AS return_event_timestamps,
arrayJoin(arrayFilter(x -> ifNull(greater(x, -1), 0), arrayMap((interval_index, interval_date, _start_event_timestamps) -> if(ifNull(equals(_start_event_timestamps[1], interval_date), isNull(_start_event_timestamps[1])
and isNull(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(ifNull(equals(start_event_timestamps[1], date_range[plus(start_interval_index, 1)]), isNull(start_event_timestamps[1])
and isNull(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), 5), _timestamp), 1), return_event_timestamps)))) AS intervals_from_base
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), in(events.event, tuple('returning_event', 'target_event')), or(and(equals(events.event, 'target_event'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'prop'), ''), 'null'), '^"|"$', ''), 'correct'), 0)), equals(events.event, 'returning_event')))
+ FROM
+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id,
+ toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ 1 AS is_start,
+ 1 AS matches_start,
+ 0 AS is_return
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), in(events.event, tuple('target_event')), and(equals(events.event, 'target_event'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'prop'), ''), 'null'), '^"|"$', ''), 'correct'), 0)))
+ UNION ALL SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id,
+ toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ 0 AS is_start,
+ 0 AS matches_start,
+ 1 AS is_return
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), in(events.event, tuple('returning_event')), and(greaterOrEquals(events.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), equals(events.event, 'returning_event'))) AS events
GROUP BY actor_id
HAVING 1) AS actor_activity
GROUP BY start_event_matching_interval,
@@ -851,23 +871,43 @@
actor_activity.intervals_from_base AS intervals_from_base,
count(DISTINCT actor_activity.actor_id) AS count
FROM
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS actor_id,
- if(and(greaterOrEquals(if(equals(minIf(toTimeZone(events.timestamp, 'UTC'), equals(events.event, 'target_event')), minIf(toTimeZone(events.timestamp, 'UTC'), and(equals(events.event, 'target_event'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'prop'), ''), 'null'), '^"|"$', ''), 'correct'), 0)))), minIf(toTimeZone(events.timestamp, 'UTC'), equals(events.event, 'target_event')), NULL), toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(if(equals(minIf(toTimeZone(events.timestamp, 'UTC'), equals(events.event, 'target_event')), minIf(toTimeZone(events.timestamp, 'UTC'), and(equals(events.event, 'target_event'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'prop'), ''), 'null'), '^"|"$', ''), 'correct'), 0)))), minIf(toTimeZone(events.timestamp, 'UTC'), equals(events.event, 'target_event')), NULL), toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), [toStartOfInterval(if(equals(minIf(toTimeZone(events.timestamp, 'UTC'), equals(events.event, 'target_event')), minIf(toTimeZone(events.timestamp, 'UTC'), and(equals(events.event, 'target_event'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'prop'), ''), 'null'), '^"|"$', ''), 'correct'), 0)))), minIf(toTimeZone(events.timestamp, 'UTC'), equals(events.event, 'target_event')), NULL), toIntervalDay(1))], []) AS start_event_timestamps,
+ (SELECT events.person_id AS actor_id,
+ if(and(ifNull(greaterOrEquals(if(equals(minIf(events.timestamp, equals(events.is_start, 1)), minIf(events.timestamp, equals(events.matches_start, 1))), minIf(events.timestamp, equals(events.is_start, 1)), NULL), toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), 0), ifNull(less(if(equals(minIf(events.timestamp, equals(events.is_start, 1)), minIf(events.timestamp, equals(events.matches_start, 1))), minIf(events.timestamp, equals(events.is_start, 1)), NULL), toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), 0)), [toStartOfInterval(if(equals(minIf(events.timestamp, equals(events.is_start, 1)), minIf(events.timestamp, equals(events.matches_start, 1))), minIf(events.timestamp, equals(events.is_start, 1)), NULL), toIntervalDay(1))], []) AS start_event_timestamps,
arrayMap(x -> plus(toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(x)), range(0, 6)) AS date_range,
- arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(events.timestamp, 'UTC')), and(equals(events.event, 'returning_event'), and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(toTimeZone(events.timestamp, 'UTC'), toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))))) AS return_event_timestamps,
+ arraySort(groupUniqArrayIf(toStartOfDay(events.timestamp), and(equals(events.is_return, 1), and(greaterOrEquals(events.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')))))) AS return_event_timestamps,
arrayJoin(arrayFilter(x -> ifNull(greater(x, -1), 0), arrayMap((interval_index, interval_date, _start_event_timestamps) -> if(ifNull(equals(_start_event_timestamps[1], interval_date), isNull(_start_event_timestamps[1])
and isNull(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(ifNull(equals(start_event_timestamps[1], date_range[plus(start_interval_index, 1)]), isNull(start_event_timestamps[1])
and isNull(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), 5), _timestamp), 1), return_event_timestamps)))) AS intervals_from_base
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), in(events.event, tuple('returning_event', 'target_event')))
+ FROM
+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id,
+ toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ 1 AS is_start,
+ and(equals(events.event, 'target_event'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'prop'), ''), 'null'), '^"|"$', ''), 'correct'), 0)) AS matches_start,
+ 0 AS is_return
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), in(events.event, tuple('target_event')), equals(events.event, 'target_event'))
+ UNION ALL SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id,
+ toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ 0 AS is_start,
+ 0 AS matches_start,
+ 1 AS is_return
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), in(events.event, tuple('returning_event')), and(greaterOrEquals(events.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), equals(events.event, 'returning_event'))) AS events
GROUP BY actor_id
HAVING 1) AS actor_activity
GROUP BY start_event_matching_interval,
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 aedab4f99a1f..8d9cc74bd448 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
@@ -3788,6 +3788,96 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixi
assert dwh_arms[0].select_from is not None
self.assertIsNone(dwh_arms[0].select_from.sample)
+ @staticmethod
+ def _where_event_name_filters(expr: Optional[ast.Expr]) -> list[list[str]]:
+ """All `event IN (...)` name tuples anywhere under the expression, in traversal order."""
+ if expr is None:
+ return []
+ if (
+ isinstance(expr, ast.CompareOperation)
+ and expr.op == ast.CompareOperationOp.In
+ and isinstance(expr.left, ast.Field)
+ and expr.left.chain == ["event"]
+ and isinstance(expr.right, ast.Tuple)
+ ):
+ return [[e.value for e in expr.right.exprs if isinstance(e, ast.Constant)]]
+ if isinstance(expr, ast.And | ast.Or):
+ return [names for child in expr.exprs for names in TestRetention._where_event_name_filters(child)]
+ return []
+
+ @staticmethod
+ def _has_timestamp_bound(expr: Optional[ast.Expr]) -> bool:
+ if expr is None:
+ return False
+ if isinstance(expr, ast.CompareOperation) and isinstance(expr.left, ast.Field):
+ return expr.left.chain[-1] == "timestamp"
+ if isinstance(expr, ast.And | ast.Or):
+ return any(TestRetention._has_timestamp_bound(child) for child in expr.exprs)
+ return False
+
+ def test_dwh_variant_property_aggregation_arms_scan_only_their_own_entity(self):
+ # Each events arm of the UNION must narrow its WHERE to its own entity. With the combined
+ # filter on both arms, a SUM/AVG retention insight scans the whole filtered event set twice,
+ # which doubles the read bytes and adds enough GROUP BY state to OOM on large teams.
+ query = RetentionQuery(
+ dateRange={"date_to": _date(10, hour=6)},
+ retentionFilter={
+ "totalIntervals": 11,
+ "targetEntity": {"id": "purchase", "type": "events"},
+ "returningEntity": {"id": "$pageview", "type": "events"},
+ "aggregationType": "sum",
+ "aggregationProperty": "amount",
+ },
+ )
+ runner = RetentionQueryRunner(team=self.team, query=query)
+
+ with patch(RETENTION_BASE_QUERY_VARIANT_PATCH_PATH, return_value=True):
+ base_query = RetentionFixedIntervalBaseQueryBuilder(runner).build()
+
+ assert base_query.select_from is not None
+ union = base_query.select_from.table
+ assert isinstance(union, ast.SelectSetQuery)
+ arm_name_filters = [
+ self._where_event_name_filters(arm.where)
+ for arm in union.select_queries()
+ if isinstance(arm, ast.SelectQuery)
+ ]
+ self.assertEqual(arm_name_filters, [[["purchase"]], [["$pageview"]]])
+
+ def test_dwh_variant_first_time_breakdown_single_scan_bounds_return_side_to_window(self):
+ # Breakdowns read event properties in the outer query, so they can't ride the tag-arm
+ # two-arm scan and stay on the single scan. Its WHERE must still split per role (start
+ # entity unbounded for the cohorting anchor, return entity bounded to the query window);
+ # a flat unbounded filter reads the return entity's entire history, which hits the
+ # read-bytes cap or an OOM for high-volume return events.
+ query = RetentionQuery(
+ dateRange={"date_to": _date(10, hour=6)},
+ breakdownFilter={"breakdowns": [{"type": "event", "property": "$browser"}]},
+ retentionFilter={
+ "totalIntervals": 11,
+ "retentionType": "retention_first_time",
+ "targetEntity": {"id": "signed_up", "type": "events"},
+ "returningEntity": {"id": "$pageview", "type": "events"},
+ },
+ )
+ runner = RetentionQueryRunner(team=self.team, query=query)
+
+ with patch(RETENTION_BASE_QUERY_VARIANT_PATCH_PATH, return_value=True):
+ base_query = RetentionFixedIntervalBaseQueryBuilder(runner).build()
+
+ assert base_query.select_from is not None
+ assert isinstance(base_query.select_from.table, ast.Field)
+ self.assertEqual(base_query.select_from.table.chain, ["events"])
+
+ where = base_query.where
+ assert isinstance(where, ast.And)
+ role_split = next(expr for expr in where.exprs if isinstance(expr, ast.Or))
+ start_branch, return_branch = role_split.exprs
+ self.assertEqual(self._where_event_name_filters(start_branch), [["signed_up"]])
+ self.assertFalse(self._has_timestamp_bound(start_branch))
+ self.assertEqual(self._where_event_name_filters(return_branch), [["$pageview"]])
+ self.assertTrue(self._has_timestamp_bound(return_branch))
+
def _create_sampling_parity_fixtures(self):
for i in range(20):
_create_person(team_id=self.team.pk, distinct_ids=[f"person{i}"])
@@ -8134,8 +8224,10 @@ class TestClickhouseRetentionGroupAggregation(
# self.assertIn(BREAKDOWN_OTHER_STRING_LABEL, breakdown_values) # Canada should be in "Other"
-class TestRetentionLegacyFirstTimeTwoArmScan(APIBaseTest):
- def _legacy_base_query(
+class TestRetentionFirstTimeTwoArmScan(APIBaseTest):
+ # The two-arm scan is shared machinery: both the legacy path and the DWH variant must produce
+ # it for the gated first-time shapes, so every structural assertion runs against both paths.
+ def _base_query(
self,
retention_type: str,
target: dict | None = None,
@@ -8143,6 +8235,7 @@ class TestRetentionLegacyFirstTimeTwoArmScan(APIBaseTest):
breakdown_filter: dict | None = None,
aggregation_property: str | None = None,
aggregation_group_type_index: int | None = None,
+ use_dwh_variant: bool = False,
) -> ast.SelectQuery:
query: dict = {
"kind": "RetentionQuery",
@@ -8160,7 +8253,7 @@ class TestRetentionLegacyFirstTimeTwoArmScan(APIBaseTest):
if aggregation_group_type_index is not None:
query["aggregation_group_type_index"] = aggregation_group_type_index
runner = RetentionQueryRunner(team=self.team, query=query)
- with patch(RETENTION_BASE_QUERY_VARIANT_PATCH_PATH, return_value=False):
+ with patch(RETENTION_BASE_QUERY_VARIANT_PATCH_PATH, return_value=use_dwh_variant):
return RetentionFixedIntervalBaseQueryBuilder(runner).build_base_query()
@staticmethod
@@ -8199,9 +8292,16 @@ class TestRetentionLegacyFirstTimeTwoArmScan(APIBaseTest):
walk(arm.where)
return found
- @parameterized.expand(["retention_first_time", "retention_first_ever_occurrence"])
- def test_first_time_modes_scan_two_arms_with_bounded_return_arm(self, retention_type):
- base_query = self._legacy_base_query(retention_type)
+ @parameterized.expand(
+ [
+ ("legacy_first_time", "retention_first_time", False),
+ ("legacy_first_ever", "retention_first_ever_occurrence", False),
+ ("variant_first_time", "retention_first_time", True),
+ ("variant_first_ever", "retention_first_ever_occurrence", True),
+ ]
+ )
+ def test_first_time_modes_scan_two_arms_with_bounded_return_arm(self, _name, retention_type, use_dwh_variant):
+ base_query = self._base_query(retention_type, use_dwh_variant=use_dwh_variant)
assert base_query.select_from is not None
self.assertEqual(base_query.select_from.alias, "events")
table = base_query.select_from.table
@@ -8218,9 +8318,28 @@ class TestRetentionLegacyFirstTimeTwoArmScan(APIBaseTest):
self.assertFalse(self._where_has_timestamp_bound(start_arm))
self.assertTrue(self._where_has_timestamp_bound(return_arm))
+ @parameterized.expand([("legacy", False), ("variant", True)])
+ def test_first_time_all_events_return_bounds_return_arm_to_window(self, _name, use_dwh_variant):
+ # The gate only needs concrete START event names, so an all-events return entity still
+ # two-arms: its arm has no name filter but must carry the window bound. Without the split
+ # this shape scans the team's entire event history (the biggest first-time over-read).
+ base_query = self._base_query(
+ "retention_first_time", returning={"id": None, "type": "events"}, use_dwh_variant=use_dwh_variant
+ )
+ assert base_query.select_from is not None
+ table = base_query.select_from.table
+ self.assertIsInstance(table, ast.SelectSetQuery)
+ start_arm, return_arm = list(table.select_queries()) # type: ignore[union-attr]
+
+ self.assertIn("signup", self._where_constants(start_arm))
+ self.assertFalse(self._where_has_timestamp_bound(start_arm))
+ self.assertNotIn("signup", self._where_constants(return_arm))
+ self.assertTrue(self._where_has_timestamp_bound(return_arm))
+
@parameterized.expand(
[
- ("recurring", "retention_recurring", None, None, None, None),
+ ("recurring", "retention_recurring", None, None, None, None, False),
+ ("recurring_variant", "retention_recurring", None, None, None, None, True),
(
"same_entity",
"retention_first_time",
@@ -8228,8 +8347,27 @@ class TestRetentionLegacyFirstTimeTwoArmScan(APIBaseTest):
{"id": "signup", "type": "events"},
None,
None,
+ False,
+ ),
+ (
+ "same_entity_variant",
+ "retention_first_time",
+ {"id": "signup", "type": "events"},
+ {"id": "signup", "type": "events"},
+ None,
+ None,
+ True,
+ ),
+ ("all_events_target", "retention_first_time", {"id": None, "type": "events"}, None, None, None, False),
+ (
+ "all_events_target_variant",
+ "retention_first_time",
+ {"id": None, "type": "events"},
+ None,
+ None,
+ None,
+ True,
),
- ("all_events_target", "retention_first_time", {"id": None, "type": "events"}, None, None, None),
(
"breakdown",
"retention_first_time",
@@ -8237,25 +8375,41 @@ class TestRetentionLegacyFirstTimeTwoArmScan(APIBaseTest):
None,
{"breakdowns": [{"type": "event", "property": "plan"}]},
None,
+ False,
),
- ("property_aggregation", "retention_first_time", None, None, None, "revenue"),
+ (
+ "breakdown_variant",
+ "retention_first_time",
+ None,
+ None,
+ {"breakdowns": [{"type": "event", "property": "plan"}]},
+ None,
+ True,
+ ),
+ # Variant property aggregation is the per-entity UNION, not a single scan, so it has no
+ # variant row here; its arm scoping is asserted in TestRetention.
+ ("property_aggregation", "retention_first_time", None, None, None, "revenue", False),
]
)
def test_keeps_single_scan_when_split_cannot_apply(
- self, _name, retention_type, target, returning, breakdown_filter, aggregation_property
+ self, _name, retention_type, target, returning, breakdown_filter, aggregation_property, use_dwh_variant
):
- base_query = self._legacy_base_query(
+ base_query = self._base_query(
retention_type,
target=target,
returning=returning,
breakdown_filter=breakdown_filter,
aggregation_property=aggregation_property,
+ use_dwh_variant=use_dwh_variant,
)
assert base_query.select_from is not None
self.assertIsInstance(base_query.select_from.table, ast.Field)
- def test_first_time_group_aggregation_filters_both_arms(self):
- base_query = self._legacy_base_query("retention_first_time", aggregation_group_type_index=0)
+ @parameterized.expand([("legacy", False), ("variant", True)])
+ def test_first_time_group_aggregation_filters_both_arms(self, _name, use_dwh_variant):
+ base_query = self._base_query(
+ "retention_first_time", aggregation_group_type_index=0, use_dwh_variant=use_dwh_variant
+ )
assert base_query.select_from is not None
table = base_query.select_from.table
self.assertIsInstance(table, ast.SelectSetQuery)