: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
feat(flags): add version-aware rollout endpoints (#100151)
James Gill1053da34b60f
diff --git a/posthog/api/mixins.py b/posthog/api/mixins.pyindex 58a755d1e80d..cb8bf9915039 100644--- a/posthog/api/mixins.py+++ b/posthog/api/mixins.py@@ -23,6 +23,10 @@ T = TypeVar("T", bound=BaseModel)_SCHEMA_HINT = "Please update the provided API schema to ensure API docs remain up to date"+# What drf-spectacular accepts for one status code, and what this decorator validates against.+# A bare serializer class or instance is as valid as an OpenApiResponse wrapping one.+ResponseDeclaration = OpenApiResponse | type[serializers.BaseSerializer[Any]] | serializers.BaseSerializer[Any] | None+class ValidatedRequest(Request):"""@@ -108,7 +112,7 @@ class _ResponseValidator:"""Checks what a view returned against the responses the decorator declares."""view_name: str- responses: dict[int, OpenApiResponse | None] | None+ responses: dict[int, ResponseDeclaration] | Nonestrict: booldef check(self, view: Any, result: Any) -> None:@@ -143,7 +147,13 @@ class _ResponseValidator:returnresponse_config = self.responses[status_code]- response_serializer = response_config.response if response_config else None+ # `responses` is passed straight to drf-spectacular, which accepts a bare serializer as+ # well as an OpenApiResponse wrapping one. Reading `.response` unconditionally raised+ # AttributeError on the bare form, so an endpoint that declared one 500ed here under+ # DEBUG while passing every test, because this block does not run with DEBUG off.+ response_serializer = (+ response_config.response if isinstance(response_config, OpenApiResponse) else response_config+ )if response_serializer is None:self._check_declared_empty(status_code, result.data)else:@@ -221,7 +231,7 @@ def validated_request(request_serializer: type[serializers.Serializer] | None = None,*,query_serializer: type[serializers.Serializer] | None = None,- responses: dict[int, OpenApiResponse | None] | None = None,+ responses: dict[int, ResponseDeclaration] | None = None,summary: str | None = None,description: str | None = None,tags: list[str] | None = None,diff --git a/posthog/api/test/test_mixins.py b/posthog/api/test/test_mixins.pyindex a3c0f72018ca..3c232eb49470 100644--- a/posthog/api/test/test_mixins.py+++ b/posthog/api/test/test_mixins.py@@ -179,11 +179,36 @@ class TestValidatedRequestDecorator(SimpleTestCase):assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERRORassert response.data["type"] == "server_error"+ # drf-spectacular accepts a bare serializer where an OpenApiResponse would go, and+ # `responses` is passed straight to it. Reading `.response` unconditionally turned the bare+ # form into an AttributeError under DEBUG, so an endpoint declaring one passed every test+ # and 500ed on a dev stack. Both forms have to reach the same validation.@parameterized.expand([- ("class", EventCaptureResponseSerializer, {"wrong_field": "value"}, "EventCaptureResponseSerializer"),- ("instance", EventCaptureResponseSerializer(), {"wrong_field": "value"}, "EventCaptureResponseSerializer"),- ("many", EventCaptureResponseSerializer(many=True), [{"wrong_field": "value"}], "ListSerializer"),+ (+ "class",+ OpenApiResponse(response=EventCaptureResponseSerializer),+ {"wrong_field": "value"},+ "EventCaptureResponseSerializer",+ ),+ (+ "instance",+ OpenApiResponse(response=EventCaptureResponseSerializer()),+ {"wrong_field": "value"},+ "EventCaptureResponseSerializer",+ ),+ (+ "many",+ OpenApiResponse(response=EventCaptureResponseSerializer(many=True)),+ [{"wrong_field": "value"}],+ "ListSerializer",+ ),+ (+ "bare_serializer",+ EventCaptureResponseSerializer,+ {"wrong_field": "value"},+ "EventCaptureResponseSerializer",+ ),])def test_invalid_response_data_logs_warning(self, _name, declared_response, response_data, serializer_class_name):@@ -191,9 +216,7 @@ class TestValidatedRequestDecorator(SimpleTestCase):@validated_request(request_serializer=EventCaptureRequestSerializer,- responses={- 200: OpenApiResponse(response=declared_response),- },+ responses={200: declared_response},)def mock_endpoint(view_self, request):# Missing required fields in responsediff --git a/posthog/tasks/update_survey_adaptive_sampling.py b/posthog/tasks/update_survey_adaptive_sampling.pyindex 6ffae0498489..4edb8b98616d 100644--- a/posthog/tasks/update_survey_adaptive_sampling.py+++ b/posthog/tasks/update_survey_adaptive_sampling.py@@ -7,7 +7,7 @@ from posthog.hogql import astfrom posthog.hogql.query import execute_hogql_queryfrom products.feature_flags.backend.facade.api import update_flag-from products.feature_flags.backend.facade.filters import set_first_release_condition_rollout+from products.feature_flags.backend.facade.filters import set_release_condition_rolloutfrom products.surveys.backend.models import Survey@@ -36,8 +36,8 @@ def _update_survey_adaptive_sampling(survey: Survey) -> None:update_flag(internal_response_sampling_flag,{- "filters": set_first_release_condition_rollout(- internal_response_sampling_flag.get_filters(), today_entry["rollout_percentage"]+ "filters": set_release_condition_rollout(+ internal_response_sampling_flag.get_filters(), 0, today_entry["rollout_percentage"])},team=survey.team,diff --git a/products/approvals/backend/actions/feature_flags.py b/products/approvals/backend/actions/feature_flags.pyindex 5a2330e259a7..c88ab5021dfe 100644--- a/products/approvals/backend/actions/feature_flags.py+++ b/products/approvals/backend/actions/feature_flags.py@@ -532,6 +532,11 @@ class UpdateFeatureFlagAction(BaseAction):triggered_paths = cls._get_triggered_paths(old_filters, new_filters)+ # A caller exempt from the serializer's opportunistic filter cleanup stays exempt when+ # the approved change replays, the way the lifecycle base records it. Without this an+ # approved rollout writes the filters back without `super_groups` and `holdout_groups`.+ skip_cleanup = bool(getattr(request, "skip_opportunistic_filter_cleanup", False))+return {"flag_id": flag.id if flag is not None else None,"flag_key": flag.key if flag is not None else change.get("key"),@@ -547,6 +552,7 @@ class UpdateFeatureFlagAction(BaseAction):"version": flag.version if flag is not None else None,"updated_at": (flag.updated_at.isoformat() if flag.updated_at else None) if flag is not None else None,},+ "skip_opportunistic_filter_cleanup": skip_cleanup,}@classmethoddiff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 9ee3f450804f..4dbdec2dc22a 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -6,7 +6,7 @@ import jsonimport mathimport loggingimport functools-from collections.abc import Iterable, Iterator, Mapping, Sequence+from collections.abc import Callable, Iterable, Iterator, Mapping, Sequencefrom dataclasses import asdictfrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Any, Literal, NoReturn, Optional, cast@@ -21,7 +21,13 @@ import requestsimport structlogfrom cryptography.fernet import InvalidTokenfrom drf_spectacular.types import OpenApiTypes-from drf_spectacular.utils import OpenApiExample, OpenApiParameter, OpenApiResponse, extend_schema_field+from drf_spectacular.utils import (+ OpenApiExample,+ OpenApiParameter,+ OpenApiResponse,+ PolymorphicProxySerializer,+ extend_schema_field,+)from prometheus_client import Counterfrom rest_framework import exceptions, request, serializers, status, viewsetsfrom rest_framework.exceptions import ErrorDetail@@ -33,7 +39,7 @@ from posthog.schema import ProductKeyfrom posthog.api.cohort import CohortSerializerfrom posthog.api.documentation import FeatureFlagFiltersSchemaSerializer, extend_schemafrom posthog.api.forbid_destroy_model import ForbidDestroyModel-from posthog.api.mixins import validated_request+from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.services.flags_service import RETRYABLE_FLAGS_SERVICE_EXCEPTIONS, get_flags_from_service@@ -101,8 +107,10 @@ from products.feature_flags.backend.api.filters_schema import (I32_MIN,I64_MAX,I64_MIN,+ LEGACY_UNKNOWN_FILTER_KEYS,PRESERVE_UNKNOWN_KEYS_CONTEXT_KEY,FeatureFlagFiltersSerializer,+ FinitePercentageField,)from products.feature_flags.backend.api.remote_config_shadow import shadow_compare_remote_configfrom products.feature_flags.backend.dependency_formats import (@@ -117,6 +125,7 @@ from products.feature_flags.backend.encrypted_flag_payloads import (get_decrypted_flag_payloads_protected,restore_redacted_flag_payloads,)+from products.feature_flags.backend.facade import filters as flag_filtersfrom products.feature_flags.backend.facade.config import ConfigFormatError, detect_config_formatfrom products.feature_flags.backend.filters_validation import collect_cross_field_violations, flatten_structural_errorsfrom products.feature_flags.backend.flag_analytics import increment_request_count@@ -244,6 +253,31 @@ def _count_filters_write_success(serializer: serializers.Serializer, operation:_count_filters_write(operation, outcome, request)+def _mirror_stored_fields(source: FeatureFlag, target: FeatureFlag) -> None:+ """Bring a stale copy of a flag up to date with the row that was just written."""+ for field in source._meta.concrete_fields:+ setattr(target, field.attname, getattr(source, field.attname))+++def _carry_loaded_state(source: FeatureFlag, target: FeatureFlag) -> None:+ """Move what a pre-lock read already loaded onto the row read under the row lock.++ The locked row is a bare `get()`, so it carries none of the prefetches, annotations and+ select_related caches `safely_get_queryset` attaches, and none of the per-save context a+ caller attached to the instance it handed the serializer. Both objects are the same flag,+ so writing and returning the locked one without them only makes the activity-log receiver+ and the response serializer re-query what the request has already read.++ Stored field values are left alone. They are the reason the locked row is read at all.+ """+ target._state.fields_cache.update(source._state.fields_cache)+ stored_fields = {field.attname for field in source._meta.concrete_fields}+ for attr, value in source.__dict__.items():+ if attr in stored_fields or attr == "_state":+ continue+ target.__dict__.setdefault(attr, value)++BEHAVIOURAL_COHORT_FOUND_ERROR_CODE = "behavioral_cohort_found"EARLY_EXIT_FLAG = "feature-flag-early-exit"@@ -474,6 +508,15 @@ REQUIRE_TAGS_ON_CREATE_ERROR = "Add at least one tag. This project requires newREQUIRE_TAGS_ON_UPDATE_ERROR = "Keep at least one tag. This project requires feature flags to stay tagged."+def flag_version_conflict_message(sent_version: int, current_version: int) -> str:+ """Shared by the rollout actions and by the serializer's own precondition, so a caller that+ loses the race before the row lock and one that loses it after read the same sentence."""+ return (+ f"This feature flag has changed since version {sent_version}; it is now at version {current_version}. "+ "Nothing was written. Read the flag again and decide the change against its current definition."+ )++def find_dependent_flags(flag_to_check: FeatureFlag) -> list[FeatureFlag]:"""Find all active flags that depend on the given flag via flag-type filter properties."""return list(@@ -1715,11 +1758,21 @@ class FeatureFlagSerializer(PRESERVE_UNKNOWN_KEYS_CONTEXT_KEY: not fully_enforced,},)+ # A caller that declares the cleanup exemption sends the stored filters back with one+ # field changed, so the legacy keys below arrive from storage rather than from the+ # client. Dropping them would rewrite targeting the caller never touched, which is the+ # thing the exemption exists to prevent, so carry them across the structural pass.+ legacy_carryover = (+ {key: merged[key] for key in LEGACY_UNKNOWN_FILTER_KEYS if key in merged}+ if getattr(self.context.get("request"), "skip_opportunistic_filter_cleanup", False)+ else {}+ )+structurally_valid = structural.is_valid()if structurally_valid:# Also normalizes the stored side (operator aliases, payload encoding, groups# default) and drops unknown keys, logging non-legacy ones.- merged = structural.validated_data+ merged = {**structural.validated_data, **legacy_carryover}else:details = [ErrorDetail(f"{violation.path}: {violation.message}", code=violation.rule_id)@@ -2293,80 +2346,6 @@ class FeatureFlagSerializer(self._update_filters(validated_data)- # Resolve `has_encrypted_payloads` against the instance so a partial PATCH- # that omits the boolean still routes through the right path.- effective_has_encrypted = validated_data.get("has_encrypted_payloads", instance.has_encrypted_payloads)-- if effective_has_encrypted:- # Ensure downstream helpers (e.g. encrypt_flag_payloads) see the- # flag even when the client didn't echo it back in this PATCH.- validated_data["has_encrypted_payloads"] = True- filters = validated_data.get("filters")- new_true_payload = ((filters or {}).get("payloads") or {}).get("true")- approved_payloads = self.context.get("approval_encrypted_payloads")-- if approved_payloads:- # The approved change request holds its payload as ciphertext, separate from the- # change being replayed, which carries only the sentinel. Restore the stored- # ciphertext for the keys the approval does not carry, then swap the approved- # ciphertext in over the keys it does.- if filters is not None:- stored_payloads = (instance.filters or {}).get("payloads") or {}- filters["payloads"] = restore_redacted_flag_payloads(filters.get("payloads") or {}, stored_payloads)- apply_approved_encrypted_payloads(validated_data, approved_payloads)- elif not new_true_payload or new_true_payload == REDACTED_PAYLOAD_VALUE:- # Preserve the existing encrypted payload when the request didn't- # supply a fresh one — either because `filters.payloads` was- # omitted (partial PATCH from the V2 form), the redacted- # placeholder was echoed back, or an empty string slipped past- # `validate_filters` (defense in depth: the public API rejects- # `""` as invalid JSON upstream, but direct serializer callers- # could still land here). Only re-inject when `filters` is- # being sent, so a filters-less PATCH stays a partial update.- if filters is not None:- stored_payloads = (instance.filters or {}).get("payloads") or {}- if not stored_payloads.get("true"):- raise exceptions.ValidationError(- "An encrypted payload is required when has_encrypted_payloads is true."- )- payloads = restore_redacted_flag_payloads(filters.get("payloads") or {}, stored_payloads)- payloads["true"] = stored_payloads["true"]- filters["payloads"] = payloads- else:- encrypt_flag_payloads(validated_data)-- elif instance.has_encrypted_payloads:- # Downgrading from encrypted to non-encrypted. Strip leftover- # ciphertext so a partial PATCH that only flipped the bit doesn't- # leave the prior encrypted blob exposed as a normal payload on- # subsequent reads (redaction is gated on has_encrypted_payloads).- filters = validated_data.get("filters")- if filters is None:- # Client didn't send filters; inject a copy of instance.filters- # with the encrypted "true" payload removed.- new_filters = copy.deepcopy(instance.filters or {})- payloads = new_filters.get("payloads") or {}- payloads.pop("true", None)- new_filters["payloads"] = payloads- validated_data["filters"] = new_filters- else:- # Client sent filters. Drop every empty/missing/redacted echo; a fresh- # non-empty plaintext is left alone (the user explicitly set a new payload- # during the downgrade). Keeping a redacted key would write the placeholder- # over ciphertext that is unreadable once the flag is unencrypted.- payloads = filters.get("payloads") or {}- filters["payloads"] = {k: v for k, v in payloads.items() if v and v != REDACTED_PAYLOAD_VALUE}-- # Opportunistically strip legacy keys on save, including on a write that sent no filters.- # A caller that declares the exemption is spared: it would otherwise persist a rewritten- # filters object for a change that never mentioned targeting.- if not getattr(request, "skip_opportunistic_filter_cleanup", False):- previous_filters = validated_data.get("filters") or instance.filters- if previous_filters and ("holdout_groups" in previous_filters or "super_groups" in previous_filters):- validated_data["filters"] = {- k: v for k, v in previous_filters.items() if k not in ("holdout_groups", "super_groups")- }-version = request_data.get("version", -1)try:@@ -2377,8 +2356,17 @@ class FeatureFlagSerializer(locked_instance = FeatureFlag.objects_including_soft_deleted.select_for_update().get(pk=instance.pk)locked_version = locked_instance.version or 0+ self._apply_stored_filter_rules(validated_data, locked_instance, request)+# NOW check for conflicts after all transformationsif version != -1 and version != locked_version:+ if getattr(request, "strict_version_precondition", False):+ # The default check below needs the caller's `original_flag` and only+ # refuses a write whose own fields collide. A caller that sends a version+ # and no prior state gets the strict reading: any change since that version+ # refuses the write. The rollout actions rely on it, because a+ # release-condition index only names the condition the caller read.+ raise Conflict(flag_version_conflict_message(version, locked_version))# Not a serializer field, so the client controls its type; the conflict helpers# index into it by field name and would raise on a list or string.original_flag = request_data.get("original_flag")@@ -2397,16 +2385,30 @@ class FeatureFlagSerializer(# Continue with the updatevalidated_data["version"] = locked_version + 1- old_key = instance.key+ # Every read and the save below use the locked row, not the instance loaded+ # before the lock. `save()` writes every field, so applying this request to the+ # stale copy would restore whatever another writer changed in the meantime for+ # a field this request never sent. A bulk delete leaves `version` untouched, so+ # the version check above cannot catch it and the flag came back undeleted.+ old_key = locked_instance.key# Clear any soft-deleted tombstone on `new_key` so the (team, key)# unique constraint doesn't block the rename. Mirrors create().new_key = validated_data.get("key")- if new_key and new_key != old_key and validated_data.get("deleted", instance.deleted) is False:- self._free_key_held_by_soft_deleted_flags(new_key, exclude_pk=instance.pk)+ if new_key and new_key != old_key and validated_data.get("deleted", locked_instance.deleted) is False:+ self._free_key_held_by_soft_deleted_flags(new_key, exclude_pk=locked_instance.pk)++ _carry_loaded_state(instance, locked_instance)with ImpersonatedContext(request):- instance = super().update(instance, validated_data)+ saved_instance = super().update(locked_instance, validated_data)++ # The write landed on the locked row, which is a different object from the one+ # the caller handed us. A caller that keeps its own reference and re-serializes+ # it — the early access feature stage transitions do — would otherwise render+ # the values this write just replaced.+ _mirror_stored_fields(saved_instance, instance)+ instance = saved_instanceexcept IntegrityError as e:self._reraise_duplicate_key_violation(e)@@ -2529,6 +2531,88 @@ class FeatureFlagSerializer().order_by("key"))+ def _apply_stored_filter_rules(self, validated_data: dict, instance: FeatureFlag, request: Any) -> None:+ """Resolve the parts of this write that are decided by what the flag already stores.++ Both rules below can seed ``validated_data["filters"]`` from the stored value on a+ request that sent none, and the save writes that value back in full. Reading a copy+ loaded before the row lock would therefore restore whatever another writer changed in+ between, on a request that never mentioned targeting.+ """+ # Resolve `has_encrypted_payloads` against the instance so a partial PATCH+ # that omits the boolean still routes through the right path.+ effective_has_encrypted = validated_data.get("has_encrypted_payloads", instance.has_encrypted_payloads)++ if effective_has_encrypted:+ # Ensure downstream helpers (e.g. encrypt_flag_payloads) see the+ # flag even when the client didn't echo it back in this PATCH.+ validated_data["has_encrypted_payloads"] = True+ filters = validated_data.get("filters")+ new_true_payload = ((filters or {}).get("payloads") or {}).get("true")+ approved_payloads = self.context.get("approval_encrypted_payloads")++ if approved_payloads:+ # The approved change request holds its payload as ciphertext, separate from the+ # change being replayed, which carries only the sentinel. Restore the stored+ # ciphertext for the keys the approval does not carry, then swap the approved+ # ciphertext in over the keys it does.+ if filters is not None:+ stored_payloads = (instance.filters or {}).get("payloads") or {}+ filters["payloads"] = restore_redacted_flag_payloads(filters.get("payloads") or {}, stored_payloads)+ apply_approved_encrypted_payloads(validated_data, approved_payloads)+ elif not new_true_payload or new_true_payload == REDACTED_PAYLOAD_VALUE:+ # Preserve the existing encrypted payload when the request didn't+ # supply a fresh one — either because `filters.payloads` was+ # omitted (partial PATCH from the V2 form), the redacted+ # placeholder was echoed back, or an empty string slipped past+ # `validate_filters` (defense in depth: the public API rejects+ # `""` as invalid JSON upstream, but direct serializer callers+ # could still land here). Only re-inject when `filters` is+ # being sent, so a filters-less PATCH stays a partial update.+ if filters is not None:+ stored_payloads = (instance.filters or {}).get("payloads") or {}+ if not stored_payloads.get("true"):+ raise exceptions.ValidationError(+ "An encrypted payload is required when has_encrypted_payloads is true."+ )+ payloads = restore_redacted_flag_payloads(filters.get("payloads") or {}, stored_payloads)+ payloads["true"] = stored_payloads["true"]+ filters["payloads"] = payloads+ else:+ encrypt_flag_payloads(validated_data)++ elif instance.has_encrypted_payloads:+ # Downgrading from encrypted to non-encrypted. Strip leftover+ # ciphertext so a partial PATCH that only flipped the bit doesn't+ # leave the prior encrypted blob exposed as a normal payload on+ # subsequent reads (redaction is gated on has_encrypted_payloads).+ filters = validated_data.get("filters")+ if filters is None:+ # Client didn't send filters; inject a copy of instance.filters+ # with the encrypted "true" payload removed.+ new_filters = copy.deepcopy(instance.filters or {})+ payloads = new_filters.get("payloads") or {}+ payloads.pop("true", None)+ new_filters["payloads"] = payloads+ validated_data["filters"] = new_filters+ else:+ # Client sent filters. Drop every empty/missing/redacted echo; a fresh+ # non-empty plaintext is left alone (the user explicitly set a new payload+ # during the downgrade). Keeping a redacted key would write the placeholder+ # over ciphertext that is unreadable once the flag is unencrypted.+ payloads = filters.get("payloads") or {}+ filters["payloads"] = {k: v for k, v in payloads.items() if v and v != REDACTED_PAYLOAD_VALUE}++ # Opportunistically strip legacy keys on save, including on a write that sent no filters.+ # A caller that declares the exemption is spared: it would otherwise persist a rewritten+ # filters object for a change that never mentioned targeting.+ if not getattr(request, "skip_opportunistic_filter_cleanup", False):+ previous_filters = validated_data.get("filters") or instance.filters+ if previous_filters and LEGACY_UNKNOWN_FILTER_KEYS & previous_filters.keys():+ validated_data["filters"] = {+ k: v for k, v in previous_filters.items() if k not in LEGACY_UNKNOWN_FILTER_KEYS+ }+def _update_filters(self, validated_data):if "get_filters" in validated_data:validated_data["filters"] = validated_data.pop("get_filters")@@ -3232,28 +3316,175 @@ class BulkDeleteResponseSerializer(serializers.Serializer):)-def flag_lifecycle_responses(bad_request: str | None = None, *, approval_gated: bool = True) -> dict[int, Any]:+def flag_lifecycle_responses(+ bad_request: str | None = None, *, approval_gated: bool = True, version_precondition: bool = False+) -> dict[int, Any]:"""Response schemas for a flag lifecycle action.- ``bad_request`` is the 400 that action can actually produce. Documenting the union of all- of them would tell an agent to expect failures its action cannot raise.+ ``bad_request`` is the 400 that action can actually produce, on top of the soft-deleted+ refusal every one of them makes. Documenting the union of all of them would tell an agent+ to expect failures its action cannot raise.``approval_gated`` says the same thing about the 409. The gate on``FeatureFlagSerializer.update`` only carries the enable, disable and update actions, andevery one of them declines a change that sets neither ``active`` nor ``filters``. Anaction whose write is ``archived`` alone therefore never opens a change request.++ ``version_precondition`` adds the other reason an action returns 409. OpenAPI carries one+ description per status code, so an action that can produce both has to describe both here."""responses: dict[int, Any] = {200: FeatureFlagSerializer}+ conflicts = []+ if version_precondition:+ conflicts.append(+ "The flag changed after the version you sent. Nothing was written. Read the flag again and "+ "decide the change against its current definition."+ )if approval_gated:- responses[409] = OpenApiResponse(- response=ErrorResponseSerializer,- description="An approval policy gates this change. A change request was opened; the flag is unchanged.",+ conflicts.append(+ "An approval policy gates this change. A change request was opened, or an open one was returned "+ "if the same action was already pending; the flag is unchanged.")+ if conflicts:+ # The two 409 reasons render different bodies, so the schema names both rather than+ # picking one and describing the other in prose.+ conflict_response: Any = FlagActionErrorSerializer+ if version_precondition and approval_gated:+ conflict_response = PolymorphicProxySerializer(+ component_name="FeatureFlagActionConflict",+ serializers=[FlagActionErrorSerializer, FlagApprovalConflictSerializer],+ resource_type_field_name=None,+ )+ elif approval_gated:+ conflict_response = FlagApprovalConflictSerializer+ responses[409] = OpenApiResponse(response=conflict_response, description=" ".join(conflicts))+ # Every action built on this refuses a soft-deleted flag, and that refusal is built as a+ # plain response rather than raised, so it renders a different body from the exception+ # envelope the other 400s use. The schema names both rather than picking one.+ reasons = ["The flag is deleted."]+ bad_request_bodies: list[Any] = [FlagActionErrorSerializer, FlagDeletedRejectionSerializer]+ if approval_gated:+ # A change matching several policies cannot be gated by one change request, so the gate+ # refuses it with a third body.+ reasons.append("The change matches more than one approval policy.")+ bad_request_bodies.append(FlagPolicyConflictSerializer)if bad_request is not None:- responses[400] = OpenApiResponse(response=ErrorResponseSerializer, description=bad_request)+ reasons.append(bad_request)+ responses[400] = OpenApiResponse(+ response=PolymorphicProxySerializer(+ component_name="FeatureFlagActionBadRequest",+ serializers=bad_request_bodies,+ resource_type_field_name=None,+ ),+ description=" ".join(reasons),+ )return responses+class FlagActionErrorSerializer(serializers.Serializer):+ """The body every DRF exception on these actions renders as.++ `ErrorResponseSerializer` declares a single `error` key, which no response on this viewset+ produces: the project exception handler renders this envelope instead. Declaring the wrong+ shape reaches the generated clients and the MCP tools, where an agent reads a key that is+ never there.+ """++ type = serializers.CharField(help_text="Error class, for example `validation_error`.")+ code = serializers.CharField(help_text="Machine-readable reason, for example `invalid_input`.")+ detail = serializers.CharField(help_text="Human-readable description of what was refused.")+ attr = serializers.CharField(+ allow_null=True, help_text="Request field the error belongs to, or null when it belongs to no single field."+ )+++class FlagDeletedRejectionSerializer(serializers.Serializer):+ """The 400 body a soft-deleted flag produces, which differs from every other error here.++ Built as a plain response rather than raised, so it carries neither the `type` nor the+ `attr` the exception handler's envelope has.+ """++ success = serializers.BooleanField(help_text="Always `false`.")+ error = serializers.CharField(+ help_text="Human-readable reason, naming the restore the caller has to do before retrying."+ )+++class FlagPolicyConflictSerializer(serializers.Serializer):+ """The 400 body a change matching several approval policies produces.++ Raised through the approvals mixin rather than the exception handler, so it carries the+ policies that matched instead of the `type`/`attr` envelope.+ """++ code = serializers.CharField(help_text="Always `policy_conflict`.")+ error = serializers.CharField(help_text="Human-readable reason the change could not be gated.")+ conflicting_policies = serializers.JSONField(help_text="The approval policies that matched this change.")+ guidance = serializers.CharField(help_text="How to split the change so each policy applies on its own.")+++class FlagApprovalConflictSerializer(serializers.Serializer):+ """The 409 body an approval policy produces, which differs from every other error here.++ Raised through the approvals mixin rather than the exception handler, so it carries the+ change request it opened instead of the `type`/`attr` envelope.+ """++ code = serializers.CharField(+ help_text="`approval_required` when this call opened the change request, "+ "`change_request_pending` when one was already open for the same action."+ )+ status = serializers.CharField(help_text="Always `approval_required`.")+ detail = serializers.CharField(help_text="Human-readable description of the policy that gated the change.")+ message = serializers.CharField(help_text="Same text as `detail`.")+ resource_type = serializers.CharField(help_text="Resource the change request targets, `feature_flag` here.")+ resource_id = serializers.CharField(help_text="Id of the flag the change request targets.")+ change_request_id = serializers.CharField(help_text="Id of the change request that was opened.")+ change_request = serializers.JSONField(help_text="The change request that was opened, serialized in full.")+ required_approvers = serializers.JSONField(help_text="Who can approve the change request.")+++FLAG_VERSION_PRECONDITION_HELP = (+ "The `version` from your most recent read of this flag. The change is refused with 409 if anyone else "+ "changed the flag after that version. A flag written before versioning reads as `null`; send that back "+ "unchanged and it is read as 0, so the value a read returns is always one this accepts."+)+++class FeatureFlagSetReleaseConditionRolloutRequestSerializer(serializers.Serializer):+ condition_index = serializers.IntegerField(+ min_value=0,+ help_text=(+ "Zero-based position of the release condition in `filters.groups`, counted from the read that "+ "produced `version`."+ ),+ )+ rollout_percentage = FinitePercentageField(+ min_value=0,+ max_value=100,+ help_text=(+ "Percentage of the users matching that condition who are served the flag, 0 through 100. On a "+ "multivariate flag this is how many matching users get a variant at all, not how the variants "+ "are split between them. Fractional percentages such as 0.5 are accepted, the same as a write "+ "that sends `filters`."+ ),+ )+ version = serializers.IntegerField(min_value=0, allow_null=True, help_text=FLAG_VERSION_PRECONDITION_HELP)+++class FeatureFlagRollOutToEveryoneRequestSerializer(serializers.Serializer):+ version = serializers.IntegerField(min_value=0, allow_null=True, help_text=FLAG_VERSION_PRECONDITION_HELP)+ variant_key = serializers.CharField(+ required=False,+ allow_null=True,+ help_text=(+ "The variant every user gets. Required for a multivariate flag and rejected for any other flag, "+ "because a release condition decides who the flag serves and not which variant they get."+ ),+ )++def apply_encrypted_payload_response_form(request: Any, feature_flag_data: dict) -> None:"""Replace stored ciphertext in a serialized flag with the form the response may carry.@@ -3318,6 +3549,22 @@ class FlagLifecycleWriteRequest(ServiceRequest):return getattr(self._request, name)+class FlagRolloutWriteRequest(FlagLifecycleWriteRequest):+ """The request a flag rollout action hands to the flag facade.++ ``strict_version_precondition`` makes ``FeatureFlagSerializer`` refuse the write when the+ caller's version is not the current one, under the row lock it already takes. ``version`` is+ the only thing in the body, because the serializer reads it from there and the action has+ already validated it through its own typed request serializer.+ """++ strict_version_precondition = True++ def __init__(self, request: request.Request, *, version: int) -> None:+ super().__init__(request)+ self.data = {"version": version}++# ClickHouse cost attribution: this viewset currently has no direct ClickHouse calls —# all ClickHouse work is delegated to helpers (user_blast_radius.py, flag_analytics.py)# that already tag their queries. If you add a new ClickHouse query reachable from an@@ -3992,6 +4239,215 @@ class FeatureFlagViewSet()return self._lifecycle_response(updated)+ # Rollout actions. Unlike the state actions above, these carry a value, so they close the+ # lost-update window rather than only shrinking it: FeatureFlagSerializer compares the+ # caller's `version` under the row lock it already takes, so no edit can land between the+ # check and the save. A transform that leaves `filters` unchanged writes nothing.++ def _rollout_precondition(self, feature_flag: FeatureFlag, version: int) -> None:+ # Repeated by the serializer under its row lock, which is the check that closes the+ # window. This one runs first so a stale caller never reaches the approval gate, which+ # sits ahead of the lock and would leave a change request for a write it then refuses.+ current_version = feature_flag.version or 0+ if version != current_version:+ raise Conflict(flag_version_conflict_message(version, current_version))++ def _rollout_action(+ self, request: ValidatedRequest, *, deleted_hint: str, transform: Callable[[dict], dict]+ ) -> Response:+ """Apply one rollout transform to the flag this request names.++ Both actions run this sequence, so their concurrency guarantees cannot drift apart. A+ change made to one copy of it would leave the other endpoint weaker while both still+ passed their own tests.+ """+ feature_flag: FeatureFlag = self.get_object()+ rejection = self._deleted_flag_rejection(feature_flag, deleted_hint)+ if rejection is not None:+ return rejection++ # A flag written before versioning reads as null; the precondition normalises the stored+ # side the same way, so a caller can send back exactly what the read returned.+ version = request.validated_data["version"] or 0+ self._rollout_precondition(feature_flag, version)++ with transaction.atomic():+ # The checks above ran against the instance loaded before the lock, which is a fast+ # path only. The decision below has to be made against this row: a write that lands+ # between the two reads leaves the earlier copy stale, and a transform computed from+ # it can compare equal to filters that no longer exist, which would answer 200 for a+ # change that was never applied.+ locked_flag = FeatureFlag.objects_including_soft_deleted.select_for_update().get(pk=feature_flag.pk)+ # Both answers below serialize this row, and a bare `get()` carries none of the+ # prefetches, annotations and select_related caches the request already loaded.+ _carry_loaded_state(feature_flag, locked_flag)+ # A bulk delete leaves `version` untouched, so the precondition cannot see one that+ # landed since the read. Without this check the write rewrites a deleted flag's+ # filters, and the change takes effect the moment anyone restores it.+ rejection = self._deleted_flag_rejection(locked_flag, deleted_hint)+ if rejection is not None:+ return rejection+ self._rollout_precondition(locked_flag, version)++ current_filters = locked_flag.get_filters()+ new_filters = transform(current_filters)+ unchanged = new_filters == current_filters++ # Both answers leave the transaction first. The response serializer runs about a dozen+ # queries, so answering inside it would hold the row lock while they ran and make every+ # other writer of this flag wait. The write needs to be outside for a second reason: the+ # approval gate creates a change request and then raises, and a transaction held across+ # it would roll that record back. The write takes the row lock again and repeats the+ # version check, so a change landing in between is refused there rather than applied over.+ if unchanged:+ return self._lifecycle_response(locked_flag)+ return self._lifecycle_response(self._rollout_write(request, locked_flag, new_filters, version))++ def _rollout_write(+ self, request: request.Request, feature_flag: FeatureFlag, filters: dict, version: int+ ) -> FeatureFlag:+ from products.feature_flags.backend.facade.api import update_flag++ return update_flag(+ feature_flag,+ {"filters": filters},+ team=self.team,+ user=request.user,+ request=FlagRolloutWriteRequest(request, version=version),+ )++ @validated_request(+ FeatureFlagSetReleaseConditionRolloutRequestSerializer,+ responses=flag_lifecycle_responses(+ "It has no release condition at that index.",+ version_precondition=True,+ ),+ )+ @action(methods=["POST"], detail=True, required_scopes=["feature_flag:write"])+ def set_release_condition_rollout(self, request: ValidatedRequest, **kwargs) -> Response:+ """+ Set what percentage of one release condition's audience a feature flag is served to.++ Changes `rollout_percentage` on the release condition at `condition_index` and nothing+ else. The condition's property filters, every other condition, the variants, payloads,+ holdout and every remaining field are left as they are.++ Send the `version` your last read returned. A change to the flag after that version is+ refused with 409, because a condition index only names the condition you read. Read the+ flag again and decide the percentage against its current definition.++ On a multivariate flag this sets how many of the matching users get a variant at all. It+ does not change how the variants are split between them.+ """+ data = request.validated_data++ def transform(current_filters: dict) -> dict:+ try:+ return flag_filters.set_release_condition_rollout(+ current_filters, data["condition_index"], data["rollout_percentage"]+ )+ except IndexError:+ condition_count = len(current_filters.get("groups") or [])+ if condition_count:+ message = (+ f"This feature flag has no release condition at index {data['condition_index']}. It has "+ f"{condition_count}, so the valid indexes are 0 through {condition_count - 1}."+ )+ else:+ message = "This feature flag has no release conditions, so there is none to set a percentage on."+ raise exceptions.ValidationError(message)++ return self._rollout_action(request, deleted_hint="changing its rollout", transform=transform)++ @validated_request(+ FeatureFlagRollOutToEveryoneRequestSerializer,+ responses=flag_lifecycle_responses(+ "The flag is gated on early access enrollment, a multivariate flag was sent no variant, "+ "or the variant is not one this flag defines.",+ version_precondition=True,+ ),+ )+ @action(methods=["POST"], detail=True, required_scopes=["feature_flag:write"])+ def roll_out_to_everyone(self, request: ValidatedRequest, **kwargs) -> Response:+ """+ Serve a feature flag to every user.++ Adds a release condition with no property filters at 100% and keeps the existing+ conditions below it. Payloads, holdout and every other field are left as they are. On a+ boolean flag, removing the new condition restores the previous targeting. On a+ multivariate flag the variant distribution is rewritten as well, so removing the+ condition restores the audience but not the old split. A flag that already leads with+ such a condition gains no second one.++ This changes targeting only. A disabled flag still serves nobody, and a holdout is+ evaluated before release conditions, so users in one keep getting the holdout variant+ instead of the rollout. A flag gated on early access enrollment is refused, because that+ gate is evaluated before release conditions too and no targeting change gets past it.++ A multivariate flag needs `variant_key`, and every other flag rejects it. A release+ condition decides who the flag serves, not which variant they get, so rolling a+ multivariate flag out to everyone also gives the named variant 100% of the variant+ distribution and every other variant 0%. To serve everyone and keep the current split+ between variants, update the flag instead.++ Send the `version` your last read returned. A change to the flag after that version is+ refused with 409. Read the flag again and decide the rollout against its current+ definition.+ """+ data = request.validated_data++ def transform(current_filters: dict) -> dict:+ self._reject_enrollment_gated_rollout(current_filters)+ variant_key = self._validated_variant_key(current_filters, data.get("variant_key"))+ return flag_filters.roll_out_to_everyone(current_filters, variant_key=variant_key)++ return self._rollout_action(request, deleted_hint="rolling it out to everyone", transform=transform)++ @staticmethod+ def _reject_enrollment_gated_rollout(current_filters: dict) -> None:+ """Refuse a flag whose early access enrollment decides the answer before targeting does.++ The matcher reads `$feature_enrollment/<key>` ahead of the release conditions and returns+ on the property being present at all, so everyone who ever saw the opt-in keeps the answer+ they already have, whichever way they answered. A catch-all condition would report a full+ rollout those users never get. Clearing the marker is the early access feature's own+ transition to general availability, not a targeting change this action makes.+ """+ if current_filters.get("feature_enrollment") is True:+ raise exceptions.ValidationError(+ "This feature flag is gated on early access enrollment, which is evaluated before its "+ "release conditions, so rolling it out here would not reach anyone who has opted in or "+ "out. Move its early access feature to general availability instead."+ )++ @staticmethod+ def _validated_variant_key(current_filters: dict, variant_key: str | None) -> str | None:+ """Resolve the variant to roll out, or refuse the request.++ A multivariate flag must name one. Without it the variant split stays as it is, which+ serves the flag to everyone and still splits them across variants. That is a plausible+ reading of "roll it out to everyone" and not the one the caller stated, so refusing+ makes the caller say which of the two it means.+ """+ variants = (current_filters.get("multivariate") or {}).get("variants") or []+ if not variants:+ if variant_key:+ raise exceptions.ValidationError(+ "This feature flag has no variants, so it cannot roll one out. Omit `variant_key`."+ )+ return None+ if not variant_key:+ keys = ", ".join(variant["key"] for variant in variants)+ raise exceptions.ValidationError(+ f"This feature flag is multivariate, so rolling it out to everyone has to name the variant "+ f"everyone gets. Pass one of: {keys}. To serve everyone and keep the current split between "+ f"variants, use a feature flag update instead."+ )+ if not any(variant["key"] == variant_key for variant in variants):+ keys = ", ".join(variant["key"] for variant in variants)+ raise exceptions.ValidationError(f"This feature flag has no variant '{variant_key}'. It defines: {keys}.")+ return variant_key+@extend_schema(parameters=[OpenApiParameter(diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 6628df5625ac..1f4b30312885 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -659,6 +659,37 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):},)+ def test_filters_less_patch_does_not_restore_targeting_changed_since_the_read(self):+ # The legacy-key cleanup seeds `filters` from what the flag stores, on a request that+ # sent none, and the save writes every field. Reading the copy loaded before the row+ # lock therefore puts that copy's targeting back, and neither side of the race bumps a+ # version this request could be checked against.+ flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="legacy-targeting",+ filters={+ "groups": [{"properties": [], "rollout_percentage": 10}],+ "super_groups": [{"properties": [], "rollout_percentage": 15}],+ },+ )+ landed = {"groups": [{"properties": [], "rollout_percentage": 90}]}+ original = FeatureFlagSerializer._update_filters++ def land_a_targeting_write(serializer, validated_data):+ original(serializer, validated_data)+ FeatureFlag.objects.filter(pk=flag.pk).update(filters={**flag.filters, **landed})++ with patch.object(FeatureFlagSerializer, "_update_filters", land_a_targeting_write):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"name": "renamed"}, format="json"+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert flag.name == "renamed"+ assert flag.filters["groups"] == landed["groups"]+@patch("products.feature_flags.backend.api.feature_flag.report_user_action")def test_group_type_index_feature_flag(self, mock_report_user_action):feature_flag = self.client.post(diff --git a/products/feature_flags/backend/api/test/test_feature_flag_rollout_actions.py b/products/feature_flags/backend/api/test/test_feature_flag_rollout_actions.pynew file mode 100644index 000000000000..14dee9023593--- /dev/null+++ b/products/feature_flags/backend/api/test/test_feature_flag_rollout_actions.py@@ -0,0 +1,523 @@+from typing import Any++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.test import RequestFactory++from parameterized import parameterized+from rest_framework import status+from rest_framework.request import Request as DRFRequest++from posthog.constants import AvailableFeature+from posthog.exceptions import Conflict+from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.personal_api_key import PersonalAPIKey+from posthog.models.utils import generate_random_token_personal, hash_key_value++from products.approvals.backend.models import ApprovalPolicy, ChangeRequest+from products.approvals.backend.services import ChangeRequestService+from products.feature_flags.backend.api.feature_flag import (+ FeatureFlagViewSet,+ FlagActionErrorSerializer,+ FlagApprovalConflictSerializer,+ FlagDeletedRejectionSerializer,+ FlagRolloutWriteRequest,+)+from products.feature_flags.backend.facade.api import update_flag+from products.feature_flags.backend.models.feature_flag import FeatureFlag++# Deliberately wider than what either action writes: every one of these must survive a rollout call.+TARGETING: dict[str, Any] = {+ "groups": [+ {+ "properties": [{"key": "email", "type": "person", "value": "@example.com", "operator": "icontains"}],+ "rollout_percentage": 10,+ "description": "internal users",+ },+ {"properties": [], "rollout_percentage": 5},+ ],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 60, "name": "Control"},+ {"key": "test", "rollout_percentage": 40},+ ]+ },+ "payloads": {"control": '{"copy": "a"}'},+ "aggregation_group_type_index": None,+}++BOOLEAN_TARGETING: dict[str, Any] = {+ "groups": [+ {"properties": [{"key": "email", "type": "person", "value": "@example.com"}], "rollout_percentage": 10},+ ],+ "payloads": {"true": '"on"'},+ "holdout": {"id": 7, "exclusion_percentage": 5},+}+++def persisted(filters: dict) -> dict:+ """What the shared flag write path stores for these filters.++ Every write that sends `filters` stamps the flag-level aggregation index onto each release+ condition, whichever endpoint sends it. It changes no targeting, so the rollout actions+ inherit the normalization rather than work around it.+ """+ aggregation = filters.get("aggregation_group_type_index")+ return {+ **filters,+ "aggregation_group_type_index": aggregation,+ "groups": [{"aggregation_group_type_index": aggregation, **group} for group in filters.get("groups") or []],+ }+++# (action, body without `version`)+ROLLOUT_ACTIONS = [+ ("set_release_condition_rollout", {"condition_index": 0, "rollout_percentage": 25}),+ ("roll_out_to_everyone", {"variant_key": "test"}),+]+++def rolled_out(action: str, filters: dict[str, Any]) -> dict[str, Any]:+ """What the ROLLOUT_ACTIONS body for `action` makes of `filters`."""+ if action == "set_release_condition_rollout":+ groups = list(filters["groups"])+ groups[0] = {**groups[0], "rollout_percentage": 25}+ return {**filters, "groups": groups}+ return {+ **filters,+ "groups": [{"properties": [], "rollout_percentage": 100}, *filters["groups"]],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 0, "name": "Control"},+ {"key": "test", "rollout_percentage": 100},+ ]+ },+ }+++class TestFeatureFlagRolloutActions(APIBaseTest):+ def _flag(self, *, key: str = "rollout-flag", filters: dict | None = None) -> FeatureFlag:+ return FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key=key,+ name="rollout flag",+ active=True,+ filters=TARGETING if filters is None else filters,+ )++ def _act(self, flag: FeatureFlag, action: str, body: dict) -> Any:+ return self.client.post(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/{action}/", body, format="json")++ def _read(self, flag: FeatureFlag) -> Any:+ return self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/").json()++ def _gate_flag_updates_on_approval(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}+ ]+ self.organization.save()+ ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key="feature_flag.update",+ conditions={},+ approver_config={"quorum": 1, "users": [self.user.id]},+ created_by=self.user,+ )++ @parameterized.expand([("first", 0, 25), ("second", 1, 25), ("fractional_canary", 0, 0.5)])+ def test_indexed_rollout_changes_only_that_condition(self, _name, condition_index, rollout_percentage):+ flag = self._flag()++ response = self._act(+ flag,+ "set_release_condition_rollout",+ {+ "condition_index": condition_index,+ "rollout_percentage": rollout_percentage,+ "version": flag.version,+ },+ )++ assert response.status_code == status.HTTP_200_OK, response.content+ flag.refresh_from_db()+ expected = {+ **TARGETING,+ "groups": [+ {**group, "rollout_percentage": rollout_percentage} if index == condition_index else group+ for index, group in enumerate(TARGETING["groups"])+ ],+ }+ assert flag.filters == persisted(expected)++ @parameterized.expand(+ [+ ("past_the_end", {"condition_index": 2, "rollout_percentage": 25}, "It has 2"),+ ("negative", {"condition_index": -1, "rollout_percentage": 25}, "greater than or equal to 0"),+ ("percentage_over_100", {"condition_index": 0, "rollout_percentage": 101}, "less than or equal to 100"),+ ]+ )+ def test_indexed_rollout_refuses_an_input_it_cannot_apply(self, _name, body, expected_message):+ flag = self._flag()++ response = self._act(flag, "set_release_condition_rollout", {**body, "version": flag.version})++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert expected_message in str(response.json())+ flag.refresh_from_db()+ assert flag.filters == TARGETING+ assert flag.version == 1++ def test_indexed_rollout_on_a_flag_with_no_conditions_says_so(self):+ flag = self._flag(filters={"groups": []})++ response = self._act(+ flag, "set_release_condition_rollout", {"condition_index": 0, "rollout_percentage": 25, "version": 1}+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "no release conditions" in response.json()["detail"]++ def test_roll_out_to_everyone_prepends_a_catch_all_on_a_boolean_flag(self):+ flag = self._flag(filters=BOOLEAN_TARGETING)++ response = self._act(flag, "roll_out_to_everyone", {"version": flag.version})++ assert response.status_code == status.HTTP_200_OK, response.content+ flag.refresh_from_db()+ assert flag.filters == persisted(+ {+ **BOOLEAN_TARGETING,+ "groups": [{"properties": [], "rollout_percentage": 100}, *BOOLEAN_TARGETING["groups"]],+ }+ )++ def test_roll_out_to_everyone_gives_the_named_variant_the_whole_distribution(self):+ flag = self._flag()++ response = self._act(flag, "roll_out_to_everyone", {"variant_key": "test", "version": flag.version})++ assert response.status_code == status.HTTP_200_OK, response.content+ flag.refresh_from_db()+ assert flag.filters == persisted(+ {+ **TARGETING,+ "groups": [{"properties": [], "rollout_percentage": 100}, *TARGETING["groups"]],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 0, "name": "Control"},+ {"key": "test", "rollout_percentage": 100},+ ]+ },+ }+ )++ def test_roll_out_to_everyone_refuses_a_multivariate_flag_with_no_variant(self):+ # "Roll it out to everyone" reads two ways on a multivariate flag: serve everyone and keep+ # the split, or serve everyone one variant. Refusing makes the caller say which.+ flag = self._flag()++ response = self._act(flag, "roll_out_to_everyone", {"version": flag.version})++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "control, test" in response.json()["detail"]+ # The declared shape reaches the generated clients and the MCP tools, where a key that is+ # not there is read as missing rather than as a schema error.+ assert set(response.json()) == set(FlagActionErrorSerializer().fields)+ flag.refresh_from_db()+ assert flag.filters == TARGETING++ @parameterized.expand(+ [+ ("unknown_variant", None, "green", "has no variant 'green'"),+ ("flag_has_no_variants", BOOLEAN_TARGETING, "test", "has no variants"),+ ]+ )+ def test_roll_out_to_everyone_refuses_a_variant_the_flag_does_not_define(+ self, _name, filters, variant_key, expected_message+ ):+ flag = self._flag(filters=filters)+ original = flag.filters++ response = self._act(flag, "roll_out_to_everyone", {"variant_key": variant_key, "version": flag.version})++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert expected_message in response.json()["detail"]+ flag.refresh_from_db()+ assert flag.filters == original++ def test_roll_out_to_everyone_refuses_a_flag_gated_on_early_access_enrollment(self):+ # The matcher answers from `$feature_enrollment/<key>` before it reads the release+ # conditions, so a catch-all condition would report a rollout that nobody who saw the+ # opt-in receives. The indexed action makes no such promise, so it is not refused.+ flag = self._flag(filters={**BOOLEAN_TARGETING, "feature_enrollment": True})++ response = self._act(flag, "roll_out_to_everyone", {"version": flag.version})++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "early access enrollment" in response.json()["detail"]+ flag.refresh_from_db()+ assert flag.filters["groups"] == BOOLEAN_TARGETING["groups"]++ def test_indexed_rollout_is_allowed_on_a_flag_gated_on_early_access_enrollment(self):+ # The refusal above belongs to `roll_out_to_everyone`, which promises everyone the flag.+ # Changing one condition's percentage makes no such promise, so it goes through.+ gated = {**BOOLEAN_TARGETING, "feature_enrollment": True}+ flag = self._flag(filters=gated)++ response = self._act(+ flag, "set_release_condition_rollout", {"condition_index": 0, "rollout_percentage": 25, "version": 1}+ )++ assert response.status_code == status.HTTP_200_OK, response.content+ flag.refresh_from_db()+ assert flag.filters == persisted(rolled_out("set_release_condition_rollout", gated))+ assert flag.filters["feature_enrollment"] is True++ @parameterized.expand(ROLLOUT_ACTIONS)+ def test_rollout_action_refuses_a_version_that_is_no_longer_current(self, action, body):+ flag = self._flag()+ stale_version = flag.version+ self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {"filters": {**TARGETING, "groups": [{"properties": [], "rollout_percentage": 80}]}},+ format="json",+ )++ response = self._act(flag, action, {**body, "version": stale_version})++ assert response.status_code == status.HTTP_409_CONFLICT, response.content+ assert f"changed since version {stale_version}" in response.json()["detail"]+ flag.refresh_from_db()+ assert flag.filters["groups"] == [+ {"properties": [], "rollout_percentage": 80, "aggregation_group_type_index": None}+ ]++ @parameterized.expand(ROLLOUT_ACTIONS)+ def test_a_fresh_read_after_a_conflict_lets_the_change_through(self, action, body):+ flag = self._flag()+ stale_version = flag.version+ self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", {"name": "renamed"}, format="json")+ assert self._act(flag, action, {**body, "version": stale_version}).status_code == status.HTTP_409_CONFLICT++ response = self._act(flag, action, {**body, "version": self._read(flag)["version"]})++ assert response.status_code == status.HTTP_200_OK, response.content+ flag.refresh_from_db()+ assert flag.filters == persisted(rolled_out(action, TARGETING))+ assert flag.name == "renamed"++ @parameterized.expand(ROLLOUT_ACTIONS)+ def test_repeating_a_rollout_action_writes_nothing(self, action, body):+ flag = self._flag()++ first = self._act(flag, action, {**body, "version": flag.version})+ assert first.status_code == status.HTTP_200_OK, first.content++ second = self._act(flag, action, {**body, "version": first.json()["version"]})++ assert second.status_code == status.HTTP_200_OK, second.content+ assert second.json()["version"] == first.json()["version"]+ assert ActivityLog.objects.filter(scope="FeatureFlag", item_id=str(flag.id), activity="updated").count() == 1++ @parameterized.expand(ROLLOUT_ACTIONS)+ def test_rollout_action_refuses_a_soft_deleted_flag(self, action, body):+ flag = self._flag()+ flag.deleted = True+ flag.save()++ response = self._act(flag, action, {**body, "version": flag.version})++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "has been deleted" in response.json()["error"]+ assert set(response.json()) == set(FlagDeletedRejectionSerializer().fields)++ @parameterized.expand(ROLLOUT_ACTIONS)+ def test_rollout_action_requires_the_feature_flag_write_scope(self, action, body):+ flag = self._flag()+ read_only_key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="read only", user=self.user, scopes=["feature_flag:read"], secure_value=hash_key_value(read_only_key)+ )+ self.client.logout()++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/{action}/",+ {**body, "version": flag.version},+ format="json",+ headers={"authorization": f"Bearer {read_only_key}"},+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content+ flag.refresh_from_db()+ assert flag.filters == TARGETING++ @parameterized.expand(ROLLOUT_ACTIONS)+ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)+ def test_a_rollout_policy_opens_a_change_request_instead_of_writing(self, action, body, _mock_enabled):+ self._gate_flag_updates_on_approval()+ flag = self._flag()++ response = self._act(flag, action, {**body, "version": flag.version})++ assert response.status_code == status.HTTP_409_CONFLICT, response.content+ assert set(response.json()) == set(FlagApprovalConflictSerializer().fields)+ change_request = ChangeRequest.objects.get(team=self.team)+ assert change_request.resource_id == str(flag.id)+ # Approving replays these filters verbatim, so anything short of the exact transform+ # here — the wrong condition, a dropped `multivariate`, a fallback to the empty request+ # body — ships a change request that applies something the caller never asked for.+ assert change_request.intent["full_request_data"]["filters"] == persisted(rolled_out(action, TARGETING))+ flag.refresh_from_db()+ assert flag.filters == TARGETING++ @parameterized.expand(ROLLOUT_ACTIONS)+ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)+ def test_approving_a_rollout_change_request_applies_the_same_change(self, action, body, _mock_enabled):+ # The replay rebuilds the write from the intent rather than from the request, so the+ # cleanup exemption has to travel in the intent. Without it the approved write drops+ # `super_groups` and `holdout_groups`, and the direct-write tests above stay green.+ self._gate_flag_updates_on_approval()+ legacy = {+ **TARGETING,+ "holdout_groups": [{"properties": [], "rollout_percentage": 5, "variant": "holdout-1"}],+ "super_groups": [{"properties": [], "rollout_percentage": 15}],+ }+ flag = self._flag(filters=legacy)++ assert self._act(flag, action, {**body, "version": flag.version}).status_code == status.HTTP_409_CONFLICT+ change_request = ChangeRequest.objects.get(team=self.team)++ assert ChangeRequestService(change_request, self.user).approve().status == "applied"++ flag.refresh_from_db()+ assert flag.filters == persisted(rolled_out(action, legacy))++ @parameterized.expand(ROLLOUT_ACTIONS)+ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)+ def test_a_stale_version_is_refused_before_a_policy_opens_a_change_request(self, action, body, _mock_enabled):+ # The gate raises before the serializer's version check runs, so only the action's own+ # pre-check keeps a stale caller out of it.+ self._gate_flag_updates_on_approval()+ flag = self._flag()+ stale_version = flag.version+ FeatureFlag.objects.filter(pk=flag.id).update(version=(flag.version or 0) + 1)++ response = self._act(flag, action, {**body, "version": stale_version})++ assert response.status_code == status.HTTP_409_CONFLICT, response.content+ assert f"changed since version {stale_version}" in response.json()["detail"]+ assert ChangeRequest.objects.filter(team=self.team).count() == 0+ flag.refresh_from_db()+ assert flag.filters == TARGETING++ @parameterized.expand(ROLLOUT_ACTIONS)+ def test_rollout_action_accepts_the_null_version_a_legacy_flag_reads_as(self, action, body):+ # `version` is nullable, so a flag written before versioning reads as null. The+ # documented flow is to send back what the read returned, and rejecting that value+ # would leave those flags with no way to use these endpoints at all.+ flag = self._flag()+ FeatureFlag.objects.filter(pk=flag.pk).update(version=None)++ response = self._act(flag, action, {**body, "version": None})++ assert response.status_code == status.HTTP_200_OK, response.content+ flag.refresh_from_db()+ assert flag.filters == persisted(rolled_out(action, TARGETING))++ @parameterized.expand(ROLLOUT_ACTIONS)+ def test_rollout_action_preserves_legacy_filter_keys(self, action, body):+ # `super_groups` carries early access enrollment targeting and `holdout_groups` the+ # pre-`holdout` encoding. Neither is a declared field, so the structural pass drops both+ # unless the write declares the cleanup exemption. A rollout write sends the stored+ # filters back, so losing them would rewrite targeting the caller never touched.+ legacy = {+ **TARGETING,+ "holdout_groups": [{"properties": [], "rollout_percentage": 5, "variant": "holdout-1"}],+ "super_groups": [{"properties": [], "rollout_percentage": 15}],+ }+ flag = self._flag(filters=legacy)++ response = self._act(flag, action, {**body, "version": flag.version})++ assert response.status_code == status.HTTP_200_OK, response.content+ flag.refresh_from_db()+ assert flag.filters["holdout_groups"] == legacy["holdout_groups"]+ assert flag.filters["super_groups"] == legacy["super_groups"]++ def test_a_rollout_is_refused_when_the_flag_is_deleted_after_it_was_read(self):+ # A bulk delete leaves `version` untouched, so the version precondition cannot see one+ # that landed since the read. Both actions run the same body, so one covers the window:+ # the delete lands between the pre-lock check and the lock.+ flag = self._flag()+ original = FeatureFlagViewSet._rollout_precondition+ fired: list[bool] = []++ def precondition(view, feature_flag, version):+ original(view, feature_flag, version)+ if not fired:+ fired.append(True)+ FeatureFlag.objects.filter(pk=flag.pk).update(deleted=True)++ with patch.object(FeatureFlagViewSet, "_rollout_precondition", precondition):+ response = self._act(+ flag,+ "set_release_condition_rollout",+ {"condition_index": 0, "rollout_percentage": 25, "version": flag.version},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content+ assert "has been deleted" in response.json()["error"]+ flag.refresh_from_db()+ assert flag.filters == TARGETING++ def test_a_no_op_rollout_is_refused_when_the_flag_changed_after_it_was_read(self):+ # The requested state already matches the copy the caller read, so the transform is a+ # no-op against it. Deciding from that copy answers 200 for a flag another write has+ # already moved on; the decision has to be made against the locked row.+ flag = self._flag()+ stale_version = flag.version+ original = FeatureFlagViewSet._rollout_precondition+ fired: list[bool] = []++ def precondition(view, feature_flag, version):+ original(view, feature_flag, version)+ if not fired:+ fired.append(True)+ FeatureFlag.objects.filter(pk=flag.pk).update(version=(flag.version or 0) + 1)++ with patch.object(FeatureFlagViewSet, "_rollout_precondition", precondition):+ response = self._act(+ flag,+ "set_release_condition_rollout",+ {+ "condition_index": 0,+ "rollout_percentage": TARGETING["groups"][0]["rollout_percentage"],+ "version": stale_version,+ },+ )++ assert response.status_code == status.HTTP_409_CONFLICT, response.content++ def test_the_serializer_refuses_a_stale_version_under_its_row_lock(self):+ # The action's own check cannot close the window: an edit can land between it and the+ # save. Only the serializer's check, under the row lock, makes the window closed.+ flag = self._flag()+ http_request = RequestFactory().post("/")+ http_request.user = self.user+ drf_request = DRFRequest(http_request)+ drf_request.user = self.user++ with self.assertRaises(Conflict):+ update_flag(+ flag,+ {"filters": {**TARGETING, "groups": [{"properties": [], "rollout_percentage": 100}]}},+ team=self.team,+ user=self.user,+ request=FlagRolloutWriteRequest(drf_request, version=(flag.version or 0) + 5),+ )++ flag.refresh_from_db()+ assert flag.filters == TARGETINGdiff --git a/products/feature_flags/backend/facade/filters.py b/products/feature_flags/backend/facade/filters.pyindex 1f9e6e77a200..9b01caec19ef 100644--- a/products/feature_flags/backend/facade/filters.py+++ b/products/feature_flags/backend/facade/filters.py@@ -125,19 +125,6 @@ def replace_variant_distribution(current_filters: dict, variants: list[dict]) ->return {**current_filters, "multivariate": {"variants": deepcopy(variants)}}-def set_first_release_condition_rollout(current_filters: dict, rollout_percentage: int) -> dict:- """Set ``groups[0].rollout_percentage``, preserving everything else byte-for-byte.-- Assumes at least one release group exists and raises (KeyError/IndexError) otherwise —- callers such as survey adaptive sampling only maintain flags they created with a- release condition in place, so a missing group is a broken invariant, not a case- to paper over.- """- new_filters = deepcopy(current_filters)- new_filters["groups"][0]["rollout_percentage"] = rollout_percentage- return new_filters--def replace_release_conditions(current_filters: dict, groups: list[dict]) -> dict:"""Replace the release ``groups`` wholesale.@@ -202,3 +189,84 @@ def group_cohort_restriction_blocker(current_filters: dict) -> CohortRestrictionif not current_filters.get("groups"):return "no_groups"return None+++def set_release_condition_rollout(current_filters: dict, condition_index: int, rollout_percentage: int | float) -> dict:+ """Set ``groups[condition_index].rollout_percentage``, preserving everything else byte-for-byte.++ Raises IndexError when the flag has no condition at that index, including for a negative+ index, which Python would otherwise resolve to a condition counted from the end. An index+ is only meaningful for the definition the caller read, so resolving it to some other+ condition would change a rule the caller never saw.+ """+ groups = current_filters.get("groups") or []+ if not 0 <= condition_index < len(groups):+ raise IndexError(f"No release condition at index {condition_index}; the flag has {len(groups)}.")+ new_filters = deepcopy(current_filters)+ new_filters["groups"][condition_index]["rollout_percentage"] = rollout_percentage+ return new_filters+++def _leads_with_unconditional_rollout(current_filters: dict) -> bool:+ """Whether the first release condition already serves every user, whatever the flag returns.++ Only the first condition is read. Release conditions are evaluated top-down and the first+ match wins, so a property-free 100% condition at the head makes every condition below it+ unreachable.++ A condition carrying a ``variant`` override does not count, even at 100%: it pins one+ variant for everyone it matches and so overrides the variant distribution rather than+ deferring to it.++ An absent or null ``rollout_percentage`` counts as 100, because that is what the matcher+ reads it as, and nothing on the write path fills the default in.++ A condition that aggregates by a different group type than the flag does not count. The+ matcher resolves aggregation per condition and skips one whose group type the evaluation+ does not supply, so such a condition does not serve everyone the flag otherwise would.+ """+ groups = current_filters.get("groups") or []+ if not groups:+ return False+ first = groups[0]+ if first.get("properties") or first.get("variant"):+ return False+ rollout_percentage = first.get("rollout_percentage")+ if rollout_percentage is not None and rollout_percentage != 100:+ return False+ flag_aggregation = current_filters.get("aggregation_group_type_index")+ return first.get("aggregation_group_type_index", flag_aggregation) == flag_aggregation+++def roll_out_to_everyone(current_filters: dict, *, variant_key: str | None = None) -> dict:+ """Serve the flag to 100% of users, preserving every other filters field.++ Prepends a property-free 100% release condition and keeps the existing conditions below+ it, so removing the new condition restores the previous targeting. While it leads, those+ conditions no longer apply, and neither do the per-user variant overrides they carry.++ ``variant_key`` gives that variant 100% of the variant distribution and every other variant+ 0%. A multivariate flag needs it, because a release condition decides who the flag serves+ and not which variant they get. Raises ValueError when the flag defines no such variant.++ A flag that already leads with a property-free 100% condition gains no second one, so a+ caller that repeats the call writes nothing.+ """+ new_filters = deepcopy(current_filters)++ if variant_key is not None:+ multivariate = new_filters.get("multivariate") or {}+ variants = multivariate.get("variants") or []+ if not any(variant.get("key") == variant_key for variant in variants):+ raise ValueError(f"Variant '{variant_key}' is not defined on this feature flag.")+ new_filters["multivariate"] = {+ **multivariate,+ "variants": [+ {**variant, "rollout_percentage": 100 if variant.get("key") == variant_key else 0}+ for variant in variants+ ],+ }++ if not _leads_with_unconditional_rollout(new_filters):+ new_filters["groups"] = [{"properties": [], "rollout_percentage": 100}, *(new_filters.get("groups") or [])]+ return new_filtersdiff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.pyindex 68ae5784a40b..3d3ffd1801be 100644--- a/products/feature_flags/backend/test/test_facade.py+++ b/products/feature_flags/backend/test/test_facade.py@@ -33,9 +33,10 @@ from products.feature_flags.backend.facade.filters import (replace_release_conditions,replace_variant_distribution,restrict_groups_to_cohort,+ roll_out_to_everyone,set_feature_enrollment,- set_first_release_condition_rollout,set_holdout,+ set_release_condition_rollout,strip_group_cohort_restriction,)from products.feature_flags.backend.facade.rules import ExperimentRuleConfig, HoldoutRef, experiment_rule_from_filters@@ -168,6 +169,35 @@ class TestFeatureFlagFacadeGatedWrites(APIBaseTest):assert change_request.intent["http_method"] == "PATCH"assert change_request.resource_id == str(flag.id)+ def test_update_does_not_resurrect_a_flag_deleted_after_it_was_read(self):+ # A bulk delete leaves `version` untouched, so the version check cannot see it. The write+ # has to apply this request to the locked row, which still carries the delete.+ flag = self._create_flag()+ stale = FeatureFlag.objects.get(pk=flag.pk)+ FeatureFlag.objects.filter(pk=flag.pk).update(deleted=True)++ update_flag(stale, {"name": "renamed"}, team=self.team, user=self.user)++ refreshed = FeatureFlag.objects_including_soft_deleted.get(pk=flag.pk)+ assert refreshed.deleted is True+ assert refreshed.name == "renamed"++ def test_update_leaves_the_instance_it_was_given_current(self):+ # The write applies to the row read under the lock, not to the object the caller passed.+ # Callers keep their own reference and re-serialize it, so it has to come back carrying+ # what was written rather than what the write replaced.+ flag = self._create_flag()++ update_flag(+ flag,+ {"name": "renamed", "filters": {"groups": [{"properties": [], "rollout_percentage": 40}]}},+ team=self.team,+ user=self.user,+ )++ assert flag.name == "renamed"+ assert flag.filters["groups"][0]["rollout_percentage"] == 40+def test_system_create_logs_system_activity(self):with self.captureOnCommitCallbacks(execute=True):flag = create_flag(@@ -682,45 +712,167 @@ class TestSetFeatureEnrollment:class TestReleaseConditionTransforms:+ @parameterized.expand([("first", 0), ("second", 1), ("last", 2)])+ def test_set_release_condition_rollout_changes_only_the_indexed_condition(self, _name, condition_index):+ filters: dict[str, Any] = {+ "groups": [+ {"properties": [{"key": "email", "type": "person"}], "rollout_percentage": 10, "variant": "control"},+ {"properties": [], "rollout_percentage": 20},+ {"properties": [{"key": "$os", "type": "person"}], "rollout_percentage": 30},+ ],+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100}]},+ "payloads": {"control": "{}"},+ "aggregation_group_type_index": 1,+ "holdout": {"id": 7, "exclusion_percentage": 5},+ }+ original = deepcopy(filters)++ result = set_release_condition_rollout(filters, condition_index, 55)++ assert result["groups"][condition_index]["rollout_percentage"] == 55+ result["groups"][condition_index]["rollout_percentage"] = original["groups"][condition_index][+ "rollout_percentage"+ ]+ assert result == original+ assert filters == original+@parameterized.expand([- (- "survey_sampling_shape",- {"groups": [{"variant": "", "rollout_percentage": 100, "properties": []}]},- ),- (- "multi_group_with_multivariate_and_payloads",- {- "groups": [- {"variant": "", "rollout_percentage": 100, "properties": [{"key": "email", "type": "person"}]},- {"properties": [], "rollout_percentage": 50},- ],- "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100}]},- "payloads": {"control": "{}"},- "aggregation_group_type_index": 1,- },- ),+ ("past_the_end", {"groups": [{"properties": [], "rollout_percentage": 10}]}, 1),+ # Python would resolve -1 to the last condition, which is a rule the caller never named.+ ("negative", {"groups": [{"properties": [], "rollout_percentage": 10}]}, -1),+ ("no_conditions", {"groups": []}, 0),+ ("missing_groups_key", {}, 0),])- def test_set_first_release_condition_rollout_only_changes_first_group_rollout(self, _name, filters):+ def test_set_release_condition_rollout_raises_for_an_index_the_flag_has_no_condition_at(+ self, _name, filters, condition_index+ ):+ with pytest.raises(IndexError):+ set_release_condition_rollout(filters, condition_index, 55)++ def test_roll_out_to_everyone_prepends_a_catch_all_and_preserves_the_rest(self):+ filters: dict[str, Any] = {+ "groups": [{"properties": [{"key": "email", "type": "person"}], "rollout_percentage": 10}],+ "payloads": {"true": '"on"'},+ "aggregation_group_type_index": 1,+ "holdout": {"id": 7, "exclusion_percentage": 5},+ "super_groups": [{"properties": [], "rollout_percentage": 15}],+ }original = deepcopy(filters)- result = set_first_release_condition_rollout(filters, 20)+ result = roll_out_to_everyone(filters)- assert result["groups"][0]["rollout_percentage"] == 20- result["groups"][0]["rollout_percentage"] = original["groups"][0]["rollout_percentage"]- assert result == original- assert filters == original # input not mutated+ assert result["groups"] == [{"properties": [], "rollout_percentage": 100}, *original["groups"]]+ assert {key: value for key, value in result.items() if key != "groups"} == {+ key: value for key, value in original.items() if key != "groups"+ }+ assert filters == original++ def test_roll_out_to_everyone_gives_the_named_variant_the_whole_distribution(self):+ filters: dict[str, Any] = {+ "groups": [{"properties": [{"key": "email", "type": "person"}], "rollout_percentage": 10}],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 60, "name": "Control"},+ {"key": "test", "rollout_percentage": 40},+ ]+ },+ "payloads": {"control": "{}"},+ }+ original = deepcopy(filters)++ result = roll_out_to_everyone(filters, variant_key="test")++ assert result["multivariate"]["variants"] == [+ {"key": "control", "rollout_percentage": 0, "name": "Control"},+ {"key": "test", "rollout_percentage": 100},+ ]+ assert result["groups"] == [{"properties": [], "rollout_percentage": 100}, *original["groups"]]+ assert result["payloads"] == original["payloads"]+ assert filters == original++ @parameterized.expand(+ [+ ("boolean", None),+ ("multivariate", "test"),+ ]+ )+ def test_roll_out_to_everyone_adds_no_second_catch_all(self, _name, variant_key):+ filters: dict[str, Any] = {+ "groups": [{"properties": [], "rollout_percentage": 100}],+ "multivariate": {+ "variants": [{"key": "control", "rollout_percentage": 0}, {"key": "test", "rollout_percentage": 100}]+ },+ }++ result = roll_out_to_everyone(roll_out_to_everyone(filters, variant_key=variant_key), variant_key=variant_key)++ assert result["groups"] == [{"properties": [], "rollout_percentage": 100}]++ @parameterized.expand(+ [+ ("absent", {"properties": []}),+ ("null", {"properties": [], "rollout_percentage": None}),+ ]+ )+ def test_roll_out_to_everyone_treats_an_implicit_full_rollout_as_a_catch_all(self, _name, leading):+ # The matcher reads an absent or null rollout_percentage as 100, and nothing on the+ # write path fills it in, so a stored flag can lead with either form.+ filters: dict[str, Any] = {"groups": [leading, {"properties": [], "rollout_percentage": 10}]}++ result = roll_out_to_everyone(filters)++ assert result["groups"] == filters["groups"]++ @parameterized.expand(+ [+ ("condition_matches_the_flag", 3, {"aggregation_group_type_index": 3}, 1),+ ("group_condition_on_a_person_flag", None, {"aggregation_group_type_index": 3}, 2),+ ("person_condition_on_a_group_flag", 3, {"aggregation_group_type_index": None}, 2),+ ("condition_omits_the_key_on_a_group_flag", 3, {}, 1),+ ]+ )+ def test_roll_out_to_everyone_prepends_unless_the_leading_condition_covers_the_flag(+ self, _name, flag_aggregation, condition_aggregation, expected_groups+ ):+ # The matcher skips a condition whose group type the evaluation does not supply, so one+ # aggregating differently from the flag serves only part of the population. The schema+ # keeps an absent key distinct from a null one, so a stored condition can carry either,+ # and only the absent form falls back to the flag's own value.+ filters: dict[str, Any] = {"groups": [{"properties": [], "rollout_percentage": 100, **condition_aggregation}]}+ if flag_aggregation is not None:+ filters["aggregation_group_type_index"] = flag_aggregation++ result = roll_out_to_everyone(filters)++ assert len(result["groups"]) == expected_groups+ assert result["groups"][-1] == filters["groups"][0]++ def test_roll_out_to_everyone_replaces_a_leading_condition_that_pins_a_variant(self):+ # A `variant` override at 100% serves that variant to everyone whatever the distribution+ # says, so keeping it would silently ignore the variant the caller asked to roll out.+ filters: dict[str, Any] = {+ "groups": [{"properties": [], "rollout_percentage": 100, "variant": "control"}],+ "multivariate": {+ "variants": [{"key": "control", "rollout_percentage": 100}, {"key": "test", "rollout_percentage": 0}]+ },+ }++ result = roll_out_to_everyone(filters, variant_key="test")++ assert result["groups"][0] == {"properties": [], "rollout_percentage": 100}+ assert result["groups"][1] == {"properties": [], "rollout_percentage": 100, "variant": "control"}@parameterized.expand([- ("missing_groups", {}, KeyError),- ("empty_groups", {"groups": []}, IndexError),+ ("unknown_variant", {"multivariate": {"variants": [{"key": "control", "rollout_percentage": 100}]}}),+ ("flag_has_no_variants", {"groups": []}),])- def test_set_first_release_condition_rollout_raises_without_a_group(self, _name, filters, expected_error):- with pytest.raises(expected_error):- set_first_release_condition_rollout(filters, 20)+ def test_roll_out_to_everyone_raises_for_a_variant_the_flag_does_not_define(self, _name, filters):+ with pytest.raises(ValueError):+ roll_out_to_everyone(filters, variant_key="test")def test_replace_release_conditions_swaps_groups_and_preserves_the_rest(self):filters: dict[str, Any] = {diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex 4ab16f24bbd0..163704cb191e 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -1206,6 +1206,87 @@ export interface ActivityLogPaginatedResponseApi {total_count: number}+/**+ * The body every DRF exception on these actions renders as.+ *+ * `ErrorResponseSerializer` declares a single `error` key, which no response on this viewset+ * produces: the project exception handler renders this envelope instead. Declaring the wrong+ * shape reaches the generated clients and the MCP tools, where an agent reads a key that is+ * never there.+ */+export interface FlagActionErrorApi {+ /** Error class, for example `validation_error`. */+ type: string+ /** Machine-readable reason, for example `invalid_input`. */+ code: string+ /** Human-readable description of what was refused. */+ detail: string+ /**+ * Request field the error belongs to, or null when it belongs to no single field.+ * @nullable+ */+ attr: string | null+}++/**+ * The 400 body a soft-deleted flag produces, which differs from every other error here.+ *+ * Built as a plain response rather than raised, so it carries neither the `type` nor the+ * `attr` the exception handler's envelope has.+ */+export interface FlagDeletedRejectionApi {+ /** Always `false`. */+ success: boolean+ /** Human-readable reason, naming the restore the caller has to do before retrying. */+ error: string+}++/**+ * The 400 body a change matching several approval policies produces.+ *+ * Raised through the approvals mixin rather than the exception handler, so it carries the+ * policies that matched instead of the `type`/`attr` envelope.+ */+export interface FlagPolicyConflictApi {+ /** Always `policy_conflict`. */+ code: string+ /** Human-readable reason the change could not be gated. */+ error: string+ /** The approval policies that matched this change. */+ conflicting_policies: unknown+ /** How to split the change so each policy applies on its own. */+ guidance: string+}++export type FeatureFlagActionBadRequestApi = FlagActionErrorApi | FlagDeletedRejectionApi | FlagPolicyConflictApi++/**+ * The 409 body an approval policy produces, which differs from every other error here.+ *+ * Raised through the approvals mixin rather than the exception handler, so it carries the+ * change request it opened instead of the `type`/`attr` envelope.+ */+export interface FlagApprovalConflictApi {+ /** `approval_required` when this call opened the change request, `change_request_pending` when one was already open for the same action. */+ code: string+ /** Always `approval_required`. */+ status: string+ /** Human-readable description of the policy that gated the change. */+ detail: string+ /** Same text as `detail`. */+ message: string+ /** Resource the change request targets, `feature_flag` here. */+ resource_type: string+ /** Id of the flag the change request targets. */+ resource_id: string+ /** Id of the change request that was opened. */+ change_request_id: string+ /** The change request that was opened, serialized in full. */+ change_request: unknown+ /** Who can approve the change request. */+ required_approvers: unknown+}+export interface DependentFlagApi {/** Feature flag ID */id: number@@ -1215,6 +1296,42 @@ export interface DependentFlagApi {name: string}+export interface FeatureFlagRollOutToEveryoneRequestApi {+ /**+ * The `version` from your most recent read of this flag. The change is refused with 409 if anyone else changed the flag after that version. A flag written before versioning reads as `null`; send that back unchanged and it is read as 0, so the value a read returns is always one this accepts.+ * @minimum 0+ * @nullable+ */+ version: number | null+ /**+ * The variant every user gets. Required for a multivariate flag and rejected for any other flag, because a release condition decides who the flag serves and not which variant they get.+ * @nullable+ */+ variant_key?: string | null+}++export type FeatureFlagActionConflictApi = FlagActionErrorApi | FlagApprovalConflictApi++export interface FeatureFlagSetReleaseConditionRolloutRequestApi {+ /**+ * Zero-based position of the release condition in `filters.groups`, counted from the read that produced `version`.+ * @minimum 0+ */+ condition_index: number+ /**+ * Percentage of the users matching that condition who are served the flag, 0 through 100. On a multivariate flag this is how many matching users get a variant at all, not how the variants are split between them. Fractional percentages such as 0.5 are accepted, the same as a write that sends `filters`.+ * @minimum 0+ * @maximum 100+ */+ rollout_percentage: number+ /**+ * The `version` from your most recent read of this flag. The change is refused with 409 if anyone else changed the flag after that version. A flag written before versioning reads as `null`; send that back unchanged and it is read as 0, so the value a read returns is always one this accepts.+ * @minimum 0+ * @nullable+ */+ version: number | null+}+export interface FeatureFlagRolloutSummaryApi {/** True if the flag is effectively rolled out to everyone, independent of recent evaluation. For boolean flags this means at least one release condition targets 100% with no property filters (or there are no release conditions); for multivariate flags it means a single variant is served to 100% via a fully rolled out release condition. This is the signal for 'fully rolled out' / GA — unlike `status`, which only reflects recent evaluation. */effectively_full_rollout: booleandiff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.tsindex e422f03bd2bf..c2b7a8e7c2fc 100644--- a/products/feature_flags/frontend/generated/api.ts+++ b/products/feature_flags/frontend/generated/api.ts@@ -27,6 +27,8 @@ import type {FeatureFlagCreateRequestSchemaApi,FeatureFlagRequestUsageListParams,FeatureFlagRequestUsageResponseApi,+ FeatureFlagRollOutToEveryoneRequestApi,+ FeatureFlagSetReleaseConditionRolloutRequestApi,FeatureFlagStatusResponseApi,FeatureFlagTestEvaluationRequestApi,FeatureFlagTestEvaluationResponseApi,@@ -831,6 +833,81 @@ export const featureFlagsRemoteConfigRetrieve = async (})}+export const getFeatureFlagsRollOutToEveryoneCreateUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/feature_flags/${id}/roll_out_to_everyone/`+}++/**+ * Serve a feature flag to every user.+ *+ * Adds a release condition with no property filters at 100% and keeps the existing+ * conditions below it. Payloads, holdout and every other field are left as they are. On a+ * boolean flag, removing the new condition restores the previous targeting. On a+ * multivariate flag the variant distribution is rewritten as well, so removing the+ * condition restores the audience but not the old split. A flag that already leads with+ * such a condition gains no second one.+ *+ * This changes targeting only. A disabled flag still serves nobody, and a holdout is+ * evaluated before release conditions, so users in one keep getting the holdout variant+ * instead of the rollout. A flag gated on early access enrollment is refused, because that+ * gate is evaluated before release conditions too and no targeting change gets past it.+ *+ * A multivariate flag needs `variant_key`, and every other flag rejects it. A release+ * condition decides who the flag serves, not which variant they get, so rolling a+ * multivariate flag out to everyone also gives the named variant 100% of the variant+ * distribution and every other variant 0%. To serve everyone and keep the current split+ * between variants, update the flag instead.+ *+ * Send the `version` your last read returned. A change to the flag after that version is+ * refused with 409. Read the flag again and decide the rollout against its current+ * definition.+ */+export const featureFlagsRollOutToEveryoneCreate = async (+ projectId: string,+ id: number,+ featureFlagRollOutToEveryoneRequestApi: FeatureFlagRollOutToEveryoneRequestApi,+ options?: RequestInit+): Promise<FeatureFlagApi> => {+ return apiMutator<FeatureFlagApi>(getFeatureFlagsRollOutToEveryoneCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(featureFlagRollOutToEveryoneRequestApi),+ })+}++export const getFeatureFlagsSetReleaseConditionRolloutCreateUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/feature_flags/${id}/set_release_condition_rollout/`+}++/**+ * Set what percentage of one release condition's audience a feature flag is served to.+ *+ * Changes `rollout_percentage` on the release condition at `condition_index` and nothing+ * else. The condition's property filters, every other condition, the variants, payloads,+ * holdout and every remaining field are left as they are.+ *+ * Send the `version` your last read returned. A change to the flag after that version is+ * refused with 409, because a condition index only names the condition you read. Read the+ * flag again and decide the percentage against its current definition.+ *+ * On a multivariate flag this sets how many of the matching users get a variant at all. It+ * does not change how the variants are split between them.+ */+export const featureFlagsSetReleaseConditionRolloutCreate = async (+ projectId: string,+ id: number,+ featureFlagSetReleaseConditionRolloutRequestApi: FeatureFlagSetReleaseConditionRolloutRequestApi,+ options?: RequestInit+): Promise<FeatureFlagApi> => {+ return apiMutator<FeatureFlagApi>(getFeatureFlagsSetReleaseConditionRolloutCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(featureFlagSetReleaseConditionRolloutRequestApi),+ })+}+export const getFeatureFlagsStatusRetrieveUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/feature_flags/${id}/status/`}diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.tsindex 906c3d2f4942..d6a4f3d72dbf 100644--- a/products/feature_flags/frontend/generated/api.zod.ts+++ b/products/feature_flags/frontend/generated/api.zod.ts@@ -1039,6 +1039,93 @@ export const FeatureFlagsCreateStaticCohortForFlagCreateBody = /* @__PURE__ */ z}).describe('Serializer mixin that handles tags for objects.')+/**+ * Serve a feature flag to every user.+ *+ * Adds a release condition with no property filters at 100% and keeps the existing+ * conditions below it. Payloads, holdout and every other field are left as they are. On a+ * boolean flag, removing the new condition restores the previous targeting. On a+ * multivariate flag the variant distribution is rewritten as well, so removing the+ * condition restores the audience but not the old split. A flag that already leads with+ * such a condition gains no second one.+ *+ * This changes targeting only. A disabled flag still serves nobody, and a holdout is+ * evaluated before release conditions, so users in one keep getting the holdout variant+ * instead of the rollout. A flag gated on early access enrollment is refused, because that+ * gate is evaluated before release conditions too and no targeting change gets past it.+ *+ * A multivariate flag needs `variant_key`, and every other flag rejects it. A release+ * condition decides who the flag serves, not which variant they get, so rolling a+ * multivariate flag out to everyone also gives the named variant 100% of the variant+ * distribution and every other variant 0%. To serve everyone and keep the current split+ * between variants, update the flag instead.+ *+ * Send the `version` your last read returned. A change to the flag after that version is+ * refused with 409. Read the flag again and decide the rollout against its current+ * definition.+ */+export const featureFlagsRollOutToEveryoneCreateBodyVersionMin = 0++export const FeatureFlagsRollOutToEveryoneCreateBody = /* @__PURE__ */ zod.object({+ version: zod+ .number()+ .min(featureFlagsRollOutToEveryoneCreateBodyVersionMin)+ .nullable()+ .describe(+ 'The `version` from your most recent read of this flag. The change is refused with 409 if anyone else changed the flag after that version. A flag written before versioning reads as `null`; send that back unchanged and it is read as 0, so the value a read returns is always one this accepts.'+ ),+ variant_key: zod+ .string()+ .nullish()+ .describe(+ 'The variant every user gets. Required for a multivariate flag and rejected for any other flag, because a release condition decides who the flag serves and not which variant they get.'+ ),+})++/**+ * Set what percentage of one release condition's audience a feature flag is served to.+ *+ * Changes `rollout_percentage` on the release condition at `condition_index` and nothing+ * else. The condition's property filters, every other condition, the variants, payloads,+ * holdout and every remaining field are left as they are.+ *+ * Send the `version` your last read returned. A change to the flag after that version is+ * refused with 409, because a condition index only names the condition you read. Read the+ * flag again and decide the percentage against its current definition.+ *+ * On a multivariate flag this sets how many of the matching users get a variant at all. It+ * does not change how the variants are split between them.+ */+export const featureFlagsSetReleaseConditionRolloutCreateBodyConditionIndexMin = 0++export const featureFlagsSetReleaseConditionRolloutCreateBodyRolloutPercentageMin = 0+export const featureFlagsSetReleaseConditionRolloutCreateBodyRolloutPercentageMax = 100++export const featureFlagsSetReleaseConditionRolloutCreateBodyVersionMin = 0++export const FeatureFlagsSetReleaseConditionRolloutCreateBody = /* @__PURE__ */ zod.object({+ condition_index: zod+ .number()+ .min(featureFlagsSetReleaseConditionRolloutCreateBodyConditionIndexMin)+ .describe(+ 'Zero-based position of the release condition in `filters.groups`, counted from the read that produced `version`.'+ ),+ rollout_percentage: zod+ .number()+ .min(featureFlagsSetReleaseConditionRolloutCreateBodyRolloutPercentageMin)+ .max(featureFlagsSetReleaseConditionRolloutCreateBodyRolloutPercentageMax)+ .describe(+ 'Percentage of the users matching that condition who are served the flag, 0 through 100. On a multivariate flag this is how many matching users get a variant at all, not how the variants are split between them. Fractional percentages such as 0.5 are accepted, the same as a write that sends `filters`.'+ ),+ version: zod+ .number()+ .min(featureFlagsSetReleaseConditionRolloutCreateBodyVersionMin)+ .nullable()+ .describe(+ 'The `version` from your most recent read of this flag. The change is refused with 409 if anyone else changed the flag after that version. A flag written before versioning reads as `null`; send that back unchanged and it is read as 0, so the value a read returns is always one this accepts.'+ ),+})+/*** Test feature flag evaluation against a specific user at an optional point in time.*diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yamlindex a1221acd61a0..c6d21ce15028 100644--- a/products/feature_flags/mcp/tools.yaml+++ b/products/feature_flags/mcp/tools.yaml@@ -522,6 +522,12 @@ tools:feature-flags-remote-config-retrieve:operation: feature_flags_remote_config_retrieveenabled: false+ feature-flags-roll-out-to-everyone-create:+ operation: feature_flags_roll_out_to_everyone_create+ enabled: false+ feature-flags-set-release-condition-rollout-create:+ operation: feature_flags_set_release_condition_rollout_create+ enabled: falsefeature-flags-staff-cache-clear-create:operation: feature_flags_staff_cache_clear_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 53abfb21fb4a..6f0f32322b29 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -43118,6 +43118,89 @@ export namespace Schemas {readonly is_eligible_for_experiment: boolean;}+ /**+ * The body every DRF exception on these actions renders as.+ *+ * `ErrorResponseSerializer` declares a single `error` key, which no response on this viewset+ * produces: the project exception handler renders this envelope instead. Declaring the wrong+ * shape reaches the generated clients and the MCP tools, where an agent reads a key that is+ * never there.+ */+ export interface FlagActionError {+ /** Error class, for example `validation_error`. */+ type: string;+ /** Machine-readable reason, for example `invalid_input`. */+ code: string;+ /** Human-readable description of what was refused. */+ detail: string;+ /**+ * Request field the error belongs to, or null when it belongs to no single field.+ * @nullable+ */+ attr: string | null;+ }++ /**+ * The 400 body a soft-deleted flag produces, which differs from every other error here.+ *+ * Built as a plain response rather than raised, so it carries neither the `type` nor the+ * `attr` the exception handler's envelope has.+ */+ export interface FlagDeletedRejection {+ /** Always `false`. */+ success: boolean;+ /** Human-readable reason, naming the restore the caller has to do before retrying. */+ error: string;+ }++ /**+ * The 400 body a change matching several approval policies produces.+ *+ * Raised through the approvals mixin rather than the exception handler, so it carries the+ * policies that matched instead of the `type`/`attr` envelope.+ */+ export interface FlagPolicyConflict {+ /** Always `policy_conflict`. */+ code: string;+ /** Human-readable reason the change could not be gated. */+ error: string;+ /** The approval policies that matched this change. */+ conflicting_policies: unknown;+ /** How to split the change so each policy applies on its own. */+ guidance: string;+ }++ export type FeatureFlagActionBadRequest = FlagActionError | FlagDeletedRejection | FlagPolicyConflict;++ /**+ * The 409 body an approval policy produces, which differs from every other error here.+ *+ * Raised through the approvals mixin rather than the exception handler, so it carries the+ * change request it opened instead of the `type`/`attr` envelope.+ */+ export interface FlagApprovalConflict {+ /** `approval_required` when this call opened the change request, `change_request_pending` when one was already open for the same action. */+ code: string;+ /** Always `approval_required`. */+ status: string;+ /** Human-readable description of the policy that gated the change. */+ detail: string;+ /** Same text as `detail`. */+ message: string;+ /** Resource the change request targets, `feature_flag` here. */+ resource_type: string;+ /** Id of the flag the change request targets. */+ resource_id: string;+ /** Id of the change request that was opened. */+ change_request_id: string;+ /** The change request that was opened, serialized in full. */+ change_request: unknown;+ /** Who can approve the change request. */+ required_approvers: unknown;+ }++ export type FeatureFlagActionConflict = FlagActionError | FlagApprovalConflict;+export interface FeatureFlagConditionPropertyAnalysis {/** Property key */key: string;@@ -43268,6 +43351,20 @@ export namespace Schemas {results: FeatureFlagRequestUsageItem[];}+ export interface FeatureFlagRollOutToEveryoneRequest {+ /**+ * The `version` from your most recent read of this flag. The change is refused with 409 if anyone else changed the flag after that version. A flag written before versioning reads as `null`; send that back unchanged and it is read as 0, so the value a read returns is always one this accepts.+ * @minimum 0+ * @nullable+ */+ version: number | null;+ /**+ * The variant every user gets. Required for a multivariate flag and rejected for any other flag, because a release condition decides who the flag serves and not which variant they get.+ * @nullable+ */+ variant_key?: string | null;+ }+export interface FeatureFlagRolloutSummary {/** True if the flag is effectively rolled out to everyone, independent of recent evaluation. For boolean flags this means at least one release condition targets 100% with no property filters (or there are no release conditions); for multivariate flags it means a single variant is served to 100% via a fully rolled out release condition. This is the signal for 'fully rolled out' / GA — unlike `status`, which only reflects recent evaluation. */effectively_full_rollout: boolean;@@ -43282,6 +43379,26 @@ export namespace Schemas {is_multivariate: boolean;}+ export interface FeatureFlagSetReleaseConditionRolloutRequest {+ /**+ * Zero-based position of the release condition in `filters.groups`, counted from the read that produced `version`.+ * @minimum 0+ */+ condition_index: number;+ /**+ * Percentage of the users matching that condition who are served the flag, 0 through 100. On a multivariate flag this is how many matching users get a variant at all, not how the variants are split between them. Fractional percentages such as 0.5 are accepted, the same as a write that sends `filters`.+ * @minimum 0+ * @maximum 100+ */+ rollout_percentage: number;+ /**+ * The `version` from your most recent read of this flag. The change is refused with 409 if anyone else changed the flag after that version. A flag written before versioning reads as `null`; send that back unchanged and it is read as 0, so the value a read returns is always one this accepts.+ * @minimum 0+ * @nullable+ */+ version: number | null;+ }+export interface FeatureFlagStatusResponse {/** Flag staleness/evaluation status: active, stale, archived, deleted, or unknown. 'active' means the flag was recently evaluated (or has no usage data yet) — it does NOT mean the flag is fully rolled out. Use the `rollout` object to determine rollout completeness. */status: string;