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): validate shared metrics like inline metrics (#108951)

Andersa859d2c195d7
diff --git a/ee/clickhouse/views/test/test_experiment_saved_metrics.py b/ee/clickhouse/views/test/test_experiment_saved_metrics.py
index 6cc6a0998b82..2feb8aaa2644 100644
--- a/ee/clickhouse/views/test/test_experiment_saved_metrics.py
+++ b/ee/clickhouse/views/test/test_experiment_saved_metrics.py
@@ -91,7 +91,7 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.json()["detail"],
- "Metric query kind must be 'ExperimentMetric'",
+ "Invalid metric: metric kind must be 'ExperimentMetric'",
)
response = self.client.post(
@@ -107,7 +107,7 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.json()["detail"],
- "Metric query kind must be 'ExperimentMetric'",
+ "Invalid metric: metric kind must be 'ExperimentMetric'",
)
response = self.client.post(
@@ -122,7 +122,7 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.json()["detail"],
- "Metric query kind must be 'ExperimentMetric'",
+ "Invalid metric: metric kind must be 'ExperimentMetric'",
)
response = self.client.post(
@@ -515,7 +515,9 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertTrue("'loc': ('numerator',), 'msg': 'Field required'" in response.json()["detail"])
+ self.assertTrue(
+ "'loc': ('ratio', 'numerator'), 'type': 'missing', 'msg': 'Field required'" in response.json()["detail"]
+ )
# Test missing denominator
response = self.client.post(
@@ -536,7 +538,9 @@ class TestExperimentSavedMetricsCRUD(APILicensedTest):
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- self.assertTrue("'loc': ('denominator',), 'msg': 'Field required'" in response.json()["detail"])
+ self.assertTrue(
+ "'loc': ('ratio', 'denominator'), 'type': 'missing', 'msg': 'Field required'" in response.json()["detail"]
+ )
def test_invalid_create(self):
response = self.client.post(
diff --git a/products/experiments/backend/experiment_saved_metric_service.py b/products/experiments/backend/experiment_saved_metric_service.py
index dd43bd2792c1..3dba5f958de7 100644
--- a/products/experiments/backend/experiment_saved_metric_service.py
+++ b/products/experiments/backend/experiment_saved_metric_service.py
@@ -5,27 +5,17 @@ from uuid import uuid4
from django.db import transaction
-import pydantic
from rest_framework.exceptions import ValidationError
-from posthog.schema import (
- ExperimentFunnelMetric,
- ExperimentFunnelsQuery,
- ExperimentMeanMetric,
- ExperimentMetricType,
- ExperimentRatioMetric,
- ExperimentRetentionMetric,
- ExperimentTrendsQuery,
-)
-
from posthog.models.team.team import Team
-from products.experiments.backend.hogql_queries.retention_validation import retention_metric_error
-from products.experiments.backend.models.experiment import (
- LEGACY_METRIC_KINDS,
- ExperimentSavedMetric,
- saved_metric_has_legacy_query,
+from products.experiments.backend.metric_utils import without_action_names
+from products.experiments.backend.metric_validation import (
+ extract_entity_nodes,
+ parse_and_validate_metric,
+ validate_metric_action_ids,
)
+from products.experiments.backend.models.experiment import ExperimentSavedMetric, saved_metric_has_legacy_query
from products.experiments.backend.warehouse_access_control import enforce_warehouse_metric_access
@@ -41,42 +31,7 @@ class ExperimentSavedMetricService:
"""Validate saved metric queries accepted by the API layer."""
if not query:
raise ValidationError("Query is required to create a saved metric")
-
- kind = query.get("kind")
- if kind in LEGACY_METRIC_KINDS:
- raise ValidationError(
- f"Legacy metric kind '{kind}' is no longer supported for new saved metrics. "
- "Use 'ExperimentMetric' instead."
- )
-
- if kind != "ExperimentMetric":
- raise ValidationError("Metric query kind must be 'ExperimentMetric'")
-
- try:
- if kind == "ExperimentMetric":
- if "metric_type" not in query:
- raise ValidationError("ExperimentMetric requires a metric_type")
- if query["metric_type"] == ExperimentMetricType.MEAN:
- ExperimentMeanMetric(**query)
- elif query["metric_type"] == ExperimentMetricType.FUNNEL:
- ExperimentFunnelMetric(**query)
- elif query["metric_type"] == ExperimentMetricType.RATIO:
- ExperimentRatioMetric(**query)
- elif query["metric_type"] == ExperimentMetricType.RETENTION:
- retention_metric = ExperimentRetentionMetric(**query)
- retention_error = retention_metric_error(retention_metric)
- if retention_error:
- raise ValidationError(retention_error)
- else:
- raise ValidationError(
- "ExperimentMetric metric_type must be 'mean', 'funnel', 'ratio', or 'retention'"
- )
- elif kind == "ExperimentTrendsQuery":
- ExperimentTrendsQuery(**query)
- elif kind == "ExperimentFunnelsQuery":
- ExperimentFunnelsQuery(**query)
- except pydantic.ValidationError as e:
- raise ValidationError(str(e.errors())) from e
+ parse_and_validate_metric(query, error_prefix="Invalid metric: ")
@transaction.atomic
def create_saved_metric(
@@ -88,6 +43,7 @@ class ExperimentSavedMetricService:
) -> ExperimentSavedMetric:
"""Create a saved metric with full business-logic validation."""
normalized_query = self.normalize_query_for_write(query)
+ validate_metric_action_ids([normalized_query], self.team.id)
enforce_warehouse_metric_access([normalized_query], team=self.team, user=self.user)
return ExperimentSavedMetric.objects.create(
@@ -105,8 +61,11 @@ class ExperimentSavedMetricService:
self._validate_update_payload(update_data, saved_metric)
if "query" in update_data:
- existing_uuid = saved_metric.query.get("uuid") if saved_metric.query else None
- update_data["query"] = self.normalize_query_for_write(update_data["query"], existing_uuid=existing_uuid)
+ update_data["query"] = self.normalize_query_for_write(
+ update_data["query"], existing_query=saved_metric.query
+ )
+ _, stored_action_ids = extract_entity_nodes([saved_metric.query] if saved_metric.query else [])
+ validate_metric_action_ids([update_data["query"]], self.team.id, known_action_ids=stored_action_ids)
enforce_warehouse_metric_access([update_data["query"]], team=self.team, user=self.user)
for attr, value in update_data.items():
@@ -128,8 +87,18 @@ class ExperimentSavedMetricService:
raise ValidationError("Saved metric does not exist or does not belong to this project")
@classmethod
- def normalize_query_for_write(cls, query: dict, *, existing_uuid: str | None = None) -> dict:
- cls.validate_query(query)
+ def normalize_query_for_write(cls, query: dict, *, existing_query: dict | None = None) -> dict:
+ existing_uuid = existing_query.get("uuid") if existing_query else None
+ # Clients resend the whole query on any edit, including a rename or a tag change. A stored
+ # query that comes back unchanged is not validated again, so a rule added after it was saved
+ # does not block those edits.
+ is_unchanged = (
+ bool(query)
+ and existing_query is not None
+ and without_action_names(query) == without_action_names(existing_query)
+ )
+ if not is_unchanged:
+ cls.validate_query(query)
normalized_query = dict(query)
incoming_uuid = normalized_query.get("uuid")
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 06561d7fe018..d2db9c35e22d 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -22,15 +22,7 @@ import structlog
from rest_framework import status
from rest_framework.exceptions import APIException, PermissionDenied, ValidationError
-from posthog.schema import (
- ActionsNode,
- ExperimentEventExposureConfig,
- ExperimentExposureCriteria,
- ExperimentFunnelMetric,
- ExperimentMeanMetric,
- ExperimentMetric,
- ExperimentRetentionMetric,
-)
+from posthog.schema import ActionsNode, ExperimentEventExposureConfig, ExperimentExposureCriteria
from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
@@ -55,12 +47,10 @@ from posthog.models.team.team import Team
from posthog.models.user import User
from posthog.utils import str_to_bool
-from products.actions.backend.models.action import Action
from products.cohorts.backend.models.cohort import Cohort
from products.event_definitions.backend.models import EventDefinition, effective_project_id_expr
from products.experiments.backend.flag_cleanup import build_cleanup_prompt, cleanup_plan
from products.experiments.backend.hogql_queries import CONTROL_VARIANT_KEY, get_baseline_variant_key
-from products.experiments.backend.hogql_queries.base_query_utils import is_threshold_supported_math
from products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprint
from products.experiments.backend.hogql_queries.exposure_query_logic import (
DEFAULT_EXPOSURE_EVENT,
@@ -70,14 +60,16 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (
get_exposure_event_and_property,
resolve_default_exposure_event,
)
-from products.experiments.backend.hogql_queries.funnel_validation import FunnelDWValidator
-from products.experiments.backend.hogql_queries.retention_validation import retention_metric_error
from products.experiments.backend.metric_utils import filter_metric_group_ids_by_event
+from products.experiments.backend.metric_validation import (
+ extract_entity_nodes,
+ parse_and_validate_metric,
+ validate_metric_action_ids,
+)
from products.experiments.backend.models.experiment import (
EXPOSURE_FROZEN_COHORT_KEY,
EXPOSURE_FROZEN_GROUP_KEY,
EXPOSURE_FROZEN_GROUP_MARKER,
- LEGACY_METRIC_KINDS,
Experiment,
ExperimentHoldout,
ExperimentMetricResult,
@@ -769,48 +761,8 @@ class ExperimentService:
f"Invalid {field_path} (kind={cls._safe_repr(kind)}): {safe_errors}. {cls.EXPOSURE_CONFIG_HINT}"
)
- # Maps the public `metric_type` literal to the pydantic class name that pydantic reports
- # in `loc[0]` when validation fails. Used to narrow union-variant errors to the variant
- # the caller picked. A drift test asserts this stays in sync with the ExperimentMetric union.
- _METRIC_TYPE_TO_CLASS = {
- "mean": "ExperimentMeanMetric",
- "funnel": "ExperimentFunnelMetric",
- "ratio": "ExperimentRatioMetric",
- "retention": "ExperimentRetentionMetric",
- }
-
- # Cap reported pydantic errors so a funnel with many steps (each producing union-variant
- # errors) cannot blow up the response size. The first N errors are the most actionable.
- _MAX_REPORTED_METRIC_ERRORS = 15
-
- _EVENTS_NODE_ID_HINT = (
- "EventsNode does not accept an 'id' field. "
- "To reference an event, use {'kind': 'EventsNode', 'event': '<event_name>'} (omit 'id'). "
- "To reference an action, switch to {'kind': 'ActionsNode', 'id': <integer_action_id>} (omit 'event')."
- )
-
@staticmethod
- def _is_events_node_actions_node_confusion(err: dict) -> bool:
- """An `id` field was passed on an EventsNode (probably meant ActionsNode)."""
- loc = tuple(err.get("loc") or ())
- if len(loc) < 2 or err.get("type") != "extra_forbidden":
- return False
- return loc[-1] == "id" and "EventsNode" in loc
-
- @classmethod
- def _build_metric_validation_hint(cls, safe_errors: list[dict]) -> str:
- """Return a targeted hint for an observed pydantic error pattern, or '' if none applies.
-
- The structural shape of valid metrics is conveyed by `safe_errors` itself (loc, type,
- msg) — adding prose duplicates the pydantic models and rots silently. Only hints
- whose facts are independent of metric shape belong here."""
- for err in safe_errors:
- if cls._is_events_node_actions_node_confusion(err):
- return cls._EVENTS_NODE_ID_HINT
- return ""
-
- @classmethod
- def validate_experiment_metrics(cls, metrics: list | None) -> None:
+ def validate_experiment_metrics(metrics: list | None) -> None:
"""Validate metric payloads accepted by the API layer."""
if metrics is None:
return
@@ -819,87 +771,7 @@ class ExperimentService:
raise ValidationError("Metrics must be a list")
for i, metric in enumerate(metrics):
- if not isinstance(metric, dict):
- raise ValidationError(f"Invalid metric at index {i}: must be a dict")
-
- kind = metric.get("kind")
- if kind in LEGACY_METRIC_KINDS:
- raise ValidationError(
- f"Invalid metric at index {i}: legacy metric kind '{kind}' is no longer supported for new experiments. "
- "Use 'ExperimentMetric' instead."
- )
-
- if kind != "ExperimentMetric":
- raise ValidationError(f"Invalid metric at index {i}: metric kind must be 'ExperimentMetric'")
-
- if kind == "ExperimentMetric":
- try:
- validated_metric = ExperimentMetric.model_validate(metric)
-
- # ExperimentMetric is a RootModel wrapping a union, so access .root to get the actual type
- actual_metric = validated_metric.root
- if isinstance(actual_metric, ExperimentFunnelMetric):
- # The experiment exposure event is prepended as step_0 at query time,
- # so series must contain at least one user-supplied step for the funnel
- # to yield a meaningful conversion metric.
- if not actual_metric.series:
- raise ValidationError(
- f"Invalid metric at index {i}: funnel metrics require at least one step. "
- "The experiment exposure event is added as the initial step automatically."
- )
- # Additional validation for funnel metrics with DW steps
- FunnelDWValidator.validate_funnel_metric(actual_metric)
- elif isinstance(actual_metric, ExperimentMeanMetric) and actual_metric.threshold is not None:
- # A threshold turns the per-user value into a binary "did the user reach N"
- # outcome, which only makes sense for sum/count math types.
- source_math = getattr(actual_metric.source, "math", None)
- if not is_threshold_supported_math(source_math):
- raise ValidationError(
- f"Invalid metric at index {i}: a threshold is only supported for "
- "sum or count (total) math types."
- )
- # A non-positive threshold is satisfied by every user (missing users
- # accumulate to 0), producing a meaningless 100% proportion.
- if actual_metric.threshold <= 0:
- raise ValidationError(f"Invalid metric at index {i}: threshold must be a positive number.")
- # Winsorization caps continuous outliers, which is meaningless once the
- # value collapses to a binary threshold outcome.
- if (
- actual_metric.lower_bound_percentile is not None
- or actual_metric.upper_bound_percentile is not None
- ):
- raise ValidationError(
- f"Invalid metric at index {i}: a threshold cannot be combined with "
- "outlier handling (winsorization)."
- )
- elif isinstance(actual_metric, ExperimentRetentionMetric):
- retention_error = retention_metric_error(actual_metric)
- if retention_error:
- raise ValidationError(f"Invalid metric at index {i}: {retention_error}")
-
- except pydantic.ValidationError as e:
- # Surface only the field locations and error types from pydantic — not the
- # echoed `input`, `ctx`, and `url` fields, which would reflect arbitrary
- # user data back into the response (potentially unbounded in size).
- safe_errors = [
- {"loc": err.get("loc"), "type": err.get("type"), "msg": err.get("msg")} for err in e.errors()
- ]
- # ExperimentMetric is a union of four variants; pydantic reports errors against
- # every variant by default. If the caller picked a metric_type, narrow to that
- # variant's errors so the message stays actionable instead of dumping 25+ errors.
- metric_type = metric.get("metric_type")
- variant_class = cls._METRIC_TYPE_TO_CLASS.get(metric_type) if isinstance(metric_type, str) else None
- if variant_class is not None:
- filtered = [err for err in safe_errors if err["loc"] and err["loc"][0] == variant_class]
- if filtered:
- safe_errors = filtered
- hint = cls._build_metric_validation_hint(safe_errors)
- if len(safe_errors) > cls._MAX_REPORTED_METRIC_ERRORS:
- truncated = safe_errors[: cls._MAX_REPORTED_METRIC_ERRORS]
- truncated.append({"truncated": f"...{len(safe_errors) - cls._MAX_REPORTED_METRIC_ERRORS} more"})
- safe_errors = truncated
- suffix = f" {hint}" if hint else ""
- raise ValidationError(f"Invalid metric at index {i}: {safe_errors}.{suffix}")
+ parse_and_validate_metric(metric, error_prefix=f"Invalid metric at index {i}: ")
VALID_STATS_METHODS = {"bayesian", "frequentist"}
@@ -1111,92 +983,6 @@ class ExperimentService:
if saved_metrics.count() != len(saved_metrics_ids):
raise ValidationError("Saved metric does not exist or does not belong to this project")
- @staticmethod
- def _extract_entity_nodes(metrics: list[dict] | None) -> tuple[set[str], set[int]]:
- """Extract event names and action IDs from all EventsNode/ActionsNode refs in metrics."""
- event_names: set[str] = set()
- action_ids: set[int] = set()
- if not metrics:
- return event_names, action_ids
-
- for metric in metrics:
- nodes: list[dict] = []
- metric_type = metric.get("metric_type")
- if metric_type == "mean":
- if source := metric.get("source"):
- nodes.append(source)
- elif metric_type == "funnel":
- nodes.extend(metric.get("series") or [])
- elif metric_type == "ratio":
- if num := metric.get("numerator"):
- nodes.append(num)
- if den := metric.get("denominator"):
- nodes.append(den)
- elif metric_type == "retention":
- if se := metric.get("start_event"):
- nodes.append(se)
- if ce := metric.get("completion_event"):
- nodes.append(ce)
-
- for node in nodes:
- kind = node.get("kind")
- if kind == "EventsNode":
- event = node.get("event")
- # Treat None and empty/whitespace-only strings as "no event"
- # (semantically equivalent to "All events"). The pydantic
- # schema permits "" but it can't reference a real event.
- if isinstance(event, str) and event.strip():
- event_names.add(event)
- elif event is not None and not isinstance(event, str):
- # Pydantic should have rejected non-str/None upstream;
- # log so we can catch any path that bypassed validation
- # rather than silently dropping the value.
- logger.warning(
- "experiment_metric_unexpected_event_type",
- event_type=type(event).__name__,
- event_value=repr(event)[:100],
- )
- elif kind == "ActionsNode":
- if (action_id := node.get("id")) is not None:
- action_ids.add(int(action_id))
-
- return event_names, action_ids
-
- @classmethod
- def validate_metric_action_ids(
- cls, metrics: list[dict] | None, team_id: int, *, known_action_ids: set[int] | None = None
- ) -> None:
- """Validate that all ActionsNode IDs reference existing, non-deleted actions for the team.
-
- Actions are explicitly created entities with stable IDs, so a reference to a
- nonexistent action is almost certainly a mistake, so we raise a hard validation error.
-
- ``known_action_ids`` exempts ids already persisted on the experiment, so an
- update is checked for what it introduces rather than for everything it
- resends. Without it, deleting a referenced action makes every later metric
- edit fail on the resent arrays. See ``update_experiment``.
- """
- _, action_ids = cls._extract_entity_nodes(metrics)
- if known_action_ids:
- action_ids -= known_action_ids
- if not action_ids:
- return
-
- existing_ids = set(
- Action.objects.filter(
- id__in=action_ids,
- team_id=team_id,
- deleted=False,
- ).values_list("id", flat=True)
- )
- missing = action_ids - existing_ids
- if missing:
- missing_str = ", ".join(str(aid) for aid in sorted(missing))
- raise ValidationError(
- f"Action(s) with ID {missing_str} not found or deleted. "
- "Each ActionsNode must reference an existing action belonging to this project."
- )
-
def validate_metric_event_names(
self, metrics: list[dict] | None, *, known_event_names: set[str] | None = None
) -> None:
@@ -1217,7 +1003,7 @@ class ExperimentService:
multi-team project can pick an event ingested by a sibling team. We
mirror that scope here to avoid rejecting legitimate selections.
"""
- all_event_names, _ = self._extract_entity_nodes(metrics)
+ all_event_names, _ = extract_entity_nodes(metrics)
event_names = all_event_names - known_event_names if known_event_names else all_event_names
if not event_names:
return
@@ -1310,8 +1096,8 @@ class ExperimentService:
running_time_calculation = running_time_calculation or {}
self.validate_experiment_metrics(metrics)
self.validate_experiment_metrics(metrics_secondary)
- self.validate_metric_action_ids(metrics, self.team.id)
- self.validate_metric_action_ids(metrics_secondary, self.team.id)
+ validate_metric_action_ids(metrics, self.team.id)
+ validate_metric_action_ids(metrics_secondary, self.team.id)
if not allow_unknown_events:
self.validate_metric_event_names(metrics)
self.validate_metric_event_names(metrics_secondary)
@@ -3537,14 +3323,14 @@ class ExperimentService:
# sections are pooled: moving a metric between them changes which array holds
# it, not which entity it references. Read before the update is applied, so
# these are the stored references.
- persisted_event_names, persisted_action_ids = self._extract_entity_nodes(
+ persisted_event_names, persisted_action_ids = extract_entity_nodes(
[*(experiment.metrics or []), *(experiment.metrics_secondary or [])]
)
if "metrics" in update_data:
update_data["metrics"] = self._assign_uuids_to_metrics(update_data["metrics"], seen=seen_metric_uuids)
self.validate_experiment_metrics(update_data["metrics"])
- self.validate_metric_action_ids(update_data["metrics"], self.team.id, known_action_ids=persisted_action_ids)
+ validate_metric_action_ids(update_data["metrics"], self.team.id, known_action_ids=persisted_action_ids)
if not allow_unknown_events:
self.validate_metric_event_names(update_data["metrics"], known_event_names=persisted_event_names)
if "metrics_secondary" in update_data:
@@ -3552,7 +3338,7 @@ class ExperimentService:
update_data["metrics_secondary"], seen=seen_metric_uuids
)
self.validate_experiment_metrics(update_data["metrics_secondary"])
- self.validate_metric_action_ids(
+ validate_metric_action_ids(
update_data["metrics_secondary"], self.team.id, known_action_ids=persisted_action_ids
)
if not allow_unknown_events:
diff --git a/products/experiments/backend/metric_utils.py b/products/experiments/backend/metric_utils.py
index 832dec47cc78..1ec589b0b3e0 100644
--- a/products/experiments/backend/metric_utils.py
+++ b/products/experiments/backend/metric_utils.py
@@ -125,6 +125,22 @@ def refresh_action_names_in_metric(
return query
+def without_action_names(obj: Any) -> Any:
+ """Copy of a metric query without the ActionsNode names.
+
+ The name is a label that `refresh_action_names_in_metric` rewrites on read, so two queries that
+ differ only in these names define the same metric.
+ """
+ if isinstance(obj, dict):
+ is_actions_node = obj.get("kind") == "ActionsNode"
+ return {
+ key: without_action_names(value) for key, value in obj.items() if not (is_actions_node and key == "name")
+ }
+ if isinstance(obj, list):
+ return [without_action_names(item) for item in obj]
+ return obj
+
+
def _collect_action_ids(obj: Any, action_ids: set[int]) -> None:
"""Recursively collect all action IDs from ActionsNode objects in the query."""
if isinstance(obj, dict):
diff --git a/products/experiments/backend/metric_validation.py b/products/experiments/backend/metric_validation.py
new file mode 100644
index 000000000000..6973554e3fd6
--- /dev/null
+++ b/products/experiments/backend/metric_validation.py
@@ -0,0 +1,224 @@
+"""Validation for an experiment metric definition, shared by the metric write paths.
+
+Inline metrics (on the experiment) and saved/shared metrics (ExperimentSavedMetric.query) are the same
+metric types, so both write paths parse and validate through `parse_and_validate_metric` and check
+referenced actions through `validate_metric_action_ids`. Checks that need a user or that the caller can
+waive (team ownership, permissions, whether a referenced event exists) stay with the callers.
+"""
+
+import pydantic
+import structlog
+from rest_framework.exceptions import ValidationError
+
+from posthog.schema import (
+ ExperimentFunnelMetric,
+ ExperimentMeanMetric,
+ ExperimentMetric as ExperimentMetricUnion,
+ ExperimentRetentionMetric,
+)
+
+from products.actions.backend.models.action import Action
+from products.experiments.backend.hogql_queries.base_query_utils import is_threshold_supported_math
+from products.experiments.backend.hogql_queries.funnel_validation import FunnelDWValidator
+from products.experiments.backend.hogql_queries.retention_validation import retention_metric_error
+from products.experiments.backend.metric_resolution import METRIC_BUILDERS, ExperimentMetric
+from products.experiments.backend.models.experiment import LEGACY_METRIC_KINDS
+
+logger = structlog.get_logger(__name__)
+
+# Cap reported pydantic errors so a funnel with many steps (each producing union-variant
+# errors) cannot blow up the response size. The first N errors are the most actionable.
+MAX_REPORTED_METRIC_ERRORS = 15
+
+EVENTS_NODE_ID_HINT = (
+ "EventsNode does not accept an 'id' field. "
+ "To reference an event, use {'kind': 'EventsNode', 'event': '<event_name>'} (omit 'id'). "
+ "To reference an action, switch to {'kind': 'ActionsNode', 'id': <integer_action_id>} (omit 'event')."
+)
+
+
+def is_events_node_actions_node_confusion(err: dict) -> bool:
+ """An `id` field was passed on an EventsNode (probably meant ActionsNode)."""
+ loc = tuple(err.get("loc") or ())
+ if len(loc) < 2 or err.get("type") != "extra_forbidden":
+ return False
+ return loc[-1] == "id" and "EventsNode" in loc
+
+
+def _metric_validation_hint(safe_errors: list[dict]) -> str:
+ """Return a targeted hint for an observed pydantic error pattern, or '' if none applies.
+
+ The structural shape of valid metrics is conveyed by `safe_errors` itself (loc, type,
+ msg) — adding prose duplicates the pydantic models and rots silently. Only hints
+ whose facts are independent of metric shape belong here."""
+ for err in safe_errors:
+ if is_events_node_actions_node_confusion(err):
+ return EVENTS_NODE_ID_HINT
+ return ""
+
+
+def _pydantic_error_message(e: pydantic.ValidationError) -> str:
+ # Surface only the field locations and error types from pydantic — not the
+ # echoed `input`, `ctx`, and `url` fields, which would reflect arbitrary
+ # user data back into the response (potentially unbounded in size).
+ safe_errors = [{"loc": err.get("loc"), "type": err.get("type"), "msg": err.get("msg")} for err in e.errors()]
+ hint = _metric_validation_hint(safe_errors)
+ if len(safe_errors) > MAX_REPORTED_METRIC_ERRORS:
+ truncated = safe_errors[:MAX_REPORTED_METRIC_ERRORS]
+ truncated.append({"truncated": f"...{len(safe_errors) - MAX_REPORTED_METRIC_ERRORS} more"})
+ safe_errors = truncated
+ suffix = f" {hint}" if hint else ""
+ return f"{safe_errors}.{suffix}"
+
+
+def _semantic_error(metric: ExperimentMetric) -> str | None:
+ """Rules the pydantic schema cannot express. FunnelDWValidator raises its own structured error."""
+ if isinstance(metric, ExperimentFunnelMetric):
+ # The experiment exposure event is prepended as step_0 at query time,
+ # so series must contain at least one user-supplied step for the funnel
+ # to yield a meaningful conversion metric.
+ if not metric.series:
+ return (
+ "funnel metrics require at least one step. "
+ "The experiment exposure event is added as the initial step automatically."
+ )
+ FunnelDWValidator.validate_funnel_metric(metric)
+ elif isinstance(metric, ExperimentMeanMetric) and metric.threshold is not None:
+ # A threshold turns the per-user value into a binary "did the user reach N"
+ # outcome, which only makes sense for sum/count math types.
+ if not is_threshold_supported_math(getattr(metric.source, "math", None)):
+ return "a threshold is only supported for sum or count (total) math types."
+ # A non-positive threshold is satisfied by every user (missing users
+ # accumulate to 0), producing a meaningless 100% proportion.
+ if metric.threshold <= 0:
+ return "threshold must be a positive number."
+ # Winsorization caps continuous outliers, which is meaningless once the
+ # value collapses to a binary threshold outcome.
+ if metric.lower_bound_percentile is not None or metric.upper_bound_percentile is not None:
+ return "a threshold cannot be combined with outlier handling (winsorization)."
+ elif isinstance(metric, ExperimentRetentionMetric):
+ return retention_metric_error(metric)
+ return None
+
+
+def parse_and_validate_metric(metric: object, *, error_prefix: str) -> ExperimentMetric:
+ """Parse a metric payload into its schema type and apply the intrinsic metric rules.
+
+ `error_prefix` locates the metric in the request, for example "Invalid metric at index 2: ".
+ """
+ if not isinstance(metric, dict):
+ raise ValidationError(f"{error_prefix}must be a dict")
+
+ kind = metric.get("kind")
+ if isinstance(kind, str) and kind in LEGACY_METRIC_KINDS:
+ raise ValidationError(
+ f"{error_prefix}legacy metric kind '{kind}' is no longer supported. Use 'ExperimentMetric' instead."
+ )
+ if kind != "ExperimentMetric":
+ raise ValidationError(f"{error_prefix}metric kind must be 'ExperimentMetric'")
+
+ metric_type = metric.get("metric_type")
+ if metric_type is None:
+ raise ValidationError(f"{error_prefix}ExperimentMetric requires a metric_type")
+ if not isinstance(metric_type, str) or metric_type not in METRIC_BUILDERS:
+ raise ValidationError(
+ f"{error_prefix}ExperimentMetric metric_type must be 'mean', 'funnel', 'ratio', or 'retention'"
+ )
+
+ try:
+ # ExperimentMetric is a RootModel over a union discriminated by metric_type, so pydantic
+ # reports errors for the chosen variant only, and .root is the concrete metric type.
+ parsed = ExperimentMetricUnion.model_validate(metric).root
+ except pydantic.ValidationError as e:
+ raise ValidationError(f"{error_prefix}{_pydantic_error_message(e)}")
+
+ error = _semantic_error(parsed)
+ if error:
+ raise ValidationError(f"{error_prefix}{error}")
+ return parsed
+
+
+def extract_entity_nodes(metrics: list[dict] | None) -> tuple[set[str], set[int]]:
+ """Extract event names and action IDs from all EventsNode/ActionsNode refs in metrics."""
+ event_names: set[str] = set()
+ action_ids: set[int] = set()
+ if not metrics:
+ return event_names, action_ids
+
+ for metric in metrics:
+ nodes: list[dict] = []
+ metric_type = metric.get("metric_type")
+ if metric_type == "mean":
+ if source := metric.get("source"):
+ nodes.append(source)
+ elif metric_type == "funnel":
+ nodes.extend(metric.get("series") or [])
+ elif metric_type == "ratio":
+ if num := metric.get("numerator"):
+ nodes.append(num)
+ if den := metric.get("denominator"):
+ nodes.append(den)
+ elif metric_type == "retention":
+ if se := metric.get("start_event"):
+ nodes.append(se)
+ if ce := metric.get("completion_event"):
+ nodes.append(ce)
+
+ for node in nodes:
+ kind = node.get("kind")
+ if kind == "EventsNode":
+ event = node.get("event")
+ # Treat None and empty/whitespace-only strings as "no event"
+ # (semantically equivalent to "All events"). The pydantic
+ # schema permits "" but it can't reference a real event.
+ if isinstance(event, str) and event.strip():
+ event_names.add(event)
+ elif event is not None and not isinstance(event, str):
+ # Pydantic should have rejected non-str/None upstream;
+ # log so we can catch any path that bypassed validation
+ # rather than silently dropping the value.
+ logger.warning(
+ "experiment_metric_unexpected_event_type",
+ event_type=type(event).__name__,
+ event_value=repr(event)[:100],
+ )
+ elif kind == "ActionsNode":
+ if (action_id := node.get("id")) is not None:
+ action_ids.add(int(action_id))
+
+ return event_names, action_ids
+
+
+def validate_metric_action_ids(
+ metrics: list[dict] | None, team_id: int, *, known_action_ids: set[int] | None = None
+) -> None:
+ """Validate that all ActionsNode IDs reference existing, non-deleted actions for the team.
+
+ Actions are explicitly created entities with stable IDs, so a reference to a
+ nonexistent action is almost certainly a mistake, so we raise a hard validation error.
+
+ ``known_action_ids`` exempts ids already persisted on the experiment or the saved
+ metric, so an update is checked for what it introduces rather than for everything it
+ resends. Without it, deleting a referenced action makes every later metric
+ edit fail on the resent arrays. See ``update_experiment``.
+ """
+ _, action_ids = extract_entity_nodes(metrics)
+ if known_action_ids:
+ action_ids -= known_action_ids
+ if not action_ids:
+ return
+
+ existing_ids = set(
+ Action.objects.filter(
+ id__in=action_ids,
+ team_id=team_id,
+ deleted=False,
+ ).values_list("id", flat=True)
+ )
+ missing = action_ids - existing_ids
+ if missing:
+ missing_str = ", ".join(str(aid) for aid in sorted(missing))
+ raise ValidationError(
+ f"Action(s) with ID {missing_str} not found or deleted. "
+ "Each ActionsNode must reference an existing action belonging to this project."
+ )
diff --git a/products/experiments/backend/test/test_experiment_saved_metric_service.py b/products/experiments/backend/test/test_experiment_saved_metric_service.py
index d5ed6ae4a38e..56b9adf10f4f 100644
--- a/products/experiments/backend/test/test_experiment_saved_metric_service.py
+++ b/products/experiments/backend/test/test_experiment_saved_metric_service.py
@@ -10,6 +10,63 @@ from products.experiments.backend.experiment_saved_metric_service import Experim
from products.experiments.backend.experiment_service import ExperimentService
from products.experiments.backend.models.experiment import ExperimentSavedMetric, ExperimentToSavedMetric
+_THRESHOLD_MEAN: dict[str, object] = {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "source": {"kind": "EventsNode", "event": "$pageview", "math": "sum", "math_property": "amount"},
+}
+
+_SHARED_RULE_CASES: list[tuple[str, dict[str, object], str]] = [
+ (
+ "funnel_without_steps",
+ {"kind": "ExperimentMetric", "metric_type": "funnel", "series": []},
+ "funnel metrics require at least one step",
+ ),
+ ("zero_threshold", {**_THRESHOLD_MEAN, "threshold": 0}, "threshold must be a positive number"),
+ (
+ "threshold_with_winsorization",
+ {**_THRESHOLD_MEAN, "threshold": 10, "upper_bound_percentile": 0.99},
+ "a threshold cannot be combined with outlier handling",
+ ),
+ (
+ "warehouse_funnel_step_without_join_key",
+ {
+ "kind": "ExperimentMetric",
+ "metric_type": "funnel",
+ "series": [
+ {
+ "kind": "ExperimentDataWarehouseNode",
+ "table_name": "orders",
+ "timestamp_field": "created_at",
+ "data_warehouse_join_key": "",
+ "events_join_key": "distinct_id",
+ }
+ ],
+ },
+ "Step 1: data_warehouse_join_key is required",
+ ),
+ (
+ "action_that_does_not_exist",
+ {"kind": "ExperimentMetric", "metric_type": "mean", "source": {"kind": "ActionsNode", "id": 999999}},
+ "Action(s) with ID 999999 not found or deleted",
+ ),
+]
+
+_STORED_ACTION_SOURCE: dict[str, object] = {
+ "kind": "ActionsNode",
+ "id": 999999,
+ "name": "Stored name",
+ "math": "sum",
+ "math_property": "amount",
+}
+
+_STORED_ACTION_MEAN: dict[str, object] = {
+ "kind": "ExperimentMetric",
+ "metric_type": "mean",
+ "uuid": "stored-uuid",
+ "source": _STORED_ACTION_SOURCE,
+}
+
class TestExperimentSavedMetricService(APIBaseTest):
def _service(self) -> ExperimentSavedMetricService:
@@ -44,7 +101,12 @@ class TestExperimentSavedMetricService(APIBaseTest):
(
"invalid_kind",
{"kind": "not-ExperimentMetric"},
- "Metric query kind must be 'ExperimentMetric'",
+ "Invalid metric: metric kind must be 'ExperimentMetric'",
+ ),
+ (
+ "unhashable_kind",
+ {"kind": ["ExperimentMetric"], "metric_type": "mean"},
+ "Invalid metric: metric kind must be 'ExperimentMetric'",
),
(
"missing_metric_type",
@@ -89,6 +151,58 @@ class TestExperimentSavedMetricService(APIBaseTest):
assert expected_error in str(ctx.exception)
+ @parameterized.expand(
+ [
+ (f"{case_name}_{path}", path, metric, fragment)
+ for case_name, metric, fragment in _SHARED_RULE_CASES
+ for path in ("create", "update")
+ ]
+ )
+ def test_saved_write_paths_apply_the_inline_metric_rules(
+ self, _: str, path: str, metric: dict[str, object], fragment: str
+ ) -> None:
+ with self.assertRaises(ValidationError) as ctx:
+ if path == "create":
+ self._service().create_saved_metric(name="Saved metric", query=metric)
+ else:
+ saved_metric = self._service().create_saved_metric(
+ name="Saved metric", query=self._valid_experiment_metric()
+ )
+ self._service().update_saved_metric(saved_metric, {"query": metric})
+
+ assert fragment in str(ctx.exception)
+
+ @parameterized.expand(
+ [
+ ("resent_as_stored", "Stored name"),
+ ("resent_with_the_action_name_refreshed_on_read", "Current name"),
+ ]
+ )
+ def test_update_saved_metric_accepts_unchanged_query_that_predates_a_rule(
+ self, _: str, resent_action_name: str
+ ) -> None:
+ stored_query = {**_STORED_ACTION_MEAN, "threshold": 0}
+ saved_metric = ExperimentSavedMetric.objects.create(
+ team=self.team, created_by=self.user, name="Original name", query=stored_query
+ )
+ resent_query = {**stored_query, "source": {**_STORED_ACTION_SOURCE, "name": resent_action_name}}
+
+ updated = self._service().update_saved_metric(saved_metric, {"name": "Renamed", "query": resent_query})
+
+ assert updated.name == "Renamed"
+ assert updated.query == resent_query
+
+ def test_update_saved_metric_accepts_a_stored_action_that_was_deleted(self) -> None:
+ saved_metric = ExperimentSavedMetric.objects.create(
+ team=self.team, created_by=self.user, name="Saved metric", query=_STORED_ACTION_MEAN
+ )
+
+ updated = self._service().update_saved_metric(
+ saved_metric, {"query": {**_STORED_ACTION_MEAN, "goal": "decrease"}}
+ )
+
+ assert updated.query["goal"] == "decrease"
+
def test_update_saved_metric_updates_fields(self) -> None:
saved_metric = ExperimentSavedMetric.objects.create(
team=self.team,
@@ -124,13 +238,15 @@ class TestExperimentSavedMetricService(APIBaseTest):
assert updated == saved_metric
save_mock.assert_not_called()
- def test_update_saved_metric_validates_query_before_mutation(self) -> None:
+ @parameterized.expand([("stored_query_is_valid", False), ("stored_query_is_empty_too", True)])
+ def test_update_saved_metric_validates_query_before_mutation(self, _: str, stored_query_is_empty: bool) -> None:
+ stored_query = {} if stored_query_is_empty else self._valid_experiment_metric()
saved_metric = ExperimentSavedMetric.objects.create(
team=self.team,
created_by=self.user,
name="Original name",
description="Original description",
- query=self._valid_experiment_metric(),
+ query=stored_query,
)
with self.assertRaises(ValidationError) as ctx:
@@ -145,7 +261,7 @@ class TestExperimentSavedMetricService(APIBaseTest):
assert "Query is required to create a saved metric" in str(ctx.exception)
saved_metric.refresh_from_db()
assert saved_metric.name == "Original name"
- assert saved_metric.query == self._valid_experiment_metric()
+ assert saved_metric.query == stored_query
def test_update_saved_metric_query_preserves_existing_uuid(self) -> None:
saved_metric = self._service().create_saved_metric(
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index b7d0957dda28..365cbfdfff99 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -48,6 +48,12 @@ from products.experiments.backend.experiment_service import (
_merge_saved_metric_links,
_resolve_scalar_updates,
)
+from products.experiments.backend.metric_resolution import METRIC_BUILDERS
+from products.experiments.backend.metric_validation import (
+ extract_entity_nodes,
+ is_events_node_actions_node_confusion,
+ logger as metric_validation_logger,
+)
from products.experiments.backend.models.experiment import (
EXPOSURE_FROZEN_COHORT_KEY,
EXPOSURE_FROZEN_GROUP_KEY,
@@ -1248,10 +1254,10 @@ class TestExperimentService(APIBaseTest):
ExperimentService.validate_experiment_metrics([self._INVALID_METRIC_EVENTS_NODE_ID])
assert "Invalid metric at index 0:" in str(ctx.exception)
- def test_metric_type_to_class_mapping_matches_schema(self) -> None:
+ def test_metric_builders_match_schema(self) -> None:
"""Drift guard: every variant of the ExperimentMetric union must have an entry in
- _METRIC_TYPE_TO_CLASS. If a new metric_type is added to the schema, this fails so
- the mapping (used to filter pydantic errors to the matching variant) stays accurate."""
+ METRIC_BUILDERS. The metric validator accepts only the metric_type values listed there,
+ so a new metric_type added to the schema fails here instead of being rejected on write."""
root_annotation = ExperimentMetric.model_fields["root"].annotation
assert root_annotation is not None, "ExperimentMetric.root has no annotation — schema is malformed"
union_variants = root_annotation.__args__
@@ -1262,9 +1268,10 @@ class TestExperimentService(APIBaseTest):
f"{variant.__name__}.metric_type has no annotation — schema is malformed"
)
schema_pairs[metric_type_annotation.__args__[0]] = variant.__name__
- assert ExperimentService._METRIC_TYPE_TO_CLASS == schema_pairs, (
- "ExperimentMetric union changed — update ExperimentService._METRIC_TYPE_TO_CLASS. "
- f"Expected {schema_pairs}, got {ExperimentService._METRIC_TYPE_TO_CLASS}"
+ builders = {metric_type: builder.__name__ for metric_type, builder in METRIC_BUILDERS.items()}
+ assert builders == schema_pairs, (
+ "ExperimentMetric union changed — update METRIC_BUILDERS in metric_resolution.py. "
+ f"Expected {schema_pairs}, got {builders}"
)
@parameterized.expand(
@@ -1294,7 +1301,7 @@ class TestExperimentService(APIBaseTest):
]
)
def test_is_events_node_actions_node_confusion_predicate(self, _: str, err: dict, expected: bool) -> None:
- assert ExperimentService._is_events_node_actions_node_confusion(err) is expected
+ assert is_events_node_actions_node_confusion(err) is expected
def test_pydantic_extra_forbidden_error_code_is_still_in_use(self) -> None:
"""Canary: the EventsNode.id hint matches on the pydantic error type slug
@@ -1307,7 +1314,7 @@ class TestExperimentService(APIBaseTest):
error_types = {err["type"] for err in e.errors()}
assert "extra_forbidden" in error_types, (
f"pydantic no longer emits 'extra_forbidden' for unknown fields — "
- f"got {error_types}. Update ExperimentService._build_metric_validation_hint."
+ f"got {error_types}. Update _metric_validation_hint in metric_validation.py."
)
else:
raise AssertionError("pydantic did not reject an unknown field on EventsNode")
@@ -6849,12 +6856,9 @@ class TestExperimentService(APIBaseTest):
# bypasses that check, we want to skip the value (don't crash, don't add a
# non-string to the lookup set) and log so we can find the offending caller.
# This is purely about the *incoming* payload shape — no DB lookup happens
- # in `_extract_entity_nodes`.
- from products.experiments.backend.experiment_service import logger as service_logger
-
- service = self._service()
- with patch.object(service_logger, "warning") as mock_warning:
- event_names = service._extract_entity_nodes(
+ # in `extract_entity_nodes`.
+ with patch.object(metric_validation_logger, "warning") as mock_warning:
+ event_names = extract_entity_nodes(
[
{
"kind": "ExperimentMetric",