: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
chore(experiments): expand facade to support experiment creation. (#56295)
Rodrigo Iloro1cfc247afaff
diff --git a/products/experiments/backend/facade/__init__.py b/products/experiments/backend/facade/__init__.pyindex 2f2d77fd694f..229377bf7b9a 100644--- a/products/experiments/backend/facade/__init__.py+++ b/products/experiments/backend/facade/__init__.py@@ -5,13 +5,11 @@ This module provides the public interface for other products to interact with ex"""from .api import create_experiment-from .contracts import CreateExperimentInput, CreateFeatureFlagInput, Experiment, FeatureFlag, FeatureFlagVariant+from .contracts import CreateExperimentInput, Experiment, FeatureFlag__all__ = ["create_experiment","CreateExperimentInput",- "CreateFeatureFlagInput","Experiment","FeatureFlag",- "FeatureFlagVariant",]diff --git a/products/experiments/backend/facade/api.py b/products/experiments/backend/facade/api.pyindex dbdea92871ce..7a66d1e2eb31 100644--- a/products/experiments/backend/facade/api.py+++ b/products/experiments/backend/facade/api.py@@ -5,6 +5,8 @@ This module provides the public interface for creating and managing experimentsusing framework-free DTOs, wrapping the existing ExperimentService."""+from rest_framework.exceptions import ValidationError+from posthog.models.team import Teamfrom posthog.models.user import User@@ -18,57 +20,35 @@ def create_experiment(*, team: Team, user: User, input_dto: CreateExperimentInpu"""Create a new experiment.- Supports both old format (parameters.feature_flag_variants)- and new format (feature_flag_filters).-Transactional safety is provided by ExperimentService.create_experiment.Args:team: Team creating the experimentuser: User creating the experiment- input_dto: Experiment creation input+ input_dto: Experiment creation input with all configurationReturns:Experiment DTORaises:- ValueError: If both old and new formats are provided+ ValidationError: If validation fails in service layer"""- # Validate that both formats are not provided- has_old_format = input_dto.parameters is not None and "feature_flag_variants" in input_dto.parameters- has_new_format = input_dto.feature_flag_filters is not None-- if has_old_format and has_new_format:- raise ValueError("Cannot provide both 'parameters.feature_flag_variants' and 'feature_flag_filters'")-- # Prepare parameters for service call- # Start with any provided parameters (e.g., minimum_detectable_effect)- parameters_dict = dict(input_dto.parameters) if input_dto.parameters else {}-- if has_new_format:- # Convert CreateFeatureFlagInput to parameters dict format- flag_filters = input_dto.feature_flag_filters- assert flag_filters is not None # Type guard: has_new_format guarantees this-- parameters_dict["feature_flag_variants"] = [- {- "key": variant.key,- "name": variant.name,- "rollout_percentage": variant.split_percent,- }- for variant in flag_filters.variants- ]-- # Add optional fields- if flag_filters.rollout_percentage is not None:- parameters_dict["rollout_percentage"] = flag_filters.rollout_percentage- if flag_filters.aggregation_group_type_index is not None:- parameters_dict["aggregation_group_type_index"] = flag_filters.aggregation_group_type_index- if flag_filters.ensure_experience_continuity is not None:- parameters_dict["ensure_experience_continuity"] = flag_filters.ensure_experience_continuity-- # Pass None if dict is empty to maintain service contract- parameters = parameters_dict or None++ # Load holdout if ID provided+ from products.experiments.backend.models.experiment import ExperimentHoldout++ holdout = None+ if input_dto.holdout_id is not None:+ try:+ holdout = ExperimentHoldout.objects.get(id=input_dto.holdout_id, team_id=team.id)+ except ExperimentHoldout.DoesNotExist:+ raise ValidationError(f"Holdout with id {input_dto.holdout_id} does not exist for this team")++ # Convert tuple to list for ordering fields (DTO uses tuple for immutability)+ primary_metrics_ordered_uuids = list(input_dto.metrics_ordering) if input_dto.metrics_ordering else None+ secondary_metrics_ordered_uuids = (+ list(input_dto.secondary_metrics_ordering) if input_dto.secondary_metrics_ordering else None+ )# Call existing service (already @transaction.atomic)service = ExperimentService(team=team, user=user)@@ -76,7 +56,29 @@ def create_experiment(*, team: Team, user: User, input_dto: CreateExperimentInpuname=input_dto.name,feature_flag_key=input_dto.feature_flag_key,description=input_dto.description,- parameters=parameters,+ type=input_dto.type,+ parameters=input_dto.parameters,+ metrics=input_dto.metrics,+ metrics_secondary=input_dto.metrics_secondary,+ secondary_metrics=input_dto.secondary_metrics,+ stats_config=input_dto.stats_config,+ exposure_criteria=input_dto.exposure_criteria,+ holdout=holdout,+ saved_metrics_ids=input_dto.saved_metrics_ids,+ start_date=input_dto.start_date,+ end_date=input_dto.end_date,+ primary_metrics_ordered_uuids=primary_metrics_ordered_uuids,+ secondary_metrics_ordered_uuids=secondary_metrics_ordered_uuids,+ create_in_folder=input_dto.create_in_folder,+ filters=input_dto.filters,+ scheduling_config=input_dto.scheduling_config,+ only_count_matured_users=input_dto.only_count_matured_users,+ archived=input_dto.archived,+ deleted=input_dto.deleted,+ conclusion=input_dto.conclusion,+ conclusion_comment=input_dto.conclusion_comment,+ serializer_context=input_dto.serializer_context,+ allow_unknown_events=input_dto.allow_unknown_events,)# Convert model to DTOdiff --git a/products/experiments/backend/facade/contracts.py b/products/experiments/backend/facade/contracts.pyindex 45fc5473a1a6..b0c743ee3a25 100644--- a/products/experiments/backend/facade/contracts.py+++ b/products/experiments/backend/facade/contracts.py@@ -10,47 +10,57 @@ from datetime import datetimefrom typing import Any-@dataclass(frozen=True)-class FeatureFlagVariant:- """Feature flag variant configuration."""-- key: str- split_percent: int- name: str | None = None---@dataclass(frozen=True)-class CreateFeatureFlagInput:- """Input for creating a feature flag (new format)."""-- key: str- variants: tuple[FeatureFlagVariant, ...]- name: str | None = None- rollout_percentage: int | None = None- aggregation_group_type_index: int | None = None- ensure_experience_continuity: bool | None = None--@dataclass(frozen=True)class CreateExperimentInput:"""Input for creating an experiment.- Supports both old format (parameters.feature_flag_variants)- and new format (feature_flag_filters).-- Note: This class is NOT hashable when parameters is non-None due to the- dict type. Use only feature_flag_filters (new format) if hashability is- required for Turbo caching. The parameters field exists only for backwards- compatibility during migration.+ Note: This class is NOT hashable when dict/list fields are non-None due to+ mutable types. Use only immutable fields if hashability is required."""+ # Required fieldsname: strfeature_flag_key: str++ # Optional basic fieldsdescription: str = ""- feature_flag_filters: CreateFeatureFlagInput | None = None+ type: str = "product"++ # Feature flag configurationparameters: dict[str, Any] | None = None+ # Metrics configuration+ metrics: list[dict] | None = None+ metrics_secondary: list[dict] | None = None+ secondary_metrics: list[dict] | None = None+ metrics_ordering: tuple[str, ...] | None = None # primary_metrics_ordered_uuids+ secondary_metrics_ordering: tuple[str, ...] | None = None # secondary_metrics_ordered_uuids+ saved_metrics_ids: list[dict] | None = None++ # Statistics and exposure configuration+ stats_config: dict | None = None+ exposure_criteria: dict | None = None+ only_count_matured_users: bool | None = None++ # Experiment lifecycle+ start_date: datetime | None = None+ end_date: datetime | None = None+ archived: bool = False+ deleted: bool = False+ conclusion: str | None = None+ conclusion_comment: str | None = None++ # Advanced configuration+ holdout_id: int | None = None # We'll pass ID, facade will load the model+ filters: dict | None = None+ scheduling_config: dict | None = None+ create_in_folder: str | None = None++ # Internal flags+ allow_unknown_events: bool = False+ serializer_context: dict | None = None+@dataclass(frozen=True)class FeatureFlag:diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 391b94ef867a..733f16f48ab2 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -24,6 +24,7 @@ from posthog.models.team.team import Teamfrom posthog.rbac.user_access_control import UserAccessControlSerializerMixinfrom products.experiments.backend.experiment_service import ExperimentService+from products.experiments.backend.facade.contracts import CreateExperimentInputfrom products.experiments.backend.metric_utils import refresh_action_names_in_metricfrom products.experiments.backend.models.experiment import Experiment, ExperimentHoldout@@ -332,69 +333,99 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSedef validate_metrics_secondary(self, value):return self._validate_metrics_list(value)+ def to_facade_dto(self) -> CreateExperimentInput:+ """Convert validated request data to facade DTO."""+ # Extract holdout ID if provided+ holdout_id = None+ if holdout := self.validated_data.get("holdout"):+ holdout_id = holdout.id if hasattr(holdout, "id") else None++ # Convert ordering lists to tuples (DTO uses tuples for immutability)+ primary_ordering = self.validated_data.get("primary_metrics_ordered_uuids")+ secondary_ordering = self.validated_data.get("secondary_metrics_ordered_uuids")++ return CreateExperimentInput(+ name=self.validated_data["name"],+ feature_flag_key=self.validated_data["get_feature_flag_key"],+ description=self.validated_data.get("description", ""),+ type=self.validated_data.get("type", "product"),+ parameters=self.validated_data.get("parameters"),+ metrics=self.validated_data.get("metrics"),+ metrics_secondary=self.validated_data.get("metrics_secondary"),+ secondary_metrics=self.validated_data.get("secondary_metrics"),+ metrics_ordering=tuple(primary_ordering) if primary_ordering else None,+ secondary_metrics_ordering=tuple(secondary_ordering) if secondary_ordering else None,+ saved_metrics_ids=self.validated_data.get("saved_metrics_ids"),+ stats_config=self.validated_data.get("stats_config"),+ exposure_criteria=self.validated_data.get("exposure_criteria"),+ only_count_matured_users=self.validated_data.get("only_count_matured_users"),+ start_date=self.validated_data.get("start_date"),+ end_date=self.validated_data.get("end_date"),+ archived=self.validated_data.get("archived", False),+ deleted=self.validated_data.get("deleted", False),+ conclusion=self.validated_data.get("conclusion"),+ conclusion_comment=self.validated_data.get("conclusion_comment"),+ holdout_id=holdout_id,+ filters=self.validated_data.get("filters"),+ scheduling_config=self.validated_data.get("scheduling_config"),+ create_in_folder=self.validated_data.get("_create_in_folder"),+ allow_unknown_events=self.validated_data.get("allow_unknown_events", False),+ serializer_context=self.context,+ )+def create(self, validated_data: dict, *args: Any, **kwargs: Any) -> Experiment:- feature_flag_key = validated_data.pop("get_feature_flag_key")- saved_metrics_ids = validated_data.pop("saved_metrics_ids", None)- create_in_folder = validated_data.pop("_create_in_folder", None)- name = validated_data.pop("name")- description = validated_data.pop("description", "")- experiment_type = validated_data.pop("type", "product")- parameters = validated_data.pop("parameters", None)- metrics = validated_data.pop("metrics", None)- metrics_secondary = validated_data.pop("metrics_secondary", None)- secondary_metrics = validated_data.pop("secondary_metrics", None)- stats_config = validated_data.pop("stats_config", None)- exposure_criteria = validated_data.pop("exposure_criteria", None)- holdout = validated_data.pop("holdout", None)- start_date = validated_data.pop("start_date", None)- end_date = validated_data.pop("end_date", None)- primary_metrics_ordered_uuids = validated_data.pop("primary_metrics_ordered_uuids", None)- secondary_metrics_ordered_uuids = validated_data.pop("secondary_metrics_ordered_uuids", None)- filters = validated_data.pop("filters", None)- scheduling_config = validated_data.pop("scheduling_config", None)- only_count_matured_users = validated_data.pop("only_count_matured_users", None)- archived = validated_data.pop("archived", False)- deleted = validated_data.pop("deleted", False)- conclusion = validated_data.pop("conclusion", None)- conclusion_comment = validated_data.pop("conclusion_comment", None)- allow_unknown_events = validated_data.pop("allow_unknown_events", False)+ """Create experiment via facade layer."""+ from products.experiments.backend.facade import create_experiment++ # Pop fields not needed for DTO but needed for validationvalidated_data.pop("update_feature_flag_params", None)- if validated_data:- raise ValidationError(f"Can't create keys: {', '.join(sorted(validated_data))} on Experiment")+ # Check for unexpected fields+ expected_fields = {+ "name",+ "get_feature_flag_key",+ "description",+ "type",+ "parameters",+ "metrics",+ "metrics_secondary",+ "secondary_metrics",+ "primary_metrics_ordered_uuids",+ "secondary_metrics_ordered_uuids",+ "saved_metrics_ids",+ "stats_config",+ "exposure_criteria",+ "only_count_matured_users",+ "start_date",+ "end_date",+ "archived",+ "deleted",+ "conclusion",+ "conclusion_comment",+ "holdout",+ "filters",+ "scheduling_config",+ "_create_in_folder",+ "allow_unknown_events",+ }+ unexpected = set(validated_data.keys()) - expected_fields+ if unexpected:+ raise ValidationError(f"Can't create keys: {', '.join(sorted(unexpected))} on Experiment")- team = Team.objects.get(id=self.context["team_id"])- service = ExperimentService(team=team, user=self.context["request"].user)+ # Convert to facade DTO+ input_dto = self.to_facade_dto()- return service.create_experiment(- name=name,- feature_flag_key=feature_flag_key,- description=description,- type=experiment_type,- parameters=parameters,- metrics=metrics,- metrics_secondary=metrics_secondary,- secondary_metrics=secondary_metrics,- stats_config=stats_config,- exposure_criteria=exposure_criteria,- holdout=holdout,- saved_metrics_ids=saved_metrics_ids,- start_date=start_date,- end_date=end_date,- primary_metrics_ordered_uuids=primary_metrics_ordered_uuids,- secondary_metrics_ordered_uuids=secondary_metrics_ordered_uuids,- create_in_folder=create_in_folder,- filters=filters,- scheduling_config=scheduling_config,- only_count_matured_users=only_count_matured_users,- archived=archived,- deleted=deleted,- conclusion=conclusion,- conclusion_comment=conclusion_comment,- serializer_context=self.context,- allow_unknown_events=allow_unknown_events,+ # Route through facade+ team = Team.objects.get(id=self.context["team_id"])+ experiment_dto = create_experiment(+ team=team,+ user=self.context["request"].user,+ input_dto=input_dto,)+ # Load instance for return (DRF expects model instance)+ return Experiment.objects.get(id=experiment_dto.id)+def update(self, instance: Experiment, validated_data: dict, *args: Any, **kwargs: Any) -> Experiment:allow_unknown_events = validated_data.pop("allow_unknown_events", False)team = Team.objects.get(id=self.context["team_id"])diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.pyindex 0dc52a0ccd6f..ce95faaf0b42 100644--- a/products/experiments/backend/presentation/views.py+++ b/products/experiments/backend/presentation/views.py@@ -38,7 +38,6 @@ from posthog.temporal.common.client import sync_connectfrom posthog.temporal.experiments.models import ExperimentTimeseriesRecalculationWorkflowInputsfrom posthog.user_permissions import UserPermissions-# TODO: Route through facade instead of direct importfrom products.experiments.backend.experiment_service import ExperimentService# TODO: Route through facade instead of direct importdiff --git a/products/experiments/backend/test/test_api.py b/products/experiments/backend/test/test_api.pyindex 0816236498ea..fd6ec746e3d3 100644--- a/products/experiments/backend/test/test_api.py+++ b/products/experiments/backend/test/test_api.py@@ -3,6 +3,9 @@ Tests for experiment facade API.These tests verify that the facade correctly wraps the existingExperimentService and converts between Django models and DTOs.++NOTE: Tests for feature_flag_filters format were removed in PR #4+to keep the facade simple. Only the parameters format is tested here."""import pytest@@ -12,54 +15,13 @@ from unittest.mock import patchfrom posthog.models.feature_flag.feature_flag import FeatureFlag as FeatureFlagModelfrom products.experiments.backend.facade.api import create_experiment-from products.experiments.backend.facade.contracts import (- CreateExperimentInput,- CreateFeatureFlagInput,- Experiment,- FeatureFlagVariant,-)+from products.experiments.backend.facade.contracts import CreateExperimentInput, Experimentfrom products.experiments.backend.models.experiment import Experiment as ExperimentModelclass TestCreateExperiment(BaseTest):- def test_create_experiment_with_new_format(self):- """Test creating experiment using new feature_flag_filters format."""- input_dto = CreateExperimentInput(- name="Test Experiment",- feature_flag_key="test-flag",- description="Test description",- feature_flag_filters=CreateFeatureFlagInput(- key="test-flag",- name="Test Flag",- variants=(- FeatureFlagVariant(key="control", name="Control", split_percent=50),- FeatureFlagVariant(key="test", name="Test", split_percent=50),- ),- ),- )-- result = create_experiment(team=self.team, user=self.user, input_dto=input_dto)-- # Verify output DTO structure- assert isinstance(result, Experiment)- assert result.name == "Test Experiment"- assert result.feature_flag_key == "test-flag"- assert result.is_draft is True-- # Verify database objects were created- experiment = ExperimentModel.objects.get(id=result.id)- assert experiment.name == "Test Experiment"- assert experiment.feature_flag.key == "test-flag"-- # Verify feature flag created- flag = FeatureFlagModel.objects.get(id=result.feature_flag_id)- # Note: Currently the service generates its own flag name- # Full feature_flag_filters support (including name) will come in a later phase- assert flag.name == "Feature Flag for Experiment Test Experiment"- assert len(flag.filters["multivariate"]["variants"]) == 2-- def test_create_experiment_with_old_format(self):- """Test creating experiment using old parameters format."""+ def test_create_experiment_with_parameters_format(self):+ """Test creating experiment using parameters format."""input_dto = CreateExperimentInput(name="Test Experiment",feature_flag_key="test-flag",@@ -117,21 +79,6 @@ class TestCreateExperiment(BaseTest):assert result.feature_flag_id == existing_flag.idassert result.feature_flag_key == "existing-flag"- def test_create_experiment_rejects_both_formats(self):- """Test that providing both old and new formats raises error."""- input_dto = CreateExperimentInput(- name="Both Formats",- feature_flag_key="both-flag",- parameters={"feature_flag_variants": [{"key": "control", "rollout_percentage": 100}]},- feature_flag_filters=CreateFeatureFlagInput(- key="both-flag",- variants=(FeatureFlagVariant(key="control", split_percent=100),),- ),- )-- with pytest.raises(ValueError, match="Cannot provide both"):- create_experiment(team=self.team, user=self.user, input_dto=input_dto)-def test_create_experiment_is_transactional(self):"""Test that experiment creation is transactional."""# Patch Experiment.objects.create to fail after flag creation@@ -141,10 +88,7 @@ class TestCreateExperiment(BaseTest):input_dto = CreateExperimentInput(name="Transactional Test",feature_flag_key="transaction-flag",- feature_flag_filters=CreateFeatureFlagInput(- key="transaction-flag",- variants=(FeatureFlagVariant(key="control", split_percent=100),),- ),+ parameters={"feature_flag_variants": [{"key": "control", "rollout_percentage": 100}]},)with pytest.raises(Exception, match="Experiment creation failed"):diff --git a/products/experiments/backend/test/test_contracts.py b/products/experiments/backend/test/test_contracts.pyindex b6266feeb9f5..ef028a9c770d 100644--- a/products/experiments/backend/test/test_contracts.py+++ b/products/experiments/backend/test/test_contracts.py@@ -3,6 +3,10 @@ Tests for experiment contracts (DTOs).These tests verify that our frozen dataclasses are immutable,hashable, and have the correct structure.++NOTE: Tests for FeatureFlagVariant and CreateFeatureFlagInput were removed+in PR #4 to keep the facade simple. The facade only supports the old+parameters format for now."""from datetime import UTC, datetime@@ -10,13 +14,7 @@ from datetime import UTC, datetimeimport pytestfrom freezegun import freeze_time-from products.experiments.backend.facade.contracts import (- CreateExperimentInput,- CreateFeatureFlagInput,- Experiment,- FeatureFlag,- FeatureFlagVariant,-)+from products.experiments.backend.facade.contracts import CreateExperimentInput, Experiment, FeatureFlagclass TestContractImmutability:@@ -25,21 +23,6 @@ class TestContractImmutability:@pytest.mark.parametrize(("instance", "field_name", "new_value"),[- pytest.param(- FeatureFlagVariant(key="test", split_percent=50),- "key",- "modified",- id="FeatureFlagVariant",- ),- pytest.param(- CreateFeatureFlagInput(- key="test",- variants=(FeatureFlagVariant(key="control", split_percent=100),),- ),- "key",- "modified",- id="CreateFeatureFlagInput",- ),pytest.param(CreateExperimentInput(name="Test", feature_flag_key="test-flag"),"name",@@ -92,37 +75,6 @@ class TestContractImmutability:class TestContractHashability:"""Test that contracts are hashable (required for Turbo caching)."""- @pytest.mark.parametrize(- "instance",- [- pytest.param(- FeatureFlagVariant(key="test", split_percent=50),- id="FeatureFlagVariant",- ),- pytest.param(- CreateFeatureFlagInput(- key="test",- variants=(FeatureFlagVariant(key="control", split_percent=100),),- ),- id="CreateFeatureFlagInput",- ),- pytest.param(- CreateExperimentInput(- name="Test",- feature_flag_key="test-flag",- feature_flag_filters=CreateFeatureFlagInput(- key="test-flag",- variants=(FeatureFlagVariant(key="control", split_percent=100),),- ),- ),- id="CreateExperimentInput_with_feature_flag_filters",- ),- ],- )- def test_input_contracts_are_hashable(self, instance):- """Test that input contracts can be hashed (raises TypeError if not hashable)."""- hash(instance)-@freeze_time("2026-03-21T12:00:00Z")@pytest.mark.parametrize("instance",@@ -156,8 +108,8 @@ class TestContractHashability:def test_experiment_input_with_parameters_is_not_hashable(self):"""Test that CreateExperimentInput with parameters dict is not hashable.- The parameters field exists only for backwards compatibility during migration.- New code should use feature_flag_filters which is hashable.+ The parameters field contains mutable types (dict/list) so the DTO+ is not hashable when those fields are set."""input_dto = CreateExperimentInput(name="Test",@@ -169,55 +121,6 @@ class TestContractHashability:hash(input_dto)-class TestFeatureFlagVariant:- def test_create_variant(self):- """Test creating a feature flag variant."""- variant = FeatureFlagVariant(- key="control",- name="Control",- split_percent=50,- )-- assert variant.key == "control"- assert variant.name == "Control"- assert variant.split_percent == 50---class TestCreateFeatureFlagInput:- def test_create_flag_input_minimal(self):- """Test creating flag input with minimal fields."""- input_dto = CreateFeatureFlagInput(- key="my-flag",- variants=(- FeatureFlagVariant(key="control", split_percent=50),- FeatureFlagVariant(key="test", split_percent=50),- ),- )-- assert input_dto.key == "my-flag"- assert len(input_dto.variants) == 2- assert input_dto.name is None-- def test_create_flag_input_full(self):- """Test creating flag input with all fields."""- input_dto = CreateFeatureFlagInput(- key="my-flag",- name="My Flag",- variants=(- FeatureFlagVariant(key="control", split_percent=50),- FeatureFlagVariant(key="test", split_percent=50),- ),- rollout_percentage=100,- aggregation_group_type_index=0,- ensure_experience_continuity=True,- )-- assert input_dto.name == "My Flag"- assert input_dto.rollout_percentage == 100- assert input_dto.aggregation_group_type_index == 0- assert input_dto.ensure_experience_continuity is True--class TestCreateExperimentInput:def test_create_experiment_input_minimal(self):"""Test creating experiment input with minimal fields."""@@ -229,32 +132,10 @@ class TestCreateExperimentInput:assert input_dto.name == "My Experiment"assert input_dto.feature_flag_key == "my-flag"assert input_dto.description == ""- assert input_dto.feature_flag_filters is Noneassert input_dto.parameters is None- def test_create_experiment_input_with_new_flag_format(self):- """Test creating experiment with new feature flag filters format."""- flag_input = CreateFeatureFlagInput(- key="my-flag",- name="My Flag",- variants=(- FeatureFlagVariant(key="control", split_percent=50),- FeatureFlagVariant(key="test", split_percent=50),- ),- )-- input_dto = CreateExperimentInput(- name="My Experiment",- feature_flag_key="my-flag",- feature_flag_filters=flag_input,- )-- assert input_dto.feature_flag_filters is not None- assert input_dto.feature_flag_filters.key == "my-flag"- assert len(input_dto.feature_flag_filters.variants) == 2-- def test_create_experiment_input_with_old_parameters_format(self):- """Test creating experiment with old parameters format."""+ def test_create_experiment_input_with_parameters_format(self):+ """Test creating experiment with parameters format."""input_dto = CreateExperimentInput(name="My Experiment",feature_flag_key="my-flag",diff --git a/products/experiments/backend/test/test_facade.py b/products/experiments/backend/test/test_facade.pynew file mode 100644index 000000000000..db774de11d19--- /dev/null+++ b/products/experiments/backend/test/test_facade.py@@ -0,0 +1,136 @@+"""Tests for experiments facade layer."""++from datetime import UTC, datetime++from freezegun import freeze_time+from posthog.test.base import APIBaseTest++from products.experiments.backend.facade import create_experiment+from products.experiments.backend.facade.contracts import CreateExperimentInput+++class TestCreateExperiment(APIBaseTest):+ """Tests for create_experiment facade function."""++ def test_create_experiment_minimal_fields(self):+ """Test creating experiment with only required fields."""+ input_dto = CreateExperimentInput(+ name="Test Experiment",+ feature_flag_key="test-flag",+ )++ result = create_experiment(team=self.team, user=self.user, input_dto=input_dto)++ # Verify DTO fields+ assert result.name == "Test Experiment"+ assert result.feature_flag_key == "test-flag"+ assert result.is_draft is True+ assert result.description is None or result.description == ""++ # Verify model was created+ from products.experiments.backend.models.experiment import Experiment++ experiment = Experiment.objects.get(id=result.id)+ assert experiment.name == "Test Experiment"+ assert experiment.feature_flag.key == "test-flag"++ def test_create_experiment_with_description(self):+ """Test creating experiment with description."""+ input_dto = CreateExperimentInput(+ name="Test Experiment",+ feature_flag_key="test-flag-2",+ description="Testing the facade layer",+ )++ result = create_experiment(team=self.team, user=self.user, input_dto=input_dto)++ assert result.description == "Testing the facade layer"++ def test_create_experiment_with_parameters_old_format(self):+ """Test creating experiment with old format (parameters.feature_flag_variants)."""+ input_dto = CreateExperimentInput(+ name="Test Experiment",+ feature_flag_key="test-flag-3",+ parameters={+ "feature_flag_variants": [+ {"key": "control", "name": "Control", "rollout_percentage": 50},+ {"key": "test", "name": "Test", "rollout_percentage": 50},+ ]+ },+ )++ result = create_experiment(team=self.team, user=self.user, input_dto=input_dto)++ assert result.name == "Test Experiment"++ # Verify feature flag has correct variants+ from posthog.models.feature_flag import FeatureFlag++ flag = FeatureFlag.objects.get(id=result.feature_flag_id)+ assert len(flag.variants) == 2++ @freeze_time("2025-01-01 12:00:00")+ def test_create_experiment_with_start_date(self):+ """Test creating launched (non-draft) experiment."""+ start_date = datetime(2025, 1, 1, 12, 0, 0, tzinfo=UTC)+ input_dto = CreateExperimentInput(+ name="Test Experiment",+ feature_flag_key="test-flag-6",+ start_date=start_date,+ )++ result = create_experiment(team=self.team, user=self.user, input_dto=input_dto)++ assert result.is_draft is False+ assert result.start_date == start_date++ def test_create_experiment_with_metrics(self):+ """Test creating experiment with metrics."""+ input_dto = CreateExperimentInput(+ name="Test Experiment",+ feature_flag_key="test-flag-7",+ metrics=[+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "$pageview"},+ }+ ],+ allow_unknown_events=True,+ )++ result = create_experiment(team=self.team, user=self.user, input_dto=input_dto)++ # Verify experiment was created with metrics+ from products.experiments.backend.models.experiment import Experiment++ experiment = Experiment.objects.get(id=result.id)+ assert experiment.metrics is not None+ assert len(experiment.metrics) == 1++ def test_create_experiment_with_all_fields(self):+ """Test creating experiment with comprehensive field set."""+ input_dto = CreateExperimentInput(+ name="Comprehensive Test",+ feature_flag_key="test-flag-8",+ description="Full feature test",+ type="web",+ parameters={"minimum_detectable_effect": 5},+ metrics=[+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "$pageview"},+ }+ ],+ stats_config={"method": "bayesian"},+ exposure_criteria={"filter_test_accounts": True},+ archived=False,+ deleted=False,+ allow_unknown_events=True,+ )++ result = create_experiment(team=self.team, user=self.user, input_dto=input_dto)++ assert result.name == "Comprehensive Test"+ assert result.description == "Full feature test"