: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(experiments): pin user maturity to first exposure (#72763)
Rodrigo Ilorof93641097522
diff --git a/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.py b/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.pyindex 1ade662fb17d..535f8d0c4535 100644--- a/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.py@@ -351,8 +351,9 @@ class ExposureQueryBuilder:)assert isinstance(query, ast.SelectQuery)- # Filter out users whose conversion window hasn't elapsed yet- maturity_having = self._maturity_having(timestamp_expr="t.last_exposure_time")+ # Filter out users whose conversion window hasn't elapsed yet, anchored on+ # first exposure+ maturity_having = self._maturity_having(timestamp_expr="t.first_exposure_time")if maturity_having is not None:if query.having is None:query.having = maturity_havingdiff --git a/products/experiments/backend/hogql_queries/experiment_funnel_query_builder.py b/products/experiments/backend/hogql_queries/experiment_funnel_query_builder.pyindex 953ea7258311..ba7720741bbd 100644--- a/products/experiments/backend/hogql_queries/experiment_funnel_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_funnel_query_builder.py@@ -937,8 +937,10 @@ class FunnelQueryBuilder:def build_maturity_having_clause_optimized(self) -> Optional[ast.Expr]:"""Maturity HAVING clause for the optimized path.- Uses maxIf to only consider exposure events (step_0 = 1) for maturity,- since entity_metrics groups over all events, not just exposures.+ Uses minIf to anchor maturity on the user's first exposure (step_0 = 1),+ matching how the variant is assigned (argMinIf on first exposure). Anchoring+ on the last exposure would keep resetting the window for flags re-evaluated+ repeatedly (e.g. backend flags), so active users would never mature."""if self._b.metric is None:return None@@ -951,7 +953,7 @@ class FunnelQueryBuilder:now = timezone.now().strftime("%Y-%m-%d %H:%M:%S")return parse_expr(- "maxIf(timestamp, step_0 = 1) + toIntervalSecond({maturity_seconds}) <= toDateTime({now}, 'UTC')",+ "minIf(timestamp, step_0 = 1) + toIntervalSecond({maturity_seconds}) <= toDateTime({now}, 'UTC')",placeholders={"maturity_seconds": ast.Constant(value=maturity_seconds),"now": ast.Constant(value=now),diff --git a/products/experiments/backend/hogql_queries/experiment_metric_values.py b/products/experiments/backend/hogql_queries/experiment_metric_values.pyindex bbd9c8919025..05376fbca2a4 100644--- a/products/experiments/backend/hogql_queries/experiment_metric_values.py+++ b/products/experiments/backend/hogql_queries/experiment_metric_values.py@@ -63,7 +63,7 @@ def build_session_conversion_window_predicate(conversion_window_seconds: int) ->return parse_expr("""metric_events_by_session.first_event_timestamp- < exposures.last_exposure_time + toIntervalSecond({conversion_window_seconds})+ < exposures.first_exposure_time + toIntervalSecond({conversion_window_seconds})""",placeholders={"conversion_window_seconds": ast.Constant(value=conversion_window_seconds),@@ -85,7 +85,7 @@ def build_conversion_window_predicate_for_events(events_alias: str, conversion_wf"""{events_alias}.timestamp >= exposures.first_exposure_timeAND {events_alias}.timestamp- < exposures.last_exposure_time + toIntervalSecond({{conversion_window_seconds}})+ < exposures.first_exposure_time + toIntervalSecond({{conversion_window_seconds}})""",placeholders={"conversion_window_seconds": ast.Constant(value=conversion_window_seconds),diff --git a/products/experiments/backend/hogql_queries/experiment_query_builder.py b/products/experiments/backend/hogql_queries/experiment_query_builder.pyindex 2207397254cd..87782f66e694 100644--- a/products/experiments/backend/hogql_queries/experiment_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_query_builder.py@@ -243,6 +243,11 @@ class ExperimentQueryBuilder:Returns a HAVING clause expression to filter out users whose conversion windowhasn't elapsed yet, or None if the feature is not enabled.+ Anchored on the user's first exposure (min timestamp), matching how the+ variant is assigned. Anchoring on the last exposure would keep resetting the+ window for flags re-evaluated repeatedly (e.g. backend flags), so active users+ would never mature. Callers pass an exposure-only timestamp expression.+Retention metrics handle maturity separately in their own start_events CTEvia _build_retention_maturity_having_clause; this function intentionallyreturns None for them.@@ -260,7 +265,7 @@ class ExperimentQueryBuilder:now = timezone.now().strftime("%Y-%m-%d %H:%M:%S")return parse_expr(- f"max({timestamp_expr}) + toIntervalSecond({{maturity_seconds}}) <= toDateTime({{now}}, 'UTC')",+ f"min({timestamp_expr}) + toIntervalSecond({{maturity_seconds}}) <= toDateTime({{now}}, 'UTC')",placeholders={"maturity_seconds": ast.Constant(value=maturity_seconds),"now": ast.Constant(value=now),diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_base.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_base.ambrindex 1e7f18bb2b27..a73eccb19cec 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_base.ambr+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_base.ambr@@ -2528,7 +2528,7 @@exposures.variant AS variant,sum(coalesce(accurateCastOrNull(metric_events.value, 'Float64'), 0)) AS valueFROM exposures- LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(86400)))))+ LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(86400)))))GROUP BY exposures.entity_id,exposures.variant)SELECT entity_metrics.variant AS variant,@@ -2600,7 +2600,7 @@exposures.variant AS variant,sum(coalesce(accurateCastOrNull(metric_events.value, 'Float64'), 0)) AS valueFROM exposures- LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(172800)))))+ LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(172800)))))GROUP BY exposures.entity_id,exposures.variant)SELECT entity_metrics.variant AS variant,@@ -2672,7 +2672,7 @@exposures.variant AS variant,sum(coalesce(accurateCastOrNull(metric_events.value, 'Float64'), 0)) AS valueFROM exposures- LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(259200)))))+ LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(259200)))))GROUP BY exposures.entity_id,exposures.variant)SELECT entity_metrics.variant AS variant,diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_funnel_metric.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_funnel_metric.ambrindex 2dee06b3e419..a4d8d11d8d1e 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_funnel_metric.ambr+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_funnel_metric.ambr@@ -1165,6 +1165,117 @@use_hive_partitioning=0'''# ---+# name: TestExperimentFunnelMetric.test_maturity_anchored_on_first_exposure_0_direct+ '''+ WITH base_events AS+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', '') AS variant_value,+ toTimeZone(events.timestamp, 'UTC') AS timestamp,+ events.uuid AS uuid,+ and(greaterOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(toTimeZone(events.timestamp, 'UTC'), assumeNotNull(toDateTime('2020-01-15 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'])) AS step_0,+ if(equals(events.event, '$pageview'), 1, 0) AS step_1,+ if(equals(events.event, 'purchase'), 1, 0) AS step_2+ 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)+ 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(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) 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), or(and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-15 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'])), and(greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-15 00:00:00', 'UTC')), toIntervalSecond(604800))), or(equals(events.event, '$pageview'), equals(events.event, 'purchase')))))),+ entity_metrics AS+ (SELECT base_events.entity_id AS entity_id,+ if(greater(uniqExactIf(base_events.variant_value, equals(base_events.step_0, 1)), 1), '$multiple', anyIf(base_events.variant_value, equals(base_events.step_0, 1))) AS variant,+ arraySort(x -> minus(0, x.1), arrayMap(result -> tuple(result.1, if(and(ifNull(greaterOrEquals(result.1, 0), 0), ifNull(greater(length(result.4), result.1), 0)), if(ifNull(greater(length(arrayElement(result.4, plus(result.1, 1))), 0), 0), toString(arrayElement(result.4, plus(result.1, 1))[1]), ''), '')), aggregate_funnel_array(3, 604800, 'first_touch', 'ordered', array(array('')), [], arraySort(t -> t.1, arrayFilter(t -> and(isNotNull(t.1), isNotNull(t.2)), groupArray(tuple(accurateCastOrNull(toTimeZone(base_events.timestamp, 'UTC'), 'Float64'), base_events.uuid, array(''), arrayFilter(x -> ifNull(greater(x, 0), 0), [multiply(1, base_events.step_0), multiply(2, base_events.step_1), multiply(3, base_events.step_2)]))))))))[1] AS value+ FROM base_events+ GROUP BY base_events.entity_id+ HAVING and(greater(countIf(equals(base_events.step_0, 1)), 0), lessOrEquals(plus(minIf(toTimeZone(base_events.timestamp, 'UTC'), equals(base_events.step_0, 1)), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-15 12:00:00', 6, 'UTC'))))+ SELECT entity_metrics.variant AS variant,+ count(entity_metrics.entity_id) AS num_users,+ countIf(ifNull(equals((entity_metrics.value).1, 2), 0)) AS total_sum,+ countIf(ifNull(equals((entity_metrics.value).1, 2), 0)) AS total_sum_of_squares,+ tuple(countIf(ifNull(greaterOrEquals((entity_metrics.value).1, 1), 0)), countIf(ifNull(greaterOrEquals((entity_metrics.value).1, 2), 0))) AS step_counts+ 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,+ 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: TestExperimentFunnelMetric.test_maturity_anchored_on_first_exposure_1_precomputed+ '''+ WITH exposures AS+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,+ if(greater(uniqExact(t.variant), 1), '$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', '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-15 00:00:00', 'UTC'))))+ GROUP BY entity_id+ HAVING lessOrEquals(plus(min(toTimeZone(t.first_exposure_time, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-15 12:00:00', 6, 'UTC'))),+ metric_events AS+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,+ toTimeZone(t.timestamp, 'UTC') AS timestamp,+ t.event_uuid AS uuid,+ arrayElement(t.steps, 1) AS step_0,+ arrayElement(t.steps, 2) AS step_1,+ arrayElement(t.steps, 3) AS step_2+ FROM experiment_metric_events_preaggregated AS t+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(t.timestamp, plus(assumeNotNull(toDateTime('2020-01-15 00:00:00', 'UTC')), toIntervalSecond(604800))))),+ entity_metrics AS+ (SELECT exposures.entity_id AS entity_id,+ exposures.variant AS variant,+ arraySort(x -> minus(0, x.1), arrayMap(result -> tuple(result.1, if(and(ifNull(greaterOrEquals(result.1, 0), 0), ifNull(greater(length(result.4), result.1), 0)), if(ifNull(greater(length(arrayElement(result.4, plus(result.1, 1))), 0), 0), toString(arrayElement(result.4, plus(result.1, 1))[1]), ''), '')), aggregate_funnel_array(3, 604800, 'first_touch', 'ordered', array(array('')), [], arraySort(t -> t.1, arrayFilter(t -> and(isNotNull(t.1), isNotNull(t.2)), groupArray(tuple(accurateCastOrNull(toTimeZone(metric_events.timestamp, 'UTC'), 'Float64'), metric_events.uuid, array(''), arrayFilter(x -> ifNull(greater(x, 0), 0), [multiply(1, metric_events.step_0), multiply(2, metric_events.step_1), multiply(3, metric_events.step_2)]))))))))[1] AS value+ FROM exposures+ LEFT JOIN metric_events ON equals(exposures.entity_id, metric_events.entity_id)+ GROUP BY exposures.entity_id,+ exposures.variant)+ SELECT entity_metrics.variant AS variant,+ count(entity_metrics.entity_id) AS num_users,+ countIf(ifNull(equals((entity_metrics.value).1, 2), 0)) AS total_sum,+ countIf(ifNull(equals((entity_metrics.value).1, 2), 0)) AS total_sum_of_squares,+ tuple(countIf(ifNull(greaterOrEquals((entity_metrics.value).1, 1), 0)), countIf(ifNull(greaterOrEquals((entity_metrics.value).1, 2), 0))) AS step_counts+ 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,+ 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: TestExperimentFunnelMetric.test_only_count_matured_users_0_direct'''WITH base_events AS@@ -1200,7 +1311,7 @@arraySort(x -> minus(0, x.1), arrayMap(result -> tuple(result.1, if(and(ifNull(greaterOrEquals(result.1, 0), 0), ifNull(greater(length(result.4), result.1), 0)), if(ifNull(greater(length(arrayElement(result.4, plus(result.1, 1))), 0), 0), toString(arrayElement(result.4, plus(result.1, 1))[1]), ''), '')), aggregate_funnel_array(3, 604800, 'first_touch', 'ordered', array(array('')), [], arraySort(t -> t.1, arrayFilter(t -> and(isNotNull(t.1), isNotNull(t.2)), groupArray(tuple(accurateCastOrNull(toTimeZone(base_events.timestamp, 'UTC'), 'Float64'), base_events.uuid, array(''), arrayFilter(x -> ifNull(greater(x, 0), 0), [multiply(1, base_events.step_0), multiply(2, base_events.step_1), multiply(3, base_events.step_2)]))))))))[1] AS valueFROM base_eventsGROUP BY base_events.entity_id- HAVING and(greater(countIf(equals(base_events.step_0, 1)), 0), lessOrEquals(plus(maxIf(toTimeZone(base_events.timestamp, 'UTC'), equals(base_events.step_0, 1)), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-15 12:00:00', 6, 'UTC'))))+ HAVING and(greater(countIf(equals(base_events.step_0, 1)), 0), lessOrEquals(plus(minIf(toTimeZone(base_events.timestamp, 'UTC'), equals(base_events.step_0, 1)), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-15 12:00:00', 6, 'UTC'))))SELECT entity_metrics.variant AS variant,count(entity_metrics.entity_id) AS num_users,countIf(ifNull(equals((entity_metrics.value).1, 2), 0)) AS total_sum,@@ -1235,7 +1346,7 @@FROM experiment_exposures_preaggregated AS tWHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '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-15 00:00:00', 'UTC'))))GROUP BY entity_id- HAVING lessOrEquals(plus(max(toTimeZone(t.last_exposure_time, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-15 12:00:00', 6, 'UTC'))),+ HAVING lessOrEquals(plus(min(toTimeZone(t.first_exposure_time, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-15 12:00:00', 6, 'UTC'))),metric_events AS(SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,toTimeZone(t.timestamp, 'UTC') AS timestamp,diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambrindex abc2c5f6f82c..5d2412e84a4d 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr@@ -1,5 +1,5 @@# serializer version: 1-# name: TestExperimentMeanMetric.test_conversion_window_extends_to_last_exposure_0_direct+# name: TestExperimentMeanMetric.test_conversion_window_anchored_on_first_exposure_0_direct'''WITH exposures AS(SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,@@ -46,7 +46,7 @@exposures.variant AS variant,sum(coalesce(accurateCastOrNull(metric_events.value, 'Float64'), 0)) AS valueFROM exposures- LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(86400)))))+ LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(86400)))))GROUP BY exposures.entity_id,exposures.variant)SELECT entity_metrics.variant AS variant,@@ -71,7 +71,7 @@use_hive_partitioning=0'''# ----# name: TestExperimentMeanMetric.test_conversion_window_extends_to_last_exposure_1_precomputed+# name: TestExperimentMeanMetric.test_conversion_window_anchored_on_first_exposure_1_precomputed'''WITH exposures AS(SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,@@ -101,7 +101,7 @@exposures.variant AS variant,sum(coalesce(accurateCastOrNull(metric_events.value, 'Float64'), 0)) AS valueFROM exposures- LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(86400)))))+ LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(86400)))))GROUP BY exposures.entity_id,exposures.variant)SELECT entity_metrics.variant AS variant,@@ -432,7 +432,7 @@HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) 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-15 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-15 12:00:00', 6, 'UTC'))),+ HAVING lessOrEquals(plus(min(toTimeZone(events.timestamp, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-15 12:00:00', 6, 'UTC'))),metric_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 timestamp,@@ -451,7 +451,7 @@exposures.variant AS variant,sum(coalesce(accurateCastOrNull(metric_events.value, 'Float64'), 0)) AS valueFROM exposures- LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(604800)))))+ LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(604800)))))GROUP BY exposures.entity_id,exposures.variant)SELECT entity_metrics.variant AS variant,@@ -488,7 +488,7 @@FROM experiment_exposures_preaggregated AS tWHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '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-15 00:00:00', 'UTC'))))GROUP BY entity_id- HAVING lessOrEquals(plus(max(toTimeZone(t.last_exposure_time, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-15 12:00:00', 6, 'UTC'))),+ HAVING lessOrEquals(plus(min(toTimeZone(t.first_exposure_time, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-15 12:00:00', 6, 'UTC'))),metric_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 timestamp,@@ -507,7 +507,7 @@exposures.variant AS variant,sum(coalesce(accurateCastOrNull(metric_events.value, 'Float64'), 0)) AS valueFROM exposures- LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(604800)))))+ LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), and(greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')), less(toTimeZone(metric_events.timestamp, 'UTC'), plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(604800)))))GROUP BY exposures.entity_id,exposures.variant)SELECT entity_metrics.variant AS variant,diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_ratio_metric.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_ratio_metric.ambrindex 0a2a44699f04..a81f322f0934 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_ratio_metric.ambr+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_ratio_metric.ambr@@ -216,7 +216,7 @@HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) 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-15 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-15 12:00:00', 6, 'UTC'))),+ HAVING lessOrEquals(plus(min(toTimeZone(events.timestamp, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-15 12:00:00', 6, 'UTC'))),numerator_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 timestamp,@@ -248,14 +248,14 @@sum(coalesce(accurateCastOrNull(numerator_events.value, 'Float64'), 0)) AS valueFROM numerator_eventsJOIN exposures ON equals(exposures.entity_id, numerator_events.entity_id)- WHERE and(greaterOrEquals(numerator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(numerator_events.timestamp, plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(604800))))+ WHERE and(greaterOrEquals(numerator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(numerator_events.timestamp, plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(604800))))GROUP BY exposures.entity_id),denominator_agg AS(SELECT exposures.entity_id AS entity_id,sum(coalesce(accurateCastOrNull(denominator_events.value, 'Float64'), 0)) AS valueFROM denominator_eventsJOIN exposures ON equals(exposures.entity_id, denominator_events.entity_id)- WHERE and(greaterOrEquals(denominator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(denominator_events.timestamp, plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(604800))))+ WHERE and(greaterOrEquals(denominator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(denominator_events.timestamp, plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(604800))))GROUP BY exposures.entity_id),entity_metrics AS(SELECT exposures.variant AS variant,@@ -302,7 +302,7 @@FROM experiment_exposures_preaggregated AS tWHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', '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-15 00:00:00', 'UTC'))))GROUP BY entity_id- HAVING lessOrEquals(plus(max(toTimeZone(t.last_exposure_time, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-15 12:00:00', 6, 'UTC'))),+ HAVING lessOrEquals(plus(min(toTimeZone(t.first_exposure_time, 'UTC')), toIntervalSecond(604800)), parseDateTime64BestEffortOrNull('2020-01-15 12:00:00', 6, 'UTC'))),numerator_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 timestamp,@@ -334,14 +334,14 @@sum(coalesce(accurateCastOrNull(numerator_events.value, 'Float64'), 0)) AS valueFROM numerator_eventsJOIN exposures ON equals(exposures.entity_id, numerator_events.entity_id)- WHERE and(greaterOrEquals(numerator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(numerator_events.timestamp, plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(604800))))+ WHERE and(greaterOrEquals(numerator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(numerator_events.timestamp, plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(604800))))GROUP BY exposures.entity_id),denominator_agg AS(SELECT exposures.entity_id AS entity_id,sum(coalesce(accurateCastOrNull(denominator_events.value, 'Float64'), 0)) AS valueFROM denominator_eventsJOIN exposures ON equals(exposures.entity_id, denominator_events.entity_id)- WHERE and(greaterOrEquals(denominator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(denominator_events.timestamp, plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(604800))))+ WHERE and(greaterOrEquals(denominator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(denominator_events.timestamp, plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(604800))))GROUP BY exposures.entity_id),entity_metrics AS(SELECT exposures.variant AS variant,@@ -1552,14 +1552,14 @@sum(coalesce(accurateCastOrNull(numerator_events.value, 'Float64'), 0)) AS valueFROM numerator_eventsJOIN exposures ON equals(exposures.entity_id, numerator_events.entity_id)- WHERE and(greaterOrEquals(numerator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(numerator_events.timestamp, plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(3600))))+ WHERE and(greaterOrEquals(numerator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(numerator_events.timestamp, plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(3600))))GROUP BY exposures.entity_id),denominator_agg AS(SELECT exposures.entity_id AS entity_id,sum(coalesce(accurateCastOrNull(denominator_events.value, 'Float64'), 0)) AS valueFROM denominator_eventsJOIN exposures ON equals(exposures.entity_id, denominator_events.entity_id)- WHERE and(greaterOrEquals(denominator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(denominator_events.timestamp, plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(3600))))+ WHERE and(greaterOrEquals(denominator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(denominator_events.timestamp, plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(3600))))GROUP BY exposures.entity_id),entity_metrics AS(SELECT exposures.variant AS variant,@@ -1637,14 +1637,14 @@sum(coalesce(accurateCastOrNull(numerator_events.value, 'Float64'), 0)) AS valueFROM numerator_eventsJOIN exposures ON equals(exposures.entity_id, numerator_events.entity_id)- WHERE and(greaterOrEquals(numerator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(numerator_events.timestamp, plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(3600))))+ WHERE and(greaterOrEquals(numerator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(numerator_events.timestamp, plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(3600))))GROUP BY exposures.entity_id),denominator_agg AS(SELECT exposures.entity_id AS entity_id,sum(coalesce(accurateCastOrNull(denominator_events.value, 'Float64'), 0)) AS valueFROM denominator_eventsJOIN exposures ON equals(exposures.entity_id, denominator_events.entity_id)- WHERE and(greaterOrEquals(denominator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(denominator_events.timestamp, plus(toTimeZone(exposures.last_exposure_time, 'UTC'), toIntervalSecond(3600))))+ WHERE and(greaterOrEquals(denominator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC')), less(denominator_events.timestamp, plus(toTimeZone(exposures.first_exposure_time, 'UTC'), toIntervalSecond(3600))))GROUP BY exposures.entity_id),entity_metrics AS(SELECT exposures.variant AS variant,diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.pyindex 98616947bc98..d81c428ce629 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_funnel_metric.py@@ -2808,3 +2808,137 @@ class TestExperimentFunnelMetric(ExperimentQueryRunnerBaseTest):assert len(result.variant_results) == 1self.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-15T12:00:00Z")+ @snapshot_clickhouse_queries+ def test_maturity_anchored_on_first_exposure(self, name, use_precomputation):+ 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, 15, 0, 0, 0),+ )++ metric = ExperimentFunnelMetric(+ series=[+ EventsNode(event="$pageview"),+ EventsNode(event="purchase"),+ ],+ conversion_window=7,+ conversion_window_unit=FunnelConversionWindowTimeUnit.DAY,+ )++ 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}"++ # Backend flag re-evaluated repeatedly: first exposure Jan 2 (window ends+ # Jan 9, matured before now=Jan 15) but a later flag call lands Jan 12+ # (window ends Jan 19, not matured). Maturity must anchor on the first+ # exposure, so this user counts.+ _create_person(distinct_ids=["user_reexposed_control"], team_id=self.team.pk)+ _create_event(+ team=self.team,+ event="$feature_flag_called",+ distinct_id="user_reexposed_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="$pageview",+ distinct_id="user_reexposed_control",+ timestamp="2020-01-03T12:00:00Z",+ properties={feature_flag_property: "control"},+ )+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id="user_reexposed_control",+ timestamp="2020-01-03T13:00:00Z",+ properties={feature_flag_property: "control"},+ )+ _create_event(+ team=self.team,+ event="$feature_flag_called",+ distinct_id="user_reexposed_control",+ timestamp="2020-01-12T12:00:00Z",+ properties={+ feature_flag_property: "control",+ "$feature_flag_response": "control",+ "$feature_flag": feature_flag.key,+ },+ )++ # Same pattern for a test user.+ _create_person(distinct_ids=["user_reexposed_test"], team_id=self.team.pk)+ _create_event(+ team=self.team,+ event="$feature_flag_called",+ distinct_id="user_reexposed_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="$pageview",+ distinct_id="user_reexposed_test",+ timestamp="2020-01-03T12:00:00Z",+ properties={feature_flag_property: "test"},+ )+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id="user_reexposed_test",+ timestamp="2020-01-03T13:00:00Z",+ properties={feature_flag_property: "test"},+ )+ _create_event(+ team=self.team,+ event="$feature_flag_called",+ distinct_id="user_reexposed_test",+ timestamp="2020-01-12T12:00:00Z",+ properties={+ feature_flag_property: "test",+ "$feature_flag_response": "test",+ "$feature_flag": feature_flag.key,+ },+ )++ flush_persons_and_events()++ query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)+ result = cast(ExperimentQueryResponse, query_runner.calculate())++ assert result.baseline is not None+ self.assertEqual(result.baseline.number_of_samples, 1)+ self.assertEqual(result.baseline.sum, 1)++ assert result.variant_results is not None+ assert len(result.variant_results) == 1+ self.assertEqual(result.variant_results[0].number_of_samples, 1)+ self.assertEqual(result.variant_results[0].sum, 1)diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_mean_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_mean_metric.pyindex 60f76e495d2f..8ac8d767521a 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_mean_metric.py+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_mean_metric.py@@ -135,7 +135,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):)@freeze_time("2020-01-10T12:00:00Z")@snapshot_clickhouse_queries- def test_conversion_window_extends_to_last_exposure(self, name, use_precomputation):+ def test_conversion_window_anchored_on_first_exposure(self, name, use_precomputation):self._setup_precomputation_test(use_precomputation)feature_flag = self.create_feature_flag()@@ -170,7 +170,7 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):distinct_id = "user_control_window"_create_person(distinct_ids=[distinct_id], team_id=self.team.pk)- # First exposure happens before the conversion window, second exposure extends it.+ # Re-exposed on Jan 5, but the conversion window is measured from first exposure (Jan 2).for timestamp in ["2020-01-02T00:00:00Z", "2020-01-05T00:00:00Z"]:_create_event(team=self.team,@@ -184,15 +184,25 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):},)- # Purchase happens outside the first window but within last exposure + window.+ # Purchase sits inside first_exposure + window, so it counts._create_event(team=self.team,event="purchase",distinct_id=distinct_id,- timestamp="2020-01-05T12:00:00Z",+ timestamp="2020-01-02T12:00:00Z",properties={feature_flag_property: "control", "amount": 25},)+ # Purchase sits outside first_exposure + window (but inside last_exposure + window),+ # so it must not count once inclusion is anchored on first exposure.+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id=distinct_id,+ timestamp="2020-01-05T12:00:00Z",+ properties={feature_flag_property: "control", "amount": 100},+ )+flush_persons_and_events()query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)@@ -202,6 +212,107 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):self.assertEqual(result.baseline.sum, 25)self.assertEqual(result.baseline.number_of_samples, 1)+ @parameterized.expand(+ [+ ("direct", False),+ ("precomputed", True),+ ]+ )+ def test_matured_user_value_stable_across_re_exposure(self, name, use_precomputation):+ 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, 15, 0, 0, 0),+ )+ experiment.stats_config = {"method": "frequentist"}++ metric = ExperimentMeanMetric(+ source=EventsNode(+ event="purchase",+ math=ExperimentMetricMathType.SUM,+ math_property="amount",+ ),+ conversion_window=1,+ conversion_window_unit=FunnelConversionWindowTimeUnit.DAY,+ )++ 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}"+ distinct_id = "user_re_exposed"+ _create_person(distinct_ids=[distinct_id], team_id=self.team.pk)++ # First exposure Jan 2; the user matures at Jan 3 (first_exposure + 1 day).+ _create_event(+ team=self.team,+ event="$feature_flag_called",+ distinct_id=distinct_id,+ timestamp="2020-01-02T00:00:00Z",+ properties={+ feature_flag_property: "control",+ "$feature_flag_response": "control",+ "$feature_flag": feature_flag.key,+ },+ )+ # Purchase inside the first-exposure window is the entity's whole value.+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id=distinct_id,+ timestamp="2020-01-02T12:00:00Z",+ properties={feature_flag_property: "control", "amount": 25},+ )+ # Backend flag re-evaluated Jan 5, with another purchase in its wake.+ _create_event(+ team=self.team,+ event="$feature_flag_called",+ distinct_id=distinct_id,+ timestamp="2020-01-05T00:00:00Z",+ properties={+ feature_flag_property: "control",+ "$feature_flag_response": "control",+ "$feature_flag": feature_flag.key,+ },+ )+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id=distinct_id,+ timestamp="2020-01-05T12:00:00Z",+ properties={feature_flag_property: "control", "amount": 100},+ )++ flush_persons_and_events()++ # Re-run right after the user matures, then again after the re-exposure. The+ # matured user's value must not grow just because the flag was re-evaluated.+ with freeze_time("2020-01-04T00:00:00Z"):+ early = cast(+ ExperimentQueryResponse,+ ExperimentQueryRunner(query=experiment_query, team=self.team).calculate(),+ )+ with freeze_time("2020-01-07T00:00:00Z"):+ late = cast(+ ExperimentQueryResponse,+ ExperimentQueryRunner(query=experiment_query, team=self.team).calculate(),+ )++ assert early.baseline is not None+ assert late.baseline is not None+ self.assertEqual(early.baseline.sum, 25)+ self.assertEqual(late.baseline.sum, 25)+@parameterized.expand([("direct", False),diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.pyindex cba6b328126b..fdc7406cdf04 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_ratio_metric.py@@ -407,6 +407,119 @@ class TestExperimentRatioMetric(ExperimentQueryRunnerBaseTest):self.assertEqual(test_variant.number_of_samples, 3)self.assertEqual(test_variant.denominator_sum, 3)+ @parameterized.expand(+ [+ ("direct", False),+ ("precomputed", True),+ ]+ )+ def test_matured_user_value_stable_across_re_exposure(self, name, use_precomputation):+ from datetime import datetime++ 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, 15, 0, 0, 0),+ )+ experiment.stats_config = {"method": "frequentist"}++ metric = ExperimentRatioMetric(+ numerator=EventsNode(+ event="purchase",+ math=ExperimentMetricMathType.SUM,+ math_property="amount",+ ),+ denominator=EventsNode(+ event="pageview",+ math=ExperimentMetricMathType.TOTAL,+ ),+ conversion_window=1,+ conversion_window_unit=FunnelConversionWindowTimeUnit.DAY,+ )++ 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)++ ff_property = f"$feature/{feature_flag.key}"+ distinct_id = "user_re_exposed"+ _create_person(distinct_ids=[distinct_id], team_id=self.team.pk)++ def _flag_call(timestamp: str) -> None:+ _create_event(+ team=self.team,+ event="$feature_flag_called",+ distinct_id=distinct_id,+ timestamp=timestamp,+ properties={+ ff_property: "control",+ "$feature_flag_response": "control",+ "$feature_flag": feature_flag.key,+ },+ )++ # First exposure Jan 2 with one purchase + one pageview inside the window.+ _flag_call("2020-01-02T00:00:00Z")+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id=distinct_id,+ timestamp="2020-01-02T12:00:00Z",+ properties={ff_property: "control", "amount": 25},+ )+ _create_event(+ team=self.team,+ event="pageview",+ distinct_id=distinct_id,+ timestamp="2020-01-02T12:00:00Z",+ properties={ff_property: "control"},+ )+ # Backend flag re-evaluated Jan 5, with more events in its wake.+ _flag_call("2020-01-05T00:00:00Z")+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id=distinct_id,+ timestamp="2020-01-05T12:00:00Z",+ properties={ff_property: "control", "amount": 100},+ )+ _create_event(+ team=self.team,+ event="pageview",+ distinct_id=distinct_id,+ timestamp="2020-01-05T12:00:00Z",+ properties={ff_property: "control"},+ )++ flush_persons_and_events()++ with freeze_time("2020-01-04T00:00:00Z"):+ early = cast(+ ExperimentQueryResponse,+ ExperimentQueryRunner(query=experiment_query, team=self.team).calculate(),+ )+ with freeze_time("2020-01-07T00:00:00Z"):+ late = cast(+ ExperimentQueryResponse,+ ExperimentQueryRunner(query=experiment_query, team=self.team).calculate(),+ )++ assert early.baseline is not None+ assert late.baseline is not None+ self.assertEqual(early.baseline.sum, 25)+ self.assertEqual(early.baseline.denominator_sum, 1)+ self.assertEqual(late.baseline.sum, 25)+ self.assertEqual(late.baseline.denominator_sum, 1)+@parameterized.expand([("direct", False),