: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
fix(experiments/mcp): Improve exposure-criteria validation messages (#58393)
Marcel Poelker498a2fbc1e2b
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex c52703ac5a1a..73a83ccf0482 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -165,24 +165,83 @@ class ExperimentService:"'key' to 'control'.")- @staticmethod- def validate_experiment_exposure_criteria(exposure_criteria: dict | None) -> None:- """Validate experiment exposure criteria payloads."""- if not exposure_criteria:+ EXPOSURE_CONFIG_KINDS = ("ExperimentEventExposureConfig", "ActionsNode")++ EXPOSURE_CONFIG_HINT = (+ "Expected either an event-based config like "+ "{'kind': 'ExperimentEventExposureConfig', 'event': '<event_name>', 'properties': []} "+ "or an action-based config like {'kind': 'ActionsNode', 'id': <action_id>}."+ )++ # Cap user-supplied values reflected into validation error messages so a large+ # or sensitive payload cannot bloat responses, logs, or error tracking. repr()+ # already escapes control characters, so the only remaining concern is length.+ _ERROR_VALUE_MAX_LEN = 80++ @classmethod+ def _safe_repr(cls, value: object) -> str:+ rendered = repr(value)+ if len(rendered) > cls._ERROR_VALUE_MAX_LEN:+ return rendered[: cls._ERROR_VALUE_MAX_LEN] + "...(truncated)"+ return rendered++ @classmethod+ def validate_experiment_exposure_criteria(cls, exposure_criteria: object) -> None:+ """Validate experiment exposure criteria payloads.++ Accepts `object` because the input arrives from a DRF `JSONField`, which+ can deserialize to any JSON shape. The validator narrows defensively.+ """+ if exposure_criteria is None:return- if "filterTestAccounts" in exposure_criteria and not isinstance(exposure_criteria["filterTestAccounts"], bool):- raise ValidationError("filterTestAccounts must be a boolean")+ if not isinstance(exposure_criteria, dict):+ raise ValidationError(+ f"exposure_criteria must be an object, got {type(exposure_criteria).__name__}. "+ "Expected shape: {'filterTestAccounts': <bool>, 'exposure_config': <object>}."+ )++ if "filterTestAccounts" in exposure_criteria:+ filter_test_accounts = exposure_criteria["filterTestAccounts"]+ if not isinstance(filter_test_accounts, bool):+ raise ValidationError(+ f"exposure_criteria.filterTestAccounts must be a boolean, got "+ f"{type(filter_test_accounts).__name__}: {cls._safe_repr(filter_test_accounts)}."+ )if "exposure_config" in exposure_criteria:exposure_config = exposure_criteria["exposure_config"]++ if not isinstance(exposure_config, dict):+ raise ValidationError(+ f"exposure_criteria.exposure_config must be an object, got "+ f"{type(exposure_config).__name__}. {cls.EXPOSURE_CONFIG_HINT}"+ )++ # `kind` is optional; missing kind defaults to ExperimentEventExposureConfig+ # to mirror the pydantic Literal default on that model.+ kind = exposure_config.get("kind", "ExperimentEventExposureConfig")+ if kind not in cls.EXPOSURE_CONFIG_KINDS:+ raise ValidationError(+ f"exposure_criteria.exposure_config.kind must be one of "+ f"{list(cls.EXPOSURE_CONFIG_KINDS)}, got {cls._safe_repr(kind)}. "+ f"{cls.EXPOSURE_CONFIG_HINT}"+ )++ model_cls = ActionsNode if kind == "ActionsNode" else ExperimentEventExposureConfigtry:- if exposure_config.get("kind") == "ActionsNode":- ActionsNode.model_validate(exposure_config)- else:- ExperimentEventExposureConfig.model_validate(exposure_config)- except Exception:- raise ValidationError("Invalid exposure criteria")+ model_cls.model_validate(exposure_config)+ except pydantic.ValidationError as e:+ # Surface only the field locations and error types from pydantic — not the+ # echoed `input` and `url` fields, which would reflect arbitrary user data+ # back into the response.+ safe_errors = [+ {"loc": err.get("loc"), "type": err.get("type"), "msg": err.get("msg")} for err in e.errors()+ ]+ raise ValidationError(+ f"Invalid exposure_criteria.exposure_config (kind={cls._safe_repr(kind)}): "+ f"{safe_errors}. {cls.EXPOSURE_CONFIG_HINT}"+ )@classmethoddef validate_experiment_metrics(cls, metrics: list | None) -> None:diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex 791132a33fba..23d9c167c8ac 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -438,6 +438,121 @@ class TestExperimentService(APIBaseTest):assert "Saved metric does not exist or does not belong to this project" in str(ctx.exception)+ @parameterized.expand(+ [+ (+ "not_a_dict",+ "not-a-dict",+ "exposure_criteria must be an object, got str",+ ),+ (+ "falsy_empty_list",+ [],+ "exposure_criteria must be an object, got list",+ ),+ (+ "falsy_empty_string",+ "",+ "exposure_criteria must be an object, got str",+ ),+ (+ "falsy_false",+ False,+ "exposure_criteria must be an object, got bool",+ ),+ (+ "filter_test_accounts_string",+ {"filterTestAccounts": "true"},+ "exposure_criteria.filterTestAccounts must be a boolean, got str: 'true'",+ ),+ (+ "filter_test_accounts_int",+ {"filterTestAccounts": 1},+ "exposure_criteria.filterTestAccounts must be a boolean, got int: 1",+ ),+ (+ "exposure_config_not_a_dict",+ {"exposure_config": "ActionsNode"},+ "exposure_criteria.exposure_config must be an object, got str",+ ),+ (+ "exposure_config_unknown_kind",+ {"exposure_config": {"kind": "EventsNode", "event": "$pageview"}},+ "exposure_criteria.exposure_config.kind must be one of "+ "['ExperimentEventExposureConfig', 'ActionsNode'], got 'EventsNode'",+ ),+ (+ "exposure_config_event_kind_missing_event",+ {"exposure_config": {"kind": "ExperimentEventExposureConfig", "properties": []}},+ "Invalid exposure_criteria.exposure_config (kind='ExperimentEventExposureConfig')",+ ),+ (+ "exposure_config_actions_kind_missing_id",+ {"exposure_config": {"kind": "ActionsNode"}},+ "Invalid exposure_criteria.exposure_config (kind='ActionsNode')",+ ),+ ]+ )+ def test_validate_experiment_exposure_criteria_rejects_invalid_payloads(+ self, _: str, exposure_criteria: object, expected_error_fragment: str+ ) -> None:+ with self.assertRaises(ValidationError) as ctx:+ ExperimentService.validate_experiment_exposure_criteria(exposure_criteria)++ assert expected_error_fragment in str(ctx.exception), (+ f"Expected fragment {expected_error_fragment!r} in error: {ctx.exception}"+ )++ @parameterized.expand(+ [+ ("none", None),+ ("empty_dict", {}),+ (+ "event_payload",+ {+ "filterTestAccounts": True,+ "exposure_config": {+ "kind": "ExperimentEventExposureConfig",+ "event": "$feature_flag_called",+ "properties": [],+ },+ },+ ),+ (+ "action_payload",+ {+ "filterTestAccounts": False,+ "exposure_config": {"kind": "ActionsNode", "id": 1},+ },+ ),+ (+ "event_payload_without_explicit_kind",+ {"exposure_config": {"event": "$pageview", "properties": []}},+ ),+ ]+ )+ def test_validate_experiment_exposure_criteria_accepts_valid_payloads(+ self, _: str, exposure_criteria: object+ ) -> None:+ ExperimentService.validate_experiment_exposure_criteria(exposure_criteria)++ def test_validate_experiment_exposure_criteria_hint_is_actionable(self) -> None:+ """The error hint should name both supported kinds so the LLM can self-correct."""+ with self.assertRaises(ValidationError) as ctx:+ ExperimentService.validate_experiment_exposure_criteria({"exposure_config": {"kind": "FunnelsQuery"}})+ message = str(ctx.exception)+ assert "ExperimentEventExposureConfig" in message+ assert "ActionsNode" in message++ def test_validate_experiment_exposure_criteria_truncates_large_user_values(self) -> None:+ """A large user-supplied value must not bloat the error message reflected back."""+ huge_kind = "x" * 10_000+ with self.assertRaises(ValidationError) as ctx:+ ExperimentService.validate_experiment_exposure_criteria({"exposure_config": {"kind": huge_kind}})+ message = str(ctx.exception)+ assert "...(truncated)" in message+ assert len(message) < 1_000, f"Error message length was {len(message)}, expected to be bounded"+# ------------------------------------------------------------------# Service contract fields# ------------------------------------------------------------------