Skip to content
Open
32 changes: 32 additions & 0 deletions api/experimentation/feature_state_metadata.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,46 @@
from typing import TYPE_CHECKING, Any, Callable

from flagsmith_schemas.api import FeatureStateMetadata
from rest_framework.exceptions import ValidationError

from experimentation.models import Experiment, ExperimentStatus
from features.constants import LIVE_EXPERIMENT_MV_OPTIONS_MESSAGE

if TYPE_CHECKING: # pragma: no cover
from environments.models import Environment
from features.models import FeatureState


def get_live_experiment(
feature_id: int, environment_id: int | None = None
) -> Experiment | None:
# Multivariate options belong to the feature, not an environment, so an
# experiment in any environment locks them. A paused experiment counts:
# changing the variants before it resumes would skew its results.
experiments = Experiment.objects.filter(
feature_id=feature_id,
status__in=(ExperimentStatus.RUNNING, ExperimentStatus.PAUSED),
)
if environment_id is not None:
experiments = experiments.filter(environment_id=environment_id)
return experiments.select_related("environment").first() # type: ignore[no-any-return]


def live_experiment_error(experiment: Experiment) -> ValidationError:
return ValidationError(
{
"detail": LIVE_EXPERIMENT_MV_OPTIONS_MESSAGE.format(
environment=experiment.environment.name
)
}
)


def check_no_live_experiment(feature_id: int) -> None:
if experiment := get_live_experiment(feature_id):
raise live_experiment_error(experiment)


def get_feature_state_metadata_builder(
environment: "Environment",
) -> Callable[["FeatureState"], dict[str, Any] | None]:
Expand Down
5 changes: 4 additions & 1 deletion api/experimentation/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
from features.feature_states.models import API_VALUE_TYPES
from features.future.services import delete_segment_override, update_flag
from features.future.types import EnvironmentDefaultRequest, SegmentOverrideRequest
from features.models import FeatureState
from features.models import Feature, FeatureState
from features.value_types import BOOLEAN, STRING
from features.versioning.versioning_service import get_environment_flags_list
from integrations.flagsmith.client import get_openfeature_client
Expand Down Expand Up @@ -621,6 +621,9 @@ def transition_experiment_status(

experiment.status = target_status
if target_status == ExperimentStatus.RUNNING and not experiment.started_at:
Feature.objects.select_for_update().filter(
pk=experiment.feature_id
).exists()
Comment thread
Zaimwa9 marked this conversation as resolved.
Resolved
experiment.started_at = timezone.now()
_remove_superseded_experiment_rollouts(
experiment, AuthorData.from_user(user)
Expand Down
4 changes: 4 additions & 0 deletions api/features/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
# Multivariate variant reported when an identity falls through to the control value
CONTROL_VARIANT_KEY = "control"
RESERVED_VARIANT_KEY_MESSAGE = f'"{CONTROL_VARIANT_KEY}" is a reserved variant key.'
LIVE_EXPERIMENT_MV_OPTIONS_MESSAGE = (
Comment thread
Zaimwa9 marked this conversation as resolved.
Resolved
'Variations cannot be changed while an experiment is running or paused in the "{environment}" '
"environment. Complete the experiment to change them."
)

# Tag filtering strategy
UNION = "UNION"
Expand Down
29 changes: 28 additions & 1 deletion api/features/import_export/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
register_task_handler,
)

from environments.models import Environment
from experimentation.feature_state_metadata import get_live_experiment
from features.import_export.constants import (
FAILED,
PROCESSING,
Expand Down Expand Up @@ -153,7 +155,12 @@ def _import_features_for_environment(feature_import: FeatureImport) -> None:
project=project,
).first()

if existing_feature and feature_import.strategy == SKIP:
if existing_feature and (
feature_import.strategy == SKIP
or _should_skip_for_live_experiment(
Comment thread
Zaimwa9 marked this conversation as resolved.
Resolved
feature_data, existing_feature, environment
)
):
continue

if existing_feature is None:
Expand All @@ -166,6 +173,26 @@ def _import_features_for_environment(feature_import: FeatureImport) -> None:
feature_import.save()


def _should_skip_for_live_experiment(
feature_data: FeatureExportData,
existing_feature: Feature,
environment: Environment,
) -> bool:
if get_live_experiment(existing_feature.id, environment.id):
return True
if not feature_data["multivariate"]:
return False
existing_variations = {
(option.type, option.value)
for option in existing_feature.multivariate_options.all()
}
adds_variation = any(
(mv_data["type"], mv_data["value"]) not in existing_variations
for mv_data in feature_data["multivariate"]
)
return bool(adds_variation and get_live_experiment(existing_feature.id))
Comment thread
Zaimwa9 marked this conversation as resolved.
Resolved


# Should only run on official flagsmith instance.
if (
settings.FLAGSMITH_ON_FLAGSMITH_FEATURE_EXPORT_ENVIRONMENT_ID
Expand Down
62 changes: 61 additions & 1 deletion api/features/multivariate/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,33 @@
CREATE_FEATURE,
VIEW_PROJECT,
)
from django.db import transaction
from django.utils.decorators import method_decorator
from drf_spectacular.utils import extend_schema
from rest_framework import viewsets
from rest_framework.decorators import api_view
from rest_framework.exceptions import ValidationError
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response

from experimentation.feature_state_metadata import check_no_live_experiment
from features.models import Feature
from projects.permissions import NestedProjectPermissions

from .models import MultivariateFeatureOption
from .serializers import MultivariateFeatureOptionSerializer

# What makes a variation. `default_percentage_allocation` is left out: the
# dashboard always sends it as 0, and it only seeds new environments.
VARIATION_FIELDS = (
"type",
"string_value",
"integer_value",
"boolean_value",
"key",
"feature",
)


@method_decorator(
name="list",
Expand Down Expand Up @@ -69,9 +83,55 @@ def get_permissions(self): # type: ignore[no-untyped-def]
def create(self, request, *args, **kwargs): # type: ignore[no-untyped-def]
feature_pk = self.kwargs.get("feature_pk")
project_pk = self.kwargs.get("project_pk")
get_object_or_404(Feature.objects.filter(project__id=project_pk), pk=feature_pk)
url_feature = get_object_or_404(
Feature.objects.filter(project__id=project_pk), pk=feature_pk
)
if "feature" in request.data and str(request.data.get("feature")) != str(
url_feature.id
):
raise ValidationError({"feature": "Feature must match the URL."})
return super().create(request, *args, **kwargs)

def perform_create(self, serializer): # type: ignore[no-untyped-def]
url_feature = get_object_or_404(
Feature.objects.filter(project__id=self.kwargs["project_pk"]),
pk=self.kwargs["feature_pk"],
)
with transaction.atomic():
Feature.objects.select_for_update().filter(pk=url_feature.pk).exists()
check_no_live_experiment(url_feature.id)
super().perform_create(serializer)

def perform_update(self, serializer): # type: ignore[no-untyped-def]
instance = serializer.instance
data = serializer.validated_data
# The dashboard PUTs every option on each save, changed or not, so only
# a change to the variation itself is checked against experiments.
if not any(
field in data and data[field] != getattr(instance, field)
for field in VARIATION_FIELDS
):
super().perform_update(serializer)
return

features = {instance.feature, data.get("feature", instance.feature)}
with transaction.atomic():
list(
Feature.objects.select_for_update()
.filter(pk__in=[feature.pk for feature in features])
.order_by("pk")
.values_list("pk", flat=True)
)
for feature in features:
check_no_live_experiment(feature.id)
super().perform_update(serializer)

def perform_destroy(self, instance): # type: ignore[no-untyped-def]
with transaction.atomic():
Feature.objects.select_for_update().filter(pk=instance.feature_id).exists()
check_no_live_experiment(instance.feature_id)
super().perform_destroy(instance)

def get_queryset(self): # type: ignore[no-untyped-def]
if getattr(self, "swagger_fake_view", False):
return MultivariateFeatureOption.objects.none()
Expand Down
43 changes: 42 additions & 1 deletion api/features/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
FeatureStateValueSerializer,
)
from common.projects.permissions import VIEW_PROJECT
from django.db import models
from django.db import models, transaction
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
Expand All @@ -28,6 +28,8 @@
from evaluation.types import EvaluatedFeatureState
from experimentation.feature_state_metadata import (
get_feature_state_metadata_builder,
get_live_experiment,
live_experiment_error,
)
from integrations.vcs.services import dispatch_vcs_on_feature_state_changed
from metadata.serializers import MetadataSerializer, MetadataSerializerMixin
Expand Down Expand Up @@ -305,6 +307,19 @@ def validate_project_features_limit(self, project: Project) -> None:
}
)

