: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): Precompute metric events for id-valued mean math (#98356)
Juraj Majerikbaff1f15ffcb
diff --git a/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md b/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.mdindex c546d6154e3a..33cb0006ad4a 100644--- a/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md+++ b/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md@@ -200,7 +200,7 @@ The exposure precomputation does NOT need this extension — exposures only occu## Scope-Implemented for **ordered funnels**, **count/sum/avg/min/max mean metrics** (per-event value stored in `numeric_value`, deduplicated on read by event identity since replayed build rows would double sums and skew averages; the aggregation itself runs at read time, so all five math types store identical rows), and **retention metrics**. Unordered funnels and ratio metrics are not yet precomputed; breakdowns, CUPED, and data warehouse sources always fall back to a direct scan.+Implemented for **ordered funnels**, **count/sum/avg/min/max mean metrics** (per-event value stored in `numeric_value`, deduplicated on read by event identity since replayed build rows would double sums and skew averages; the aggregation itself runs at read time, so all five math types store identical rows), **dau/unique_session mean metrics** (the read counts distinct IDs from `entity_id`/`session_id`, which every mean build stores; `numeric_value` holds the same constant a count metric stores, so a count metric and an ID-math metric on the same source share build jobs), and **retention metrics**. Unordered funnels, unique-group and HogQL math, and ratio metrics are not precomputed; breakdowns, CUPED, and data warehouse sources always fall back to a direct scan.Retention stores one row per event matching the start or completion predicate, with two flags in `steps` (`steps[1]` = matched start_event, `steps[2]` = matched completion_event; one event can match both). The read path swaps the two raw-events CTE sources for flag-filtered reads of the precomputed table; start anchoring (FIRST_SEEN/LAST_SEEN), the per-user retention window, the maturity gate, and the same-event exclusion all stay read-time, so they behave identically on both paths. The scan extension past the experiment end is `conversion_window + retention_window_end` rather than the conversion window alone, and retention is gated behind the default-off `experiments-retention-metric-events-preaggregation` flag (fail-safe: absent or unevaluable means direct scan) so it can be disabled independently of funnel/mean.diff --git a/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py b/products/experiments/backend/hogql_queries/experiment_mean_query_builder.pyindex 8857fa20ac6d..111573cdd585 100644--- a/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py@@ -1,6 +1,12 @@from typing import TYPE_CHECKING, cast-from posthog.schema import ActionsNode, EventsNode, ExperimentDataWarehouseNode, ExperimentMeanMetric+from posthog.schema import (+ ActionsNode,+ EventsNode,+ ExperimentDataWarehouseNode,+ ExperimentMeanMetric,+ ExperimentMetricMathType,+)from posthog.hogql import astfrom posthog.hogql.parser import parse_expr, parse_select@@ -140,12 +146,22 @@ class MeanQueryBuilder:# INSERT would otherwise double-count sums. Same defense as the exposures read;# the funnel read skips it because funnel evaluation tolerates duplicate events.entity_id_cast = "toUUID(t.entity_id)" if self._b.entity_key == "person_id" else "t.entity_id"+ # For ID-valued math the value is the ID itself: the stored entity_id+ # is the person id (dau) and session_id is the unique_session value,+ # so the downstream count(distinct) matches the direct path.+ math_type = getattr(self._b.metric.source, "math", None) or ExperimentMetricMathType.TOTAL+ if math_type == ExperimentMetricMathType.DAU:+ value_select = entity_id_cast+ elif math_type == ExperimentMetricMathType.UNIQUE_SESSION:+ value_select = "any(t.session_id)"+ else:+ value_select = "any(t.numeric_value)"metric_events_cte = f"""metric_events AS (SELECT{entity_id_cast} AS entity_id,t.timestamp AS timestamp,- any(t.numeric_value) AS value+ {value_select} AS valueFROM experiment_metric_events_preaggregated AS tWHERE t.job_id IN {{metric_events_job_ids}}AND t.team_id = {{metric_events_team_id}}@@ -290,9 +306,13 @@ class MeanQueryBuilder:Returns the SELECT query that the lazy computation system wraps in anINSERT INTO experiment_metric_events_preaggregated. This is the writepath — it scans the events table and stores one row per matching metric- event with its per-event value in numeric_value. The value is already- coalesced to a non-null float by _build_value_expr(), so storing it in- the non-nullable numeric_value column is lossless.+ event with its per-event value in numeric_value. For numeric math the+ value is already coalesced to a non-null float by _build_value_expr(),+ so storing it in the non-nullable numeric_value column is lossless.+ For ID-valued math (dau, unique_session) the read side counts distinct+ IDs from entity_id/session_id instead, and numeric_value stores the+ same constant a count metric stores, so the build query hashes the same+ as a count metric on the same source and the two share precompute jobs.The query uses {time_window_min} and {time_window_max} placeholders filledby the lazy computation system for each daily bucket. The experiment date@@ -323,9 +343,21 @@ class MeanQueryBuilder:AND {metric_event_filter}"""+ math_type = getattr(source, "math", None) or ExperimentMetricMathType.TOTAL+ if math_type in (ExperimentMetricMathType.DAU, ExperimentMetricMathType.UNIQUE_SESSION):+ # _build_value_expr() returns the ID itself for these math types, which+ # cannot go into the Float64 column. Build the count-metric expression+ # node for node so repr-based job hashing matches a count metric build.+ value_expr: ast.Expr = ast.Call(+ name="coalesce",+ args=[ast.Call(name="toFloat", args=[ast.Constant(value=1)]), ast.Constant(value=0)],+ )+ else:+ value_expr = self._b._build_value_expr()+placeholders: dict[str, ast.Expr] = {"entity_key": parse_expr(self._b.entity_key),- "value_expr": self._b._build_value_expr(),+ "value_expr": value_expr,"experiment_date_from": self._b.date_range_query.date_from_as_hogql(),"experiment_date_to": self._b.date_range_query.date_to_as_hogql(),"conversion_window_seconds": ast.Constant(value=self._b._get_conversion_window_seconds()),diff --git a/products/experiments/backend/hogql_queries/experiment_metric_values.py b/products/experiments/backend/hogql_queries/experiment_metric_values.pyindex 05376fbca2a4..4ef8f3737567 100644--- a/products/experiments/backend/hogql_queries/experiment_metric_values.py+++ b/products/experiments/backend/hogql_queries/experiment_metric_values.py@@ -236,11 +236,15 @@ def build_value_aggregation_expr(placeholders={"value_expr": value_expr},)- # Count distinct values, filtering out null UUIDs and empty strings+ # The precomputed read casts entity_id with accurateCastOrNull, which+ # yields Nullable(UUID), so both UUID spellings must hit the zero-UUID+ # filter or the direct and precomputed paths diverge for personless+ # (zero-UUID) entities.return parse_expr(f"""toFloat(count(distinctmultiIf(- toTypeName({column_ref}) = 'UUID' AND reinterpretAsUInt128({column_ref}) = 0, NULL,+ isNull({column_ref}), NULL,+ toTypeName({column_ref}) IN ('UUID', 'Nullable(UUID)') AND reinterpretAsUInt128(assumeNotNull({column_ref})) = 0, NULL,toString({column_ref}) = '', NULL,{column_ref})diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.pyindex bc37c1359274..7fc82c83a782 100644--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py@@ -480,8 +480,9 @@ class ExperimentQueryRunner(QueryRunner):def _metric_events_precompute_applicable(self) -> bool:"""- Metric-events precompute supports ordered funnels, numeric mean metrics- (count/sum/avg/min/max), and retention metrics, in all cases without+ 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 withoutbreakdowns, CUPED, or data warehouse sources."""if self._get_breakdowns_for_builder() or self.cuped_config.enabled or self.is_data_warehouse_query:@@ -493,21 +494,32 @@ class ExperimentQueryRunner(QueryRunner):if not isinstance(source, (EventsNode, ActionsNode)):return False# Session-property means aggregate via a per-session dedup CTE that the- # precomputed table can't feed; ID-valued math (unique session/DAU/group)- # and HogQL expressions don't fit the Float64 numeric_value column.+ # 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 Falsemath_type = getattr(source, "math", None) or ExperimentMetricMathType.TOTAL- # These math types are safe because the build query stores the same+ # Numeric math types are safe because the build query stores the same# coalesced per-event float regardless of math type, and the math is# applied at read time by build_value_aggregation_expr on both paths.- return math_type in (+ if math_type in (ExperimentMetricMathType.TOTAL,ExperimentMetricMathType.SUM,ExperimentMetricMathType.AVG,ExperimentMetricMathType.MIN,ExperimentMetricMathType.MAX,- )+ ):+ return True+ # unique_session counts distinct session_id, which every mean build stores.+ if math_type == ExperimentMetricMathType.UNIQUE_SESSION:+ return True+ # 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 Falseif isinstance(self.metric, ExperimentRetentionMetric):if not isinstance(self.metric.start_event, (EventsNode, ActionsNode)) or not isinstance(self.metric.completion_event, (EventsNode, ActionsNode)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 1cd1724a637a..290c4cd4b9f6 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@@ -2444,7 +2444,7 @@entity_metrics AS(SELECT exposures.entity_id AS entity_id,exposures.variant AS variant,- accurateCastOrNull(count(DISTINCT multiIf(and(equals(toTypeName(metric_events.value), 'UUID'), equals(reinterpretAsUInt128(metric_events.value), 0)), NULL, equals(toString(metric_events.value), ''), NULL, metric_events.value)), 'Float64') AS value+ accurateCastOrNull(count(DISTINCT multiIf(isNull(metric_events.value), NULL, and(in(toTypeName(metric_events.value), tuple('UUID', 'Nullable(UUID)')), equals(reinterpretAsUInt128(assumeNotNull(metric_events.value)), 0)), NULL, equals(toString(metric_events.value), ''), NULL, metric_events.value)), 'Float64') AS valueFROM exposuresLEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')))GROUP BY exposures.entity_id,@@ -2471,7 +2471,7 @@use_hive_partitioning=0'''# ----# name: TestExperimentQueryRunner.test_query_runner_with_unique_users_metric+# name: TestExperimentQueryRunner.test_query_runner_with_unique_users_metric_0_direct'''WITH exposures AS(SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,@@ -2506,7 +2506,7 @@entity_metrics AS(SELECT exposures.entity_id AS entity_id,exposures.variant AS variant,- accurateCastOrNull(count(DISTINCT multiIf(and(equals(toTypeName(metric_events.value), 'UUID'), equals(reinterpretAsUInt128(metric_events.value), 0)), NULL, equals(toString(metric_events.value), ''), NULL, metric_events.value)), 'Float64') AS value+ accurateCastOrNull(count(DISTINCT multiIf(isNull(metric_events.value), NULL, and(in(toTypeName(metric_events.value), tuple('UUID', 'Nullable(UUID)')), equals(reinterpretAsUInt128(assumeNotNull(metric_events.value)), 0)), NULL, equals(toString(metric_events.value), ''), NULL, metric_events.value)), 'Float64') AS valueFROM exposuresLEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')))GROUP BY exposures.entity_id,@@ -2533,6 +2533,58 @@use_hive_partitioning=0'''# ---+# name: TestExperimentQueryRunner.test_query_runner_with_unique_users_metric_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']), 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-10 00:00:00', 'UTC'))))+ GROUP BY entity_id),+ metric_events AS+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,+ toTimeZone(t.timestamp, 'UTC') AS timestamp,+ accurateCastOrNull(t.entity_id, 'UUID') AS value+ 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']), equals(t.team_id, 99999), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2020-01-10 00:00:00', 'UTC')), toIntervalSecond(0))))+ GROUP BY t.entity_id,+ toTimeZone(t.timestamp, 'UTC'),+ t.event_uuid),+ entity_metrics AS+ (SELECT exposures.entity_id AS entity_id,+ exposures.variant AS variant,+ accurateCastOrNull(count(DISTINCT multiIf(isNull(metric_events.value), NULL, and(in(toTypeName(metric_events.value), tuple('UUID', 'Nullable(UUID)')), equals(reinterpretAsUInt128(assumeNotNull(metric_events.value)), 0)), NULL, ifNull(equals(toString(metric_events.value), ''), 0), NULL, metric_events.value)), 'Float64') AS value+ FROM exposures+ LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')))+ 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+ FROM entity_metrics+ GROUP BY entity_metrics.variant+ LIMIT 50000 SETTINGS join_algorithm='grace_hash',+ grace_hash_join_initial_buckets=2,+ 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: TestExperimentQueryRunner.test_query_runner_without_feature_flag_property'''WITH exposures ASdiff --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 96369d8a7de5..13cfa8f8589f 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@@ -1492,7 +1492,7 @@entity_metrics AS(SELECT exposures.entity_id AS entity_id,exposures.variant AS variant,- accurateCastOrNull(count(DISTINCT multiIf(and(equals(toTypeName(metric_events.value), 'UUID'), equals(reinterpretAsUInt128(metric_events.value), 0)), NULL, equals(toString(metric_events.value), ''), NULL, metric_events.value)), 'Float64') AS value+ accurateCastOrNull(count(DISTINCT multiIf(isNull(metric_events.value), NULL, and(in(toTypeName(metric_events.value), tuple('UUID', 'Nullable(UUID)')), equals(reinterpretAsUInt128(assumeNotNull(metric_events.value)), 0)), NULL, equals(toString(metric_events.value), ''), NULL, metric_events.value)), 'Float64') AS valueFROM exposuresLEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')))GROUP BY exposures.entity_id,@@ -1532,22 +1532,18 @@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']), equals(t.team_id, 99999), greaterOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), lessOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC'))))GROUP BY entity_id),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,- events.`$session_id` AS value- 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)- WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, '$pageview'))),+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,+ toTimeZone(t.timestamp, 'UTC') AS timestamp,+ any(t.session_id) AS value+ 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']), equals(t.team_id, 99999), greaterOrEquals(t.timestamp, assumeNotNull(toDateTime('2024-01-01 00:00:00', 'UTC'))), less(t.timestamp, plus(assumeNotNull(toDateTime('2024-01-15 12:00:00', 'UTC')), toIntervalSecond(0))))+ GROUP BY t.entity_id,+ toTimeZone(t.timestamp, 'UTC'),+ t.event_uuid),entity_metrics AS(SELECT exposures.entity_id AS entity_id,exposures.variant AS variant,- accurateCastOrNull(count(DISTINCT multiIf(and(equals(toTypeName(metric_events.value), 'UUID'), equals(reinterpretAsUInt128(metric_events.value), 0)), NULL, equals(toString(metric_events.value), ''), NULL, metric_events.value)), 'Float64') AS value+ accurateCastOrNull(count(DISTINCT multiIf(isNull(metric_events.value), NULL, and(in(toTypeName(metric_events.value), tuple('UUID', 'Nullable(UUID)')), equals(reinterpretAsUInt128(assumeNotNull(metric_events.value)), 0)), NULL, equals(toString(metric_events.value), ''), NULL, metric_events.value)), 'Float64') AS valueFROM exposuresLEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')))GROUP BY exposures.entity_id,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 01de175b8ba7..fed027d93c77 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@@ -1110,7 +1110,7 @@GROUP BY exposures.entity_id),denominator_agg AS(SELECT exposures.entity_id AS entity_id,- accurateCastOrNull(count(DISTINCT multiIf(and(equals(toTypeName(denominator_events.value), 'UUID'), equals(reinterpretAsUInt128(denominator_events.value), 0)), NULL, equals(toString(denominator_events.value), ''), NULL, denominator_events.value)), 'Float64') AS value+ accurateCastOrNull(count(DISTINCT multiIf(isNull(denominator_events.value), NULL, and(in(toTypeName(denominator_events.value), tuple('UUID', 'Nullable(UUID)')), equals(reinterpretAsUInt128(assumeNotNull(denominator_events.value)), 0)), NULL, equals(toString(denominator_events.value), ''), NULL, denominator_events.value)), 'Float64') AS valueFROM denominator_eventsJOIN exposures ON equals(exposures.entity_id, denominator_events.entity_id)WHERE greaterOrEquals(denominator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC'))@@ -1195,7 +1195,7 @@GROUP BY exposures.entity_id),denominator_agg AS(SELECT exposures.entity_id AS entity_id,- accurateCastOrNull(count(DISTINCT multiIf(and(equals(toTypeName(denominator_events.value), 'UUID'), equals(reinterpretAsUInt128(denominator_events.value), 0)), NULL, equals(toString(denominator_events.value), ''), NULL, denominator_events.value)), 'Float64') AS value+ accurateCastOrNull(count(DISTINCT multiIf(isNull(denominator_events.value), NULL, and(in(toTypeName(denominator_events.value), tuple('UUID', 'Nullable(UUID)')), equals(reinterpretAsUInt128(assumeNotNull(denominator_events.value)), 0)), NULL, equals(toString(denominator_events.value), ''), NULL, denominator_events.value)), 'Float64') AS valueFROM denominator_eventsJOIN exposures ON equals(exposures.entity_id, denominator_events.entity_id)WHERE greaterOrEquals(denominator_events.timestamp, toTimeZone(exposures.first_exposure_time, 'UTC'))diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.pyindex 040d1ad1983f..528f691c77ca 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_base.py@@ -2071,10 +2071,21 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):self.assertEqual(test_variant.sum, 240)self.assertEqual(test_variant.number_of_samples, 3)+ @parameterized.expand(+ [+ ("direct", False),+ ("precomputed", True),+ ]+ )@freeze_time("2020-01-01T12:00:00Z")@snapshot_clickhouse_queries- def test_query_runner_with_unique_users_metric(self):+ def test_query_runner_with_unique_users_metric(self, name, use_precomputation):"""Test that unique users metric correctly counts unique users, not total events."""+ # The precomputed read embeds per-run job UUIDs; zero all numbers so the+ # snapshot is stable across runs.+ self.snapshot_replace_all_numbers = True+ 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), end_date=datetime(2020, 1, 10)@@ -2098,7 +2109,7 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):)experiment.metrics = [metric.model_dump(mode="json")]- experiment.save()+ self._save_experiment_with_precomputation(experiment, use_precomputation)# Create test data with multiple events per user to verify unique counting# Control: 3 users, but user_0 has 3 events, user_1 has 2 events, user_2 has 1 event@@ -2163,6 +2174,10 @@ class TestExperimentQueryRunner(ExperimentQueryRunnerBaseTest):query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)result = query_runner.calculate()++ # A broken precomputed read silently falls back to the direct scan; assert the intended path ran.+ assert query_runner._metric_events_precomputed is use_precomputation+assert result.variant_results is not Noneself.assertEqual(len(result.variant_results), 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 8ac8d767521a..f6d9650c7eea 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@@ -606,6 +606,9 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)result = cast(ExperimentQueryResponse, query_runner.calculate())+ # A broken precomputed read silently falls back to the direct scan; assert the intended path ran.+ assert query_runner._metric_events_precomputed is use_precomputation+assert result.baseline is not Noneassert result.variant_results is not Noneself.assertEqual(len(result.variant_results), 1)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 90fa613dbaf4..db5a85e54db4 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@@ -174,6 +174,32 @@ class TestExperimentMeanMetricEventsPreaggregation(ExperimentQueryRunnerBaseTestassert first_result.job_ids == second_result.job_idsassert mock_sync_execute.call_count == len(first_result.job_ids)+ @patch("products.analytics_platform.backend.lazy_computation.lazy_computation_executor.sync_execute")+ def test_dau_metric_shares_precompute_jobs_with_count_metric(self, mock_sync_execute):+ feature_flag = self.create_feature_flag(key="shared-mean-metric-events-jobs")+ experiment = self.create_experiment(+ feature_flag=feature_flag,+ start_date=datetime(2024, 1, 1),+ end_date=datetime(2024, 1, 10),+ )+ # ID-valued math stores the same rows as a count metric, so the build+ # queries must hash the same and share jobs instead of building twice.+ count_metric = ExperimentMeanMetric(source=EventsNode(event="purchase"))+ dau_metric = ExperimentMeanMetric(source=EventsNode(event="purchase", math=ExperimentMetricMathType.DAU))++ count_result = self._build_runner(experiment, count_metric)._ensure_metric_events_precomputed(+ self._build_lazy_computation_builder(experiment, feature_flag, count_metric)+ )+ dau_result = self._build_runner(experiment, dau_metric)._ensure_metric_events_precomputed(+ self._build_lazy_computation_builder(experiment, feature_flag, dau_metric)+ )++ assert count_result.ready is True+ assert dau_result.ready is True+ assert count_result.job_ids == dau_result.job_ids+ # Only the count run executed INSERTs; the dau run reused its jobs.+ assert mock_sync_execute.call_count == len(count_result.job_ids)+@parameterized.expand([("count_default_math", EventsNode(event="purchase"), True),@@ -198,8 +224,18 @@ class TestExperimentMeanMetricEventsPreaggregation(ExperimentQueryRunnerBaseTestTrue,),(- "unique_session_id_valued",+ "unique_session",EventsNode(event="purchase", math=ExperimentMetricMathType.UNIQUE_SESSION),+ True,+ ),+ (+ "dau",+ EventsNode(event="purchase", math=ExperimentMetricMathType.DAU),+ True,+ ),+ (+ "unique_group",+ EventsNode(event="purchase", math=ExperimentMetricMathType.UNIQUE_GROUP, math_group_type_index=1),False,),(