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 samplingFactor parity gap in DWH variant (#64402)

Thomas Obermüller2c8db87809bd
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 ed53bf697f0a..e4da41cc0021 100644
--- a/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py
+++ b/posthog/hogql_queries/insights/retention/retention_base_query_fixed.py
@@ -62,6 +62,23 @@ class RetentionFixedIntervalBaseQueryBuilder(RetentionBaseQueryBuilder):
selected_breakdown_value=selected_breakdown_value,
)
+ def apply_sampling(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):
+ if self.query.samplingFactor is None or not isinstance(self.query.samplingFactor, float):
+ return
+ for arm, entity in zip(select_from.table.select_queries(), [self.start_event, self.return_event]):
+ if entity.type == EntityType.DATA_WAREHOUSE:
+ continue
+ arm_from = arm.select_from if isinstance(arm, ast.SelectQuery) else None
+ if arm_from is not None:
+ arm_from.sample = ast.SampleExpr(
+ sample_value=ast.RatioExpr(left=ast.Constant(value=self.query.samplingFactor))
+ )
+ return
+
+ super().apply_sampling(base_query)
+
# Nested fixed-interval query with data warehouse support.
# Intended as a drop-in replacement for the legacy query while we verify
# parity in production.
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 2dc61657e7da..ff3857be7c2c 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
@@ -454,6 +454,65 @@
use_hive_partitioning=0
'''
# ---
+# name: TestRetention.test_day_interval_sampled.1
+ '''
+ SELECT actor_activity.start_interval_index AS start_event_matching_interval,
+ actor_activity.intervals_from_base AS intervals_from_base,
+ 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('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1)), toIntervalDay(x)), range(0, 11)) 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), 11), _timestamp), 1), return_event_timestamps)))) AS intervals_from_base
+ FROM
+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS actor_id,
+ arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(events.timestamp, 'UTC')), and(equals(events.event, '$pageview'), 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 start_event_timestamps,
+ [] AS return_event_timestamps
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 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('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(events.event, tuple('$pageview')), or(equals(events.event, '$pageview'), equals(events.event, '$pageview')))
+ GROUP BY actor_id
+ UNION ALL SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS actor_id,
+ [] AS start_event_timestamps,
+ arraySort(groupUniqArrayIf(toStartOfDay(toTimeZone(events.timestamp, 'UTC')), and(equals(events.event, '$pageview'), 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
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 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('2020-06-10 00:00:00', 'UTC')), toIntervalDay(1))), less(events.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(events.event, tuple('$pageview')), or(equals(events.event, '$pageview'), equals(events.event, '$pageview')))
+ GROUP BY actor_id) AS retention_events
+ GROUP BY actor_id
+ HAVING 1) AS actor_activity
+ GROUP BY start_event_matching_interval,
+ intervals_from_base
+ ORDER BY start_event_matching_interval ASC,
+ intervals_from_base ASC
+ LIMIT 100000 SETTINGS 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: TestRetention.test_month_interval_with_person_on_events_v2
'''
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 940b93012433..2218388c600b 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
@@ -56,7 +56,4 @@ class RetentionBaseQueryVariantComparisonMixin:
if query.get("breakdownFilter"):
return True
- if query.get("samplingFactor") is not None:
- return True
-
return False
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 ff0e97fe63f2..f05ccea81864 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
@@ -24,6 +24,7 @@ from rest_framework.exceptions import ValidationError
from posthog.schema import HogQLQueryModifiers, InCohortVia, RetentionQuery
+from posthog.hogql import ast
from posthog.hogql.constants import LimitContext
from posthog.hogql.query import execute_hogql_query
@@ -35,8 +36,10 @@ from posthog.constants import (
TREND_FILTER_TYPE_EVENTS,
)
from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
+from posthog.hogql_queries.insights.retention.retention_base_query_fixed import RetentionFixedIntervalBaseQueryBuilder
from posthog.hogql_queries.insights.retention.retention_query_runner import RetentionQueryRunner
from posthog.hogql_queries.insights.retention.test.retention_base_query_variant import (
+ RETENTION_BASE_QUERY_VARIANT_PATCH_PATH,
RetentionBaseQueryVariantComparisonMixin,
)
from posthog.hogql_queries.insights.retention.test.utils import pad, pluck
@@ -3662,6 +3665,82 @@ class TestRetention(RetentionBaseQueryVariantComparisonMixin, ClickhouseTestMixi
),
)
+ def test_dwh_variant_pushes_sampling_into_event_subqueries(self):
+ # The variant wraps a UNION ALL in a JoinExpr; SAMPLE on that wrapper never reaches the inner
+ # events scans, so it must be pushed into each FROM events arm where ClickHouse can apply it.
+ query = RetentionQuery(
+ dateRange={"date_to": _date(10, hour=6)},
+ samplingFactor=0.5,
+ retentionFilter={"totalIntervals": 11},
+ )
+ 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)
+ self.assertIsNone(base_query.select_from.sample)
+
+ event_arms = [
+ arm
+ for arm in union.select_queries()
+ if isinstance(arm, ast.SelectQuery)
+ and arm.select_from is not None
+ and isinstance(arm.select_from.table, ast.Field)
+ and arm.select_from.table.chain == ["events"]
+ ]
+ self.assertEqual(len(event_arms), 2)
+ for arm in event_arms:
+ assert arm.select_from is not None
+ sample = arm.select_from.sample
+ assert isinstance(sample, ast.SampleExpr)
+ self.assertEqual(sample.sample_value.left.value, 0.5)
+
+ def _create_sampling_parity_fixtures(self):
+ for i in range(20):
+ _create_person(team_id=self.team.pk, distinct_ids=[f"person{i}"])
+ _create_events(
+ self.team,
+ [(f"person{i}", _date(day)) for i in range(20) for day in range(7)],
+ )
+
+ @parameterized.expand([("factor_0_1", 0.1), ("factor_0_5", 0.5), ("factor_1_0", 1.0)])
+ def test_sampling_parity_recurring(self, _name: str, sampling_factor: float):
+ # run_query asserts the legacy and DWH-variant paths return identical results. Deterministic
+ # SAMPLE BY cityHash64(distinct_id) makes the single-scan legacy query and the two-arm variant
+ # union sample the same rows, so parity must hold at every factor.
+ self._create_sampling_parity_fixtures()
+
+ result = self.run_query(
+ query={
+ "dateRange": {"date_to": _date(10, hour=6)},
+ "samplingFactor": sampling_factor,
+ "retentionFilter": {"totalIntervals": 11},
+ }
+ )
+ self.assertEqual(len(result), 11)
+
+ @parameterized.expand([("factor_0_1", 0.1), ("factor_0_5", 0.5), ("factor_1_0", 1.0)])
+ def test_sampling_parity_first_time(self, _name: str, sampling_factor: float):
+ # First-time retention anchors on minIf over the sampled stream; the variant computes it in a
+ # separate union arm from the legacy single scan, so this exercises a different aggregation than
+ # the recurring case. run_query asserts the two paths stay identical under sampling.
+ self._create_sampling_parity_fixtures()
+
+ result = self.run_query(
+ query={
+ "dateRange": {"date_to": _date(10, hour=6)},
+ "samplingFactor": sampling_factor,
+ "retentionFilter": {
+ "totalIntervals": 11,
+ "retentionType": RETENTION_FIRST_OCCURRENCE_MATCHING_FILTERS,
+ },
+ }
+ )
+ self.assertEqual(len(result), 11)
+
def test_retention_with_breakdown_with_person_properties(self):
_create_person(team_id=self.team.pk, distinct_ids=["person1"], properties={"country": "US"})
_create_person(team_id=self.team.pk, distinct_ids=["person2"], properties={"country": "UK"})