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(insights): support minimumOccurrences > 1 in strict-calendar DWH retention variant (#64077)

Thomas Obermüller397261542965
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 c0c08b672f72..ed53bf697f0a 100644
--- a/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py
+++ b/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py
@@ -92,13 +92,36 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
alias="start_event_timestamps",
expr=parse_expr("arrayFlatten(groupArray(start_event_timestamps))"),
),
- ast.Alias(
- alias="return_event_timestamps",
- expr=parse_expr("arrayFlatten(groupArray(return_event_timestamps))"),
- ),
- self._date_range_alias(),
]
+ # Property aggregation ignores minimum_occurrences (matching the legacy path), so the threshold filter only
+ # applies to the events-only / data-warehouse return shapes. When it applies, the per-actor dupes the return
+ # subquery emitted are flattened here, counted per interval, and intervals below the threshold are dropped.
+ apply_minimum_occurrences = self.minimum_occurrences > 1 and not self.has_property_aggregation
+
+ if apply_minimum_occurrences:
+ select_fields.append(self._date_range_alias())
+ select_fields.extend(
+ self._get_minimum_occurrences_aliases(
+ minimum_occurrences=self.minimum_occurrences,
+ with_dupes_expr=parse_expr("arrayFlatten(groupArray(return_event_timestamps))"),
+ )
+ )
+ select_fields.append(
+ ast.Alias(
+ alias="return_event_timestamps",
+ expr=self._minimum_occurrences_return_timestamps_expr(self.minimum_occurrences),
+ )
+ )
+ else:
+ select_fields.append(
+ ast.Alias(
+ alias="return_event_timestamps",
+ expr=parse_expr("arrayFlatten(groupArray(return_event_timestamps))"),
+ )
+ )
+ select_fields.append(self._date_range_alias())
+
if self.has_property_aggregation:
select_fields.extend(
[
@@ -246,7 +269,7 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
start_event_timestamps_expr = timestamps_expr
return_event_timestamps_expr = ast.Array(exprs=[])
else:
- timestamps_expr = self._get_return_event_timestamps_expr(
+ timestamps_expr = self._get_dwh_return_timestamps_expr(
minimum_occurrences=self.minimum_occurrences,
start_of_interval_sql=start_of_interval_sql,
return_entity_expr=entity_expr,
@@ -380,8 +403,20 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
minimum_occurrences_aliases = self._get_minimum_occurrences_aliases(
minimum_occurrences=self.minimum_occurrences,
- start_of_interval_sql=start_of_interval_sql,
- return_entity_expr=self.return_entity_expr,
+ with_dupes_expr=parse_expr(
+ """
+ groupArrayIf(
+ {start_of_interval_timestamp},
+ {returning_entity_expr} and
+ {filter_timestamp}
+ )
+ """,
+ {
+ "start_of_interval_timestamp": start_of_interval_sql,
+ "returning_entity_expr": self.return_entity_expr,
+ "filter_timestamp": self.events_timestamp_filter(),
+ },
+ ),
)
if self.has_property_aggregation:
@@ -543,33 +578,22 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
return inner_query
- def _get_minimum_occurrences_aliases(
- self, minimum_occurrences: int, start_of_interval_sql: ast.Expr, return_entity_expr: ast.Expr
- ) -> list[ast.Alias]:
+ def _get_minimum_occurrences_aliases(self, minimum_occurrences: int, with_dupes_expr: ast.Expr) -> list[ast.Alias]:
"""
Only include the following expressions when minimum occurrences value is set and greater than one. The query
with occurrences uses slightly more RAM, what can make some existing queries go over the max memory setting we
have and having them stop working.
+
+ ``with_dupes_expr`` is the per-actor multiset of return-event interval starts (duplicates retained). The legacy
+ single-query path builds it directly from the events table; the UNION ALL variant flattens the dupes already
+ emitted by its return subquery. The downstream counts-per-interval logic is identical for both.
"""
if minimum_occurrences == 1:
return []
return_event_timestamps_with_dupes = ast.Alias(
alias="return_event_timestamps_with_dupes",
- expr=parse_expr(
- """
- groupArrayIf(
- {start_of_interval_timestamp},
- {returning_entity_expr} and
- {filter_timestamp}
- )
- """,
- {
- "start_of_interval_timestamp": start_of_interval_sql,
- "returning_entity_expr": return_entity_expr,
- "filter_timestamp": self.events_timestamp_filter(),
- },
- ),
+ expr=with_dupes_expr,
)
return_event_counts_by_interval = ast.Alias(
alias="return_event_counts_by_interval",
@@ -590,6 +614,55 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
)
return [return_event_timestamps_with_dupes, return_event_counts_by_interval]
+ def _minimum_occurrences_return_timestamps_expr(self, minimum_occurrences: int) -> ast.Expr:
+ # Keep only the intervals where the actor had at least `minimum_occurrences` return events. Relies on the
+ # date_range and return_event_counts_by_interval aliases (from _get_minimum_occurrences_aliases) being in
+ # scope in the same SELECT.
+ return parse_expr(
+ """
+ arrayFilter(
+ (date, counts) -> counts >= {minimum_occurrences},
+ date_range,
+ return_event_counts_by_interval
+ )
+ """,
+ {"minimum_occurrences": ast.Constant(value=minimum_occurrences)},
+ )
+
+ def _get_dwh_return_timestamps_expr(
+ self,
+ minimum_occurrences: int,
+ start_of_interval_sql: ast.Expr,
+ return_entity_expr: ast.Expr,
+ timestamp_field: ast.Expr | None,
+ ) -> ast.Expr:
+ # The variant's return subquery is already grouped per actor. With a threshold of 1 we emit the deduped set of
+ # return intervals. With a higher threshold we keep duplicates so the outer aggregation can count per-interval
+ # occurrences and drop intervals below the threshold — the per-actor source for the legacy
+ # return_event_timestamps_with_dupes alias.
+ if minimum_occurrences > 1:
+ return parse_expr(
+ """
+ groupArrayIf(
+ {start_of_interval_sql},
+ {return_entity_expr} and
+ {filter_timestamp}
+ )
+ """,
+ {
+ "start_of_interval_sql": start_of_interval_sql,
+ "return_entity_expr": return_entity_expr,
+ "filter_timestamp": self.events_timestamp_filter(field=timestamp_field),
+ },
+ )
+
+ return self._get_return_event_timestamps_expr(
+ minimum_occurrences=1,
+ start_of_interval_sql=start_of_interval_sql,
+ return_entity_expr=return_entity_expr,
+ timestamp_field=timestamp_field,
+ )
+
def _date_range_alias(self) -> ast.Alias:
return ast.Alias(
alias="date_range",
@@ -825,18 +898,7 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
)
if minimum_occurrences > 1:
- # return_event_counts_by_interval is only calculated when minimum_occurrences > 1.
- # See _get_minimum_occurrences_aliases method.
- return parse_expr(
- """
- arrayFilter(
- (date, counts) -> counts >= {minimum_occurrences},
- date_range,
- return_event_counts_by_interval,
- )
- """,
- {"minimum_occurrences": ast.Constant(value=minimum_occurrences)},
- )
+ return self._minimum_occurrences_return_timestamps_expr(minimum_occurrences)
return parse_expr(
"""
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 f979552541d6..940b93012433 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
@@ -53,12 +53,6 @@ class RetentionBaseQueryVariantComparisonMixin:
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:
- retention_filter = cast(dict[str, Any], query.get("retentionFilter") or {})
-
- minimum_occurrences = retention_filter.get("minimumOccurrences") or 1
- if minimum_occurrences > 1:
- return True
-
if query.get("breakdownFilter"):
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 47d59738baff..bc3b40297c94 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
@@ -385,6 +385,89 @@ class TestRetentionDataWarehouse(ClickhouseTestMixin, APIBaseTest):
),
)
+ def test_retention_data_warehouse_return_event_with_minimum_occurrences(self):
+ # Same cohorts as test_retention_data_warehouse_different_tables, but the data warehouse return entity now
+ # only counts an interval when the user renewed at least twice that day. user-1 (two renewals on 01-02) and
+ # user-3 (two renewals on 01-03) qualify; user-2's single renewal on 01-03 falls below the threshold and is
+ # dropped — the one cell that differs from the minimumOccurrences = 1 result.
+ person_ids = self._create_people()
+ signups_table_name = self._create_data_warehouse_table(
+ filename="warehouse_min_occ_signups.csv",
+ table_name="warehouse_min_occ_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"],
+ [3, person_ids["user-3"], "2025-01-02 09:00:00"],
+ [4, person_ids["user-4"], "2025-01-02 10:00:00"],
+ ],
+ table_columns={
+ "id": "Int64",
+ "person_id": "UUID",
+ "signed_up_at": "DateTime64(3, 'UTC')",
+ },
+ )
+ renewals_table_name = self._create_data_warehouse_table(
+ filename="warehouse_min_occ_renewals.csv",
+ table_name="warehouse_min_occ_renewals",
+ header=["id", "person_id", "renewed_at"],
+ rows=[
+ [1, person_ids["user-1"], "2025-01-02 09:00:00"],
+ [2, person_ids["user-1"], "2025-01-02 15:00:00"], # second renewal same day → qualifies interval 1
+ [3, person_ids["user-2"], "2025-01-03 12:00:00"], # only one renewal → below threshold, dropped
+ [4, person_ids["user-3"], "2025-01-03 08:00:00"],
+ [5, person_ids["user-3"], "2025-01-03 20:00:00"], # second renewal same day → qualifies interval 1
+ ],
+ table_columns={
+ "id": "Int64",
+ "person_id": "UUID",
+ "renewed_at": "DateTime64(3, 'UTC')",
+ },
+ )
+
+ 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,
+ "minimumOccurrences": 2,
+ "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": renewals_table_name,
+ "name": renewals_table_name,
+ "type": "data_warehouse",
+ "table_name": renewals_table_name,
+ "aggregation_target_field": "person_id",
+ "timestamp_field": "renewed_at",
+ },
+ },
+ }
+ )
+
+ self.assertEqual(
+ pluck(result, "values", "count"),
+ pad(
+ [
+ [2, 1, 0, 0],
+ [2, 1, 0],
+ [0, 0],
+ [0],
+ [0],
+ ]
+ ),
+ )
+
def test_retention_data_warehouse_property_aggregation_different_tables(self) -> None:
person_ids = self._create_people()
signups_table_name = self._create_data_warehouse_table(
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 ac3fdc5c00b6..ff0e97fe63f2 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
@@ -979,6 +979,55 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixi
pluck(result, "values", "count"),
)
+ @parameterized.expand(
+ [
+ ("threshold_2", 2, 3),
+ ("threshold_3", 3, 2),
+ ("threshold_5", 5, 1),
+ ]
+ )
+ def test_recurring_retention_minimum_occurrences_thresholds(
+ self, _name: str, minimum_occurrences: int, expected_interval_1: int
+ ):
+ # Recurring retention with a higher occurrence threshold: all four people cohort on day 0 (signed_up), then
+ # return a different number of times on day 1. Only those at or above the threshold count for interval 1, so
+ # the interval-1 cell shrinks as the threshold rises (3 -> 2 -> 1). The variant comparison harness asserts the
+ # data-warehouse variant matches the legacy path for each threshold.
+ for distinct_id in ["personA", "personB", "personC", "personD"]:
+ _create_person(team_id=self.team.pk, distinct_ids=[distinct_id])
+
+ _create_events(
+ self.team,
+ [("personA", _date(0)), ("personB", _date(0)), ("personC", _date(0)), ("personD", _date(0))],
+ "signed_up",
+ )
+ _create_events(
+ self.team,
+ [
+ *[("personA", _date(1))] * 5,
+ *[("personB", _date(1))] * 3,
+ *[("personC", _date(1))] * 2,
+ ("personD", _date(1)),
+ ],
+ "used_feature",
+ )
+
+ result = self.run_query(
+ query={
+ "dateRange": {"date_to": _date(2, hour=6)},
+ "retentionFilter": {
+ "totalIntervals": 3,
+ "targetEntity": {"id": "signed_up", "type": "events"},
+ "returningEntity": {"id": "used_feature", "type": "events"},
+ "minimumOccurrences": minimum_occurrences,
+ },
+ }
+ )
+ self.assertEqual(
+ pad([[4, expected_interval_1, 0], [0, 0], [0]]),
+ pluck(result, "values", "count"),
+ )
+
def test_rolling_retention_doesnt_double_count_same_user(self):
_create_person(team_id=self.team.pk, distinct_ids=["person1"])
_create_person(team_id=self.team.pk, distinct_ids=["person2"])
@@ -3118,8 +3167,43 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixi
],
)
- def test_retention_first_time_ever_with_minimum_occurrences(self):
- """Test first time ever retention with minimum occurrences requirement"""
+ @parameterized.expand(
+ [
+ # threshold 2: person1's 2 day-2 pageviews and person2's 2 day-5 pageviews both still qualify
+ (
+ "threshold_2",
+ 2,
+ [
+ [0, 0, 0, 0, 0, 0, 0], # Day 0: no one
+ [1, 1, 0, 0, 0, 0, 0], # Day 1: person1 (signup), returns day 2 with 2+ pageviews
+ [1, 1, 0, 1, 0, 0, 0], # Day 2: person2 (signup), returns day 3 and 5 with 2+ pageviews
+ [1, 0, 0, 0, 0, 0, 0], # Day 3: person3 (signup), but doesn't return with 2+ pageviews
+ [0, 0, 0, 0, 0, 0, 0], # Day 4: no new users
+ [0, 0, 0, 0, 0, 0, 0], # Day 5: no new users
+ [0, 0, 0, 0, 0, 0, 0], # Day 6: no new users
+ [0, 0, 0, 0, 0, 0, 0], # Day 7: no new users
+ ],
+ ),
+ # threshold 3: only person2's 3 day-3 pageviews clear the bar; the day-2 and day-5 two-pageview days drop
+ (
+ "threshold_3",
+ 3,
+ [
+ [0, 0, 0, 0, 0, 0, 0], # Day 0: no one
+ [1, 0, 0, 0, 0, 0, 0], # Day 1: person1 (signup), only 2 day-2 pageviews -> below threshold
+ [1, 1, 0, 0, 0, 0, 0], # Day 2: person2 (signup), 3 day-3 pageviews qualify; 2 day-5 don't
+ [1, 0, 0, 0, 0, 0, 0], # Day 3: person3 (signup), only 1 day-4 pageview
+ [0, 0, 0, 0, 0, 0, 0], # Day 4: no new users
+ [0, 0, 0, 0, 0, 0, 0], # Day 5: no new users
+ [0, 0, 0, 0, 0, 0, 0], # Day 6: no new users
+ [0, 0, 0, 0, 0, 0, 0], # Day 7: no new users
+ ],
+ ),
+ ]
+ )
+ def test_retention_first_time_ever_with_minimum_occurrences(
+ self, _name: str, minimum_occurrences: int, expected_counts: list[list[int]]
+ ):
_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"])
@@ -3157,7 +3241,7 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixi
"type": TREND_FILTER_TYPE_EVENTS,
},
"returningEntity": {"id": "$pageview", "name": "$pageview", "type": "events"},
- "minimumOccurrences": 2, # Require at least 2 pageviews in a day to count as retention
+ "minimumOccurrences": minimum_occurrences,
},
}
)
@@ -3167,23 +3251,7 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixi
pluck(result, "label"),
["Day 0", "Day 1", "Day 2", "Day 3", "Day 4", "Day 5", "Day 6", "Day 7"],
)
-
- # Person1: first event on day 1 (signup), has 2 pageviews on day 2 (qualifies)
- # Person2: first event on day 2 (signup), has 3 pageviews on day 3 and 2 on day 5 (both qualify)
- # Person3: first event on day 3 (signup), has only 1 pageview on day 4 (doesn't qualify)
- self.assertEqual(
- pluck(result, "values", "count"),
- [
- [0, 0, 0, 0, 0, 0, 0], # Day 0: no one
- [1, 1, 0, 0, 0, 0, 0], # Day 1: person1 (signup), returns day 2 with 2+ pageviews
- [1, 1, 0, 1, 0, 0, 0], # Day 2: person2 (signup), returns day 3 and 5 with 2+ pageviews
- [1, 0, 0, 0, 0, 0, 0], # Day 3: person3 (signup), but doesn't return with 2+ pageviews
- [0, 0, 0, 0, 0, 0, 0], # Day 4: no new users
- [0, 0, 0, 0, 0, 0, 0], # Day 5: no new users
- [0, 0, 0, 0, 0, 0, 0], # Day 6: no new users
- [0, 0, 0, 0, 0, 0, 0], # Day 7: no new users
- ],
- )
+ self.assertEqual(pluck(result, "values", "count"), expected_counts)
def test_retention_first_time_ever_actors_query(self):
"""Test actors query for first time ever retention"""