def update(self, instance: Feature, validated_data: dict[str, Any]) -> Feature:
with transaction.atomic():
Feature.objects.select_for_update().filter(pk=instance.pk).exists()
if "multivariate_options" in validated_data and (
experiment := get_live_experiment(instance.id)
):
if self._changes_multivariate_options(
validated_data["multivariate_options"], instance
):
raise live_experiment_error(experiment)
validated_data.pop("multivariate_options")
return super().update(instance, validated_data) # type: ignore[no-any-return]

def validate_multivariate_options(self, multivariate_options): # type: ignore[no-untyped-def]
if multivariate_options:
user = self.context["request"].user
Expand All @@ -324,6 +339,32 @@ def validate_multivariate_options(self, multivariate_options): # type: ignore[n
raise serializers.ValidationError("Invalid percentage allocation")
return multivariate_options

def _changes_multivariate_options(
self,
multivariate_options: list[dict[str, Any]] | None,
instance: Feature,
) -> bool:
# The frontend resubmits the whole feature, so only a real change to
# variation value/type counts. `default_percentage_allocation` only
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
# seeds new options or environments and does not affect live variants.
fields = (
"type",
"integer_value",
"string_value",
"boolean_value",
)
current = NestedMultivariateFeatureOptionSerializer(
instance.multivariate_options.all(), many=True
).data

def signature(options) -> list[tuple[Any, ...]]: # type: ignore[no-untyped-def]
return sorted(
(tuple(option.get(field) for field in fields) for option in options),
key=repr,
)

return signature(current) != signature(multivariate_options or [])

def validate_owners(self, owners: list[FFAdminUser]) -> list[FFAdminUser]:
project: Project = self.context["project"]
invalid_users = [
Expand Down
Loading
Loading