Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(flags): accept the row version on flag enable and disable (#123453)

Anders719b890f58f4
diff --git a/docs/internal/feature-flags/django-api-endpoints.md b/docs/internal/feature-flags/django-api-endpoints.md
index 6699e02c59f8..3a03a23cb941 100644
--- a/docs/internal/feature-flags/django-api-endpoints.md
+++ b/docs/internal/feature-flags/django-api-endpoints.md
@@ -98,12 +98,14 @@ Both actions **proxy to the Rust flags service** via `get_flags_from_service()`
### Lifecycle state actions
`enable`, `disable`, `archive` and `unarchive` are the typed alternative to `PATCH` for the two state fields.
-They take no request body, so a caller cannot send back targeting it read a moment ago.
-That shrinks the lost-update window but does not close it: the serializer saves the instance `get_object()` loaded and Django writes every column, so an edit committed between that read and the save is still reverted.
+None of them reads targeting from the request body, so a caller cannot send back targeting it read a moment ago.
+Without `version`, that shrinks the lost-update window but does not close it: the serializer saves the instance `get_object()` loaded and Django writes every column, so an edit committed between that read and the save is still reverted.
A version-sending `PATCH` has the same hole, because the conflict check only fires when the caller's own fields overlap.
What these endpoints remove is the caller-held read, which spans as long as the caller takes rather than the inside of one request.
Each one delegates to the matching function in `products/feature_flags/backend/facade/api.py`, which routes the write through `FeatureFlagSerializer` — the same path `PATCH` uses, so the approval gate, the dependency guards, cache invalidation and activity logging all still apply.
-The write bumps `version` under a row lock, but the stale-write conflict check does not run: it compares a caller-supplied `version`, and these endpoints take no body.
+The write bumps `version` under a row lock.
+When `enable` or `disable` gets `version`, a stale value returns 409, and a config version 2 flag requires it.
+`archive` and `unarchive` take no body, so the stale-write check does not run for them.
All four declare `feature_flag:write`, so object-level access control requires editor.
They are POST but they update, so each one hands the facade a `FlagLifecycleWriteRequest` that reports the write as a PATCH.
Two things branch on the method: the serializer runs create-only validation on POST, and the approval gate returns no resource id for POST, which made pending change requests for different flags collide.
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index cfbe867c565a..4d6fcc03372e 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -2114,6 +2114,18 @@ class FeatureFlagSerializer(
def _validate_filters_inner(self, filters, operation: str):
stored_filters = (self.instance.filters or {}) if self.instance is not None else {}
+ if filters and detect_config_format(stored_filters).kind == "v2" and detect_config_format(filters).kind == "v1":
+ # Writing version 1 filters would silently convert the flag, which nothing may do.
+ hint = (
+ "Send the complete version 2 document with version 2 and its rules, or leave filters out"
+ if self._v2_limits is not None
+ else "Its targeting can't be changed through the API yet. Leave filters out"
+ )
+ raise serializers.ValidationError(
+ "This flag uses config version 2, so version 1 filters (groups, multivariate, payloads) "
+ f"cannot be written to it. {hint} to change other fields.",
+ code="v1_filters_on_v2_flag",
+ )
reserved_variant_key = _reserved_variant_key(filters, stored=stored_filters)
if reserved_variant_key is not None:
message = (
@@ -3943,6 +3955,19 @@ class FeatureFlagSetReleaseConditionRolloutRequestSerializer(serializers.Seriali
version = serializers.IntegerField(min_value=0, allow_null=True, help_text=FLAG_VERSION_PRECONDITION_HELP)
+class FeatureFlagSetActiveRequestSerializer(serializers.Serializer):
+ version = serializers.IntegerField(
+ required=False,
+ min_value=0,
+ allow_null=True,
+ help_text=(
+ "The `version` from your most recent read of this flag. Required when the flag's `filters.version` is "
+ "2, optional otherwise. When sent, the change is refused with 409 if anyone else changed the flag after "
+ "that version. Null is the same as leaving it out."
+ ),
+ )
+
+
class FeatureFlagRollOutToEveryoneRequestSerializer(serializers.Serializer):
version = serializers.IntegerField(min_value=0, allow_null=True, help_text=FLAG_VERSION_PRECONDITION_HELP)
variant_key = serializers.CharField(
@@ -3984,7 +4009,7 @@ class FlagLifecycleWriteRequest(ServiceRequest):
extraction returns None for POST, so pending change requests for different flags collide and
the second one is dropped as a duplicate. Reporting the write as the PATCH it is fixes both.
- ``data`` stays empty because these endpoints declare no body. The serializer reads ``version``
+ ``data`` stays empty whatever the caller sent. The serializer reads ``version``
and ``original_flag`` off the request, so a body echoed back from an earlier read could
otherwise discard the state change and still return 200.
@@ -4019,8 +4044,8 @@ class FlagLifecycleWriteRequest(ServiceRequest):
return getattr(self._request, name)
-class FlagRolloutWriteRequest(FlagLifecycleWriteRequest):
- """The request a flag rollout action hands to the flag facade.
+class FlagVersionCheckedWriteRequest(FlagLifecycleWriteRequest):
+ """The request a flag rollout action, or a toggle that sends `version`, 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
@@ -4399,18 +4424,18 @@ class FeatureFlagViewSet(
# rewrites `filters`, so a caller no longer reads the flag, mutates one field, and sends
# the whole targeting object back.
#
- # That shrinks the lost-update window; it does not close it. The serializer saves the
- # instance get_object() loaded, and Django writes every column, so an edit committed
- # between that read and the save is still reverted. A version-sending PATCH has the same
- # hole: the conflict check only fires when the caller's own fields overlap. What these
+ # Without `version`, that shrinks the lost-update window but does not close it. The
+ # serializer saves the instance get_object() loaded, and Django writes every column, so an
+ # edit committed between that read and the save is still reverted. A version-sending PATCH
+ # has the same hole: the conflict check only fires when the caller's own fields overlap. What these
# endpoints remove is the caller-held read, which spans as long as the caller takes
# rather than the inside of one request.
#
# Each routes through the flag facade, which writes through FeatureFlagSerializer — the
# same path PATCH uses, so the approval gate, the dependency guards, cache invalidation
- # and activity logging all apply. The write bumps `version` under a row lock, but the
- # stale-write conflict check does not run: it compares a caller-supplied `version`, and
- # these endpoints take no body.
+ # and activity logging all apply. The write bumps `version` under a row lock. The
+ # stale-write conflict check runs only when the caller sends `version`, which enable and
+ # disable accept and a config version 2 flag requires.
#
# A flag already in the requested state is returned with no write, so a caller retrying in
# order cannot bump the version or log a change that did not happen. Two calls racing still
@@ -4426,14 +4451,17 @@ class FeatureFlagViewSet(
apply_encrypted_payload_response_form(self.request, data)
return Response(data, status=status.HTTP_200_OK)
- def _set_active(self, request: request.Request, *, active: bool) -> Response:
- from products.feature_flags.backend.facade.api import set_flag_active
+ def _set_active(self, request: ValidatedRequest, *, active: bool) -> Response:
+ from products.feature_flags.backend.facade.api import set_flag_active, update_flag
feature_flag: FeatureFlag = self.get_object()
rejection = self._deleted_flag_rejection(feature_flag, "enabling it" if active else "disabling it")
if rejection is not None:
return rejection
- if feature_flag.active != active:
+ if feature_flag.active == active:
+ return self._lifecycle_response(feature_flag)
+ version = request.validated_data.get("version")
+ if version is None:
feature_flag = set_flag_active(
feature_flag,
active,
@@ -4441,19 +4469,30 @@ class FeatureFlagViewSet(
user=request.user,
request=FlagLifecycleWriteRequest(request),
)
+ else:
+ # The serializer reads `version` from the request for a config version 1 flag.
+ # It reads `version` from the written data for a config version 2 flag, so both carry it.
+ self._version_precondition(feature_flag, version)
+ feature_flag = update_flag(
+ feature_flag,
+ {"active": active, "version": version},
+ team=self.team,
+ user=request.user,
+ request=FlagVersionCheckedWriteRequest(request, version=version),
+ )
return self._lifecycle_response(feature_flag)
- @action(
- methods=["POST"],
- detail=True,
- required_scopes=["feature_flag:write"],
- request=None,
+ @validated_request(
+ FeatureFlagSetActiveRequestSerializer,
responses=flag_lifecycle_responses(
"The flag is archived, one of the flags it depends on is disabled, a flag it depends "
- "on uses an unsupported configuration format, or a cohort it targets has been deleted."
+ "on uses an unsupported configuration format, a cohort it targets has been deleted, or "
+ "the flag uses config version 2 and no `version` was sent.",
+ version_precondition=True,
),
)
- def enable(self, request: request.Request, **kwargs) -> Response:
+ @action(methods=["POST"], detail=True, required_scopes=["feature_flag:write"])
+ def enable(self, request: ValidatedRequest, **kwargs) -> Response:
"""
Enable a feature flag.
@@ -4462,17 +4501,21 @@ class FeatureFlagViewSet(
flag whose own flag dependencies are disabled or use an unsupported configuration
format is also refused, as is a flag whose release conditions target a deleted cohort.
An already-enabled flag is returned unchanged.
+
+ Send the `version` your last read returned. A flag whose `filters.version` is 2 requires
+ it, and for any flag a change after that version is refused with 409.
"""
return self._set_active(request, active=True)
- @action(
- methods=["POST"],
- detail=True,
- required_scopes=["feature_flag:write"],
- request=None,
- responses=flag_lifecycle_responses("Another active flag depends on this one."),
+ @validated_request(
+ FeatureFlagSetActiveRequestSerializer,
+ responses=flag_lifecycle_responses(
+ "Another active flag depends on this one, or the flag uses config version 2 and no `version` was sent.",
+ version_precondition=True,
+ ),
)
- def disable(self, request: request.Request, **kwargs) -> Response:
+ @action(methods=["POST"], detail=True, required_scopes=["feature_flag:write"])
+ def disable(self, request: ValidatedRequest, **kwargs) -> Response:
"""
Disable a feature flag.
@@ -4482,6 +4525,9 @@ class FeatureFlagViewSet(
A disabled flag stops evaluating for every consumer, including a linked experiment or a
session replay setting. Read the full definition first to report that impact.
+
+ Send the `version` your last read returned. A flag whose `filters.version` is 2 requires
+ it, and for any flag a change after that version is refused with 409.
"""
return self._set_active(request, active=False)
@@ -4549,12 +4595,12 @@ class FeatureFlagViewSet(
)
return self._lifecycle_response(updated)
- # Rollout actions. Unlike the state actions above, these carry a value, so they close the
+ # Rollout actions. These require `version`, so, like a toggle that sends it, 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:
+ def _version_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.
@@ -4585,7 +4631,7 @@ class FeatureFlagViewSet(
# 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)
+ self._version_precondition(feature_flag, version)
with transaction.atomic():
# The checks above ran against the instance loaded before the lock, which is a fast
@@ -4603,7 +4649,7 @@ class FeatureFlagViewSet(
rejection = self._deleted_flag_rejection(locked_flag, deleted_hint)
if rejection is not None:
return rejection
- self._rollout_precondition(locked_flag, version)
+ self._version_precondition(locked_flag, version)
current_filters = locked_flag.get_filters()
new_filters = transform(current_filters)
@@ -4629,7 +4675,7 @@ class FeatureFlagViewSet(
{"filters": filters},
team=self.team,
user=request.user,
- request=FlagRolloutWriteRequest(request, version=version),
+ request=FlagVersionCheckedWriteRequest(request, version=version),
)
@validated_request(
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py
index 25479951a2ff..f148e6c6ad82 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py
@@ -211,6 +211,25 @@ class TestV2SafetyWritesNeedNoAdmission(V2UpdateTestCase):
flag.refresh_from_db()
assert (flag.active, flag.archived, flag.version) == (active, False, 3)
+ def test_the_disable_action_takes_the_row_version(self) -> None:
+ flag = self.flag(active=True)
+ assert self.post_action(flag, "disable", {"version": 2}).status_code == status.HTTP_409_CONFLICT
+ response = self.post_action(flag, "disable", {"version": 3})
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ flag.refresh_from_db()
+ assert (flag.active, flag.version) == (False, 4)
+ (entry,) = self.activity(flag)
+ assert self.changed_fields(entry) == {"active", "version"}
+
+ def test_the_enable_action_still_needs_admission(self) -> None:
+ flag = self.flag(active=False)
+ response = self.post_action(flag, "enable", {"version": 3})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["code"] == "unsupported_config_version"
+ flag.refresh_from_db()
+ assert (flag.active, flag.version) == (False, 3)
+ assert self.activity(flag) == []
+
class TestAdmittedV2Creation(AdmittedV2TestCase):
def setUp(self) -> None:
@@ -398,6 +417,22 @@ class TestAdmittedV2Enabling(AdmittedV2TestCase):
assert (flag.active, flag.version) == (False, 5)
assert [entry.activity for entry in self.activity(flag)] == ["updated", "updated"]
+ def test_the_toggle_actions_need_and_check_the_row_version(self) -> None:
+ flag = self.flag(active=False)
+ missing = self.post_action(flag, "enable")
+ assert missing.status_code == status.HTTP_400_BAD_REQUEST
+ assert (missing.json()["attr"], missing.json()["code"]) == ("version", "required")
+ response = self.post_action(flag, "enable", {"version": 3})
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert (response.json()["active"], response.json()["version"]) == (True, 4)
+ stale = self.post_action(flag, "disable", {"version": 3})
+ assert stale.status_code == status.HTTP_409_CONFLICT
+ assert stale.json()["detail"] == flag_version_conflict_message(3, 4)
+ assert self.post_action(flag, "disable", {"version": 4}).status_code == status.HTTP_200_OK
+ flag.refresh_from_db()
+ assert (flag.active, flag.version, flag.filters) == (False, 5, config(targeted(), rollout()))
+ assert [entry.activity for entry in self.activity(flag)] == ["updated", "updated"]
+
def test_enabling_reports_a_disabled_flag_the_rule_targeting_depends_on(self) -> None:
dependency = FeatureFlag.objects.create(team=self.team, key="base-flag", active=False, created_by=self.user)
# Stored past the validator, which does not admit flag targeting yet. The non-integer key is skipped.
@@ -527,3 +562,53 @@ class TestV2PilotLifecycle(AdmittedV2TestCase):
history = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/versions/1/")
assert history.status_code == status.HTTP_200_OK, history.json()
assert (history.json()["filters"]["rules"], history.json()["active"]) == (stored["rules"], False)
+
+
+V1_FILTERS = {"groups": [{"properties": [], "rollout_percentage": 100}]}
+V1_MULTIVARIATE_FILTERS = {
+ **V1_FILTERS,
+ "multivariate": {
+ "variants": [{"key": "control", "rollout_percentage": 50}, {"key": "test", "rollout_percentage": 50}]
+ },
+ "payloads": {"test": '{"color": "blue"}'},
+}
+
+
+class TestV1FiltersOnAV2Flag(V2UpdateTestCase):
+ """Version 1 filters never convert a v2 flag back, whether or not the project may write v2."""
+
+ @parameterized.expand(
+ [
+ (f"{shape}_{method}_{'admitted' if admitted else 'closed'}", filters, method, admitted)
+ for shape, filters in [
+ ("groups", V1_FILTERS),
+ ("multivariate", V1_MULTIVARIATE_FILTERS),
+ ("explicit_version_1", {"version": 1, **V1_FILTERS}),
+ ]
+ for method in ["patch", "put"]
+ for admitted in [False, True]
+ ]
+ )
+ def test_the_write_is_refused_with_its_own_code(
+ self, _name: str, filters: dict, method: str, admitted: bool
+ ) -> None:
+ flag = self.flag(active=True)
+ stored = flag.filters
+ with admit_v2(self.team.id if admitted else -1):
+ response = self.patch_flag(flag, {"key": flag.key, "version": 3, "filters": filters}, method=method)
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ body = response.json()
+ assert (body["attr"], body["code"]) == ("filters", "v1_filters_on_v2_flag")
+ assert "config version 2" in body["detail"]
+ assert ("version 2 document" in body["detail"]) is admitted
+ flag.refresh_from_db()
+ assert (flag.filters, flag.version, flag.active) == (stored, 3, True)
+ assert self.activity(flag) == []
+
+ def test_the_facade_refuses_it_too(self) -> None:
+ flag = self.flag()
+ with admit_v2(self.team.id), self.assertRaises(ValidationError) as caught:
+ flag_facade.update_flag(flag, {"version": 3, "filters": V1_FILTERS}, team=self.team, user=self.user)
+ assert caught.exception.get_codes() == {"filters": ["v1_filters_on_v2_flag"]}
+ flag.refresh_from_db()
+ assert flag.version == 3
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py
index eb6514511807..d281f3e35b0b 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py
@@ -149,6 +149,10 @@ class V2UpdateTestCase(APIBaseTest):
f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", data, format="json"
)
+ def post_action(self, flag: FeatureFlag, action: str, data: dict | None = None):
+ url = f"/api/projects/{self.team.id}/feature_flags/{flag.id}/{action}/"
+ return self.client.post(url, data or {}, format="json")
+
def post_flag(self, data: dict):
return self.client.post(f"/api/projects/{self.team.id}/feature_flags/", data, format="json")
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_version.py b/products/feature_flags/backend/api/test/test_feature_flag_config_version.py
index faf67818453f..e07813ee91f9 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag_config_version.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_version.py
@@ -37,7 +37,10 @@ class TestFeatureFlagConfigVersionValidation(SimpleTestCase):
with override_settings(FEATURE_FLAG_FILTERS_ENFORCED_RULES=enforced_rules):
serializer = FeatureFlagSerializer(flag, data=data, partial=True)
assert not serializer.is_valid()
- assert serializer.errors["filters"][0].code == "unsupported_config_version"
+ # Version 1 filters sent to a stored v2 row get their own code.
+ v1_onto_v2 = version == 2 and bool(data.get("filters"))
+ expected = "v1_filters_on_v2_flag" if v1_onto_v2 else "unsupported_config_version"
+ assert serializer.errors["filters"][0].code == expected
@parameterized.expand(
[
@@ -56,24 +59,29 @@ class TestFeatureFlagConfigVersionValidation(SimpleTestCase):
assert not serializer.is_valid()
assert serializer.errors["filters"][0].code == "reserved_config_version"
- def test_incoming_version_error_precedes_stored_format_error(self) -> None:
+ @parameterized.expand(
+ [("unsupported_stored", 3, "reserved_config_version"), ("v2_stored", 2, "v1_filters_on_v2_flag")]
+ )
+ def test_incoming_version_error_precedes_stored_format_error(self, _name: str, stored: int, code: str) -> None:
serializer = FeatureFlagSerializer(
- FeatureFlag(filters={"version": 2}), data={"filters": {"version": 1}}, partial=True
+ FeatureFlag(filters={"version": stored}), data={"filters": {"version": 1}}, partial=True
)
assert not serializer.is_valid()
- assert serializer.errors["filters"][0].code == "reserved_config_version"
+ assert serializer.errors["filters"][0].code == code
@override_settings(FEATURE_FLAG_FILTERS_ENFORCED_RULES={"cross_field.variant_rollout_sum_not_100"})
class TestFeatureFlagConfigVersionWrites(APIBaseTest):
@parameterized.expand(
[
- ("patch", {}, None),
- ("patch", {"filters": {}}, "filters"),
- ("put", {"filters": {"groups": []}}, "filters"),
+ ("patch", {}, None, "unsupported_config_version"),
+ ("patch", {"filters": {}}, "filters", "unsupported_config_version"),
+ ("put", {"filters": {"groups": []}}, "filters", "v1_filters_on_v2_flag"),
]
)
- def test_unsupported_stored_config_is_not_rewritten(self, method: str, data: dict, attr: str | None) -> None:
+ def test_unsupported_stored_config_is_not_rewritten(
+ self, method: str, data: dict, attr: str | None, code: str
+ ) -> None:
filters = {"version": 2, "return_type": "boolean", "default_value": False, "rules": []}
flag = FeatureFlag.objects.create(team=self.team, key="stored-config", filters=filters, version=7)
response = getattr(self.client, method)(
@@ -82,7 +90,7 @@ class TestFeatureFlagConfigVersionWrites(APIBaseTest):
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert response.json()["code"] == "unsupported_config_version"
+ assert response.json()["code"] == code
assert response.json()["attr"] == attr
flag.refresh_from_db()
assert flag.filters == filters
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_lifecycle_actions.py b/products/feature_flags/backend/api/test/test_feature_flag_lifecycle_actions.py
index dfa2dfd98dd8..deb67a988cf7 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag_lifecycle_actions.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag_lifecycle_actions.py
@@ -8,10 +8,14 @@ from django.test import override_settings
from parameterized import parameterized
from rest_framework import status
+from posthog.constants import AvailableFeature
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
from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE, flag_payload_codec
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -112,10 +116,10 @@ class TestFeatureFlagLifecycleActions(APIBaseTest):
@parameterized.expand(STATE_CASES)
def test_action_ignores_a_caller_supplied_body(self, case, active, archived, expected_active, expected_archived):
# A caller-supplied stale targeting object cannot overwrite another edit, because
- # lifecycle actions ignore the request body. `version` and `original_flag` are
- # in the body because the flag UI sends both on every PATCH, so an agent porting a
- # PATCH call keeps them. Together they used to make the serializer discard the state
- # change and still return 200.
+ # lifecycle actions ignore the request body apart from `version`. `version` and
+ # `original_flag` are in the body because the flag UI sends both on every PATCH, so an
+ # agent porting a PATCH call keeps them. Together they used to make the serializer
+ # discard the state change and still return 200.
action = case.split("_")[0]
flag = self._flag(active=active, archived=archived)
@@ -127,7 +131,7 @@ class TestFeatureFlagLifecycleActions(APIBaseTest):
"key": "hijacked",
"active": not expected_active,
"archived": not expected_archived,
- "version": 999,
+ "version": None,
"original_flag": {"active": expected_active, "archived": expected_archived},
},
)
@@ -139,15 +143,89 @@ class TestFeatureFlagLifecycleActions(APIBaseTest):
assert flag.active is expected_active
assert flag.archived is expected_archived
+ @parameterized.expand([("enable", False), ("disable", True)])
+ def test_toggle_refuses_a_stale_version_and_writes_nothing(self, action, active):
+ flag = self._flag(active=active)
+
+ response = self._act(flag, action, {"version": 0})
+
+ assert response.status_code == status.HTTP_409_CONFLICT, response.content
+ flag.refresh_from_db()
+ assert (flag.active, flag.version) == (active, 1)
+ assert not ActivityLog.objects.filter(scope="FeatureFlag", item_id=str(flag.id), activity="updated").exists()
+
+ @parameterized.expand([("enable", False), ("disable", True)])
+ def test_toggle_refuses_a_version_that_went_stale_after_the_action_checked_it(self, action, active):
+ # The action's early check passes, then another write lands before the row lock.
+ flag = self._flag(active=active)
+ original = FeatureFlagViewSet._version_precondition
+
+ def precondition(view, feature_flag, version):
+ original(view, feature_flag, version)
+ FeatureFlag.objects.filter(pk=flag.pk).update(version=2)
+
+ with patch.object(FeatureFlagViewSet, "_version_precondition", precondition):
+ response = self._act(flag, action, {"version": 1})
+
+ assert response.status_code == status.HTTP_409_CONFLICT, response.content
+ flag.refresh_from_db()
+ assert (flag.active, flag.version) == (active, 2)
+
+ @parameterized.expand([("enable", False, 1), ("disable", True, 1), ("enable", False, None)])
+ def test_toggle_accepts_the_current_or_a_null_version(self, action, active, version):
+ flag = self._flag(active=active)
+
+ response = self._act(flag, action, {"version": version})
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ flag.refresh_from_db()
+ assert (flag.active, flag.version) == (not active, 2)
+
+ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+ def test_approving_a_versioned_toggle_applies_it(self, _mock_enabled):
+ 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.disable",
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+ flag = self._flag(active=True)
+
+ response = self._act(flag, "disable", {"version": 1})
+
+ assert response.status_code == status.HTTP_409_CONFLICT, response.content
+ assert response.json()["code"] == "approval_required"
+ change_request = ChangeRequest.objects.get(team=self.team)
+ assert ChangeRequestService(change_request, self.user).approve().status == "applied"
+ flag.refresh_from_db()
+ assert (flag.active, flag.version, flag.filters) == (False, 2, TARGETING)
+
+ @parameterized.expand([("archive", True, False), ("unarchive", False, True)])
+ def test_archive_actions_ignore_a_stale_version(self, action, active, archived):
+ flag = self._flag(active=active, archived=archived)
+
+ response = self._act(flag, action, {"version": 0})
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ flag.refresh_from_db()
+ assert flag.archived is not archived
+
@parameterized.expand(STATE_CASES)
def test_repeating_an_action_writes_nothing(self, case, active, archived, _expected_active, _expected_archived):
action = case.split("_")[0]
flag = self._flag(active=active, archived=archived)
- first = self._act(flag, action)
+ read_version = {"version": flag.version}
+ first = self._act(flag, action, read_version)
assert first.status_code == status.HTTP_200_OK, first.content
- second = self._act(flag, action)
+ second = self._act(flag, action, read_version)
assert second.status_code == status.HTTP_200_OK, second.content
assert second.json()["version"] == first.json()["version"]
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.py
index dcfb9711fd7e..0be37ccf4a16 100644
--- 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.py
@@ -22,7 +22,7 @@ from products.feature_flags.backend.api.feature_flag import (
FlagActionErrorSerializer,
FlagApprovalConflictSerializer,
FlagDeletedRejectionSerializer,
- FlagRolloutWriteRequest,
+ FlagVersionCheckedWriteRequest,
)
from products.feature_flags.backend.facade.api import update_flag
from products.feature_flags.backend.models.feature_flag import FeatureFlag
@@ -344,7 +344,8 @@ class TestFeatureFlagRolloutActions(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
assert response.json()["code"] == "unsupported_config_version"
flag.refresh_from_db()
- assert flag.filters == v2_filters
+ assert (flag.filters, flag.version) == (v2_filters, 1)
+ assert not ActivityLog.objects.filter(scope="FeatureFlag", item_id=str(flag.id), activity="updated").exists()
@parameterized.expand(ROLLOUT_ACTIONS)
def test_rollout_action_requires_the_feature_flag_write_scope(self, action, body):
@@ -464,7 +465,7 @@ class TestFeatureFlagRolloutActions(APIBaseTest):
# 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
+ original = FeatureFlagViewSet._version_precondition
fired: list[bool] = []
def precondition(view, feature_flag, version):
@@ -473,7 +474,7 @@ class TestFeatureFlagRolloutActions(APIBaseTest):
fired.append(True)
FeatureFlag.objects.filter(pk=flag.pk).update(deleted=True)
- with patch.object(FeatureFlagViewSet, "_rollout_precondition", precondition):
+ with patch.object(FeatureFlagViewSet, "_version_precondition", precondition):
response = self._act(
flag,
"set_release_condition_rollout",
@@ -491,7 +492,7 @@ class TestFeatureFlagRolloutActions(APIBaseTest):
# already moved on; the decision has to be made against the locked row.
flag = self._flag()
stale_version = flag.version
- original = FeatureFlagViewSet._rollout_precondition
+ original = FeatureFlagViewSet._version_precondition
fired: list[bool] = []
def precondition(view, feature_flag, version):
@@ -500,7 +501,7 @@ class TestFeatureFlagRolloutActions(APIBaseTest):
fired.append(True)
FeatureFlag.objects.filter(pk=flag.pk).update(version=(flag.version or 0) + 1)
- with patch.object(FeatureFlagViewSet, "_rollout_precondition", precondition):
+ with patch.object(FeatureFlagViewSet, "_version_precondition", precondition):
response = self._act(
flag,
"set_release_condition_rollout",
@@ -528,7 +529,7 @@ class TestFeatureFlagRolloutActions(APIBaseTest):
{"filters": {**TARGETING, "groups": [{"properties": [], "rollout_percentage": 100}]}},
team=self.team,
user=self.user,
- request=FlagRolloutWriteRequest(drf_request, version=(flag.version or 0) + 5),
+ request=FlagVersionCheckedWriteRequest(drf_request, version=(flag.version or 0) + 5),
)
flag.refresh_from_db()
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index d021922fd435..ff9636910323 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -1652,6 +1652,17 @@ export interface DependentFlagApi {
name: string
}
+export interface FeatureFlagSetActiveRequestApi {
+ /**
+ * The `version` from your most recent read of this flag. Required when the flag's `filters.version` is 2, optional otherwise. When sent, the change is refused with 409 if anyone else changed the flag after that version. Null is the same as leaving it out.
+ * @minimum 0
+ * @nullable
+ */
+ version?: number | null
+}
+
+export type FeatureFlagActionConflictApi = FlagActionErrorApi | FlagApprovalConflictApi
+
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.
@@ -1666,8 +1677,6 @@ export interface FeatureFlagRollOutToEveryoneRequestApi {
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`.
diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.ts
index 0b66403c8588..db8469b33934 100644
--- a/products/feature_flags/frontend/generated/api.ts
+++ b/products/feature_flags/frontend/generated/api.ts
@@ -29,6 +29,7 @@ import type {
FeatureFlagRequestUsageListParams,
FeatureFlagRequestUsageResponseApi,
FeatureFlagRollOutToEveryoneRequestApi,
+ FeatureFlagSetActiveRequestApi,
FeatureFlagSetReleaseConditionRolloutRequestApi,
FeatureFlagStatusResponseApi,
FeatureFlagTestEvaluationRequestApi,
@@ -826,15 +827,21 @@ export const getFeatureFlagsDisableCreateUrl = (projectId: string, id: number) =
*
* A disabled flag stops evaluating for every consumer, including a linked experiment or a
* session replay setting. Read the full definition first to report that impact.
+ *
+ * Send the `version` your last read returned. A flag whose `filters.version` is 2 requires
+ * it, and for any flag a change after that version is refused with 409.
*/
export const featureFlagsDisableCreate = async (
projectId: string,
id: number,
+ featureFlagSetActiveRequestApi?: FeatureFlagSetActiveRequestApi,
options?: RequestInit
): Promise<FeatureFlagApi> => {
return apiMutator<FeatureFlagApi>(getFeatureFlagsDisableCreateUrl(projectId, id), {
...options,
method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(featureFlagSetActiveRequestApi),
})
}
@@ -850,15 +857,21 @@ export const getFeatureFlagsEnableCreateUrl = (projectId: string, id: number) =>
* flag whose own flag dependencies are disabled or use an unsupported configuration
* format is also refused, as is a flag whose release conditions target a deleted cohort.
* An already-enabled flag is returned unchanged.
+ *
+ * Send the `version` your last read returned. A flag whose `filters.version` is 2 requires
+ * it, and for any flag a change after that version is refused with 409.
*/
export const featureFlagsEnableCreate = async (
projectId: string,
id: number,
+ featureFlagSetActiveRequestApi?: FeatureFlagSetActiveRequestApi,
options?: RequestInit
): Promise<FeatureFlagApi> => {
return apiMutator<FeatureFlagApi>(getFeatureFlagsEnableCreateUrl(projectId, id), {
...options,
method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(featureFlagSetActiveRequestApi),
})
}
diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.ts
index e0f2c59e809b..1cfaaddc0851 100644
--- a/products/feature_flags/frontend/generated/api.zod.ts
+++ b/products/feature_flags/frontend/generated/api.zod.ts
@@ -1038,6 +1038,55 @@ export const FeatureFlagsPartialUpdateBody = /* @__PURE__ */ zod.object({
),
})
+/**
+ * Disable a feature flag.
+ *
+ * Sets `active` to false and changes nothing else. Targeting, variants, payloads, tags and
+ * archived state are left as they are. Refused when other active flags depend on this one.
+ * An already-disabled flag is returned unchanged.
+ *
+ * A disabled flag stops evaluating for every consumer, including a linked experiment or a
+ * session replay setting. Read the full definition first to report that impact.
+ *
+ * Send the `version` your last read returned. A flag whose `filters.version` is 2 requires
+ * it, and for any flag a change after that version is refused with 409.
+ */
+export const featureFlagsDisableCreateBodyVersionMin = 0
+
+export const FeatureFlagsDisableCreateBody = /* @__PURE__ */ zod.object({
+ version: zod
+ .number()
+ .min(featureFlagsDisableCreateBodyVersionMin)
+ .nullish()
+ .describe(
+ "The `version` from your most recent read of this flag. Required when the flag's `filters.version` is 2, optional otherwise. When sent, the change is refused with 409 if anyone else changed the flag after that version. Null is the same as leaving it out."
+ ),
+})
+
+/**
+ * Enable a feature flag.
+ *
+ * Sets `active` to true and changes nothing else. Targeting, variants, payloads, tags and
+ * archived state are left as they are. An archived flag is refused: unarchive it first. A
+ * flag whose own flag dependencies are disabled or use an unsupported configuration
+ * format is also refused, as is a flag whose release conditions target a deleted cohort.
+ * An already-enabled flag is returned unchanged.
+ *
+ * Send the `version` your last read returned. A flag whose `filters.version` is 2 requires
+ * it, and for any flag a change after that version is refused with 409.
+ */
+export const featureFlagsEnableCreateBodyVersionMin = 0
+
+export const FeatureFlagsEnableCreateBody = /* @__PURE__ */ zod.object({
+ version: zod
+ .number()
+ .min(featureFlagsEnableCreateBodyVersionMin)
+ .nullish()
+ .describe(
+ "The `version` from your most recent read of this flag. Required when the flag's `filters.version` is 2, optional otherwise. When sent, the change is refused with 409 if anyone else changed the flag after that version. Null is the same as leaving it out."
+ ),
+})
+
/**
* Serve a feature flag to every user.
*
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index d688bfbabcde..261f001017cc 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -165,7 +165,12 @@ tools:
Sets `active` to false and changes nothing else. This tool never accepts or replaces the `filters` object,
- so targeting, rollout percentages, variants and payloads cannot change. There is no request body.
+ so targeting, rollout percentages, variants and payloads cannot change.
+
+
+ Pass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag
+ first and send its current `version`; never guess it. With `version`, a change made after that read returns
+ 409: read the flag again and decide against its current state.
A disabled flag stops evaluating everywhere, so every caller falls back to its own default. Tell the user
@@ -218,8 +223,13 @@ tools:
Sets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so
- targeting, rollout percentages, variants and payloads cannot change. There is no request body. To change who
- the flag is served to, use `update-feature-flag`.
+ targeting, rollout percentages, variants and payloads cannot change. To change who the flag is served to,
+ use `update-feature-flag`.
+
+
+ Pass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag
+ first and send its current `version`; never guess it. With `version`, a change made after that read returns
+ 409: read the flag again and decide against its current state.
Returns 400 when the flag is archived (call `feature-flag-unarchive` first), when a flag it depends on is
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 66b94a855ad5..dd99e5aa8b51 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -6692,7 +6692,7 @@
}
},
"feature-flag-disable": {
- "description": "Turn a feature flag off. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to false and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body.\n\nA disabled flag stops evaluating everywhere, so every caller falls back to its own default. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition. `feature-flag-get-definition-by-key` already returns it, and `feature-flag-get-definition` returns it by ID.\n\nReturns 400 when other active flags depend on this one; `feature-flags-dependent-flags-retrieve` lists them. Returns 409 when an approval policy gates disabling. Disabling an already-disabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags, and an archived flag is already disabled. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag off at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
+ "description": "Turn a feature flag off. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to false and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change.\n\nPass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag first and send its current `version`; never guess it. With `version`, a change made after that read returns 409: read the flag again and decide against its current state.\n\nA disabled flag stops evaluating everywhere, so every caller falls back to its own default. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition. `feature-flag-get-definition-by-key` already returns it, and `feature-flag-get-definition` returns it by ID.\n\nReturns 400 when other active flags depend on this one; `feature-flags-dependent-flags-retrieve` lists them. Returns 409 when an approval policy gates disabling. Disabling an already-disabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags, and an archived flag is already disabled. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag off at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
"category": "Feature flags",
"feature": "flags",
"summary": "Disable feature flag",
@@ -6707,7 +6707,7 @@
}
},
"feature-flag-enable": {
- "description": "Turn a feature flag on. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body. To change who the flag is served to, use `update-feature-flag`.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first), when a flag it depends on is disabled, or when a release condition targets a deleted cohort (remove that condition with `update-feature-flag`). Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
+ "description": "Turn a feature flag on. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. To change who the flag is served to, use `update-feature-flag`.\n\nPass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag first and send its current `version`; never guess it. With `version`, a change made after that read returns 409: read the flag again and decide against its current state.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first), when a flag it depends on is disabled, or when a release condition targets a deleted cohort (remove that condition with `update-feature-flag`). Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
"category": "Feature flags",
"feature": "flags",
"summary": "Enable feature flag",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index d772a8208b74..b39f29febc68 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -6850,7 +6850,7 @@
}
},
"feature-flag-disable": {
- "description": "Turn a feature flag off. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to false and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body.\n\nA disabled flag stops evaluating everywhere, so every caller falls back to its own default. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition. `feature-flag-get-definition-by-key` already returns it, and `feature-flag-get-definition` returns it by ID.\n\nReturns 400 when other active flags depend on this one; `feature-flags-dependent-flags-retrieve` lists them. Returns 409 when an approval policy gates disabling. Disabling an already-disabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags, and an archived flag is already disabled. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag off at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
+ "description": "Turn a feature flag off. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to false and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change.\n\nPass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag first and send its current `version`; never guess it. With `version`, a change made after that read returns 409: read the flag again and decide against its current state.\n\nA disabled flag stops evaluating everywhere, so every caller falls back to its own default. Tell the user what else this affects: linked experiments, surveys, early access features and session replay settings all appear in the flag's full definition. `feature-flag-get-definition-by-key` already returns it, and `feature-flag-get-definition` returns it by ID.\n\nReturns 400 when other active flags depend on this one; `feature-flags-dependent-flags-retrieve` lists them. Returns 409 when an approval policy gates disabling. Disabling an already-disabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags, and an archived flag is already disabled. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag off at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
"category": "Feature flags",
"feature": "flags",
"summary": "Disable feature flag",
@@ -6865,7 +6865,7 @@
}
},
"feature-flag-enable": {
- "description": "Turn a feature flag on. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. There is no request body. To change who the flag is served to, use `update-feature-flag`.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first), when a flag it depends on is disabled, or when a release condition targets a deleted cohort (remove that condition with `update-feature-flag`). Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
+ "description": "Turn a feature flag on. Requires the flag's numeric ID; use `feature-flag-get-definition-by-key` to get it from a key, or `feature-flag-get-all` to search by key or name.\n\nSets `active` to true and changes nothing else. This tool never accepts or replaces the `filters` object, so targeting, rollout percentages, variants and payloads cannot change. To change who the flag is served to, use `update-feature-flag`.\n\nPass `version` from the flag you read. A flag whose `filters.version` is 2 requires it, so read the flag first and send its current `version`; never guess it. With `version`, a change made after that read returns 409: read the flag again and decide against its current state.\n\nReturns 400 when the flag is archived (call `feature-flag-unarchive` first), when a flag it depends on is disabled, or when a release condition targets a deleted cohort (remove that condition with `update-feature-flag`). Returns 409 when an approval policy gates enabling. Enabling an already-enabled flag succeeds and changes nothing, so retrying is safe.\n\n`feature-flag-get-definition-by-key` also finds archived flags. `feature-flag-get-all` hides archived flags unless you pass `{\"archived\":\"true\"}`.\n\nTo turn the flag on at a future time instead, use `scheduled-changes-create` with the `update_status` operation.",
"category": "Feature flags",
"feature": "flags",
"summary": "Enable feature flag",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b07ae1e7212e..758a27d58520 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -54654,6 +54654,15 @@ export namespace Schemas {
is_multivariate: boolean;
}
+ export interface FeatureFlagSetActiveRequest {
+ /**
+ * The `version` from your most recent read of this flag. Required when the flag's `filters.version` is 2, optional otherwise. When sent, the change is refused with 409 if anyone else changed the flag after that version. Null is the same as leaving it out.
+ * @minimum 0
+ * @nullable
+ */
+ version?: number | null;
+ }
+
export interface FeatureFlagSetReleaseConditionRolloutRequest {
/**
* Zero-based position of the release condition in `filters.groups`, counted from the read that produced `version`.
diff --git a/services/mcp/src/generated/feature_flags/api.ts b/services/mcp/src/generated/feature_flags/api.ts
index a9a55b243e66..cc26130de34b 100644
--- a/services/mcp/src/generated/feature_flags/api.ts
+++ b/services/mcp/src/generated/feature_flags/api.ts
@@ -984,6 +984,9 @@ export const FeatureFlagsDependentFlagsListParams = () => zod.object({
*
* A disabled flag stops evaluating for every consumer, including a linked experiment or a
* session replay setting. Read the full definition first to report that impact.
+ *
+ * Send the `version` your last read returned. A flag whose `filters.version` is 2 requires
+ * it, and for any flag a change after that version is refused with 409.
*/
export const FeatureFlagsDisableCreateParams = () => zod.object({
id: zod.number().describe('A unique integer value identifying this feature flag.'),
@@ -994,6 +997,18 @@ export const FeatureFlagsDisableCreateParams = () => zod.object({
),
})
+export const featureFlagsDisableCreateBodyVersionMin = 0
+
+export const FeatureFlagsDisableCreateBody = () => zod.object({
+ version: zod
+ .number()
+ .min(featureFlagsDisableCreateBodyVersionMin)
+ .nullish()
+ .describe(
+ "The `version` from your most recent read of this flag. Required when the flag's `filters.version` is 2, optional otherwise. When sent, the change is refused with 409 if anyone else changed the flag after that version. Null is the same as leaving it out."
+ ),
+})
+
/**
* Enable a feature flag.
*
@@ -1002,6 +1017,9 @@ export const FeatureFlagsDisableCreateParams = () => zod.object({
* flag whose own flag dependencies are disabled or use an unsupported configuration
* format is also refused, as is a flag whose release conditions target a deleted cohort.
* An already-enabled flag is returned unchanged.
+ *
+ * Send the `version` your last read returned. A flag whose `filters.version` is 2 requires
+ * it, and for any flag a change after that version is refused with 409.
*/
export const FeatureFlagsEnableCreateParams = () => zod.object({
id: zod.number().describe('A unique integer value identifying this feature flag.'),
@@ -1012,6 +1030,18 @@ export const FeatureFlagsEnableCreateParams = () => zod.object({
),
})
+export const featureFlagsEnableCreateBodyVersionMin = 0
+
+export const FeatureFlagsEnableCreateBody = () => zod.object({
+ version: zod
+ .number()
+ .min(featureFlagsEnableCreateBodyVersionMin)
+ .nullish()
+ .describe(
+ "The `version` from your most recent read of this flag. Required when the flag's `filters.version` is 2, optional otherwise. When sent, the change is refused with 409 if anyone else changed the flag after that version. Null is the same as leaving it out."
+ ),
+})
+
/**
* Serve a feature flag to every user.
*
diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.ts
index bdec76234877..bf9e63895851 100644
--- a/services/mcp/src/tools/generated/feature_flags.ts
+++ b/services/mcp/src/tools/generated/feature_flags.ts
@@ -148,12 +148,13 @@ const featureFlagArchive = (): ToolBase<
})
const FeatureFlagDisableSchema = () => {
+ const FeatureFlagsDisableCreateBody = orvalSchemas.FeatureFlagsDisableCreateBody()
const FeatureFlagsDisableCreateParams = orvalSchemas.FeatureFlagsDisableCreateParams()
return z.preprocess(
normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),
- FeatureFlagsDisableCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, FeatureFlagsDisableCreateParams.shape['id']),
- })
+ FeatureFlagsDisableCreateParams.omit({ project_id: true })
+ .extend(FeatureFlagsDisableCreateBody.shape)
+ .extend({ id: z.preprocess(castStringToInt, FeatureFlagsDisableCreateParams.shape['id']) })
)
}
@@ -165,9 +166,14 @@ const featureFlagDisable = (): ToolBase<
schema: FeatureFlagDisableSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof FeatureFlagDisableSchema>>) => {
const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.version !== undefined) {
+ body['version'] = params.version
+ }
const result = await context.api.request<Schemas.FeatureFlag>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/disable/`,
+ body,
})
const filtered = pickResponseFields(result, [
'id',
@@ -182,12 +188,13 @@ const featureFlagDisable = (): ToolBase<
})
const FeatureFlagEnableSchema = () => {
+ const FeatureFlagsEnableCreateBody = orvalSchemas.FeatureFlagsEnableCreateBody()
const FeatureFlagsEnableCreateParams = orvalSchemas.FeatureFlagsEnableCreateParams()
return z.preprocess(
normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),
- FeatureFlagsEnableCreateParams.omit({ project_id: true }).extend({
- id: z.preprocess(castStringToInt, FeatureFlagsEnableCreateParams.shape['id']),
- })
+ FeatureFlagsEnableCreateParams.omit({ project_id: true })
+ .extend(FeatureFlagsEnableCreateBody.shape)
+ .extend({ id: z.preprocess(castStringToInt, FeatureFlagsEnableCreateParams.shape['id']) })
)
}
@@ -199,9 +206,14 @@ const featureFlagEnable = (): ToolBase<
schema: FeatureFlagEnableSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof FeatureFlagEnableSchema>>) => {
const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.version !== undefined) {
+ body['version'] = params.version
+ }
const result = await context.api.request<Schemas.FeatureFlag>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/feature_flags/${encodeURIComponent(String(params.id))}/enable/`,
+ body,
})
const filtered = pickResponseFields(result, [
'id',
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-disable.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-disable.json
index 88cc27e940e9..bb4ec461de69 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-disable.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-disable.json
@@ -4,6 +4,18 @@
"id": {
"description": "A unique integer value identifying this feature flag.",
"type": "number"
+ },
+ "version": {
+ "anyOf": [
+ {
+ "minimum": 0,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The `version` from your most recent read of this flag. Required when the flag's `filters.version` is 2, optional otherwise. When sent, the change is refused with 409 if anyone else changed the flag after that version. Null is the same as leaving it out."
}
},
"required": ["id"],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-enable.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-enable.json
index 88cc27e940e9..bb4ec461de69 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-enable.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/feature-flag-enable.json
@@ -4,6 +4,18 @@
"id": {
"description": "A unique integer value identifying this feature flag.",
"type": "number"
+ },
+ "version": {
+ "anyOf": [
+ {
+ "minimum": 0,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "The `version` from your most recent read of this flag. Required when the flag's `filters.version` is 2, optional otherwise. When sent, the change is refused with 409 if anyone else changed the flag after that version. Null is the same as leaving it out."
}
},
"required": ["id"],
diff --git a/services/mcp/tests/unit/feature-flag-lifecycle-tools.test.ts b/services/mcp/tests/unit/feature-flag-lifecycle-tools.test.ts
index 339cee85b7fd..ec652bcf2057 100644
--- a/services/mcp/tests/unit/feature-flag-lifecycle-tools.test.ts
+++ b/services/mcp/tests/unit/feature-flag-lifecycle-tools.test.ts
@@ -5,12 +5,26 @@ import { GENERATED_TOOL_MAP } from '@/tools/generated'
import { getToolDefinition } from '@/tools/toolDefinitions'
import type { Context } from '@/tools/types'
+// The toggles also take `version`: a flag on config version 2 refuses a toggle without it.
const LIFECYCLE_TOOLS = [
- 'feature-flag-enable',
- 'feature-flag-disable',
- 'feature-flag-archive',
- 'feature-flag-unarchive',
-]
+ {
+ name: 'feature-flag-enable',
+ case: 'versioned',
+ keys: ['id', 'version'],
+ input: { id: 42, version: 3 },
+ body: { version: 3 },
+ },
+ {
+ name: 'feature-flag-disable',
+ case: 'versioned',
+ keys: ['id', 'version'],
+ input: { id: 42, version: 3 },
+ body: { version: 3 },
+ },
+ { name: 'feature-flag-enable', case: 'unversioned', keys: ['id', 'version'], input: { id: 42 }, body: {} },
+ { name: 'feature-flag-archive', case: 'no body', keys: ['id'], input: { id: 42 }, body: undefined },
+ { name: 'feature-flag-unarchive', case: 'no body', keys: ['id'], input: { id: 42 }, body: undefined },
+] as const
const ROLLOUT_TOOLS = [
{
@@ -35,7 +49,7 @@ describe('feature flag lifecycle tools', () => {
// The snapshot test would also catch a `filters` param appearing here, but it is
// silenced by `vitest -u`. These assertions are not: the whole point of the lifecycle
// tools is that an agent cannot send targeting through them.
- it.each(LIFECYCLE_TOOLS)('%s takes the flag id and nothing else', (name) => {
+ it.each(LIFECYCLE_TOOLS)('$name takes the flag id and no targeting ($case)', ({ name, keys }) => {
const tool = GENERATED_TOOL_MAP[name]?.()
expect(tool, `${name} is missing from the generated tool map`).not.toBeUndefined()
@@ -44,24 +58,27 @@ describe('feature flag lifecycle tools', () => {
required?: string[]
}
- expect(Object.keys(schema.properties ?? {})).toEqual(['id'])
+ expect(Object.keys(schema.properties ?? {}).sort()).toEqual([...keys].sort())
expect(schema.required).toEqual(['id'])
})
- it.each(LIFECYCLE_TOOLS)('%s declares the write scope and a reversible, idempotent action', (name) => {
- const definition = getToolDefinition(name)
+ it.each(LIFECYCLE_TOOLS)(
+ '$name declares the write scope and a reversible, idempotent action ($case)',
+ ({ name }) => {
+ const definition = getToolDefinition(name)
- expect(definition.description).toContain('never accepts or replaces the `filters` object')
- expect(definition.required_scopes).toEqual(['feature_flag:write'])
- expect(definition.annotations?.readOnlyHint).toBe(false)
- expect(definition.annotations?.destructiveHint).toBe(false)
- expect(definition.annotations?.idempotentHint).toBe(true)
- })
+ expect(definition.description).toContain('never accepts or replaces the `filters` object')
+ expect(definition.required_scopes).toEqual(['feature_flag:write'])
+ expect(definition.annotations?.readOnlyHint).toBe(false)
+ expect(definition.annotations?.destructiveHint).toBe(false)
+ expect(definition.annotations?.idempotentHint).toBe(true)
+ }
+ )
// The tool name and the URL it posts to come from separate lines of the same YAML entry,
// so nothing above notices `feature-flag-enable` wired to `/disable/`. An agent asked to
// turn a flag on would turn it off.
- it.each(LIFECYCLE_TOOLS)('%s posts to its own endpoint', async (name) => {
+ it.each(LIFECYCLE_TOOLS)('$name posts to its own endpoint ($case)', async ({ name, input, body }) => {
const requestMock = vi.fn().mockResolvedValue({ id: 42 })
const context = {
api: {
@@ -71,11 +88,12 @@ describe('feature flag lifecycle tools', () => {
stateManager: { getProjectId: vi.fn().mockResolvedValue('17') },
} as unknown as Context
- await GENERATED_TOOL_MAP[name]!().handler(context, { id: 42 })
+ await GENERATED_TOOL_MAP[name]!().handler(context, input)
- expect(requestMock).toHaveBeenCalledWith({
+ expect(requestMock).toHaveBeenCalledExactlyOnceWith({
method: 'POST',
path: `/api/projects/17/feature_flags/42/${name.replace('feature-flag-', '')}/`,
+ ...(body === undefined ? {} : { body }),
})
})
it.each(ROLLOUT_TOOLS)('$name exposes only the intended fields and annotations', ({ name, keys, required }) => {