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): skip metrics without a known metric_type in recalculation (#100204)

Juraj Majerik9c8626ddea34
diff --git a/products/experiments/backend/temporal/metric_resolution.py b/products/experiments/backend/temporal/metric_resolution.py
index 7dc05b7a04ad..fc282208efc6 100644
--- a/products/experiments/backend/temporal/metric_resolution.py
+++ b/products/experiments/backend/temporal/metric_resolution.py
@@ -17,8 +17,8 @@ from products.experiments.backend.models.experiment import Experiment
ExperimentMetric = ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric
-# Modern ExperimentMetric types (kind="ExperimentMetric"). Legacy Trends/Funnels metrics never enter these
-# workflows, so there is no fallback — an unexpected metric_type surfaces as an error at the call site.
+# Modern ExperimentMetric types (kind="ExperimentMetric"). Legacy Trends/Funnels metrics carry no
+# metric_type and are filtered out by is_scheduled_metric, so they never reach build_metric.
METRIC_BUILDERS: dict[str, type[ExperimentMetric]] = {
"mean": ExperimentMeanMetric,
"funnel": ExperimentFunnelMetric,
@@ -43,9 +43,10 @@ def _merge_saved_metric_breakdowns(saved_query: dict[str, Any], metadata: dict[s
def is_scheduled_metric(metric: dict[str, Any] | None) -> bool:
"""Recalculation and the canary address metrics by uuid, so a metric dict without one is
- never scheduled. Shared with the enrollment census so its build-load count filters the
- same way."""
- return bool(metric and metric.get("uuid"))
+ never scheduled. Legacy Trends/Funnels definitions carry no metric_type and cannot be
+ built, so they are excluded too. Shared with the enrollment census so its build-load
+ count filters the same way."""
+ return bool(metric and metric.get("uuid") and metric.get("metric_type") in METRIC_BUILDERS)
def iter_metric_dicts(experiment: Experiment) -> list[dict[str, Any]]:
diff --git a/products/experiments/backend/temporal/recalculation_logic.py b/products/experiments/backend/temporal/recalculation_logic.py
index 5154cbbca87a..4c1e1b87bbf3 100644
--- a/products/experiments/backend/temporal/recalculation_logic.py
+++ b/products/experiments/backend/temporal/recalculation_logic.py
@@ -42,7 +42,7 @@ from products.experiments.backend.models.experiment import (
ExperimentMetricResult,
ExperimentMetricsRecalculation,
)
-from products.experiments.backend.temporal.metric_resolution import build_metric, find_metric_dict
+from products.experiments.backend.temporal.metric_resolution import build_metric, find_metric_dict, is_scheduled_metric
from products.experiments.backend.temporal.models import (
CONCURRENCY_LIMIT_RETRY_DELAY_SECONDS,
MAX_METRIC_ATTEMPTS,
@@ -134,15 +134,17 @@ def discover_experiment_metrics(experiment: Experiment) -> list[ExperimentMetric
# Inline metrics carry their uuid directly on the dict; the metric_type is the source list.
for source, metric_type in [(experiment.metrics, "primary"), (experiment.metrics_secondary, "secondary")]:
for metric in source or []:
- _add(metric.get("uuid"), metric_type)
+ if is_scheduled_metric(metric):
+ _add(metric.get("uuid"), metric_type)
# Saved (shared) metrics live in the M2M through-model: uuid is on saved_metric.query["uuid"], and
# primary/secondary is recorded on the link's metadata["type"] (default "primary").
for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all():
saved_query = link.saved_metric.query
- metric_uuid = saved_query.get("uuid") if saved_query else None
+ if not is_scheduled_metric(saved_query):
+ continue
metric_type = link.metadata.get("type", "primary") if link.metadata else "primary"
- _add(metric_uuid, metric_type)
+ _add(saved_query.get("uuid"), metric_type)
return metrics_to_recalculate
diff --git a/products/experiments/backend/temporal/test_enrollment_census_logic.py b/products/experiments/backend/temporal/test_enrollment_census_logic.py
index 7fe1d2e60a28..80cafd713146 100644
--- a/products/experiments/backend/temporal/test_enrollment_census_logic.py
+++ b/products/experiments/backend/temporal/test_enrollment_census_logic.py
@@ -33,7 +33,7 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlag
def _metric() -> dict[str, Any]:
- return {"kind": "ExperimentMetric", "uuid": str(uuid.uuid4())}
+ return {"kind": "ExperimentMetric", "metric_type": "mean", "uuid": str(uuid.uuid4())}
def _stats(**overrides: Any) -> TeamDirectScanStats:
diff --git a/products/experiments/backend/temporal/test_metric_resolution.py b/products/experiments/backend/temporal/test_metric_resolution.py
index 874acdfc6763..2067fd831c23 100644
--- a/products/experiments/backend/temporal/test_metric_resolution.py
+++ b/products/experiments/backend/temporal/test_metric_resolution.py
@@ -41,7 +41,8 @@ class TestMetricResolution(BaseTest):
assert resolved["source"] == "inline"
def test_resolution_order_is_primary_secondary_saved(self):
- primary, secondary = {"uuid": str(uuid.uuid4())}, {"uuid": str(uuid.uuid4())}
+ primary = {"uuid": str(uuid.uuid4()), "metric_type": "mean"}
+ secondary = {"uuid": str(uuid.uuid4()), "metric_type": "mean"}
experiment = self._experiment(metrics=[primary], metrics_secondary=[secondary])
saved_uuid = str(uuid.uuid4())
self._attach_saved(experiment, {"uuid": saved_uuid, "metric_type": "mean"})
@@ -75,7 +76,14 @@ class TestMetricResolution(BaseTest):
assert resolved is not None
assert resolved["breakdownFilter"] == {"breakdowns": []}
- def test_metrics_without_uuid_are_excluded(self):
- experiment = self._experiment(metrics=[{"metric_type": "funnel"}])
+ def test_unschedulable_metrics_are_excluded(self):
+ experiment = self._experiment(
+ metrics=[
+ {"metric_type": "funnel"},
+ {"uuid": str(uuid.uuid4())},
+ {"uuid": str(uuid.uuid4()), "kind": "ExperimentTrendsQuery"},
+ ]
+ )
self._attach_saved(experiment, {"metric_type": "funnel"})
+ self._attach_saved(experiment, {"uuid": str(uuid.uuid4())})
assert iter_metric_dicts(experiment) == []
diff --git a/products/experiments/backend/temporal/test_recalculation_activities.py b/products/experiments/backend/temporal/test_recalculation_activities.py
index 54ad5a11ee16..eeffbf85559d 100644
--- a/products/experiments/backend/temporal/test_recalculation_activities.py
+++ b/products/experiments/backend/temporal/test_recalculation_activities.py
@@ -142,6 +142,17 @@ class TestRecalculationActivities(BaseTest):
{"m1", "s1"},
{"primary", "secondary"},
),
+ (
+ "legacy_metric_without_metric_type_skipped",
+ [
+ {"uuid": "m1", "metric_type": "mean", "kind": "ExperimentMetric"},
+ {"uuid": "legacy", "kind": "ExperimentTrendsQuery"},
+ ],
+ [],
+ [],
+ {"m1"},
+ {"primary"},
+ ),
]
)
def test_discover_persists_metric_uuids(self, name: str, primary, secondary, saved, expected_uuids, expected_types):
@@ -650,18 +661,17 @@ class TestCalculateActivity(BaseTest):
assert "m1" in recalc.metric_errors
def test_bad_metric_type_fails_at_calculation(self):
- # Legacy metrics never reach this workflow, so there's no discovery-time type guard; an unexpected
- # metric_type raises while building the metric. The activity records the failure to metric_errors
- # and re-raises so Temporal's retry policy can handle potentially transient errors.
+ # An unknown metric_type is unschedulable, so the calc lookup fails the metric permanently
+ # instead of raising KeyError while building it.
exp = self._experiment(
flag_key="calc-badtype",
metrics=[{"uuid": "m-bad", "metric_type": "nonsense", "kind": "ExperimentMetric"}],
)
recalc = self._recalc(exp, metric_uuids=["m-bad"])
- with pytest.raises(KeyError):
- _calculate(exp.id, "m-bad", str(recalc.id), _QUERY_TO)
+ result = _calculate(exp.id, "m-bad", str(recalc.id), _QUERY_TO)
+ assert result.success is False
recalc.refresh_from_db()
assert len(recalc.metric_errors) == 1
assert "m-bad" in recalc.metric_errors