: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 enable, disable, archive and unarchive endpoints (#92133)
James Gill91f3eb870233
diff --git a/docs/internal/feature-flags/django-api-endpoints.md b/docs/internal/feature-flags/django-api-endpoints.mdindex 13d5464296ab..13c731d2a468 100644--- a/docs/internal/feature-flags/django-api-endpoints.md+++ b/docs/internal/feature-flags/django-api-endpoints.md@@ -60,6 +60,10 @@ Standard REST on `/api/projects/{id}/feature_flags/`. Hard `DELETE` is blocked| `GET` | `.../feature_flags/{pk}/status/` | Flag status (ACTIVE, STALE, DELETED, UNKNOWN) || `GET` | `.../feature_flags/{pk}/dependent_flags/` | Flags that depend on this flag || `POST` | `.../feature_flags/{pk}/dashboard/` | Create a usage dashboard for the flag |+| `POST` | `.../feature_flags/{pk}/enable/` | Set `active: true` only |+| `POST` | `.../feature_flags/{pk}/disable/` | Set `active: false` only |+| `POST` | `.../feature_flags/{pk}/archive/` | Set `archived: true`, disabling the flag in the same write when needed |+| `POST` | `.../feature_flags/{pk}/unarchive/` | Set `archived: false` only, leaving the flag disabled |### Organization endpoints@@ -78,6 +82,25 @@ A caller who can see a project but can't edit flags there gets a `failed` entryBoth actions **proxy to the Rust flags service** via `get_flags_from_service()` in `posthog/api/services/flags_service.py`. The Rust service URL defaults to `http://localhost:3001` (configured via `FEATURE_FLAGS_SERVICE_URL` in `posthog/settings/data_stores.py`).+### 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.+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.+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.++A flag already in the requested state is returned unchanged with no write at all, which keeps the actions safe to retry: no version bump and no activity entry for a change that did not happen.++`archive` matches the UI contract by disabling an enabled flag in the same write, because an archived flag must be disabled.+`unarchive` leaves the flag disabled; enabling it is a separate call.+It is the one action that cannot return a 409: every gated action declines a change that sets neither `active` nor `filters`, so an `archived`-only write never opens a change request.+### `create_static_cohort_for_flag`Creates a static cohort containing all users that match a flag's conditions. This is the **only remaining use** of the legacy Python flag matching code in `posthog/models/feature_flag/flag_matching.py`.diff --git a/products/approvals/backend/actions/feature_flags.py b/products/approvals/backend/actions/feature_flags.pyindex 7dd6c1cfd66d..5fce68cad4a4 100644--- a/products/approvals/backend/actions/feature_flags.py+++ b/products/approvals/backend/actions/feature_flags.py@@ -240,6 +240,11 @@ class FeatureFlagActionBase(BaseAction):if field in change:gated_changes[field] = change[field]+ # A caller exempt from the serializer's opportunistic filter cleanup stays exempt when+ # the approved change replays, otherwise approving a lifecycle action strips the legacy+ # keys the direct call preserves.+ skip_cleanup = bool(getattr(request, "skip_opportunistic_filter_cleanup", False))+if flag is None:# Create: no row yet — baseline is a disabled flag and the payload is the create body.return {@@ -249,6 +254,7 @@ class FeatureFlagActionBase(BaseAction):"gated_changes": gated_changes,"full_request_data": dict(change),"preconditions": {"version": None, "updated_at": None},+ "skip_opportunistic_filter_cleanup": skip_cleanup,}return {@@ -261,6 +267,7 @@ class FeatureFlagActionBase(BaseAction):"version": flag.version,"updated_at": flag.updated_at.isoformat() if flag.updated_at else None,},+ "skip_opportunistic_filter_cleanup": skip_cleanup,}@classmethod@@ -331,7 +338,10 @@ class EnableFeatureFlagAction(FeatureFlagActionBase):return {"description": f"Enable feature flag '{intent_data.get('flag_key', 'unknown')}'","before": intent_data.get("current_state", {}),- "after": intent_data.get("gated_changes", {}),+ # The applied change, not just the gated subset. Archiving an enabled flag writes+ # `archived` alongside `active`, and only `active` is gated — showing `gated_changes`+ # asked an approver to consent to a disable and then archived the flag too.+ "after": intent_data.get("full_request_data") or intent_data.get("gated_changes", {}),}@@ -348,7 +358,10 @@ class DisableFeatureFlagAction(FeatureFlagActionBase):return {"description": f"Disable feature flag '{intent_data.get('flag_key', 'unknown')}'","before": intent_data.get("current_state", {}),- "after": intent_data.get("gated_changes", {}),+ # The applied change, not just the gated subset. Archiving an enabled flag writes+ # `archived` alongside `active`, and only `active` is gated — showing `gated_changes`+ # asked an approver to consent to a disable and then archived the flag too.+ "after": intent_data.get("full_request_data") or intent_data.get("gated_changes", {}),}diff --git a/products/approvals/backend/services.py b/products/approvals/backend/services.pyindex 01c9274899ce..2cda98d41829 100644--- a/products/approvals/backend/services.py+++ b/products/approvals/backend/services.py@@ -26,10 +26,14 @@ logger = logging.getLogger(__name__)class RequestContext:- def __init__(self, method: str, user, data: dict):+ def __init__(self, method: str, user, data: dict, skip_opportunistic_filter_cleanup: bool = False):self.method = methodself.user = userself.data = data+ # Carried from the original request via the intent. A write that sent no filters must not+ # have them rewritten on replay either, and the exemption cannot be inferred here: an+ # approved ordinary update should still get the cleanup.+ self.skip_opportunistic_filter_cleanup = skip_opportunistic_filter_cleanupself.session: dict[str, Any] = {}self.META: dict[str, str] = {}self.headers: dict[str, str] = {}@@ -58,6 +62,7 @@ def apply_change_request(change_request: ChangeRequest, request=None) -> Any:method=change_request.intent.get("http_method", "PATCH"), # Stored in intent JSONuser=change_request.created_by, # Already in ChangeRequestdata=change_request.intent.get("gated_changes", change_request.intent), # Already in ChangeRequest+ skip_opportunistic_filter_cleanup=bool(change_request.intent.get("skip_opportunistic_filter_cleanup")),)# Build base context with common metadatadiff --git a/products/approvals/backend/tests/test_feature_flag_bypass_matrix.py b/products/approvals/backend/tests/test_feature_flag_bypass_matrix.pyindex 75c41b4d0efb..82947b9e9c16 100644--- a/products/approvals/backend/tests/test_feature_flag_bypass_matrix.py+++ b/products/approvals/backend/tests/test_feature_flag_bypass_matrix.py@@ -9,6 +9,7 @@ policy guards it.Each closed bypass below maps to a fix on this branch:- direct PATCH enable/disable/update -> the baseline control the gate exists for+ - lifecycle enable/disable/archive actions -> thin state endpoints routed through the same gate- experiment launch / pause / resume -> flag flips routed through FeatureFlagSerializer- experiment ship_variant -> variant rollout rewrite gated by feature_flag.update- web-experiment variant rollout edit -> update_experiment() variant write, gated by feature_flag.update@@ -33,11 +34,13 @@ from unittest.mock import patchfrom django.utils import timezone+from parameterized import parameterizedfrom rest_framework.test import APIRequestFactoryfrom posthog.constants import AvailableFeaturefrom posthog.tasks.process_scheduled_changes import process_scheduled_changes+from products.approvals.backend.actions.feature_flags import DisableFeatureFlagActionfrom products.approvals.backend.exceptions import ApprovalRequiredfrom products.approvals.backend.models import ApprovalPolicy, ChangeRequest, ChangeRequestStatefrom products.approvals.backend.services import ChangeRequestService@@ -127,6 +130,136 @@ class TestDirectAndCreateBypassMatrix(FeatureFlagBypassMatrixBase):assert flag.active is Trueself._assert_one_pending_zero_applied()+ @parameterized.expand(+ [+ ("enable", "feature_flag.enable", False),+ ("disable", "feature_flag.disable", True),+ # Archiving an enabled flag disables it in the same write, so the disable policy applies.+ ("archive", "feature_flag.disable", True),+ ]+ )+ # The class-level _is_approvals_enabled patch wraps the expanded case, so its mock arrives+ # before the parameterized arguments.+ def test_lifecycle_action_is_gated(self, _mock_enabled, action, action_key, active):+ _enable_policy_for(self, action_key)+ flag = self._flag(active=active)++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/{action}/", {}, format="json"+ )++ assert response.status_code == 409+ assert response.json().get("code") == "approval_required"+ flag.refresh_from_db()+ assert flag.active is active+ assert flag.archived is False+ self._assert_one_pending_zero_applied()++ @parameterized.expand([("disable", True), ("archive", True), ("enable", False)])+ def test_approved_lifecycle_change_preserves_legacy_filter_keys(self, _mock_enabled, action, active):+ # The direct path is exempt from the serializer's opportunistic legacy-key cleanup, but+ # the exemption has to survive into the replay. It travels in the intent: inferring it+ # at apply time would also exempt an approved ordinary update, which should still clean.+ _enable_policy_for(self, "feature_flag.disable" if active else "feature_flag.enable")+ legacy = {+ "groups": [{"properties": [], "rollout_percentage": 30}],+ "holdout_groups": [{"properties": [], "rollout_percentage": 5}],+ "super_groups": [{"properties": [], "rollout_percentage": 15}],+ }+ flag = FeatureFlag.objects.create(+ team=self.team, key=f"legacy-{action}", active=active, filters=dict(legacy), created_by=self.user+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/{action}/", {}, format="json"+ )+ assert response.status_code == 409+ cr = ChangeRequest.objects.get(id=response.json()["change_request_id"])+ assert ChangeRequestService(cr, self.user).approve().status == "applied"++ flag.refresh_from_db()+ assert flag.filters == legacy++ def test_archive_change_request_shows_the_approver_both_fields(self, _mock_enabled):+ # Only `active` is gated, so `gated_changes` carries only that. Approving applies+ # `archived` too, so a display built from the gated subset asked for consent to a+ # disable and then archived the flag.+ _enable_policy_for(self, "feature_flag.disable")+ flag = self._flag(active=True)++ response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/archive/", {}, format="json")+ assert response.status_code == 409++ cr = ChangeRequest.objects.get(id=response.json()["change_request_id"])+ after = DisableFeatureFlagAction.get_display_data(cr.intent)["after"]+ assert after == {"active": False, "archived": True}++ def test_approving_an_archive_applies_both_state_fields(self, _mock_enabled):+ # Archiving an enabled flag writes `archived` and `active` together, but only `active`+ # is what the disable policy gates. The change request has to carry both, or approving+ # it disables the flag and silently drops the archive the caller asked for.+ _enable_policy_for(self, "feature_flag.disable")+ flag = self._flag(active=True)++ response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/archive/", {}, format="json")+ assert response.status_code == 409+ cr = ChangeRequest.objects.get(id=response.json()["change_request_id"])++ assert ChangeRequestService(cr, self.user).approve().status == "applied"++ flag.refresh_from_db()+ assert flag.archived is True+ assert flag.active is False++ @parameterized.expand(+ [+ ("unarchive", "feature_flag.enable"),+ ("unarchive", "feature_flag.disable"),+ ("archive_disabled", "feature_flag.enable"),+ ("archive_disabled", "feature_flag.disable"),+ ]+ )+ def test_archived_only_lifecycle_write_is_not_gated(self, _mock_enabled, case, action_key):+ # An archived-only write changes neither `active` nor `filters`, so every gated action+ # declines it. These pass through with no change request even under an enable or disable+ # policy, and a regression that starts gating them would not fail the cases above.+ _enable_policy_for(self, action_key)+ action = "unarchive" if case == "unarchive" else "archive"+ flag = self._flag(active=False, key=f"matrix-{case}")+ if case == "unarchive":+ flag.archived = True+ flag.save()++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/{action}/", {}, format="json"+ )++ assert response.status_code == 200, response.content+ flag.refresh_from_db()+ assert flag.archived is (case != "unarchive")+ assert flag.active is False+ assert ChangeRequest.objects.count() == 0++ def test_lifecycle_actions_gate_each_flag_separately(self, _mock_enabled):+ # The gate keys duplicate detection on resource_id, which it derives from the request+ # method: it returns None for POST. A lifecycle action that reported itself as POST+ # stored NULL, so the second flag's request matched the first as a duplicate and was+ # dropped — the caller got a 409 naming someone else's change request and nothing was+ # queued for their flag.+ _enable_policy_for(self, "feature_flag.disable")+ first = self._flag(active=True, key="matrix-flag-one")+ second = self._flag(active=True, key="matrix-flag-two")++ for flag in (first, second):+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/disable/", {}, format="json"+ )+ assert response.status_code == 409+ assert response.json().get("code") == "approval_required"++ assert ChangeRequest.objects.filter(state=ChangeRequestState.PENDING).count() == 2+ assert {cr.resource_id for cr in ChangeRequest.objects.all()} == {str(first.id), str(second.id)}+def test_direct_patch_rollout_change_is_gated(self, _mock_enabled):_any_rollout_change_policy(self)flag = self._flag(active=True, rollout=20)diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex b529eb70d224..adfc77be2d78 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -40,7 +40,7 @@ from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedFieldfrom posthog.api.services.flags_service import RETRYABLE_FLAGS_SERVICE_EXCEPTIONS, get_flags_from_servicefrom posthog.api.shared import UserBasicSerializerfrom posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixin-from posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, ErrorResponseSerializer, action+from posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, ErrorResponseSerializer, ServiceRequest, actionfrom posthog.auth import (IDJagAccessTokenAuthentication,OAuthAccessTokenAuthentication,@@ -2184,12 +2184,15 @@ class FeatureFlagSerializer(payloads.pop("true", None)filters["payloads"] = payloads- # Opportunistically strip legacy keys on save.- 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")- }+ # 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)@@ -3032,6 +3035,92 @@ class BulkDeleteResponseSerializer(serializers.Serializer):)+def flag_lifecycle_responses(bad_request: str | None = None, *, approval_gated: bool = True) -> 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.++ ``approval_gated`` says the same thing about the 409. The gate on+ ``FeatureFlagSerializer.update`` only carries the enable, disable and update actions, and+ every one of them declines a change that sets neither ``active`` nor ``filters``. An+ action whose write is ``archived`` alone therefore never opens a change request.+ """+ responses: dict[int, Any] = {200: FeatureFlagSerializer}+ if approval_gated:+ responses[409] = OpenApiResponse(+ response=ErrorResponseSerializer,+ description="An approval policy gates this change. A change request was opened; the flag is unchanged.",+ )+ if bad_request is not None:+ responses[400] = OpenApiResponse(response=ErrorResponseSerializer, description=bad_request)+ return responses+++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.++ ``filters`` serializes the stored dict, so every surface returning a flag has to apply this+ or it hands out the raw ciphertext. A personal API key gets plaintext, anything else gets the+ redacted placeholder. Kept in one place because list, retrieve and the lifecycle actions+ each carried their own copy of the same rule, free to drift apart.+ """+ if not feature_flag_data.get("has_encrypted_payloads", False):+ return+ filters = feature_flag_data.get("filters")+ if not isinstance(filters, dict) or "payloads" not in filters:+ # `default_filters()` has no `payloads` key, so the flag can carry the boolean without+ # one. Indexing here raised after the write had committed, leaving the caller a 500 for+ # a change that had already landed and 500ing again on every retry.+ return+ filters["payloads"] = get_decrypted_flag_payloads_protected(request, filters["payloads"])+++class FlagLifecycleWriteRequest(ServiceRequest):+ """The request a flag lifecycle action hands to the flag facade.++ The actions are POST but they perform an update, and two things in the write path branch on+ the method. ``FeatureFlagSerializer.validate`` runs create-only validation on POST, so a team+ with ``require_evaluation_contexts`` set would get "at least one evaluation context is+ required to create a new feature flag" from a state flip. The approval gate's resource-id+ 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``+ 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.++ Everything else defers to the real request, so impersonation attribution and analytics behave+ as they do on any other flag write.+ """++ # A lifecycle write sends no filters, so the serializer's opportunistic legacy-key cleanup+ # would rewrite targeting this caller never touched. Declared here rather than inferred from+ # the request class, mirroring how `is_system` declares intent to the same serializer.+ skip_opportunistic_filter_cleanup = True++ def __init__(self, request: request.Request) -> None:+ self._request = request+ # ServiceRequest.__init__ is skipped on purpose. It assigns a narrow default to every+ # attribute it knows about, and an instance attribute shadows __getattr__, so anything+ # it sets can no longer reach the real request. Setting only what this shim controls+ # keeps the rest delegating, including fields ServiceRequest gains later.+ self.user = request.user+ self.is_system = False+ self.method = "PATCH"+ self.data: dict = {}+ # Not delegated: a request built without session middleware has no `session`, and+ # impersonation detection indexes into it.+ self.session = getattr(request, "session", {})++ def __getattr__(self, name: str) -> Any:+ # Reached only for attributes __init__ does not set, so `method` and `data` always+ # come from this shim rather than the real request.+ if name == "_request":+ raise AttributeError(name)+ return getattr(self._request, name)++# 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@@ -3277,11 +3366,7 @@ class FeatureFlagViewSet(if not is_evaluation_contexts_enabled:feature_flag["evaluation_contexts"] = []- # If flag is using encrypted payloads, replace them with redacted string or unencrypted value- if feature_flag.get("has_encrypted_payloads", False):- feature_flag["filters"]["payloads"] = get_decrypted_flag_payloads_protected(- request, feature_flag["filters"]["payloads"]- )+ apply_encrypted_payload_response_form(request, feature_flag)return response@@ -3294,18 +3379,19 @@ class FeatureFlagViewSet(if not is_evaluation_contexts_enabled:feature_flag_data["evaluation_contexts"] = []- # If flag is using encrypted payloads, replace them with redacted string or unencrypted value- if feature_flag_data.get("has_encrypted_payloads", False):- feature_flag_data["filters"]["payloads"] = get_decrypted_flag_payloads_protected(- request, feature_flag_data["filters"]["payloads"]- )+ apply_encrypted_payload_response_form(request, feature_flag_data)return response@staticmethoddef _deleted_flag_rejection(feature_flag: FeatureFlag, restore_hint: str) -> Response | None:- """Dashboard-generating actions refuse soft-deleted flags: they would recreate the- auto-generated insights that the delete_feature_flag_usage_insights sweep deletes."""+ """Refuse a soft-deleted flag.++ Dashboard-generating actions use this because they would recreate the auto-generated+ insights that the delete_feature_flag_usage_insights sweep deletes. The lifecycle+ actions use it because evaluation reads through a manager that excludes deleted rows,+ so reporting a state change on one would be a success for a flag that serves nobody.+ """if not feature_flag.deleted:return Nonereturn Response(@@ -3428,6 +3514,154 @@ class FeatureFlagViewSet(status=200,)+ # Lifecycle actions — the typed, single-purpose alternative to PATCH for the two state+ # fields. Each one changes only `active` and/or `archived`. None of them accepts or+ # 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+ # 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.+ #+ # 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+ # both write: the state check runs before the lock, so each bumps the version and the second+ # logs a version-only change.+ #+ # The facade is imported inside each action because it imports this module's serializer.++ def _lifecycle_response(self, feature_flag: FeatureFlag) -> Response:+ data = self.get_serializer(feature_flag).data+ # Unlike retrieve(), this does not blank `evaluation_contexts`: it is a write response+ # and matches partial_update.+ 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++ 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:+ feature_flag = set_flag_active(+ feature_flag,+ active,+ team=self.team,+ user=request.user,+ request=FlagLifecycleWriteRequest(request),+ )+ return self._lifecycle_response(feature_flag)++ @action(+ methods=["POST"],+ detail=True,+ required_scopes=["feature_flag:write"],+ request=None,+ responses=flag_lifecycle_responses("The flag is archived, or one of the flags it depends on is disabled."),+ )+ def enable(self, request: request.Request, **kwargs) -> Response:+ """+ 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 is also refused. An already-enabled flag+ is returned unchanged.+ """+ 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."),+ )+ def disable(self, request: request.Request, **kwargs) -> Response:+ """+ 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.+ """+ return self._set_active(request, active=False)++ @action(+ methods=["POST"],+ detail=True,+ required_scopes=["feature_flag:write"],+ request=None,+ responses=flag_lifecycle_responses("The flag is enabled and another active flag depends on it."),+ )+ def archive(self, request: request.Request, **kwargs) -> Response:+ """+ Archive a feature flag, hiding it from the default flag list.++ Sets `archived` to true. An archived flag must be disabled, so an enabled flag also gets+ `active` set to false in the same write. Targeting, variants and payloads are left as+ they are, and linked experiment and survey history is preserved. Archiving an enabled+ flag is refused when other active flags depend on it. An already-archived flag is+ returned unchanged.+ """+ from products.feature_flags.backend.facade.api import archive_flag++ feature_flag: FeatureFlag = self.get_object()+ rejection = self._deleted_flag_rejection(feature_flag, "archiving it")+ if rejection is not None:+ return rejection+ if feature_flag.archived:+ return self._lifecycle_response(feature_flag)+ updated = archive_flag(+ feature_flag,+ team=self.team,+ user=request.user,+ request=FlagLifecycleWriteRequest(request),+ disable_if_active=True,+ )+ return self._lifecycle_response(updated)++ @action(+ methods=["POST"],+ detail=True,+ required_scopes=["feature_flag:write"],+ request=None,+ responses=flag_lifecycle_responses(approval_gated=False),+ )+ def unarchive(self, request: request.Request, **kwargs) -> Response:+ """+ Restore an archived feature flag to the default flag list.++ Sets `archived` to false and changes nothing else. The flag stays disabled; enable it+ with a separate call. An already-unarchived flag is returned unchanged.+ """+ from products.feature_flags.backend.facade.api import unarchive_flag++ feature_flag: FeatureFlag = self.get_object()+ rejection = self._deleted_flag_rejection(feature_flag, "unarchiving it")+ if rejection is not None:+ return rejection+ if not feature_flag.archived:+ return self._lifecycle_response(feature_flag)+ updated = unarchive_flag(+ feature_flag, team=self.team, user=request.user, request=FlagLifecycleWriteRequest(request)+ )+ return self._lifecycle_response(updated)+@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 891f257fc2cc..df87f982416a 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -7999,6 +7999,33 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):status_response = self.client.get(f"/api/projects/{self.team.pk}/feature_flags/{flag.id}/status/")self.assertEqual(status_response.status_code, status.HTTP_403_FORBIDDEN)+ # The lifecycle actions declare feature_flag:write, so viewer access reads the flag but+ # cannot flip its state.+ viewable_flag = FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ name="read-only flag",+ key="read-only-flag",+ )+ AccessControl.objects.create(+ resource="feature_flag", resource_id=viewable_flag.id, team=self.team, access_level="viewer"+ )++ assert (+ self.client.get(f"/api/projects/{self.team.pk}/feature_flags/{viewable_flag.id}/").status_code+ == status.HTTP_200_OK+ )+ for lifecycle_action in ("enable", "disable", "archive", "unarchive"):+ lifecycle_response = self.client.post(+ f"/api/projects/{self.team.pk}/feature_flags/{viewable_flag.id}/{lifecycle_action}/",+ {},+ format="json",+ )+ assert lifecycle_response.status_code == status.HTTP_403_FORBIDDEN, lifecycle_action+ viewable_flag.refresh_from_db()+ assert viewable_flag.active is True+ assert viewable_flag.archived is False+def test_org_admin_can_list_flag_with_default_none_after_grantee_removed(self) -> None:# Regression: a flag with a team-wide "none" default plus a single explicit# editor grant becomes invisible to everyone once the grantee is removeddiff --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.pynew file mode 100644index 000000000000..dfa2dfd98dd8--- /dev/null+++ b/products/feature_flags/backend/api/test/test_feature_flag_lifecycle_actions.py@@ -0,0 +1,370 @@+from typing import Any++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.test import override_settings++from parameterized import parameterized+from rest_framework import status++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.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE, flag_payload_codec+from products.feature_flags.backend.models.feature_flag import FeatureFlag++# Deliberately more than the state fields: every one of these must survive a lifecycle call.+TARGETING: dict[str, Any] = {+ "groups": [+ {+ "properties": [{"key": "email", "type": "person", "value": "@example.com", "operator": "icontains"}],+ "rollout_percentage": 37,+ "variant": "control",+ },+ {"properties": [], "rollout_percentage": 5},+ ],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 60},+ {"key": "test", "rollout_percentage": 40},+ ]+ },+ "payloads": {"control": '{"copy": "a"}'},+}++# (action, starting active, starting archived, resulting active, resulting archived)+STATE_CASES = [+ ("enable", False, False, True, False),+ ("disable", True, False, False, False),+ # Both archive paths: the facade only sends `active` when the flag is still enabled, and+ # only that write engages the disable approval policy.+ ("archive_enabled", True, False, False, True),+ ("archive_disabled", False, False, False, True),+ ("unarchive", False, True, False, False),+]++LIFECYCLE_ACTIONS = [("enable",), ("disable",), ("archive",), ("unarchive",)]+++class TestFeatureFlagLifecycleActions(APIBaseTest):+ def _flag(+ self,+ *,+ key: str = "lifecycle-flag",+ active: bool = True,+ archived: bool = False,+ filters: dict | None = None,+ ) -> FeatureFlag:+ return FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key=key,+ name="lifecycle flag",+ active=active,+ archived=archived,+ filters=TARGETING if filters is None else filters,+ )++ def _act(self, flag: FeatureFlag, action: str, data: dict | None = None) -> Any:+ return self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/{action}/",+ data if data is not None else {},+ format="json",+ )++ def _dependent_of(self, flag: FeatureFlag, *, key: str = "dependent-flag", active: bool = True) -> FeatureFlag:+ return FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key=key,+ active=active,+ filters={+ "groups": [+ {+ "properties": [+ {"key": str(flag.id), "type": "flag", "value": "true", "operator": "flag_evaluates_to"}+ ],+ "rollout_percentage": 100,+ }+ ]+ },+ )++ @parameterized.expand(STATE_CASES)+ def test_action_changes_only_the_state_fields(self, case, active, archived, expected_active, expected_archived):+ action = case.split("_")[0]+ flag = self._flag(active=active, archived=archived)++ response = self._act(flag, action)++ assert response.status_code == status.HTTP_200_OK, response.content+ assert response.json()["active"] is expected_active+ assert response.json()["archived"] is expected_archived+ flag.refresh_from_db()+ assert flag.active is expected_active+ assert flag.archived is expected_archived+ assert flag.filters == TARGETING+ assert flag.key == "lifecycle-flag"+ assert flag.name == "lifecycle flag"++ @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.+ action = case.split("_")[0]+ flag = self._flag(active=active, archived=archived)++ response = self._act(+ flag,+ action,+ {+ "filters": {"groups": [{"properties": [], "rollout_percentage": 100}]},+ "key": "hijacked",+ "active": not expected_active,+ "archived": not expected_archived,+ "version": 999,+ "original_flag": {"active": expected_active, "archived": expected_archived},+ },+ )++ assert response.status_code == status.HTTP_200_OK, response.content+ flag.refresh_from_db()+ assert flag.filters == TARGETING+ assert flag.key == "lifecycle-flag"+ assert flag.active is expected_active+ assert flag.archived is expected_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)+ assert first.status_code == status.HTTP_200_OK, first.content++ second = self._act(flag, action)++ 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(+ [+ ("enable", False, False),+ ("disable", True, False),+ ("archive", True, False),+ ("unarchive", False, True),+ ]+ )+ def test_action_preserves_legacy_filter_keys(self, action, active, archived):+ # The serializer opportunistically strips `holdout_groups` and `super_groups` on any+ # save, falling back to the stored filters when the write sent none. That silently+ # rewrote targeting on a state flip, which is exactly what these endpoints promise not+ # to do. TARGETING carries neither key, so nothing else here would catch it.+ legacy = {+ "groups": [{"properties": [], "rollout_percentage": 30}],+ "holdout_groups": [{"properties": [], "rollout_percentage": 5, "variant": "holdout-1"}],+ "super_groups": [{"properties": [], "rollout_percentage": 15}],+ }+ flag = self._flag(active=active, archived=archived, filters=legacy)++ response = self._act(flag, action)++ assert response.status_code == status.HTTP_200_OK, response.content+ flag.refresh_from_db()+ assert flag.filters == legacy++ @parameterized.expand(LIFECYCLE_ACTIONS)+ def test_action_survives_encrypted_payloads_with_no_payloads_key(self, action):+ # `default_filters()` has no `payloads` key, so a flag can carry+ # `has_encrypted_payloads` without one. The response step indexed it directly and raised+ # after the write had committed: the caller got a 500 for a change that had landed, and+ # every retry 500d again on the no-op path.+ flag = self._flag(+ active=(action == "disable" or action == "archive"),+ archived=(action == "unarchive"),+ filters={"groups": []},+ )+ flag.is_remote_configuration = True+ flag.has_encrypted_payloads = True+ flag.save()++ response = self._act(flag, action)++ assert response.status_code == status.HTTP_200_OK, response.content++ @parameterized.expand(LIFECYCLE_ACTIONS)+ def test_action_refuses_a_soft_deleted_flag(self, action):+ # Detail routes resolve soft-deleted flags on purpose, so `get_object()` returns one.+ # Evaluation reads through a manager that excludes them, so a 200 here would report a+ # state change on a flag that serves nobody, and unarchive would claim to have restored+ # it to a list that still hides it.+ flag = self._flag(active=(action == "disable" or action == "archive"), archived=(action == "unarchive"))+ flag.deleted = True+ flag.save()++ response = self._act(flag, action)++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "has been deleted" in response.json()["error"]++ def test_enable_refuses_an_archived_flag(self):+ flag = self._flag(active=False, archived=True)++ response = self._act(flag, "enable")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["detail"] == "Cannot enable an archived feature flag. Unarchive it first."+ flag.refresh_from_db()+ assert flag.active is False++ @parameterized.expand([("disable",), ("archive",)])+ def test_action_refuses_a_flag_other_active_flags_depend_on(self, action):+ flag = self._flag(active=True)+ dependent = self._dependent_of(flag)++ response = self._act(flag, action)++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "Cannot disable this feature flag because other flags depend on it" in response.json()["detail"]+ assert f"{dependent.key} (ID: {dependent.id})" in response.json()["detail"]+ flag.refresh_from_db()+ assert flag.active is True+ assert flag.archived is False++ def test_enable_refuses_a_flag_whose_dependency_is_disabled(self):+ dependency = self._flag(key="dependency-flag", active=False, filters={"groups": []})+ flag = self._dependent_of(dependency, key="depends-on-disabled", active=False)++ response = self._act(flag, "enable")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "depends on disabled flags" in response.json()["detail"]+ flag.refresh_from_db()+ assert flag.active is False++ def test_action_records_the_state_change_in_the_activity_log(self):+ flag = self._flag(active=False)++ assert self._act(flag, "enable").status_code == status.HTTP_200_OK++ entry = ActivityLog.objects.get(scope="FeatureFlag", item_id=str(flag.id), activity="updated")+ changed_fields = {change["field"] for change in (entry.detail or {})["changes"]}+ assert "active" in changed_fields+ assert "filters" not in changed_fields+ assert entry.user == self.user++ @override_settings(FLAGS_REDIS_URL="redis://test")+ @patch("products.feature_flags.backend.flags_cache._enqueue_invalidation")+ def test_action_invalidates_the_flags_cache(self, mock_enqueue):+ flag = self._flag(active=False)+ mock_enqueue.reset_mock()++ with self.captureOnCommitCallbacks(execute=True):+ assert self._act(flag, "enable").status_code == status.HTTP_200_OK++ mock_enqueue.assert_called_with(self.team.id)++ @parameterized.expand(+ [+ ("enable", False, False),+ ("disable", True, False),+ ("archive", True, False),+ ("unarchive", False, True),+ ]+ )+ def test_action_works_when_the_team_requires_evaluation_contexts(self, action, active, archived):+ # The actions are POST but they update, and FeatureFlagSerializer.validate runs+ # create-only validation on POST. Reported as POST, every one of these returned+ # "at least one evaluation context is required to create a new feature flag".+ self.team.require_evaluation_contexts = True+ self.team.save()+ flag = self._flag(active=active, archived=archived)++ with patch("posthoganalytics.feature_enabled", return_value=True):+ response = self._act(flag, action)++ assert response.status_code == status.HTTP_200_OK, response.content++ @parameterized.expand([("session", False), ("personal_api_key", True)])+ def test_encrypted_payload_is_never_returned_as_ciphertext(self, _name, use_personal_api_key):+ # `filters` serializes the stored dict, so without the response step these endpoints+ # hand out the raw Fernet blob that every other flag surface withholds.+ ciphertext = flag_payload_codec().encrypt(b'"secret"').decode("utf-8")+ flag = self._flag(+ active=False,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}], "payloads": {"true": ciphertext}},+ )+ flag.is_remote_configuration = True+ flag.has_encrypted_payloads = True+ flag.save()++ headers: dict[str, str] = {}+ if use_personal_api_key:+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="write", user=self.user, scopes=["*"], secure_value=hash_key_value(token)+ )+ self.client.logout()+ headers = {"authorization": f"Bearer {token}"}++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/enable/", {}, format="json", headers=headers+ )++ assert response.status_code == status.HTTP_200_OK, response.content+ payload = response.json()["filters"]["payloads"]["true"]+ # Same rule as retrieve: a personal API key decrypts, anything else gets the placeholder.+ assert payload == ('"secret"' if use_personal_api_key else REDACTED_PAYLOAD_VALUE)+ flag.refresh_from_db()+ assert flag.filters["payloads"]["true"] == ciphertext++ def test_write_scoped_key_can_change_state(self):+ # The denial tests below pass just as well if the declared scope stops resolving to+ # anything a write key satisfies, which would 403 every MCP flag flip.+ flag = self._flag(active=False)+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="write", user=self.user, scopes=["feature_flag:write"], secure_value=hash_key_value(token)+ )+ self.client.logout()++ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/enable/",+ {},+ format="json",+ headers={"authorization": f"Bearer {token}"},+ )++ assert response.status_code == status.HTTP_200_OK, response.content+ flag.refresh_from_db()+ assert flag.active is True++ @parameterized.expand(LIFECYCLE_ACTIONS)+ def test_action_requires_the_feature_flag_write_scope(self, action):+ flag = self._flag(active=False, archived=False)+ 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}/",+ {},+ 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.active is False+ assert flag.archived is Falsediff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.tsindex ba2a2c520a65..e761bfa9614b 100644--- a/products/feature_flags/frontend/generated/api.ts+++ b/products/feature_flags/frontend/generated/api.ts@@ -740,6 +740,30 @@ export const featureFlagsActivityRetrieve = async (})}+export const getFeatureFlagsArchiveCreateUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/feature_flags/${id}/archive/`+}++/**+ * Archive a feature flag, hiding it from the default flag list.+ *+ * Sets `archived` to true. An archived flag must be disabled, so an enabled flag also gets+ * `active` set to false in the same write. Targeting, variants and payloads are left as+ * they are, and linked experiment and survey history is preserved. Archiving an enabled+ * flag is refused when other active flags depend on it. An already-archived flag is+ * returned unchanged.+ */+export const featureFlagsArchiveCreate = async (+ projectId: string,+ id: number,+ options?: RequestInit+): Promise<FeatureFlagApi> => {+ return apiMutator<FeatureFlagApi>(getFeatureFlagsArchiveCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getFeatureFlagsCreateStaticCohortForFlagCreateUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/feature_flags/${id}/create_static_cohort_for_flag/`}@@ -801,6 +825,54 @@ export const featureFlagsDependentFlagsList = async (})}+export const getFeatureFlagsDisableCreateUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/feature_flags/${id}/disable/`+}++/**+ * 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.+ */+export const featureFlagsDisableCreate = async (+ projectId: string,+ id: number,+ options?: RequestInit+): Promise<FeatureFlagApi> => {+ return apiMutator<FeatureFlagApi>(getFeatureFlagsDisableCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}++export const getFeatureFlagsEnableCreateUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/feature_flags/${id}/enable/`+}++/**+ * 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 is also refused. An already-enabled flag+ * is returned unchanged.+ */+export const featureFlagsEnableCreate = async (+ projectId: string,+ id: number,+ options?: RequestInit+): Promise<FeatureFlagApi> => {+ return apiMutator<FeatureFlagApi>(getFeatureFlagsEnableCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getFeatureFlagsEnrichUsageDashboardCreateUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/feature_flags/${id}/enrich_usage_dashboard/`}@@ -886,6 +958,27 @@ export const featureFlagsTestEvaluationCreate = async (})}+export const getFeatureFlagsUnarchiveCreateUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/feature_flags/${id}/unarchive/`+}++/**+ * Restore an archived feature flag to the default flag list.+ *+ * Sets `archived` to false and changes nothing else. The flag stays disabled; enable it+ * with a separate call. An already-unarchived flag is returned unchanged.+ */+export const featureFlagsUnarchiveCreate = async (+ projectId: string,+ id: number,+ options?: RequestInit+): Promise<FeatureFlagApi> => {+ return apiMutator<FeatureFlagApi>(getFeatureFlagsUnarchiveCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ })+}+export const getFeatureFlagsVersionsRetrieveUrl = (projectId: string, id: number, versionNumber: number) => {return `/api/projects/${projectId}/feature_flags/${id}/versions/${versionNumber}/`}diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yamlindex 4364baf7d284..0813942c413c 100644--- a/products/feature_flags/mcp/tools.yaml+++ b/products/feature_flags/mcp/tools.yaml@@ -92,6 +92,15 @@ tools:environments-evaluation-context-suggestions-destroy:operation: environments_evaluation_context_suggestions_destroyenabled: false+ feature-flag-archive:+ operation: feature_flags_archive_create+ enabled: false+ feature-flag-disable:+ operation: feature_flags_disable_create+ enabled: false+ feature-flag-enable:+ operation: feature_flags_enable_create+ enabled: falsefeature-flag-get-all:operation: feature_flags_listenabled: true@@ -142,6 +151,9 @@ tools:param_overrides:id:cast: string-int+ feature-flag-unarchive:+ operation: feature_flags_unarchive_create+ enabled: falsefeature-flags-activity-retrieve:operation: feature_flags_activity_retrieveenabled: true