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): Reject unknown exposure criteria keys at write time (#86938)

Juraj Majerikac0bd833e38c
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index b72bd55e8866..4b582c6f76af 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -25,6 +25,7 @@ from rest_framework.exceptions import APIException, PermissionDenied, Validation
from posthog.schema import (
ActionsNode,
ExperimentEventExposureConfig,
+ ExperimentExposureCriteria,
ExperimentFunnelMetric,
ExperimentMeanMetric,
ExperimentMetric,
@@ -644,6 +645,14 @@ class ExperimentService:
return rendered[: cls._ERROR_VALUE_MAX_LEN] + "...(truncated)"
return rendered
+ @classmethod
+ def strip_unknown_exposure_criteria_keys(cls, exposure_criteria: dict | None) -> dict | None:
+ """Drop unknown top-level keys from stored criteria (writes accepted them before
+ the unknown-key rejection below existed)."""
+ if not isinstance(exposure_criteria, dict):
+ return exposure_criteria
+ return {k: v for k, v in exposure_criteria.items() if k in ExperimentExposureCriteria.model_fields}
+
@classmethod
def validate_experiment_exposure_criteria(cls, exposure_criteria: object) -> None:
"""Validate experiment exposure criteria payloads.
@@ -660,6 +669,21 @@ class ExperimentService:
"Expected shape: {'filterTestAccounts': <bool>, 'exposure_config': <object>}."
)
+ # Reject unknown top-level keys: they used to be silently saved, and the strict
+ # read-side parse then broke every results/exposure query for the experiment
+ # (reads now tolerate them, but new writes should fail fast with a pointer).
+ unknown_keys = set(exposure_criteria) - set(ExperimentExposureCriteria.model_fields)
+ if unknown_keys:
+ hint = (
+ " Property filters on the exposure event belong at exposure_criteria.exposure_config.properties."
+ if "properties" in unknown_keys
+ else ""
+ )
+ raise ValidationError(
+ f"exposure_criteria contains unknown key(s): {', '.join(sorted(unknown_keys))}.{hint} "
+ f"Allowed keys: {', '.join(sorted(ExperimentExposureCriteria.model_fields))}."
+ )
+
if "filterTestAccounts" in exposure_criteria:
filter_test_accounts = exposure_criteria["filterTestAccounts"]
if not isinstance(filter_test_accounts, bool):
@@ -4142,7 +4166,10 @@ class ExperimentService:
"ensure_experience_continuity": bool(source_experiment.feature_flag.ensure_experience_continuity),
}
- self.validate_experiment_exposure_criteria(source_experiment.exposure_criteria)
+ # Stored criteria can carry unknown top-level keys accepted before writes rejected
+ # them — strip those instead of failing the clone on data the user didn't write.
+ cloned_exposure_criteria = self.strip_unknown_exposure_criteria_keys(source_experiment.exposure_criteria)
+ self.validate_experiment_exposure_criteria(cloned_exposure_criteria)
self.validate_experiment_metrics(source_experiment.metrics)
self.validate_experiment_metrics(source_experiment.metrics_secondary)
@@ -4191,7 +4218,7 @@ class ExperimentService:
metrics_secondary=cloned_metrics_secondary,
stats_config=source_experiment.stats_config,
scheduling_config=source_experiment.scheduling_config,
- exposure_criteria=source_experiment.exposure_criteria,
+ exposure_criteria=cloned_exposure_criteria,
saved_metrics_ids=saved_metrics_data,
primary_metrics_ordered_uuids=cloned_primary_ordering,
secondary_metrics_ordered_uuids=cloned_secondary_ordering,
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index 8e022e59d313..04dc24eec7c1 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -809,6 +809,17 @@ class TestExperimentService(APIBaseTest):
},
"exposure_criteria.activation_config requires the default exposure event",
),
+ (
+ "unknown_top_level_properties",
+ {"properties": [{"key": "email", "value": "x"}]},
+ "exposure_criteria contains unknown key(s): properties. Property filters on the "
+ "exposure event belong at exposure_criteria.exposure_config.properties.",
+ ),
+ (
+ "unknown_top_level_key",
+ {"filterTestAccounts": True, "custom_thing": 1},
+ "exposure_criteria contains unknown key(s): custom_thing",
+ ),
]
)
def test_validate_experiment_exposure_criteria_rejects_invalid_payloads(
@@ -855,6 +866,10 @@ class TestExperimentService(APIBaseTest):
"explicit_null_configs",
{"exposure_config": None, "activation_config": None},
),
+ (
+ "multiple_variant_handling",
+ {"multiple_variant_handling": "exclude"},
+ ),
(
"null_activation_with_custom_exposure",
{
@@ -2503,6 +2518,26 @@ class TestExperimentService(APIBaseTest):
# Same flag key → reuses the existing flag
assert dup.feature_flag.id == source.feature_flag.id
+ def test_duplicate_experiment_strips_legacy_unknown_exposure_criteria_keys(self):
+ # Stored criteria can carry unknown keys accepted before write-side rejection;
+ # duplicating such an experiment must succeed and drop them.
+ self._create_flag(key="dup-legacy-criteria")
+ service = self._service()
+ source = service.create_experiment(
+ name="Legacy criteria",
+ feature_flag_key="dup-legacy-criteria",
+ exposure_criteria={"filterTestAccounts": True},
+ )
+ source.exposure_criteria = {"filterTestAccounts": True, "properties": [{"key": "email"}]}
+ source.save(update_fields=["exposure_criteria"])
+
+ dup = service.duplicate_experiment(source)
+
+ criteria = dup.exposure_criteria
+ assert criteria is not None
+ assert criteria.get("filterTestAccounts") is True
+ assert "properties" not in criteria
+
def test_duplicate_experiment_generates_unique_name(self):
self._create_flag(key="dup-unique-1")
service = self._service()
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 8e02969fc76e..dac35575e168 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -4827,9 +4827,11 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
"start_date": "2024-01-01T10:00:00Z",
"stats_config": {"method": "frequentist"},
"exposure_criteria": {
- "kind": "ExperimentEventExposureConfig",
- "event": "$feature_flag_called",
- "properties": [],
+ "exposure_config": {
+ "kind": "ExperimentEventExposureConfig",
+ "event": "$feature_flag_called",
+ "properties": [],
+ },
},
},
)
@@ -4837,9 +4839,9 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):
updated_metrics = response.json()["metrics"]
expected_updated_fingerprints = {
- "mean": "d6a393e5456b71c16961c45e07eb17cb86e4f7972549033f9883c99430248c02",
- "funnel": "9f7888cb2f7f9c3dac2b6482a964eef6911f97e376ed53305ed6653f7f70ce9b",
- "ratio": "1b83a833a62ff9c2f01ba86be1f3e578b97749d3264e08ff9e76d863865e3ff3",
+ "mean": "24bf7ca8d497f33ace065e9e5facd961a4a2cb68938263b4008266fb22055f98",
+ "funnel": "c1325e7c9c494859e14901f144e99532745d6c22a8cb1536ef1cd9574cfa5672",
+ "ratio": "9d74f7f895166c1ac12708a4bc2aa8c61c963bb98a9ad15fecf747b79e706631",
}
for metric in updated_metrics: