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.

fix(experiments): match frontend breakdownFilter wrapper for saved metric cache (#60412)

Juraj Majerik3ca286663c03
diff --git a/posthog/temporal/experiments/activities.py b/posthog/temporal/experiments/activities.py
index afde1cc5a01e..e46c21f9f709 100644
--- a/posthog/temporal/experiments/activities.py
+++ b/posthog/temporal/experiments/activities.py
@@ -392,9 +392,11 @@ def _calculate_experiment_saved_metric_sync(
)
saved_metric = None
+ saved_metric_metadata: dict = {}
for exp_to_sm in experiment.experimenttosavedmetric_set.select_related("saved_metric").all():
if exp_to_sm.saved_metric.query.get("uuid") == metric_uuid:
saved_metric = exp_to_sm.saved_metric
+ saved_metric_metadata = exp_to_sm.metadata or {}
break
if not saved_metric:
@@ -406,7 +408,17 @@ def _calculate_experiment_saved_metric_sync(
error_message=f"Saved metric {metric_uuid} not found for experiment {experiment_id}",
)
- query = saved_metric.query
+ # The frontend wraps every saved metric with breakdownFilter.breakdowns from
+ # the link metadata before posting to /query (see sharedMetricsToExperimentMetrics
+ # in experimentLogic.tsx). The activity must apply the same wrapper or the
+ # response cache key diverges and the warmed entry is never read.
+ query = {
+ **saved_metric.query,
+ "breakdownFilter": {
+ **(saved_metric.query.get("breakdownFilter") or {}),
+ "breakdowns": saved_metric_metadata.get("breakdowns") or [],
+ },
+ }
metric_type = query.get("metric_type")
metric_obj: Union[ExperimentMeanMetric, ExperimentFunnelMetric, ExperimentRatioMetric]
if metric_type == "mean":
diff --git a/posthog/temporal/experiments/test_cache_warming.py b/posthog/temporal/experiments/test_cache_warming.py
index 7d405d03e39a..9150f52276a4 100644
--- a/posthog/temporal/experiments/test_cache_warming.py
+++ b/posthog/temporal/experiments/test_cache_warming.py
@@ -15,7 +15,12 @@ from posthog.hogql_queries.experiments.experiment_query_runner import Experiment
from posthog.hogql_queries.experiments.test.experiment_query_runner.base import ExperimentQueryRunnerBaseTest
from posthog.hogql_queries.experiments.utils import get_experiment_stats_method
from posthog.hogql_queries.query_runner import ExecutionMode
-from posthog.temporal.experiments.activities import _calculate_experiment_regular_metric_sync
+from posthog.temporal.experiments.activities import (
+ _calculate_experiment_regular_metric_sync,
+ _calculate_experiment_saved_metric_sync,
+)
+
+from products.experiments.backend.models.experiment import ExperimentSavedMetric, ExperimentToSavedMetric
@override_settings(IN_UNIT_TESTING=True)
@@ -96,3 +101,95 @@ class TestTemporalRecalcWarmsResponseCache(ExperimentQueryRunnerBaseTest):
)
assert isinstance(warm_response, CachedExperimentQueryResponse)
self.assertTrue(warm_response.is_cached)
+
+ @freeze_time("2020-01-10T12:00:00Z")
+ def test_temporal_activity_warms_query_cache_for_saved_metric(self):
+ """
+ Saved metrics take a different path: the frontend merges
+ ExperimentToSavedMetric.metadata.breakdowns into a breakdownFilter on
+ the metric before posting to /query. The activity must apply the same
+ merge or the cache key diverges. This test covers that path.
+ """
+ feature_flag = self.create_feature_flag()
+ experiment = self.create_experiment(
+ feature_flag=feature_flag,
+ start_date=datetime(2020, 1, 1, 0, 0, 0),
+ )
+
+ metric = ExperimentMeanMetric(uuid=str(uuid4()), source=EventsNode(event="purchase"))
+ metric_dict = metric.model_dump(mode="json")
+
+ saved_metric = ExperimentSavedMetric.objects.create(
+ name="test saved metric",
+ team=self.team,
+ query=metric_dict,
+ created_by=self.user,
+ )
+ # No breakdowns on the link metadata — mirrors the production scenario
+ # where the frontend still wraps the metric with breakdownFilter: {breakdowns: []}.
+ ExperimentToSavedMetric.objects.create(
+ experiment=experiment,
+ saved_metric=saved_metric,
+ metadata={"type": "primary"},
+ )
+
+ feature_flag_property = f"$feature/{feature_flag.key}"
+ for variant in ("control", "test"):
+ for i in range(5):
+ distinct_id = f"user_{variant}_{i}"
+ _create_person(distinct_ids=[distinct_id], team_id=self.team.pk)
+ _create_event(
+ team=self.team,
+ event="$feature_flag_called",
+ distinct_id=distinct_id,
+ timestamp="2020-01-02T12:00:00Z",
+ properties={
+ feature_flag_property: variant,
+ "$feature_flag_response": variant,
+ "$feature_flag": feature_flag.key,
+ },
+ )
+ _create_event(
+ team=self.team,
+ event="purchase",
+ distinct_id=distinct_id,
+ timestamp="2020-01-02T12:01:00Z",
+ properties={feature_flag_property: variant},
+ )
+ flush_persons_and_events()
+
+ # Build the metric the way the frontend does for saved metrics:
+ # wrap with breakdownFilter merged from link.metadata.breakdowns
+ # (see sharedMetricsToExperimentMetrics in experimentLogic.tsx).
+ frontend_metric_dict = {
+ **metric_dict,
+ "breakdownFilter": {"breakdowns": []},
+ }
+ frontend_query = ExperimentQuery.model_validate(
+ {
+ "kind": "ExperimentQuery",
+ "experiment_id": experiment.id,
+ "metric": frontend_metric_dict,
+ }
+ )
+
+ cache.clear()
+
+ fingerprint = compute_metric_fingerprint(
+ metric_dict,
+ experiment.start_date,
+ get_experiment_stats_method(experiment),
+ experiment.exposure_criteria,
+ only_count_matured_users=experiment.only_count_matured_users,
+ )
+ with patch("posthog.temporal.experiments.activities.close_old_connections"):
+ activity_result = _calculate_experiment_saved_metric_sync.func( # type: ignore[attr-defined]
+ experiment.id, metric_dict["uuid"], fingerprint
+ )
+ self.assertTrue(activity_result.success, msg=activity_result.error_message)
+
+ warm_response = ExperimentQueryRunner(query=frontend_query, team=self.team).run(
+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
+ )
+ assert isinstance(warm_response, CachedExperimentQueryResponse)
+ self.assertTrue(warm_response.is_cached)