Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(experiments): precompute metric events for avg/min/max mean metrics (#96149)

Juraj Majerike40514bfd3ad
diff --git a/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md b/products/experiments/backend/hogql_queries/METRIC_EVENTS_PRECOMPUTATION.md
index c1331ac2b786..c546d6154e3a 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 mean metrics** (per-event value stored in `numeric_value`, deduplicated on read by event identity since replayed build rows would double sums), 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), 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.
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_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.py
index ba154b73439e..cb066518c533 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py
@@ -474,9 +474,9 @@ class ExperimentQueryRunner(QueryRunner):
def _metric_events_precompute_applicable(self) -> bool:
"""
- Metric-events precompute supports ordered funnels, count/sum-style mean
- metrics, and retention metrics, in all cases without breakdowns, CUPED,
- or data warehouse sources.
+ Metric-events precompute supports ordered funnels, numeric mean metrics
+ (count/sum/avg/min/max), and retention metrics, in all cases without
+ breakdowns, CUPED, or data warehouse sources.
"""
if self._get_breakdowns_for_builder() or self.cuped_config.enabled or self.is_data_warehouse_query:
return False
@@ -492,7 +492,16 @@ class ExperimentQueryRunner(QueryRunner):
if is_session_property_metric(source):
return False
math_type = getattr(source, "math", None) or ExperimentMetricMathType.TOTAL
- return math_type in (ExperimentMetricMathType.TOTAL, ExperimentMetricMathType.SUM)
+ # These 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 (
+ ExperimentMetricMathType.TOTAL,
+ ExperimentMetricMathType.SUM,
+ ExperimentMetricMathType.AVG,
+ ExperimentMetricMathType.MIN,
+ ExperimentMetricMathType.MAX,
+ )
if 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_mean_metric.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr
index aa14decb2c1a..57ca709e64b6 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
@@ -1042,18 +1042,14 @@
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,
- coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'amount'), ''), 'null'), '^"|"$', ''), 'Float64'), 0) 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, 'purchase'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ any(t.numeric_value) 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,
@@ -1170,18 +1166,14 @@
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,
- coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'amount'), ''), 'null'), '^"|"$', ''), 'Float64'), 0) 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, 'purchase'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ any(t.numeric_value) 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,
@@ -1298,18 +1290,14 @@
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,
- coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'amount'), ''), 'null'), '^"|"$', ''), 'Float64'), 0) 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, 'purchase'))),
+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,
+ toTimeZone(t.timestamp, 'UTC') AS timestamp,
+ any(t.numeric_value) 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,
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.py
index ee0d111ba251..90fa613dbaf4 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
@@ -183,9 +183,19 @@ class TestExperimentMeanMetricEventsPreaggregation(ExperimentQueryRunnerBaseTest
True,
),
(
- "avg_not_yet_allowlisted",
+ "avg",
EventsNode(event="purchase", math=ExperimentMetricMathType.AVG, math_property="amount"),
- False,
+ True,
+ ),
+ (
+ "min",
+ EventsNode(event="purchase", math=ExperimentMetricMathType.MIN, math_property="amount"),
+ True,
+ ),
+ (
+ "max",
+ EventsNode(event="purchase", math=ExperimentMetricMathType.MAX, math_property="amount"),
+ True,
),
(
"unique_session_id_valued",