: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
refactor(experiments): name metric role and metric kind separately (#109424)
Anders56b1fdeb6520
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsxindex 22be74f2787c..175495d4cbd2 100644--- a/frontend/src/scenes/experiments/experimentLogic.tsx+++ b/frontend/src/scenes/experiments/experimentLogic.tsx@@ -1303,10 +1303,9 @@ export const experimentLogic = kea<experimentLogicType>([}},duplicateSharedMetricAsInlineMetric: (state, { sharedMetricId, isSecondary, newUuid }) => {- const metricType = isSecondary ? 'secondary' : 'primary'+ const role = isSecondary ? 'secondary' : 'primary'const savedMetric = (state?.saved_metrics || []).find(- (m: ExperimentSavedMetric) =>- m.saved_metric === sharedMetricId && m.metadata?.type === metricType+ (m: ExperimentSavedMetric) => m.saved_metric === sharedMetricId && m.metadata?.type === role)if (!savedMetric) {diff --git a/products/dashboards/backend/widgets/experiment_results.py b/products/dashboards/backend/widgets/experiment_results.pyindex 8e12a6359739..c2247bed6b45 100644--- a/products/dashboards/backend/widgets/experiment_results.py+++ b/products/dashboards/backend/widgets/experiment_results.py@@ -78,10 +78,10 @@ def _collect_metric_dicts(experiment: Experiment) -> tuple[list[dict[str, Any]],"name": saved_query.get("name") or link.saved_metric.name,}# Links default to primary when untyped; an unrecognized type belongs to neither section.- metric_type = (link.metadata or {}).get("type", "primary")- if metric_type == "secondary":+ role = (link.metadata or {}).get("type", "primary")+ if role == "secondary":secondary.append(metric_dict)- elif metric_type == "primary":+ elif role == "primary":primary.append(metric_dict)_sort_by_ordered_uuids(primary, experiment.primary_metrics_ordered_uuids)diff --git a/products/experiments/backend/experiment_summary_data_service.py b/products/experiments/backend/experiment_summary_data_service.pyindex 8d1b56050eef..3b50418ce580 100644--- a/products/experiments/backend/experiment_summary_data_service.py+++ b/products/experiments/backend/experiment_summary_data_service.py@@ -277,8 +277,8 @@ class ExperimentSummaryDataService:# without it the summary falls back to raw event names.if link.saved_metric.name:query = {**query, "name": link.saved_metric.name}- metric_type = (link.metadata or {}).get("type", "primary")- if metric_type == "primary":+ role = (link.metadata or {}).get("type", "primary")+ if role == "primary":primary_metrics.append(query)else:secondary_metrics.append(query)diff --git a/products/experiments/backend/temporal/models.py b/products/experiments/backend/temporal/models.pyindex 75c3eb5db915..d8af658559e4 100644--- a/products/experiments/backend/temporal/models.py+++ b/products/experiments/backend/temporal/models.py@@ -99,7 +99,7 @@ class ExperimentMetricsRecalculationWorkflowInputs:fairness_key: str | None = None[email protected](frozen=False)class ExperimentMetricToRecalculate:"""A single metric to recalculate.@@ -109,7 +109,9 @@ class ExperimentMetricToRecalculate:experiment_id: intmetric_uuid: str- metric_type: str # "primary" or "secondary"+ # The metric's role ("primary" or "secondary"), not its kind. Recorded workflow histories carry this+ # field name, so renaming it breaks their replay.+ metric_type: str@dataclasses.dataclassdiff --git a/products/experiments/backend/temporal/recalculation_activities.py b/products/experiments/backend/temporal/recalculation_activities.pyindex 201b3d2f70f3..d2438252d6ce 100644--- a/products/experiments/backend/temporal/recalculation_activities.py+++ b/products/experiments/backend/temporal/recalculation_activities.py@@ -105,14 +105,15 @@ async def calculate_experiment_metric_for_recalculation(metric_uuid: str,recalculation_id: str,query_to: str,- metric_type: str = "primary",+ role: str = "primary",) -> MetricRecalculationResult:"""Calculate one metric, write its recalc-fingerprinted result to ExperimentMetricResult, and fold theprogress update (counter + error) into the same job atomically. query_to is the run's shared data-window end.- metric_type is the primary/secondary classification carried from discovery; it's threaded into the per-metric- PostHog event so the capture path doesn't have to re-query the saved-metric M2M to resolve it. Defaults to- "primary" so existing call sites and tests that don't pass it remain valid.+ role ("primary" or "secondary") is carried from discovery in ExperimentMetricToRecalculate.metric_type; it's+ threaded into the per-metric PostHog event so the capture path doesn't have to re-query the saved-metric M2M+ to resolve it. Defaults to "primary" so existing call sites and tests that don't pass it remain valid. The+ workflow passes these arguments by position, so recorded histories depend on their order, not their names.Finality is derived from activity.info().attempt against MAX_METRIC_ATTEMPTS, the same constant theworkflow's RetryPolicy is built from, so both sides agree on which attempt is the last. On the final@@ -128,7 +129,7 @@ async def calculate_experiment_metric_for_recalculation(async with Heartbeater(factor=_HEARTBEAT_FACTOR):task = asyncio.ensure_future(_calculate_experiment_metric_for_recalculation_sync(- experiment_id, metric_uuid, recalculation_id, query_to, metric_type, is_final_attempt, attempt+ experiment_id, metric_uuid, recalculation_id, query_to, role, is_final_attempt, attempt))try:diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.pyindex e3c70b213947..929ab1c2ee4e 100644--- a/products/experiments/backend/temporal/recalculation_logic.py+++ b/products/experiments/backend/temporal/recalculation_logic.py@@ -128,7 +128,8 @@ def _discover_experiment_metrics_sync(recalculation_id: str) -> list[ExperimentMexperiment = recalculation.experiment# request_recalculation sets total_metrics from the same resolver, so the run's progress count- # matches the metrics this activity schedules.+ # matches the metrics this activity schedules. The payload keeps the role in metric_type because+ # recorded workflow histories carry that field name.metrics_to_recalculate = [ExperimentMetricToRecalculate(experiment_id=experiment.id, metric_uuid=metric.uuid, metric_type=metric.role)for metric in get_metrics_for_calculation(experiment)@@ -514,7 +515,7 @@ def _fail(def _capture_experiment_metric_event(experiment: Experiment,metric_uuid: str,- metric_type: str,+ role: str,metric_dict: dict | None,event: str,extra_properties: dict[str, Any],@@ -523,9 +524,9 @@ def _capture_experiment_metric_event("""Emit a per-metric product analytics event. Telemetry must never fail the activity, so any erroris swallowed. Attributed to the experiment creator, falling back to a team-scoped distinct_id.- `metric_type` is the primary/secondary classification carried from discovery- (`ExperimentMetricToRecalculate.metric_type`), threaded through the workflow + activity args so the- capture path doesn't have to re-query the M2M to resolve it.+ `role` ("primary" or "secondary") is carried from discovery in `ExperimentMetricToRecalculate.metric_type`,+ threaded through the workflow + activity args so the capture path doesn't have to re-query the M2M to+ resolve it.Every recalc trigger is user-originated (manual click, page load, stale/auto refresh), so context is"ui" with mechanism "orchestrated"; `trigger` carries the finer-grained origin.@@ -545,7 +546,7 @@ def _capture_experiment_metric_event("team_id": team.id,"metric_uuid": metric_uuid,"metric_kind": (metric_dict or {}).get("metric_type"),- "is_primary": metric_type == "primary",+ "is_primary": role == "primary","execution_mode": "recalculation","context": "ui","mechanism": "orchestrated",@@ -607,7 +608,7 @@ def _calculate_experiment_metric_for_recalculation_sync(metric_uuid: str,recalculation_id: str,query_to: str,- metric_type: str = "primary",+ role: str = "primary",is_final_attempt: bool = True,attempt: int = 1,) -> MetricRecalculationResult:@@ -713,7 +714,7 @@ def _calculate_experiment_metric_for_recalculation_sync(_capture_experiment_metric_event(experiment,metric_uuid,- metric_type,+ role,metric_dict,"experiment metric error",{@@ -770,7 +771,7 @@ def _calculate_experiment_metric_for_recalculation_sync(_capture_experiment_metric_event(experiment,metric_uuid,- metric_type,+ role,metric_dict,"experiment metric finished",{"duration_ms": round((time.perf_counter() - calc_started_at) * 1000)},@@ -799,7 +800,7 @@ def _calculate_experiment_metric_for_recalculation_sync(_capture_experiment_metric_event(experiment,metric_uuid,- metric_type,+ role,metric_dict,"experiment metric error",{@@ -843,7 +844,7 @@ def _calculate_experiment_metric_for_recalculation_sync(_capture_experiment_metric_event(experiment,metric_uuid,- metric_type,+ role,metric_dict,"experiment metric retry",{@@ -906,7 +907,7 @@ def _calculate_experiment_metric_for_recalculation_sync(_capture_experiment_metric_event(experiment,metric_uuid,- metric_type,+ role,metric_dict,"experiment metric retry",{diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.pyindex b2dc7dff858c..b9b84d2ea0dc 100644--- a/products/experiments/backend/temporal/test_recalculation_activities.py+++ b/products/experiments/backend/temporal/test_recalculation_activities.py@@ -85,14 +85,12 @@ def _calculate(metric_uuid: str,recalculation_id: str,query_to: str,- metric_type: str = "primary",+ role: str = "primary",is_final_attempt: bool = True,attempt: int = 1,):with patch("products.experiments.backend.temporal.recalculation_logic.close_old_connections"):- return _calculate_raw(- experiment_id, metric_uuid, recalculation_id, query_to, metric_type, is_final_attempt, attempt- )+ return _calculate_raw(experiment_id, metric_uuid, recalculation_id, query_to, role, is_final_attempt, attempt)@pytest.mark.django_db(transaction=True)@@ -124,13 +122,13 @@ class TestRecalculationActivities(BaseTest):) -> ExperimentMetricsRecalculation:return ExperimentMetricsRecalculation.objects.create(team=self.team, experiment=exp, trigger=trigger)- def _attach_saved_metric(self, exp: Experiment, uuid: str, metric_type: str) -> None:+ def _attach_saved_metric(self, exp: Experiment, uuid: str, role: str) -> None:saved = ExperimentSavedMetric.objects.create(team=self.team,name=f"saved-{uuid}",query={"uuid": uuid, "kind": "ExperimentMetric", "metric_type": "mean"},)- ExperimentToSavedMetric.objects.create(experiment=exp, saved_metric=saved, metadata={"type": metric_type})+ ExperimentToSavedMetric.objects.create(experiment=exp, saved_metric=saved, metadata={"type": role})@parameterized.expand([@@ -180,13 +178,13 @@ class TestRecalculationActivities(BaseTest):),])- def test_discover_persists_metric_uuids(self, name: str, primary, secondary, saved, expected_uuids, expected_types):+ def test_discover_persists_metric_uuids(self, name: str, primary, secondary, saved, expected_uuids, expected_roles):exp = self._experiment(flag_key=f"discover-{name}")exp.metrics = primaryexp.metrics_secondary = secondaryexp.save()- for uuid, metric_type in saved:- self._attach_saved_metric(exp, uuid, metric_type)+ for uuid, role in saved:+ self._attach_saved_metric(exp, uuid, role)recalc = self._recalc(exp)metrics = _discover(str(recalc.id))@@ -194,7 +192,7 @@ class TestRecalculationActivities(BaseTest):recalc.refresh_from_db()assert set(recalc.metric_uuids) == expected_uuidsassert {m.metric_uuid for m in metrics} == expected_uuids- assert {m.metric_type for m in metrics} == expected_types+ assert {m.metric_type for m in metrics} == expected_roles@parameterized.expand([@@ -1667,9 +1665,8 @@ class TestRecalculationAnalytics(BaseTest):assert props["execution_mode"] == "recalculation"def test_secondary_metric_is_not_marked_primary(self):- # metric_type is now threaded through from the workflow's discovery output rather than re-derived- # from a fresh DB lookup. The activity's caller (workflow) reads the value from- # ExperimentMetricToRecalculate; tests pass it explicitly to exercise the same path.+ # The workflow passes the role from discovery (ExperimentMetricToRecalculate.metric_type), and the+ # calculation does not look it up again, so the test passes it explicitly to exercise the same path.exp = self._experiment(flag_key="an-secondary", secondary=[_mean_metric("s1")])recalc = self._recalc(exp, metric_uuids=["s1"])@@ -1678,7 +1675,7 @@ class TestRecalculationAnalytics(BaseTest):"products.experiments.backend.temporal.recalculation_logic.ExperimentQueryRunner") as mock_runner:mock_runner.return_value.run.return_value.model_dump.return_value = {}- _calculate(exp.id, "s1", str(recalc.id), _QUERY_TO, metric_type="secondary")+ _calculate(exp.id, "s1", str(recalc.id), _QUERY_TO, role="secondary")assert captured[0]["properties"]["is_primary"] is Falsediff --git a/products/experiments/backend/temporal/test_recalculation_workflow.py b/products/experiments/backend/temporal/test_recalculation_workflow.pyindex bb3fa28ae093..13fc386f3bc1 100644--- a/products/experiments/backend/temporal/test_recalculation_workflow.py+++ b/products/experiments/backend/temporal/test_recalculation_workflow.py@@ -66,9 +66,9 @@ def _make_mock_activities(metric_uuid: str,recalculation_id: str,query_to: str,- metric_type: str = "primary",+ role: str = "primary",) -> MetricRecalculationResult:- calculate_calls.append((experiment_id, metric_uuid, recalculation_id, query_to, metric_type))+ calculate_calls.append((experiment_id, metric_uuid, recalculation_id, query_to, role))return metric_results.get(metric_uuid, MetricRecalculationResult(metric_uuid=metric_uuid, success=True))activities = [mock_discover, mock_update_progress, mock_calculate]@@ -185,7 +185,7 @@ class TestExperimentMetricsRecalculationWorkflow:metric_uuid: str,recalculation_id: str,query_to: str,- metric_type: str = "primary",+ role: str = "primary",) -> MetricRecalculationResult:attempts[metric_uuid] = attempts.get(metric_uuid, 0) + 1if metric_uuid == "m2" and attempts[metric_uuid] <= 2:@@ -219,7 +219,7 @@ class TestExperimentMetricsRecalculationWorkflow:metric_uuid: str,recalculation_id: str,query_to: str,- metric_type: str,+ role: str,is_final_attempt: bool,attempt: int,) -> MetricRecalculationResult:@@ -385,7 +385,7 @@ class TestExperimentMetricsRecalculationWorkflow:metric_uuid: str,recalculation_id: str,query_to: str,- metric_type: str = "primary",+ role: str = "primary",) -> MetricRecalculationResult:return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)@@ -437,7 +437,7 @@ class TestExperimentMetricsRecalculationWorkflow:metric_uuid: str,recalculation_id: str,query_to: str,- metric_type: str = "primary",+ role: str = "primary",) -> MetricRecalculationResult:return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)@@ -471,7 +471,7 @@ class TestExperimentMetricsRecalculationWorkflow:metric_uuid: str,recalculation_id: str,query_to: str,- metric_type: str = "primary",+ role: str = "primary",) -> MetricRecalculationResult:return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)@@ -513,7 +513,7 @@ class TestExperimentMetricsRecalculationWorkflow:metric_uuid: str,recalculation_id: str,query_to: str,- metric_type: str = "primary",+ role: str = "primary",) -> MetricRecalculationResult:return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)@@ -548,7 +548,7 @@ class TestExperimentMetricsRecalculationWorkflow:metric_uuid: str,recalculation_id: str,query_to: str,- metric_type: str = "primary",+ role: str = "primary",) -> MetricRecalculationResult:return MetricRecalculationResult(metric_uuid=metric_uuid, success=True)diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex af618051b8b0..8119c3dcfd1a 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -2424,8 +2424,8 @@ class TestExperimentService(APIBaseTest):ctx = service._build_serializer_context()# fresh payload per call — update_experiment mutates update_data in place- def attach(metric_type: str) -> dict:- return {"saved_metrics_ids": [{"id": saved_metric.id, "metadata": {"type": metric_type}}]}+ def attach(role: str) -> dict:+ return {"saved_metrics_ids": [{"id": saved_metric.id, "metadata": {"type": role}}]}if initial_type is not None:service.update_experiment(experiment, attach(initial_type), serializer_context=ctx)@@ -6384,7 +6384,7 @@ class TestExperimentService(APIBaseTest):_name: str,field: str,other_field: str,- metric_type: str,+ role: str,collides: bool,) -> None:self._create_flag(key="attach-dedup-with-saved")@@ -6428,7 +6428,7 @@ class TestExperimentService(APIBaseTest):)updated = service.update_experiment(- experiment, {"saved_metrics_ids": [{"id": sm.id, "metadata": {"type": metric_type}}]}+ experiment, {"saved_metrics_ids": [{"id": sm.id, "metadata": {"type": role}}]})sm.refresh_from_db()@@ -6449,7 +6449,7 @@ class TestExperimentService(APIBaseTest):])def test_update_regenerates_stored_inline_copy_that_collides_with_saved_metric_uuid(- self, _name: str, field: str, ordering_attr: str, metric_type: str, attach_another: bool+ self, _name: str, field: str, ordering_attr: str, role: str, attach_another: bool) -> None:self._create_flag(key="stored-collision")shared_uuid = "77bfb66a-51f5-48d0-a87e-bde2b4c958a6"@@ -6468,7 +6468,7 @@ class TestExperimentService(APIBaseTest):name="Stored collision",feature_flag_key="stored-collision",allow_unknown_events=True,- saved_metrics_ids=[{"id": sm.id, "metadata": {"type": metric_type}}],+ saved_metrics_ids=[{"id": sm.id, "metadata": {"type": role}}],)Experiment.objects.filter(id=experiment.id).update(**{@@ -6485,9 +6485,9 @@ class TestExperimentService(APIBaseTest):)experiment.refresh_from_db()- saved_metrics_ids = [{"id": sm.id, "metadata": {"type": metric_type}}]+ saved_metrics_ids = [{"id": sm.id, "metadata": {"type": role}}]if attach_another:- saved_metrics_ids.append({"id": self._make_saved_metric("Another").id, "metadata": {"type": metric_type}})+ saved_metrics_ids.append({"id": self._make_saved_metric("Another").id, "metadata": {"type": role}})payload: dict = {"saved_metrics_ids": saved_metrics_ids}else:payload = {field: deepcopy(getattr(experiment, field))}@@ -6540,7 +6540,7 @@ class TestExperimentService(APIBaseTest):])def test_detaching_saved_metric_keeps_uuid_its_stored_inline_copy_uses(- self, metric_type: str, field: str, ordering_attr: str+ self, role: str, field: str, ordering_attr: str) -> None:self._create_flag(key="detach-stored-collision")shared_uuid = "99bfb66a-51f5-48d0-a87e-bde2b4c958a6"@@ -6556,7 +6556,7 @@ class TestExperimentService(APIBaseTest):name="Detach stored collision",feature_flag_key="detach-stored-collision",allow_unknown_events=True,- saved_metrics_ids=[{"id": sm.id, "metadata": {"type": metric_type}}],+ saved_metrics_ids=[{"id": sm.id, "metadata": {"type": role}}],)Experiment.objects.filter(id=experiment.id).update(**{field: [metric], ordering_attr: [shared_uuid]})experiment.refresh_from_db()diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex 0464f1e8201c..c07635fa169e 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -8289,7 +8289,7 @@ class TestExperimentAuxiliaryEndpoints(_HoistFlagConfigClientMixin, ClickhouseTe])def test_bulk_remove_shared_metrics_does_not_touch_ordering(- self, metric_type: str, ordering_field: str, other_ordering_field: str+ self, role: str, ordering_field: str, other_ordering_field: str):saved_metric_uuids: list[str] = []saved_metric_ids: list[int] = []@@ -8314,10 +8314,10 @@ class TestExperimentAuxiliaryEndpoints(_HoistFlagConfigClientMixin, ClickhouseTef"/api/projects/{self.team.id}/experiments/",{"allow_unknown_events": True,- "name": f"Bulk Remove Activity Test ({metric_type})",- "feature_flag_key": f"bulk-remove-activity-{metric_type}",+ "name": f"Bulk Remove Activity Test ({role})",+ "feature_flag_key": f"bulk-remove-activity-{role}","saved_metrics_ids": [- {"id": saved_metric_id, "metadata": {"type": metric_type}} for saved_metric_id in saved_metric_ids+ {"id": saved_metric_id, "metadata": {"type": role}} for saved_metric_id in saved_metric_ids],ordering_field: saved_metric_uuids,},@@ -8329,7 +8329,7 @@ class TestExperimentAuxiliaryEndpoints(_HoistFlagConfigClientMixin, ClickhouseTelogs_before = ActivityLog.objects.filter(item_id=str(experiment_id), scope="Experiment").count()# A removal sends no ordering: the stale entries match nothing and are ignored on read.- inline_metrics_field = "metrics" if metric_type == "primary" else "metrics_secondary"+ inline_metrics_field = "metrics" if role == "primary" else "metrics_secondary"remove_response = self.client.patch(f"/api/projects/{self.team.id}/experiments/{experiment_id}/",{diff --git a/products/experiments/backend/test/test_setup_context.py b/products/experiments/backend/test/test_setup_context.pyindex ba16c4347c84..84f244fb4d66 100644--- a/products/experiments/backend/test/test_setup_context.py+++ b/products/experiments/backend/test/test_setup_context.py@@ -1133,7 +1133,7 @@ class TestPostgresSections(APIBaseTest):self._saved_metric("Retention", _retention_metric("retention", start_event="purchase", completion_event="renewed"))- for experiment, saved_metric, metric_type in [+ for experiment, saved_metric, role in [(live_a, popular, "primary"),(live_b, popular, "secondary"),(live_a, inflated, "primary"),@@ -1141,7 +1141,7 @@ class TestPostgresSections(APIBaseTest):(deleted_b, inflated, "primary"),]:ExperimentToSavedMetric.objects.create(- experiment=experiment, saved_metric=saved_metric, metadata={"type": metric_type}+ experiment=experiment, saved_metric=saved_metric, metadata={"type": role})# Three aggregates over the same experiments subquery; a refactor that unrolls them turns