: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
feat(experiments): tag metric-events precompute skip reason (#113706)
Juraj Majerik41c1692fb6f6
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 71877f2d5927..9492c5acae3a 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -512,6 +512,11 @@ class QueryTags(BaseModel):replay_event_query_operand: Optional[Literal["AND", "OR"]] = Nonereplay_event_query_range_days: Optional[float] = Noneexperiment_metric_events_path: Optional[str] = None # "direct_scan", "precomputed", or "not_applicable"+ # Why the metric-events side is not precomputable (set on the metric read when metric_events_path is+ # "not_applicable"): "breakdown", "cuped", "data_warehouse", "funnel_order_type", "non_event_source",+ # "session_property_math", "group_math", "unsupported_math", "retention_window", or "metric_type"+ # (ratio). None/absent when the metric-events side is precomputable.+ experiment_metric_events_skip_reason: Optional[str] = Noneexperiment_query_surface: Optional[str] = None # "metric", "exposures_timeseries", "actors", "precompute_build"experiment_precompute_table: Optional[str] = None # on precompute_build rows: "exposures" or "metric_events"# Why precompute was not used (set on the metric read). One of "override_direct", "team_disabled",diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.pyindex df74bfcf0c82..74f06d1d92aa 100644--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py@@ -477,28 +477,41 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):return None # precompute was attempted; a direct path means the build failed / wasn't readydef _metric_events_precompute_applicable(self) -> bool:+ return self._metric_events_ineligibility_reason() is None++ def _metric_events_ineligibility_reason(self) -> Optional[str]:"""- Metric-events precompute supports ordered funnels, mean metrics with- numeric math (count/sum/avg/min/max) or ID-valued math (unique users /- unique sessions), and retention metrics, in all cases without- breakdowns, CUPED, or data warehouse sources.+ Why metric-events precompute cannot serve this metric, or None when it can.+ Supported: ordered funnels, mean metrics with numeric math (count/sum/avg/min/max)+ or ID-valued math (unique users / unique sessions), and retention metrics, in all+ cases without breakdowns, CUPED, or data warehouse sources.++ Tagged on the read as `experiment_metric_events_skip_reason`, the metric-events+ counterpart of `experiment_precompute_skip_reason`, so query-log analysis can split+ the not_applicable path by cause. Values are part of that reporting contract."""+ if self._get_breakdowns_for_builder():+ return "breakdown"# CUPED extends the metric scan back by lookback_days for the pre-exposure covariate,# but the precomputed metric_events table covers only the experiment window.- if self._get_breakdowns_for_builder() or self.cuped_config.enabled or self.is_data_warehouse_query:- return False+ if self.cuped_config.enabled:+ return "cuped"+ if self.is_data_warehouse_query:+ return "data_warehouse"if isinstance(self.metric, ExperimentFunnelMetric):- return (self.metric.funnel_order_type or "ordered") == "ordered"+ if (self.metric.funnel_order_type or "ordered") == "ordered":+ return None+ return "funnel_order_type"if isinstance(self.metric, ExperimentMeanMetric):source = self.metric.sourceif not isinstance(source, (EventsNode, ActionsNode)):- return False+ return "non_event_source"# Session-property means aggregate via a per-session dedup CTE that the# precomputed table can't feed. Unique-group math is excluded because# the build INSERT can't resolve $group_N (MATERIALIZED on# sharded_events), and HogQL math because user expressions are arbitrary.if is_session_property_metric(source):- return False+ return "session_property_math"math_type = getattr(source, "math", None) or ExperimentMetricMathType.TOTAL# Numeric math types are safe because the build query stores the same# coalesced per-event float regardless of math type, and the math is@@ -510,26 +523,28 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):ExperimentMetricMathType.MIN,ExperimentMetricMathType.MAX,):- return True+ return None# unique_session counts distinct session_id, which every mean build stores.if math_type == ExperimentMetricMathType.UNIQUE_SESSION:- return True+ return None# dau counts distinct entity_id, which is the person id only when the# experiment is person-keyed. Group experiments never reach precompute,# but keep the guard explicit in case that exclusion is ever lifted.if math_type == ExperimentMetricMathType.DAU:- return self.group_type_index is None- return False+ return None if self.group_type_index is None else "group_math"+ return "unsupported_math"if isinstance(self.metric, ExperimentRetentionMetric):if not isinstance(self.metric.start_event, (EventsNode, ActionsNode)) or not isinstance(self.metric.completion_event, (EventsNode, ActionsNode)):- return False+ return "non_event_source"extension_seconds = get_conversion_window_seconds(self.metric) + conversion_window_to_seconds(self.metric.retention_window_end, self.metric.retention_window_unit)- return extension_seconds <= METRIC_EVENTS_MAX_WINDOW_EXTENSION_SECONDS- return False+ if extension_seconds <= METRIC_EVENTS_MAX_WINDOW_EXTENSION_SECONDS:+ return None+ return "retention_window"+ return "metric_type"@propertydef metric_events_path(self) -> str:@@ -659,6 +674,7 @@ class ExperimentQueryRunner(ExperimentResultsCacheMixin, QueryRunner):tag_queries(experiment_exposures_path=exposures_path,experiment_metric_events_path=metric_events_path,+ experiment_metric_events_skip_reason=self._metric_events_ineligibility_reason(),experiment_execution_path=exposures_path,experiment_precompute_skip_reason=skip_reason.value if skip_reason is not None else None,experiment_scan_date_from=self.date_range.date_from,diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_mean_metric_events_preaggregation.py b/products/experiments/backend/hogql_queries/test/test_experiment_mean_metric_events_preaggregation.pyindex 64e313e933ed..276217be73b7 100644--- a/products/experiments/backend/hogql_queries/test/test_experiment_mean_metric_events_preaggregation.py+++ b/products/experiments/backend/hogql_queries/test/test_experiment_mean_metric_events_preaggregation.py@@ -207,55 +207,55 @@ class TestExperimentMeanMetricEventsPreaggregation(ExperimentQueryRunnerBaseTest@parameterized.expand([- ("count_default_math", EventsNode(event="purchase"), True),+ ("count_default_math", EventsNode(event="purchase"), None),("sum",EventsNode(event="purchase", math=ExperimentMetricMathType.SUM, math_property="amount"),- True,+ None,),("avg",EventsNode(event="purchase", math=ExperimentMetricMathType.AVG, math_property="amount"),- True,+ None,),("min",EventsNode(event="purchase", math=ExperimentMetricMathType.MIN, math_property="amount"),- True,+ None,),("max",EventsNode(event="purchase", math=ExperimentMetricMathType.MAX, math_property="amount"),- True,+ None,),("unique_session",EventsNode(event="purchase", math=ExperimentMetricMathType.UNIQUE_SESSION),- True,+ None,),("dau",EventsNode(event="purchase", math=ExperimentMetricMathType.DAU),- True,+ None,),("unique_group",EventsNode(event="purchase", math=ExperimentMetricMathType.UNIQUE_GROUP, math_group_type_index=1),- False,+ "unsupported_math",),("hogql_user_expression",EventsNode(event="purchase", math=ExperimentMetricMathType.HOGQL, math_hogql="sum(properties.amount)"),- False,+ "unsupported_math",),("session_property",EventsNode(event="purchase", math=ExperimentMetricMathType.SUM, math_property="$session_duration"),- False,+ "session_property_math",),])- def test_mean_metric_events_precompute_gate(self, _name, source, applicable):+ def test_mean_metric_events_precompute_gate(self, _name, source, skip_reason):feature_flag = self.create_feature_flag(key="mean-metric-events-gate")experiment = self.create_experiment(feature_flag=feature_flag,@@ -266,4 +266,5 @@ class TestExperimentMeanMetricEventsPreaggregation(ExperimentQueryRunnerBaseTestrunner = self._build_runner(experiment, metric)- assert runner._metric_events_precompute_applicable() is applicable+ assert runner._metric_events_ineligibility_reason() == skip_reason+ assert runner._metric_events_precompute_applicable() is (skip_reason is None)diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_retention_metric_events_preaggregation.py b/products/experiments/backend/hogql_queries/test/test_experiment_retention_metric_events_preaggregation.pyindex 4d26f72a1fad..9b0154002db2 100644--- a/products/experiments/backend/hogql_queries/test/test_experiment_retention_metric_events_preaggregation.py+++ b/products/experiments/backend/hogql_queries/test/test_experiment_retention_metric_events_preaggregation.py@@ -322,20 +322,20 @@ class TestExperimentRetentionMetricEventsPreaggregation(ExperimentQueryRunnerBas@parameterized.expand([- ("events_nodes", _retention_metric(), True),- ("data_warehouse_start", _retention_metric(start_event=DW_NODE), False),- ("data_warehouse_completion", _retention_metric(completion_event=DW_NODE), False),+ ("events_nodes", _retention_metric(), None),+ ("data_warehouse_start", _retention_metric(start_event=DW_NODE), "data_warehouse"),+ ("data_warehouse_completion", _retention_metric(completion_event=DW_NODE), "data_warehouse"),("breakdown",_retention_metric(breakdown_filter=BreakdownFilter(breakdowns=[Breakdown(property="$browser")])),- False,+ "breakdown",),# retention_window_end is an unrestricted user input; an absurd window must# not stretch the precompute horizon into thousands of daily build jobs- ("window_beyond_precompute_horizon", _retention_metric(retention_window_end=10_000), False),+ ("window_beyond_precompute_horizon", _retention_metric(retention_window_end=10_000), "retention_window"),])- def test_retention_metric_events_precompute_gate(self, _name, metric, applicable):+ def test_retention_metric_events_precompute_gate(self, _name, metric, skip_reason):feature_flag = self.create_feature_flag(key="retention-metric-events-gate")experiment = self.create_experiment(feature_flag=feature_flag,@@ -345,4 +345,5 @@ class TestExperimentRetentionMetricEventsPreaggregation(ExperimentQueryRunnerBasrunner = self._build_runner(experiment, metric)- assert runner._metric_events_precompute_applicable() is applicable+ assert runner._metric_events_ineligibility_reason() == skip_reason+ assert runner._metric_events_precompute_applicable() is (skip_reason is None)