: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): Strip unknown exposure criteria keys from stored experiments (#88225)
Juraj Majerikef0f5202d0cc
diff --git a/products/experiments/backend/migrations/0035_strip_unknown_exposure_criteria_keys.py b/products/experiments/backend/migrations/0035_strip_unknown_exposure_criteria_keys.pynew file mode 100644index 000000000000..e434289a8cd1--- /dev/null+++ b/products/experiments/backend/migrations/0035_strip_unknown_exposure_criteria_keys.py@@ -0,0 +1,49 @@+from django.db import migrations++BATCH_SIZE = 1000++# Writes used to accept unknown top-level exposure_criteria keys (e.g. `properties`, which+# belongs at exposure_config.properties). The query API parses stored criteria with a strict+# schema, so affected experiments fail every results/exposure query. Strip unknown keys from+# existing rows; the write path now rejects them, so bad data cannot reaccumulate.+# Frozen copy of posthog.schema.ExperimentExposureCriteria fields — migrations don't import app code.+ALLOWED_KEYS = (+ "activation_config",+ "exposure_config",+ "filterTestAccounts",+ "multiple_variant_handling",+)+++def strip_unknown_exposure_criteria_keys(apps, schema_editor):+ Experiment = apps.get_model("experiments", "Experiment")++ # Unknown keys can't be expressed as a has_key filter, so walk every row with criteria+ # set — experiments are rare objects, this is a small table.+ experiment_ids = list(+ Experiment.objects.exclude(exposure_criteria=None).values_list("id", flat=True).order_by("id")+ )++ for start in range(0, len(experiment_ids), BATCH_SIZE):+ batch_ids = experiment_ids[start : start + BATCH_SIZE]+ to_update = []+ for experiment in Experiment.objects.filter(id__in=batch_ids).only("id", "exposure_criteria"):+ criteria = experiment.exposure_criteria+ if not criteria or not isinstance(criteria, dict):+ continue+ stripped = {k: v for k, v in criteria.items() if k in ALLOWED_KEYS}+ if stripped != criteria:+ experiment.exposure_criteria = stripped+ to_update.append(experiment)+ if to_update:+ Experiment.objects.bulk_update(to_update, ["exposure_criteria"], batch_size=BATCH_SIZE)+++class Migration(migrations.Migration):+ dependencies = [+ ("experiments", "0034_backfill_precomputation_enabled_set_by"),+ ]++ operations = [+ migrations.RunPython(strip_unknown_exposure_criteria_keys, migrations.RunPython.noop),+ ]diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txtindex 8b2ebf8729a4..b8bf9e743df0 100644--- a/products/experiments/backend/migrations/max_migration.txt+++ b/products/experiments/backend/migrations/max_migration.txt@@ -1 +1 @@-0034_backfill_precomputation_enabled_set_by+0035_strip_unknown_exposure_criteria_keysdiff --git a/products/experiments/backend/test/test_migration_0035.py b/products/experiments/backend/test/test_migration_0035.pynew file mode 100644index 000000000000..c848a7520e0d--- /dev/null+++ b/products/experiments/backend/test/test_migration_0035.py@@ -0,0 +1,62 @@+from typing import Any++from posthog.test.base import TestMigrations+++class StripUnknownExposureCriteriaKeysMigrationTest(TestMigrations):+ migrate_from = "0034_backfill_precomputation_enabled_set_by"+ migrate_to = "0035_strip_unknown_exposure_criteria_keys"++ CLASS_DATA_LEVEL_SETUP = False++ @property+ def app(self) -> str:+ return "experiments"++ def setUpBeforeMigration(self, apps: Any) -> None:+ Organization = apps.get_model("posthog", "Organization")+ Project = apps.get_model("posthog", "Project")+ Team = apps.get_model("posthog", "Team")+ FeatureFlag = apps.get_model("feature_flags", "FeatureFlag")+ Experiment = apps.get_model("experiments", "Experiment")++ org = Organization.objects.create(name="Test Organization")+ project = Project.objects.create(id=999996, organization=org, name="Test Project")+ team = Team.objects.create(organization=org, project=project, name="Test Team")++ def make_experiment(name: str, exposure_criteria: dict | None) -> Any:+ flag = FeatureFlag.objects.create(team=team, created_by=None, key=f"flag-{name}")+ return Experiment.objects.create(+ team=team, name=name, feature_flag=flag, exposure_criteria=exposure_criteria+ )++ self.stray_properties_id = make_experiment(+ "stray-properties",+ {"filterTestAccounts": True, "properties": [{"key": "email", "value": "x"}]},+ ).id+ self.config_at_criteria_level_id = make_experiment(+ "config-at-criteria-level",+ {"kind": "ExperimentEventExposureConfig", "event": "$pageview", "properties": []},+ ).id+ self.valid_id = make_experiment(+ "valid",+ {+ "filterTestAccounts": False,+ "exposure_config": {"event": "$pageview", "properties": []},+ "multiple_variant_handling": "exclude",+ },+ ).id+ self.null_id = make_experiment("null-criteria", None).id++ def test_strips_only_unknown_keys(self) -> None:+ assert self.apps is not None+ Experiment = self.apps.get_model("experiments", "Experiment")++ assert Experiment.objects.get(id=self.stray_properties_id).exposure_criteria == {"filterTestAccounts": True}+ assert Experiment.objects.get(id=self.config_at_criteria_level_id).exposure_criteria == {}+ assert Experiment.objects.get(id=self.valid_id).exposure_criteria == {+ "filterTestAccounts": False,+ "exposure_config": {"event": "$pageview", "properties": []},+ "multiple_variant_handling": "exclude",+ }+ assert Experiment.objects.get(id=self.null_id).exposure_criteria is None