: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
perf(experiments): batch action-name refresh in experiments list (#64377)
Anders7726c34fe398
diff --git a/ee/clickhouse/views/experiment_saved_metrics.py b/ee/clickhouse/views/experiment_saved_metrics.pyindex 1f2e11428118..05595371c5c8 100644--- a/ee/clickhouse/views/experiment_saved_metrics.py+++ b/ee/clickhouse/views/experiment_saved_metrics.py@@ -37,9 +37,12 @@ class ExperimentToSavedMetricSerializer(serializers.ModelSerializer):def to_representation(self, instance: ExperimentToSavedMetric):data = super().to_representation(instance)- # Refresh action names to show current names instead of stale cached values+ # Refresh action names to show current names instead of stale cached values.+ # actions_by_id is preloaded once per page by ExperimentListSerializer (shared via the+ # parent serializer context); None when used standalone, falling back to a per-call query.team = instance.experiment.team- data["query"] = refresh_action_names_in_metric(data.get("query"), team)+ actions_by_id = self.context.get("actions_by_id")+ data["query"] = refresh_action_names_in_metric(data.get("query"), team, actions_by_id)return datadiff --git a/frontend/src/scenes/experiments/experimentsLogic.ts b/frontend/src/scenes/experiments/experimentsLogic.tsindex 6a22401e9ca7..ed9f5db87bb6 100644--- a/frontend/src/scenes/experiments/experimentsLogic.ts+++ b/frontend/src/scenes/experiments/experimentsLogic.ts@@ -513,12 +513,11 @@ export const experimentsLogic = kea<experimentsLogicType>([}),afterMount(({ actions, values }) => {actions.loadExperimentsStats()- // Sync modal page with URL on mount+ // Sync modal page with URL on mount. Eligible flags themselves are loaded lazily when the+ // "link existing flag" modal opens (openFeatureFlagModal listener), not on every list mount.const urlPage = values.featureFlagModalPageFromURLif (urlPage !== 1) {actions.setFeatureFlagModalFilters({ page: urlPage })- } else {- actions.loadFeatureFlagModalFeatureFlags()}}),actionToUrl(({ values }) => {diff --git a/products/experiments/backend/metric_utils.py b/products/experiments/backend/metric_utils.pyindex 6eb545e8b597..1325446400ad 100644--- a/products/experiments/backend/metric_utils.py+++ b/products/experiments/backend/metric_utils.py@@ -46,7 +46,11 @@ def get_default_metric_title(metric_dict: dict) -> str:logger = logging.getLogger(__name__)-def refresh_action_names_in_metric(query: dict[str, Any] | None, team: Team) -> dict[str, Any] | None:+def refresh_action_names_in_metric(+ query: dict[str, Any] | None,+ team: Team,+ actions_by_id: dict[int, str] | None = None,+) -> dict[str, Any] | None:"""Update ActionsNode names in a metric query to reflect current action names.@@ -61,6 +65,9 @@ def refresh_action_names_in_metric(query: dict[str, Any] | None, team: Team) ->Args:query: The metric query dictionary (ExperimentMetric)team: The team to fetch actions for+ actions_by_id: Optional preloaded {action_id: name} map. When provided, the+ per-call DB query is skipped — callers serializing many experiments can+ resolve every action in one batched query and pass the result in here.Returns:Updated query dict with refreshed action names, or original query if errors occur@@ -79,11 +86,12 @@ def refresh_action_names_in_metric(query: dict[str, Any] | None, team: Team) ->if not action_ids:return query- # Fetch all actions in a single query- # Only include actions that still exist (not deleted)- actions_by_id = {- action.id: action.name for action in Action.objects.filter(id__in=action_ids, team=team, deleted=False)- }+ if actions_by_id is None:+ # Fetch all actions in a single query+ # Only include actions that still exist (not deleted)+ actions_by_id = {+ action.id: action.name for action in Action.objects.filter(id__in=action_ids, team=team, deleted=False)+ }# Update action names throughout the query# If an action was deleted, its ID won't be in actions_by_id and the old name will be preserved@@ -137,6 +145,24 @@ def _update_action_names(obj: Any, actions_by_id: dict[int, str]) -> None:_update_action_names(item, actions_by_id)+def resolve_action_names(metrics: list[dict[str, Any] | None], team: Team) -> dict[int, str]:+ """Resolve {action_id: name} for every ActionsNode across many metric queries in one query.++ Lets callers serializing a page of experiments batch action-name resolution instead of+ issuing a separate query per metric. Pass the result into ``refresh_action_names_in_metric``.+ Returns an empty map (no query) when no actions are referenced.+ """+ action_ids: set[int] = set()+ for metric in metrics:+ if metric:+ _collect_action_ids(metric, action_ids)++ if not action_ids:+ return {}++ return {action.id: action.name for action in Action.objects.filter(id__in=action_ids, team=team, deleted=False)}++def _collect_event_names_and_action_ids(obj: Any, event_names: set[str], action_ids: set[int]) -> None:"""Recursively collect EventsNode event names and ActionsNode IDs from a metric query."""if isinstance(obj, dict):diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex d5f4d5d4f38a..d7af82c06b2b 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -31,7 +31,7 @@ from products.experiments.backend.facade.contracts import CreateExperimentInputfrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprintfrom products.experiments.backend.hogql_queries.utils import get_experiment_stats_methodfrom products.experiments.backend.llm_metric_templates import TEMPLATE_NAMES-from products.experiments.backend.metric_utils import refresh_action_names_in_metric+from products.experiments.backend.metric_utils import refresh_action_names_in_metric, resolve_action_namesfrom products.experiments.backend.models.experiment import Experiment, ExperimentHoldout, ExperimentMetricsRecalculationfrom products.experiments.backend.running_time_calculator import METRIC_TYPE_CHOICESfrom products.feature_flags.backend.api.feature_flag import MinimalFeatureFlagSerializer@@ -106,6 +106,34 @@ class ExperimentRunningTimeCalculationField(serializers.JSONField):pass+class ExperimentListSerializer(serializers.ListSerializer):+ """Batches action-name resolution across a whole page of experiments.++ ``ExperimentSerializer.to_representation`` refreshes stale cached action names on every+ metric, which would otherwise issue one ``Action`` query per metric per experiment. Here we+ resolve every referenced action in a single query and hand the map down via the shared+ serializer context, so a 100-experiment page does one action query instead of hundreds.+ """++ def to_representation(self, data):+ instances = list(data)++ metric_queries: list[dict[str, Any] | None] = []+ team: Team | None = None+ for instance in instances:+ team = instance.team+ metric_queries.extend(instance.metrics or [])+ metric_queries.extend(instance.metrics_secondary or [])+ # Saved metrics are prefetched via experimenttosavedmetric_set+ for relation in instance.experimenttosavedmetric_set.all():+ metric_queries.append(relation.saved_metric.query)++ if team is not None:+ self.context["actions_by_id"] = resolve_action_names(metric_queries, team)++ return super().to_representation(instances)++class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):feature_flag_key = serializers.CharField(source="get_feature_flag_key",@@ -302,6 +330,7 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSe"status","user_access_level",]+ list_serializer_class = ExperimentListSerializerdef get_fields(self):fields = super().get_fields()@@ -326,12 +355,16 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSe"explicitDate": True,}+ # actions_by_id is preloaded once per page by ExperimentListSerializer to avoid an+ # Action query per metric; None on detail/launch/archive paths (falls back to a query).+ actions_by_id = self.context.get("actions_by_id")+# Refresh action names in inline metrics (metrics and metrics_secondary)# The columns are nullable, so the keys can be present with a None valuefor metrics_list in [data.get("metrics") or [], data.get("metrics_secondary") or []]:for i, metric in enumerate(metrics_list):# Refresh action names to show current names instead of stale cached values- refreshed_metric = refresh_action_names_in_metric(metric, instance.team)+ refreshed_metric = refresh_action_names_in_metric(metric, instance.team, actions_by_id)if refreshed_metric:metrics_list[i] = refreshed_metricmetric = refreshed_metricdiff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex 4f2cb6b1d438..7e5ae13c893f 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -367,6 +367,67 @@ class TestExperimentCRUD(APILicensedTest):# Query count must stay flat as rows grow — five experiments must not cost more than one.self.assertLessEqual(len(five_rows.captured_queries), len(single_row.captured_queries))+ def _create_experiment_with_action_metrics(self, index: int) -> tuple[Experiment, Action]:+ action = Action.objects.create(team=self.team, name=f"Action {index}", steps_json=[{"event": f"event_{index}"}])+ flag = FeatureFlag.objects.create(team=self.team, key=f"action-metric-flag-{index}", created_by=self.user)+ experiment = Experiment.objects.create(+ team=self.team,+ name=f"Action metric experiment {index}",+ feature_flag=flag,+ created_by=self.user,+ metrics=[+ {"kind": "ExperimentMetric", "metric_type": "mean", "source": {"kind": "ActionsNode", "id": action.id}}+ ],+ metrics_secondary=[+ {"kind": "ExperimentMetric", "metric_type": "mean", "source": {"kind": "ActionsNode", "id": action.id}}+ ],+ )+ saved_metric = ExperimentSavedMetric.objects.create(+ team=self.team,+ name=f"Saved action metric {index}",+ created_by=self.user,+ query={+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "ActionsNode", "id": action.id},+ },+ )+ ExperimentToSavedMetric.objects.create(experiment=experiment, saved_metric=saved_metric)+ return experiment, action++ def test_listing_experiments_with_action_metrics_is_not_nplus1(self) -> None:+ # Action names are refreshed per metric during serialization; without batching this is one+ # Action query per metric per experiment. Query count must stay flat as rows grow.+ self._create_experiment_with_action_metrics(0)++ with CaptureQueriesContext(connection) as single_row:+ response = self.client.get(f"/api/projects/{self.team.id}/experiments")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 1)++ for i in range(1, 5):+ self._create_experiment_with_action_metrics(i)++ with CaptureQueriesContext(connection) as five_rows:+ response = self.client.get(f"/api/projects/{self.team.id}/experiments")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["count"], 5)++ self.assertLessEqual(len(five_rows.captured_queries), len(single_row.captured_queries))++ def test_listing_experiments_refreshes_action_names(self) -> None:+ experiment, action = self._create_experiment_with_action_metrics(0)+ action.name = "Renamed action"+ action.save()++ response = self.client.get(f"/api/projects/{self.team.id}/experiments")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ result = next(r for r in response.json()["results"] if r["id"] == experiment.id)++ self.assertEqual(result["metrics"][0]["source"]["name"], "Renamed action")+ self.assertEqual(result["metrics_secondary"][0]["source"]["name"], "Renamed action")+ self.assertEqual(result["saved_metrics"][0]["query"]["source"]["name"], "Renamed action")+def test_creating_updating_basic_experiment(self):ff_key = "a-b-tests"response = self.client.post(