: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
refactor(experiments): evaluate metric maturity through one gate (#109410)
Anders9d0ba271da97
diff --git a/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.py b/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.pyindex b6816e4b51bd..b92588295775 100644--- a/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_exposure_query_builder.py@@ -1,5 +1,3 @@-from collections.abc import Callable-from posthog.schema import ExperimentEventExposureConfig, MultipleVariantHandlingfrom posthog.hogql import ast@@ -9,7 +7,7 @@ from posthog.hogql.property import property_to_exprfrom products.experiments.backend.hogql_queries import MULTIPLE_VARIANT_KEYfrom products.experiments.backend.hogql_queries.base_query_utils import event_or_action_to_filterfrom products.experiments.backend.hogql_queries.breakdown_injector import BreakdownInjector-from products.experiments.backend.hogql_queries.experiment_query_context import ExperimentQueryContext+from products.experiments.backend.hogql_queries.experiment_query_context import ExperimentQueryContext, MaturityGatefrom products.experiments.backend.hogql_queries.exposure_query_logic import (DEFAULT_EXPOSURE_EVENT,EXPERIMENT_EXPOSURE_EVENT,@@ -54,28 +52,30 @@ class ExposureQueryBuilder:The builder takes the experiment-level invariants via ``ExperimentQueryContext``plus the narrow inputs that depend on the current metric/precomputation state:- the optional ``breakdown_injector``, a ``maturity_having_builder`` callable- (which produces the maturity HAVING clause for a given timestamp expression),- and the optional ``preaggregation_job_ids`` used to read from the precomputed- exposures table instead of scanning events.+ the optional ``breakdown_injector``, the ``maturity`` gate of the current build+ with the metric's ``maturity_window_seconds`` (the window starts at the entity's+ first exposure), and the optional ``preaggregation_job_ids`` used to read from+ the precomputed exposures table instead of scanning events."""def __init__(self,context: ExperimentQueryContext,breakdown_injector: BreakdownInjector | None = None,- maturity_having_builder: Callable[[str], ast.Expr | None] | None = None,+ maturity: MaturityGate | None = None,+ maturity_window_seconds: int = 0,preaggregation_job_ids: list[str] | None = None,):self.context = contextself.breakdown_injector = breakdown_injector- self.maturity_having_builder = maturity_having_builder+ self.maturity = maturity+ self.maturity_window_seconds = maturity_window_secondsself.preaggregation_job_ids = preaggregation_job_ids- def _maturity_having(self, timestamp_expr: str = "timestamp") -> ast.Expr | None:- if self.maturity_having_builder is None:+ def _maturity_having(self, first_exposure_time: ast.Expr) -> ast.Expr | None:+ if self.maturity is None:return None- return self.maturity_having_builder(timestamp_expr)+ return self.maturity.condition(first_exposure_time, self.maturity_window_seconds)def timeseries_query(self) -> ast.SelectQuery:"""Daily exposure counts per variant. Each entity counts once, on its first exposure day."""@@ -426,7 +426,7 @@ class ExposureQueryBuilder:exposure_query.select.append(ast.Alias(alias=alias, expr=breakdown_attributed))# Filter out users whose conversion window hasn't elapsed yet- maturity_having = self._maturity_having()+ maturity_having = self._maturity_having(parse_expr("min(timestamp)"))if maturity_having is not None:if exposure_query.having is None:exposure_query.having = maturity_having@@ -478,7 +478,7 @@ class ExposureQueryBuilder:# 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")+ maturity_having = self._maturity_having(parse_expr("min(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 010d8bf58f40..1348c74c6f0a 100644--- a/products/experiments/backend/hogql_queries/experiment_funnel_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_funnel_query_builder.py@@ -1,7 +1,5 @@from typing import TYPE_CHECKING, Optional, cast-from django.utils import timezone-from posthog.schema import ExperimentDataWarehouseNode, ExperimentFunnelMetric, MultipleVariantHandling, StepOrderValuefrom posthog.hogql import ast@@ -15,6 +13,7 @@ from products.experiments.backend.hogql_queries.base_query_utils import (funnel_evaluation_expr,funnel_steps_to_filter,)+from products.experiments.backend.hogql_queries.experiment_query_context import MaturityGatefrom products.experiments.backend.hogql_queries.funnel_step_builder import FunnelStepBuilderfrom products.experiments.backend.hogql_queries.funnel_validation import FunnelDWValidatorfrom products.experiments.backend.hogql_queries.metric_source import MetricSourceInfo@@ -42,8 +41,9 @@ class FunnelQueryBuilder:reads that shared state and those helpers through it."""- def __init__(self, builder: "ExperimentQueryBuilder"):+ def __init__(self, builder: "ExperimentQueryBuilder", maturity: MaturityGate | None = None):self._b = builder+ self._maturity = maturitydef build_funnel_query(self) -> ast.SelectQuery:if self.should_use_optimized_funnel_query():@@ -184,7 +184,7 @@ class FunnelQueryBuilder:)"""- exposure_query = self._b._get_exposure_query()+ exposure_query = self._b._get_exposure_query(self._maturity)if has_dw_steps:# FunnelDWValidator guarantees that all DW steps use the same events_join_keyfirst_dw_step = next(s for s in self._b.metric.series if isinstance(s, ExperimentDataWarehouseNode))@@ -840,20 +840,8 @@ class FunnelQueryBuilder:on the last exposure would keep resetting the window for flags re-evaluatedrepeatedly (e.g. backend flags), so active users would never mature."""- if self._b.metric is None:- return None- if not self._b.only_count_matured_users:- return None-- maturity_seconds = self._b._get_maturity_window_seconds()- if maturity_seconds == 0:+ if self._maturity is None:return None-- now = timezone.now().strftime("%Y-%m-%d %H:%M:%S")- return parse_expr(- "minIf(timestamp, step_0 = 1) + toIntervalSecond({maturity_seconds}) <= toDateTime({now}, 'UTC')",- placeholders={- "maturity_seconds": ast.Constant(value=maturity_seconds),- "now": ast.Constant(value=now),- },+ return self._maturity.condition(+ parse_expr("minIf(timestamp, step_0 = 1)"), self._b._get_maturity_window_seconds())diff --git a/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py b/products/experiments/backend/hogql_queries/experiment_mean_query_builder.pyindex 5e6eaa0af84c..8b7f5d7919df 100644--- a/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py@@ -16,6 +16,7 @@ from products.experiments.backend.hogql_queries.base_query_utils import (is_session_property_metric,validate_session_property,)+from products.experiments.backend.hogql_queries.experiment_query_context import MaturityGatefrom products.experiments.backend.hogql_queries.metric_source import MetricSourceInfoif TYPE_CHECKING:@@ -32,8 +33,9 @@ class MeanQueryBuilder:and the shared exposure, metric-value, and CUPED helpers through it."""- def __init__(self, builder: "ExperimentQueryBuilder"):+ def __init__(self, builder: "ExperimentQueryBuilder", maturity: MaturityGate | None = None):self._b = builder+ self._maturity = maturitydef get_session_property_ctes(self) -> str:"""@@ -206,7 +208,7 @@ class MeanQueryBuilder:source_info = MetricSourceInfo.from_source(self._b.metric.source, entity_key=self._b.entity_key)- exposure_query = self._b._get_exposure_query()+ exposure_query = self._b._get_exposure_query(self._maturity)if source_info.kind == "datawarehouse":assert isinstance(self._b.metric.source, ExperimentDataWarehouseNode)events_join_key_parts = cast(list[str | int], self._b.metric.source.events_join_key.split("."))@@ -272,7 +274,7 @@ class MeanQueryBuilder:"""Placeholders for the CTEs from get_session_property_ctes()."""assert isinstance(self._b.metric, ExperimentMeanMetric)- exposure_query = self._b._get_exposure_query()+ exposure_query = self._b._get_exposure_query(self._maturity)return {"exposure_select_query": exposure_query,diff --git a/products/experiments/backend/hogql_queries/experiment_query_builder.py b/products/experiments/backend/hogql_queries/experiment_query_builder.pyindex 55c108b4fb1a..18b424a2783b 100644--- a/products/experiments/backend/hogql_queries/experiment_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_query_builder.py@@ -18,7 +18,6 @@ from posthog.schema import (from posthog.hogql import astfrom posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS-from posthog.hogql.parser import parse_exprfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models.team.team import Team@@ -41,6 +40,7 @@ from products.experiments.backend.hogql_queries.experiment_metric_values importfrom products.experiments.backend.hogql_queries.experiment_query_context import (ExperimentPrecomputationContext,ExperimentQueryContext,+ MaturityGate,)from products.experiments.backend.hogql_queries.experiment_ratio_query_builder import RatioQueryBuilderfrom products.experiments.backend.hogql_queries.experiment_retention_query_builder import RetentionQueryBuilder@@ -194,16 +194,19 @@ class ExperimentQueryBuilder:self.preaggregation_job_ids = precomputation_context.exposure_job_idsself.metric_events_preaggregation_job_ids = precomputation_context.metric_events_job_ids+ # The only clock read of a build, so every maturity filter in the query uses the same cutoff.+ maturity = MaturityGate.of(self.context, computed_at=timezone.now())+assert self.metric is not None, "metric is required for build_query()"match self.metric:case ExperimentFunnelMetric():- query = self._build_funnel_query()+ query = self._build_funnel_query(maturity)case ExperimentMeanMetric():- query = self._build_mean_query()+ query = self._build_mean_query(maturity)case ExperimentRatioMetric():- query = self._build_ratio_query()+ query = self._build_ratio_query(maturity)case ExperimentRetentionMetric():- query = self._build_retention_query()+ query = self._build_retention_query(maturity)case _:raise NotImplementedError(f"Only funnel, mean, ratio, and retention metrics are supported. Got {type(self.metric)}"@@ -212,26 +215,30 @@ class ExperimentQueryBuilder:query.limit = ast.Constant(value=self.QUERY_RESULT_LIMIT)return query- def _exposure_query_builder(self) -> ExposureQueryBuilder:- """Built per call so it picks up the ``preaggregation_job_ids`` that build_query() sets."""+ def _exposure_query_builder(self, maturity: MaturityGate | None = None) -> ExposureQueryBuilder:+ """+ Built per call so it picks up the ``preaggregation_job_ids`` that build_query() sets.+ Only the exposure select of build_query() passes ``maturity``.+ """return ExposureQueryBuilder(context=self.context,breakdown_injector=self.breakdown_injector,- maturity_having_builder=self._build_maturity_having_clause,+ maturity=maturity,+ maturity_window_seconds=self._get_maturity_window_seconds(),preaggregation_job_ids=self.preaggregation_job_ids,)- def _funnel_query_builder(self) -> FunnelQueryBuilder:- return FunnelQueryBuilder(self)+ def _funnel_query_builder(self, maturity: MaturityGate | None = None) -> FunnelQueryBuilder:+ return FunnelQueryBuilder(self, maturity=maturity)- def _retention_query_builder(self) -> RetentionQueryBuilder:- return RetentionQueryBuilder(self)+ def _retention_query_builder(self, maturity: MaturityGate | None = None) -> RetentionQueryBuilder:+ return RetentionQueryBuilder(self, maturity=maturity)- def _mean_query_builder(self) -> MeanQueryBuilder:- return MeanQueryBuilder(self)+ def _mean_query_builder(self, maturity: MaturityGate | None = None) -> MeanQueryBuilder:+ return MeanQueryBuilder(self, maturity=maturity)- def _ratio_query_builder(self) -> RatioQueryBuilder:- return RatioQueryBuilder(self)+ def _ratio_query_builder(self, maturity: MaturityGate | None = None) -> RatioQueryBuilder:+ return RatioQueryBuilder(self, maturity=maturity)def _cuped_query_builder(self) -> CupedQueryBuilder:return CupedQueryBuilder(self)@@ -257,54 +264,27 @@ class ExperimentQueryBuilder:def _get_maturity_window_seconds(self) -> int:"""- Non-retention metrics only. Retention uses- RetentionQueryBuilder.get_retention_maturity_seconds() and applies maturity- in its start_events CTE, anchored on the start_event timestamp.+ The maturity window that starts at the entity's first exposure: the conversion+ window, or 0 when there is no metric. Anchored on the first exposure, 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.++ Retention returns 0: it applies maturity in its start_events CTE, anchored on+ the start_event timestamp, with RetentionQueryBuilder.get_retention_maturity_seconds()."""+ if self.metric is None or isinstance(self.metric, ExperimentRetentionMetric):+ return 0return self._get_conversion_window_seconds()- 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.-- 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 apply maturity in their own start_events CTE through- RetentionQueryBuilder.build_retention_maturity_having_clause(), so this- 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-- maturity_seconds = self._get_maturity_window_seconds()- if maturity_seconds == 0:- return None-- now = timezone.now().strftime("%Y-%m-%d %H:%M:%S")- return parse_expr(- f"min({timestamp_expr}) + toIntervalSecond({{maturity_seconds}}) <= toDateTime({{now}}, 'UTC')",- placeholders={- "maturity_seconds": ast.Constant(value=maturity_seconds),- "now": ast.Constant(value=now),- },- )-- def _build_funnel_query(self) -> ast.SelectQuery:- return self._funnel_query_builder().build_funnel_query()+ def _build_funnel_query(self, maturity: MaturityGate) -> ast.SelectQuery:+ return self._funnel_query_builder(maturity).build_funnel_query()- def _build_mean_query(self) -> ast.SelectQuery:- return self._mean_query_builder().build_mean_query()+ def _build_mean_query(self, maturity: MaturityGate) -> ast.SelectQuery:+ return self._mean_query_builder(maturity).build_mean_query()- def _build_ratio_query(self) -> ast.SelectQuery:- return self._ratio_query_builder().build_ratio_query()+ def _build_ratio_query(self, maturity: MaturityGate) -> ast.SelectQuery:+ return self._ratio_query_builder(maturity).build_ratio_query()def _build_conversion_window_predicate(self) -> ast.Expr:"""Uses "metric_events" as the events alias."""@@ -420,8 +400,8 @@ class ExperimentQueryBuilder:"""return self._exposure_query_builder().build_exposure_step_predicate()- def _get_exposure_query(self) -> ast.SelectQuery:- return self._exposure_query_builder().select_query()+ def _get_exposure_query(self, maturity: MaturityGate | None = None) -> ast.SelectQuery:+ return self._exposure_query_builder(maturity).select_query()def get_exposure_query_for_precomputation(self) -> tuple[str, dict[str, ast.Expr]]:"""@@ -462,5 +442,5 @@ class ExperimentQueryBuilder:return self._retention_query_builder().get_metric_events_window_extension_seconds()return self._get_conversion_window_seconds()- def _build_retention_query(self) -> ast.SelectQuery:- return self._retention_query_builder().build_retention_query()+ def _build_retention_query(self, maturity: MaturityGate) -> ast.SelectQuery:+ return self._retention_query_builder(maturity).build_retention_query()diff --git a/products/experiments/backend/hogql_queries/experiment_query_context.py b/products/experiments/backend/hogql_queries/experiment_query_context.pyindex 2c10b53972cd..b0451f3f7e4e 100644--- a/products/experiments/backend/hogql_queries/experiment_query_context.py+++ b/products/experiments/backend/hogql_queries/experiment_query_context.py@@ -1,7 +1,12 @@from dataclasses import dataclass+from datetime import UTC, datetimefrom posthog.schema import ActionsNode, Breakdown, ExperimentEventExposureConfig, MultipleVariantHandling+from posthog.hogql import ast+from posthog.hogql.parser import parse_expr++from posthog.dataclasses import frozenfrom posthog.hogql_queries.utils.query_date_range import QueryDateRangefrom posthog.models.team.team import Team@@ -42,3 +47,36 @@ class ExperimentPrecomputationContext:exposure_job_ids: list[str] | None = Nonemetric_events_job_ids: list[str] | None = None+++@frozen+class MaturityGate:+ """Excludes entities whose maturity window has not ended when the query is built.++ Every maturity filter of one build uses this gate, so they all compare against+ the same cutoff. ``computed_at`` is the only time input.+ """++ enabled: bool+ computed_at: datetime++ @classmethod+ def of(cls, context: ExperimentQueryContext, *, computed_at: datetime) -> "MaturityGate":+ return cls(enabled=context.only_count_matured_users, computed_at=computed_at)++ def condition(self, anchor: ast.Expr, window_seconds: int) -> ast.Expr | None:+ """``anchor + window <= cutoff``, or None when maturity filtering is off or the window is empty.++ ``anchor`` is the per-entity timestamp that the window starts from, for example+ ``min(timestamp)`` of the exposure events.+ """+ if not self.enabled or window_seconds == 0:+ return None+ return parse_expr(+ "{anchor} + toIntervalSecond({window_seconds}) <= toDateTime({cutoff}, 'UTC')",+ placeholders={+ "anchor": anchor,+ "window_seconds": ast.Constant(value=window_seconds),+ "cutoff": ast.Constant(value=self.computed_at.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S")),+ },+ )diff --git a/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.py b/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.pyindex 5f92fb1e78a7..12c32fc065a9 100644--- a/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_ratio_query_builder.py@@ -5,6 +5,7 @@ from posthog.schema import ExperimentDataWarehouseNode, ExperimentMetricOutlierHfrom posthog.hogql import astfrom posthog.hogql.parser import parse_expr, parse_select+from products.experiments.backend.hogql_queries.experiment_query_context import MaturityGatefrom products.experiments.backend.hogql_queries.metric_source import MetricSourceInfoif TYPE_CHECKING:@@ -20,8 +21,9 @@ class RatioQueryBuilder:exposure and metric-value helpers through it."""- def __init__(self, builder: "ExperimentQueryBuilder"):+ def __init__(self, builder: "ExperimentQueryBuilder", maturity: MaturityGate | None = None):self._b = builder+ self._maturity = maturitydef build_ratio_query(self) -> ast.SelectQuery:assert isinstance(self._b.metric, ExperimentRatioMetric)@@ -218,7 +220,7 @@ class RatioQueryBuilder:denom_entity_field = denom_source_info.entity_keydenom_timestamp_field = denom_source_info.timestamp_field- exposure_query = self._b._get_exposure_query()+ exposure_query = self._b._get_exposure_query(self._maturity)if num_source_info.kind == "datawarehouse" or denom_source_info.kind == "datawarehouse":# argMin takes each join key from the first exposure, so each entity_id gets one# identifier per component. Do not add the join keys to GROUP BY: a user withdiff --git a/products/experiments/backend/hogql_queries/experiment_retention_query_builder.py b/products/experiments/backend/hogql_queries/experiment_retention_query_builder.pyindex d3783041640d..cc2bf5471ca0 100644--- a/products/experiments/backend/hogql_queries/experiment_retention_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_retention_query_builder.py@@ -1,7 +1,5 @@from typing import TYPE_CHECKING, Optional-from django.utils import timezone-from posthog.schema import (ActionsNode,EventsNode,@@ -22,6 +20,7 @@ from products.experiments.backend.hogql_queries.base_query_utils import (data_warehouse_node_to_filter,event_or_action_to_filter,)+from products.experiments.backend.hogql_queries.experiment_query_context import MaturityGateif TYPE_CHECKING:from products.experiments.backend.hogql_queries.experiment_query_builder import ExperimentQueryBuilder@@ -38,8 +37,9 @@ class RetentionQueryBuilder:through it."""- def __init__(self, builder: "ExperimentQueryBuilder"):+ def __init__(self, builder: "ExperimentQueryBuilder", maturity: MaturityGate | None = None):self._b = builder+ self._maturity = maturitydef get_retention_maturity_seconds(self) -> int:"""@@ -130,21 +130,12 @@ class RetentionQueryBuilder:"""assert isinstance(self._b.metric, ExperimentRetentionMetric)- if not self._b.only_count_matured_users:- return ast.Constant(value=True)-- maturity_seconds = self.get_retention_maturity_seconds()- if maturity_seconds == 0:+ if self._maturity is None:return ast.Constant(value=True)-- now = timezone.now().strftime("%Y-%m-%d %H:%M:%S")- return parse_expr(- "exposures.first_exposure_time + toIntervalSecond({maturity_seconds}) <= toDateTime({now}, 'UTC')",- placeholders={- "maturity_seconds": ast.Constant(value=maturity_seconds),- "now": ast.Constant(value=now),- },+ condition = self._maturity.condition(+ parse_expr("exposures.first_exposure_time"), self.get_retention_maturity_seconds())+ return condition if condition is not None else ast.Constant(value=True)def build_retention_maturity_having_clause(self) -> Optional[ast.Expr]:"""@@ -157,24 +148,9 @@ class RetentionQueryBuilder:"""if not isinstance(self._b.metric, ExperimentRetentionMetric):return None- if not self._b.only_count_matured_users:+ if self._maturity is None: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),- },- )+ return self._maturity.condition(self.build_start_event_timestamp_expr(), self.get_retention_maturity_seconds())def build_retention_query(self) -> ast.SelectQuery:"""@@ -326,7 +302,7 @@ class RetentionQueryBuilder:)placeholders = {- "exposure_select_query": self._b._get_exposure_query(),+ "exposure_select_query": self._b._get_exposure_query(self._maturity),"entity_key": parse_expr(self._b.entity_key),"completion_event_predicate": self.build_completion_event_predicate(),"retention_window_start_interval": self.build_retention_window_interval(