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(experiments): anchor retention maturity on start_event timestamp (#59266)

Juraj Majerik27e729adae1c
diff --git a/posthog/hogql_queries/experiments/experiment_query_builder.py b/posthog/hogql_queries/experiments/experiment_query_builder.py
index b639b2dd18c5..563049cf5edd 100644
--- a/posthog/hogql_queries/experiments/experiment_query_builder.py
+++ b/posthog/hogql_queries/experiments/experiment_query_builder.py
@@ -246,40 +246,37 @@ class ExperimentQueryBuilder:
def _get_maturity_window_seconds(self) -> int:
"""
- Returns the total maturity window in seconds.
- For retention metrics: conversion_window (may be 0) + retention_window_end.
- For other metrics: conversion_window.
- Returns 0 when no maturity window can be derived.
-
- Known limitation (retention metrics): the maturity HAVING clause is applied
- to the exposures CTE and anchored on max(exposure_timestamp), not on the
- user's start_event timestamp. This is a good approximation when start_event
- happens shortly after exposure (the common case), but understates required
- maturity when there's a long gap between exposure and start. A user exposed
- long ago who only starts the day before analysis runs will pass the maturity
- check even though their retention window has barely opened, and will likely
- be counted as "not retained", diluting the metric. Proper fix is to anchor
- retention maturity on max(start_event_timestamp) inside the retention query's
- entity_metrics CTE; tracked as a follow-up.
+ Returns the maturity window in seconds for non-retention metrics.
+ Retention metrics use _get_retention_maturity_seconds and apply maturity
+ in the start_events CTE, anchored on start_event timestamp.
"""
- conversion_window_seconds = self._get_conversion_window_seconds()
+ return self._get_conversion_window_seconds()
- if isinstance(self.metric, ExperimentRetentionMetric):
- retention_window_end_seconds = conversion_window_to_seconds(
- self.metric.retention_window_end,
- self.metric.retention_window_unit,
- )
- return conversion_window_seconds + retention_window_end_seconds
-
- return conversion_window_seconds
+ def _get_retention_maturity_seconds(self) -> int:
+ """
+ Returns the maturity window in seconds for retention metrics.
+ Equals retention_window_end converted to seconds; conversion_window does
+ not contribute because retention maturity is anchored on start_event.
+ """
+ assert isinstance(self.metric, ExperimentRetentionMetric)
+ return conversion_window_to_seconds(
+ self.metric.retention_window_end,
+ self.metric.retention_window_unit,
+ )
def _build_maturity_having_clause(self, timestamp_expr: str = "timestamp") -> Optional[ast.Expr]:
"""
Returns a HAVING clause expression to filter out users whose conversion window
hasn't elapsed yet, or None if the feature is not enabled.
+
+ Retention metrics handle maturity separately in their own start_events CTE
+ via _build_retention_maturity_having_clause; this function intentionally
+ returns None for them.
"""
if self.metric is None:
return None
+ if isinstance(self.metric, ExperimentRetentionMetric):
+ return None
if not self.only_count_matured_users:
return None
@@ -296,6 +293,36 @@ class ExperimentQueryBuilder:
},
)
+ def _build_retention_maturity_having_clause(self) -> Optional[ast.Expr]:
+ """
+ Returns a HAVING clause for the retention query's start_events CTE that
+ filters out users whose retention window has not yet fully elapsed since
+ their start_event.
+
+ Anchored on the user's start_event timestamp (min or max of start event
+ timestamps, depending on start_handling).
+ """
+ if not isinstance(self.metric, ExperimentRetentionMetric):
+ return None
+ if not self.only_count_matured_users:
+ return None
+
+ maturity_seconds = self._get_retention_maturity_seconds()
+ if maturity_seconds == 0:
+ return None
+
+ now = timezone.now().strftime("%Y-%m-%d %H:%M:%S")
+ start_timestamp_expr = self._build_start_event_timestamp_expr()
+
+ return parse_expr(
+ "{start_ts} + toIntervalSecond({maturity_seconds}) <= toDateTime({now}, 'UTC')",
+ placeholders={
+ "start_ts": start_timestamp_expr,
+ "maturity_seconds": ast.Constant(value=maturity_seconds),
+ "now": ast.Constant(value=now),
+ },
+ )
+
def _build_funnel_query(self) -> ast.SelectQuery:
"""
Builds query for funnel metrics.
@@ -2641,6 +2668,18 @@ class ExperimentQueryBuilder:
assert isinstance(query, ast.SelectQuery)
+ # Inject maturity HAVING clause into the start_events CTE, anchored on
+ # the user's start_event timestamp so users whose retention window has
+ # not yet elapsed are excluded from the denominator.
+ retention_maturity = self._build_retention_maturity_having_clause()
+ if retention_maturity is not None and query.ctes and "start_events" in query.ctes:
+ start_events_cte = query.ctes["start_events"]
+ if isinstance(start_events_cte, ast.CTE) and isinstance(start_events_cte.expr, ast.SelectQuery):
+ if start_events_cte.expr.having is None:
+ start_events_cte.expr.having = retention_maturity
+ else:
+ start_events_cte.expr.having = ast.And(exprs=[start_events_cte.expr.having, retention_maturity])
+
# Inject breakdown columns if breakdown filter is present
if self.breakdown_injector:
self.breakdown_injector.inject_retention_breakdown_columns(query)
diff --git a/posthog/hogql_queries/experiments/test/experiment_query_runner/__snapshots__/test_retention_metric.ambr b/posthog/hogql_queries/experiments/test/experiment_query_runner/__snapshots__/test_retention_metric.ambr
index 1d6c3b3b3d7b..8a88517963d7 100644
--- a/posthog/hogql_queries/experiments/test/experiment_query_runner/__snapshots__/test_retention_metric.ambr
+++ b/posthog/hogql_queries/experiments/test/experiment_query_runner/__snapshots__/test_retention_metric.ambr
@@ -185,8 +185,7 @@
GROUP BY person.id
HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC'))), and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0)), ifNull(notILike(toString(events__person.properties___email), '%@posthog.com%'), 1), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''), ['control', 'test']))
- GROUP BY entity_id
- HAVING lessOrEquals(plus(max(toTimeZone(events.timestamp, 'UTC')), toIntervalSecond(864000)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC'))),
+ GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp
@@ -200,7 +199,8 @@
HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(259200))), equals(events.event, 'signup')), and(greaterOrEquals(events.timestamp, exposures.first_exposure_time), lessOrEquals(events.timestamp, plus(exposures.first_exposure_time, toIntervalSecond(259200)))))
- GROUP BY exposures.entity_id),
+ GROUP BY exposures.entity_id
+ HAVING lessOrEquals(plus(min(toTimeZone(events.timestamp, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC'))),
completion_events AS
(SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
@@ -256,8 +256,7 @@
argMin(t.exposure_session_id, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_session_id
FROM experiment_exposures_preaggregated AS t
WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), greaterOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC'))))
- GROUP BY entity_id
- HAVING ifNull(lessOrEquals(plus(max(toTimeZone(t.last_exposure_time, 'UTC')), toIntervalSecond(864000)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC')), 0)),
+ GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp
@@ -271,7 +270,8 @@
HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(259200))), equals(events.event, 'signup')), and(greaterOrEquals(events.timestamp, exposures.first_exposure_time), lessOrEquals(events.timestamp, plus(exposures.first_exposure_time, toIntervalSecond(259200)))))
- GROUP BY exposures.entity_id),
+ GROUP BY exposures.entity_id
+ HAVING lessOrEquals(plus(min(toTimeZone(events.timestamp, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC'))),
completion_events AS
(SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
@@ -317,6 +317,166 @@
use_hive_partitioning=0
'''
# ---
+# name: TestExperimentRetentionMetric.test_only_count_matured_users_anchors_on_start_event_0_direct
+ '''
+ WITH exposures AS
+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
+ if(ifNull(greater(uniqExact(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', '')), 1), 0), '$multiple', any(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''))) AS variant,
+ min(toTimeZone(events.timestamp, 'UTC')) AS first_exposure_time,
+ max(toTimeZone(events.timestamp, 'UTC')) AS last_exposure_time,
+ argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS exposure_event_uuid,
+ argMin(events.`$session_id`, toTimeZone(events.timestamp, 'UTC')) AS exposure_session_id
+ 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC'))), and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0)), ifNull(notILike(toString(events__person.properties___email), '%@posthog.com%'), 1), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''), ['control', 'test']))
+ GROUP BY entity_id),
+ start_events AS
+ (SELECT exposures.entity_id AS entity_id,
+ min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp
+ 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
+ WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'signup')), greaterOrEquals(events.timestamp, exposures.first_exposure_time))
+ GROUP BY exposures.entity_id
+ HAVING lessOrEquals(plus(min(toTimeZone(events.timestamp, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC'))),
+ completion_events AS
+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
+ toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
+ 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(604800))), equals(events.event, 'login'))),
+ entity_metrics AS
+ (SELECT exposures.entity_id AS entity_id,
+ exposures.variant AS variant,
+ max(if(and(isNotNull(toTimeZone(completion_events.completion_timestamp, 'UTC')), ifNull(greaterOrEquals(toStartOfDay(toTimeZone(completion_events.completion_timestamp, 'UTC')), plus(toStartOfDay(start_events.start_timestamp), toIntervalDay(7))), 0), ifNull(lessOrEquals(toStartOfDay(toTimeZone(completion_events.completion_timestamp, 'UTC')), plus(toStartOfDay(start_events.start_timestamp), toIntervalDay(7))), 0)), 1, 0)) AS value
+ FROM exposures
+ INNER JOIN start_events ON equals(exposures.entity_id, start_events.entity_id)
+ LEFT JOIN completion_events ON and(equals(exposures.entity_id, completion_events.entity_id), and(greaterOrEquals(toTimeZone(completion_events.completion_timestamp, 'UTC'), start_events.start_timestamp), lessOrEquals(toTimeZone(completion_events.completion_timestamp, 'UTC'), plus(start_events.start_timestamp, toIntervalSecond(691200)))))
+ GROUP BY exposures.entity_id,
+ exposures.variant)
+ SELECT entity_metrics.variant AS variant,
+ count(entity_metrics.entity_id) AS num_users,
+ sum(entity_metrics.value) AS total_sum,
+ sum(power(entity_metrics.value, 2)) AS total_sum_of_squares,
+ count(entity_metrics.entity_id) AS denominator_sum,
+ count(entity_metrics.entity_id) AS denominator_sum_squares,
+ sum(entity_metrics.value) AS numerator_denominator_sum_product
+ FROM entity_metrics
+ WHERE notEmpty(variant)
+ GROUP BY entity_metrics.variant
+ LIMIT 50000 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=39728447488,
+ enable_analyzer=1,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestExperimentRetentionMetric.test_only_count_matured_users_anchors_on_start_event_1_precomputed
+ '''
+ WITH exposures AS
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ if(ifNull(greater(uniqExact(t.variant), 1), 0), '$multiple', argMin(t.variant, toTimeZone(t.first_exposure_time, 'UTC'))) AS variant,
+ min(toTimeZone(t.first_exposure_time, 'UTC')) AS first_exposure_time,
+ max(toTimeZone(t.last_exposure_time, 'UTC')) AS last_exposure_time,
+ argMin(t.exposure_event_uuid, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_event_uuid,
+ argMin(t.exposure_session_id, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_session_id
+ FROM experiment_exposures_preaggregated AS t
+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), greaterOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC'))))
+ GROUP BY entity_id),
+ start_events AS
+ (SELECT exposures.entity_id AS entity_id,
+ min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp
+ 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
+ WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'signup')), greaterOrEquals(events.timestamp, exposures.first_exposure_time))
+ GROUP BY exposures.entity_id
+ HAVING lessOrEquals(plus(min(toTimeZone(events.timestamp, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC'))),
+ completion_events AS
+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
+ toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
+ 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 ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 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), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(604800))), equals(events.event, 'login'))),
+ entity_metrics AS
+ (SELECT exposures.entity_id AS entity_id,
+ exposures.variant AS variant,
+ max(if(and(isNotNull(toTimeZone(completion_events.completion_timestamp, 'UTC')), ifNull(greaterOrEquals(toStartOfDay(toTimeZone(completion_events.completion_timestamp, 'UTC')), plus(toStartOfDay(start_events.start_timestamp), toIntervalDay(7))), 0), ifNull(lessOrEquals(toStartOfDay(toTimeZone(completion_events.completion_timestamp, 'UTC')), plus(toStartOfDay(start_events.start_timestamp), toIntervalDay(7))), 0)), 1, 0)) AS value
+ FROM exposures
+ INNER JOIN start_events ON equals(exposures.entity_id, start_events.entity_id)
+ LEFT JOIN completion_events ON and(equals(exposures.entity_id, completion_events.entity_id), and(greaterOrEquals(toTimeZone(completion_events.completion_timestamp, 'UTC'), start_events.start_timestamp), lessOrEquals(toTimeZone(completion_events.completion_timestamp, 'UTC'), plus(start_events.start_timestamp, toIntervalSecond(691200)))))
+ GROUP BY exposures.entity_id,
+ exposures.variant)
+ SELECT entity_metrics.variant AS variant,
+ count(entity_metrics.entity_id) AS num_users,
+ sum(entity_metrics.value) AS total_sum,
+ sum(power(entity_metrics.value, 2)) AS total_sum_of_squares,
+ count(entity_metrics.entity_id) AS denominator_sum,
+ count(entity_metrics.entity_id) AS denominator_sum_squares,
+ sum(entity_metrics.value) AS numerator_denominator_sum_product
+ FROM entity_metrics
+ WHERE notEmpty(variant)
+ GROUP BY entity_metrics.variant
+ LIMIT 50000 SETTINGS load_balancing='in_order',
+ 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=39728447488,
+ enable_analyzer=1,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
# name: TestExperimentRetentionMetric.test_only_count_matured_users_without_conversion_window_0_direct
'''
WITH exposures AS
@@ -345,8 +505,7 @@
GROUP BY person.id
HAVING and(ifNull(equals(argMax(person.is_deleted, person.version), 0), 0), ifNull(less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))), 0))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.id)
WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC'))), and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0)), ifNull(notILike(toString(events__person.properties___email), '%@posthog.com%'), 1), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''), ['control', 'test']))
- GROUP BY entity_id
- HAVING lessOrEquals(plus(max(toTimeZone(events.timestamp, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC'))),
+ GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp
@@ -360,7 +519,8 @@
HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'signup')), greaterOrEquals(events.timestamp, exposures.first_exposure_time))
- GROUP BY exposures.entity_id),
+ GROUP BY exposures.entity_id
+ HAVING lessOrEquals(plus(min(toTimeZone(events.timestamp, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC'))),
completion_events AS
(SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
@@ -416,8 +576,7 @@
argMin(t.exposure_session_id, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_session_id
FROM experiment_exposures_preaggregated AS t
WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), greaterOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC'))))
- GROUP BY entity_id
- HAVING ifNull(lessOrEquals(plus(max(toTimeZone(t.last_exposure_time, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC')), 0)),
+ GROUP BY entity_id),
start_events AS
(SELECT exposures.entity_id AS entity_id,
min(toTimeZone(events.timestamp, 'UTC')) AS start_timestamp
@@ -431,7 +590,8 @@
HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
INNER JOIN exposures ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), exposures.entity_id)
WHERE and(equals(events.team_id, 99999), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-25 00:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'signup')), greaterOrEquals(events.timestamp, exposures.first_exposure_time))
- GROUP BY exposures.entity_id),
+ GROUP BY exposures.entity_id
+ HAVING lessOrEquals(plus(min(toTimeZone(events.timestamp, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-25 12:00:00', 6, 'UTC'))),
completion_events AS
(SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
toTimeZone(events.timestamp, 'UTC') AS completion_timestamp
diff --git a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_retention_metric.py b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_retention_metric.py
index 134dafb80cfa..5f49021e2549 100644
--- a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_retention_metric.py
+++ b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_retention_metric.py
@@ -1926,3 +1926,131 @@ class TestExperimentRetentionMetric(ExperimentQueryRunnerBaseTest):
assert len(result.variant_results) == 1
self.assertEqual(result.variant_results[0].number_of_samples, 1)
self.assertEqual(result.variant_results[0].sum, 1)
+
+ @parameterized.expand(
+ [
+ ("direct", False),
+ ("precomputed", True),
+ ]
+ )
+ @freeze_time("2020-01-25T12:00:00Z")
+ @snapshot_clickhouse_queries
+ def test_only_count_matured_users_anchors_on_start_event(self, name, use_precomputation):
+ # Maturity must be anchored on the user's start_event timestamp, not their
+ # first exposure. A user exposed long ago who only does the start_event
+ # recently has not had enough time for their retention window to elapse.
+ self._setup_precomputation_test(use_precomputation)
+
+ feature_flag = self.create_feature_flag()
+ experiment = self.create_experiment(
+ feature_flag=feature_flag,
+ start_date=datetime(2020, 1, 1, 0, 0, 0),
+ end_date=datetime(2020, 1, 25, 0, 0, 0),
+ )
+
+ # Day-7 retention, no conversion_window. Maturity = 7 days from start_event.
+ metric = ExperimentRetentionMetric(
+ start_event=EventsNode(
+ event="signup",
+ math=ExperimentMetricMathType.TOTAL,
+ ),
+ completion_event=EventsNode(
+ event="login",
+ math=ExperimentMetricMathType.TOTAL,
+ ),
+ retention_window_start=7,
+ retention_window_end=7,
+ retention_window_unit=FunnelConversionWindowTimeUnit.DAY,
+ start_handling=StartHandling.FIRST_SEEN,
+ )
+
+ experiment_query = ExperimentQuery(
+ experiment_id=experiment.id,
+ kind="ExperimentQuery",
+ metric=metric,
+ )
+
+ experiment.only_count_matured_users = True
+ experiment.metrics = [metric.model_dump(mode="json")]
+ self._save_experiment_with_precomputation(experiment, use_precomputation)
+
+ feature_flag_property = f"$feature/{feature_flag.key}"
+
+ # Early-starter control: exposed Jan 2, signup Jan 2, mature on Jan 9.
+ _create_person(distinct_ids=["user_early_starter_control"], team_id=self.team.pk)
+ _create_event(
+ team=self.team,
+ event="$feature_flag_called",
+ distinct_id="user_early_starter_control",
+ timestamp="2020-01-02T12:00:00Z",
+ properties={
+ feature_flag_property: "control",
+ "$feature_flag_response": "control",
+ "$feature_flag": feature_flag.key,
+ },
+ )
+ _create_event(
+ team=self.team,
+ event="signup",
+ distinct_id="user_early_starter_control",
+ timestamp="2020-01-02T12:01:00Z",
+ properties={feature_flag_property: "control"},
+ )
+
+ # Late-starter control: exposed Jan 2 but signup only on Jan 22.
+ # Under start_event anchor: maturity = Jan 22 + 7d = Jan 29 > Jan 25, so excluded.
+ # Under any exposure-based anchor (min or max): min(exp) = Jan 2, so it would
+ # incorrectly include this user. This test only passes under start_event anchor.
+ _create_person(distinct_ids=["user_late_starter_control"], team_id=self.team.pk)
+ _create_event(
+ team=self.team,
+ event="$feature_flag_called",
+ distinct_id="user_late_starter_control",
+ timestamp="2020-01-02T12:00:00Z",
+ properties={
+ feature_flag_property: "control",
+ "$feature_flag_response": "control",
+ "$feature_flag": feature_flag.key,
+ },
+ )
+ _create_event(
+ team=self.team,
+ event="signup",
+ distinct_id="user_late_starter_control",
+ timestamp="2020-01-22T12:00:00Z",
+ properties={feature_flag_property: "control"},
+ )
+
+ # Early-starter test: same shape as early-starter control.
+ _create_person(distinct_ids=["user_early_starter_test"], team_id=self.team.pk)
+ _create_event(
+ team=self.team,
+ event="$feature_flag_called",
+ distinct_id="user_early_starter_test",
+ timestamp="2020-01-02T12:00:00Z",
+ properties={
+ feature_flag_property: "test",
+ "$feature_flag_response": "test",
+ "$feature_flag": feature_flag.key,
+ },
+ )
+ _create_event(
+ team=self.team,
+ event="signup",
+ distinct_id="user_early_starter_test",
+ timestamp="2020-01-02T12:01:00Z",
+ properties={feature_flag_property: "test"},
+ )
+
+ flush_persons_and_events()
+
+ query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)
+ result = cast(ExperimentQueryResponse, query_runner.calculate())
+
+ # Only early-starters should appear in results; late-starter excluded.
+ assert result.baseline is not None
+ self.assertEqual(result.baseline.number_of_samples, 1)
+
+ assert result.variant_results is not None
+ assert len(result.variant_results) == 1
+ self.assertEqual(result.variant_results[0].number_of_samples, 1)