: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): ask for a rollback reason when a flag edit lowers exposure (#124415)
Gustavo H. Strassburger8fee975c3d1a
diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex f6cbaeea6437..1a57b6cfd930 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -832,6 +832,7 @@'__module__','__static_attributes__','__str__',+ '_activity_context','_activity_trigger','_evaluation_tag_names','_has_experiment',diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.tsindex a139a8827069..e5269d3062e1 100644--- a/products/desktop/packages/api-client/src/generated.ts+++ b/products/desktop/packages/api-client/src/generated.ts@@ -19504,7 +19504,23 @@ export namespace Schemas {api_version_deprecation: ExternalDataSourceApiVersionDeprecation | null;connection_warning: string | null;}>;+ /**+ * * `errors` - Errors or bugs+ * * `metrics` - Metrics got worse+ * * `planned` - It was planned+ * * `wrong_configuration` - Wrong configuration+ * * `other` - Other+ */+ export type RollbackReasonEnum =+ | "errors"+ | "metrics"+ | "planned"+ | "wrong_configuration"+ | "other";export type PatchedFeatureFlagPartialUpdateRequestSchema = Partial<{+ ask_rollback_reason: boolean;+ rollback_reason: RollbackReasonEnum | NullEnum;+ rollback_reason_note: string | null;key: string;name: string;filters: FeatureFlagFiltersSchema;diff --git a/products/feature_flags/backend/activity_logging.py b/products/feature_flags/backend/activity_logging.pyindex 6268a24022ca..1e4f71c21f14 100644--- a/products/feature_flags/backend/activity_logging.py+++ b/products/feature_flags/backend/activity_logging.py@@ -58,5 +58,6 @@ def handle_feature_flag_change(changes=changes,name=after_update.key,trigger=trigger,+ context=getattr(after_update, "_activity_context", None),),)diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex a3eeac9b1abb..196910c3c27d 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -126,6 +126,12 @@ from products.feature_flags.backend.encrypted_flag_payloads import (get_decrypted_flag_payloads_protected,restore_redacted_flag_payloads,)+from products.feature_flags.backend.exposure_change import (+ ExposureChange,+ ExposureDirection,+ FlagExposureConfig,+ classify_exposure_change,+)from products.feature_flags.backend.facade import (config_writes,filters as flag_filters,@@ -154,6 +160,7 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlag, Featfrom products.feature_flags.backend.models.team_feature_flag_policy_config import team_requires_flag_tagsfrom products.feature_flags.backend.realtime_targeting import is_realtime_cohort_flag_targeting_enabledfrom products.feature_flags.backend.reserved_variant_keys import is_reserved_variant_key+from products.feature_flags.backend.rollback_reason import RollbackReason, RollbackReasonContextfrom products.feature_flags.backend.session_recording_links import (REPLAY_GATE_DELETE_ERROR,ReplayFlagGates,@@ -1308,7 +1315,40 @@ class FeatureFlagCreateRequestSchemaSerializer(serializers.Serializer):)-class FeatureFlagPartialUpdateRequestSchemaSerializer(serializers.Serializer):+ROLLBACK_REASON_FIELDS = frozenset({"ask_rollback_reason", "rollback_reason", "rollback_reason_note"})+++class FeatureFlagRollbackReasonSerializer(serializers.Serializer):+ ask_rollback_reason = serializers.BooleanField(+ required=False,+ default=False,+ help_text="When true, the edit lowers the flag's exposure, and the request sends no `rollback_reason`, the "+ "flag is not saved and the response is a 409 with the code `rollback_reason_required`. Send the edit again "+ "without this field to save it, with or without a `rollback_reason`. Ignored for an edit that needs approval "+ "and for a config version 2 flag.",+ )+ rollback_reason = serializers.ChoiceField(+ choices=RollbackReason.choices,+ required=False,+ allow_null=True,+ help_text="Why this edit lowers the flag's exposure, for example a rollback after errors. Stored on the "+ "activity log entry of the edit. Not stored for an edit that needs approval or for a config version 2 flag.",+ )+ rollback_reason_note = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ max_length=1000,+ help_text="A free-text note for `rollback_reason`. Requires `rollback_reason`.",+ )++ def validate(self, attrs: dict) -> dict:+ if attrs.get("rollback_reason_note") and not attrs.get("rollback_reason"):+ raise serializers.ValidationError({"rollback_reason_note": "Send a rollback_reason with the note."})+ return attrs+++class FeatureFlagPartialUpdateRequestSchemaSerializer(FeatureFlagRollbackReasonSerializer):key = serializers.CharField(required=False, help_text="Feature flag key.")name = serializers.CharField(required=False,@@ -1941,8 +1981,10 @@ class FeatureFlagSerializer(def _unsupported_v2_fields(self, attrs: dict, allowed: frozenset[str]) -> set[str]:submitted = set(self.initial_data) if isinstance(self.initial_data, Mapping) else set()names = {"filters" if field == "get_filters" else field for field in attrs} | submitted- # DRF drops unknown and read-only input fields; original_flag stays an ignored v1 compatibility field.- return names - allowed - {"original_flag"}+ # DRF drops unknown and read-only input fields; original_flag stays an ignored v1 compatibility field. The+ # rollback reason fields are request metadata that a version 2 write ignores, so a client may send them with+ # any edit.+ return names - allowed - {"original_flag"} - ROLLBACK_REASON_FIELDSdef _resolve_v2_document(self, submitted: object, *, stored: Mapping[str, Any], flag_id: int | None) -> dict:"""Resolve server-owned identity against ``stored`` and validate; the result is the exact document persisted."""@@ -2736,6 +2778,14 @@ class FeatureFlagSerializer(request_data = {}validated_data["last_modified_by"] = request.user+ # These are not flag fields, so they never reach the model. They come from the data this serializer validates,+ # not from the request body, because a service caller can pass a request whose body is for another endpoint.+ initial_data = getattr(self, "initial_data", None)+ rollback_input = FeatureFlagRollbackReasonSerializer(+ data=initial_data if isinstance(initial_data, dict) else {}+ )+ rollback_input.is_valid(raise_exception=True)+ rollback_change: ExposureChange | None = None# Prevent DRF from attempting to set reverse FK relation directlyvalidated_data.pop("evaluation_contexts", None)@@ -2853,6 +2903,16 @@ class FeatureFlagSerializer()validated_data = self._discard_unchanged_stale_fields(validated_data, original_flag)+ if not self._v2_write:+ rollback = rollback_input.validated_data+ rollback_change = self._classify_for_rollback_reason(locked_instance, validated_data, rollback)+ if rollback_change is not None:+ locked_instance._activity_context = RollbackReasonContext(+ rollback_reason=rollback["rollback_reason"],+ rollback_reason_note=rollback.get("rollback_reason_note") or None,+ exposure_direction=rollback_change.direction,+ )+# Continue with the updatevalidated_data["version"] = locked_version + 1# Every read and the save below use the locked row, not the instance loaded@@ -2919,6 +2979,20 @@ class FeatureFlagSerializer(team=instance.team,request=request,)+ if rollback_change is not None:+ report_user_action(+ request.user,+ "feature flag rollback reason given",+ {+ "feature_flag_id": instance.id,+ "feature_flag_version": instance.version,+ "rollback_reason": rollback_input.validated_data["rollback_reason"],+ "has_note": bool(rollback_input.validated_data.get("rollback_reason_note")),+ "exposure_direction": rollback_change.direction,+ },+ team=instance.team,+ request=request,+ )# If flag is using encrypted payloads, replace them with redacted string or unencrypted value# if the request was made with a personal API key@@ -2932,6 +3006,59 @@ class FeatureFlagSerializer(return instance+ def _classify_for_rollback_reason(+ self, locked_instance: FeatureFlag, validated_data: dict, rollback: dict+ ) -> ExposureChange | None:+ """Classifies the edit only when the request asks for a rollback reason or sends one, so other saves pay+ nothing. Returns the classification when the request sends a reason. Raises the `rollback_reason_required`+ 409, and so refuses the save, when the request asks for a reason, sends none, and the edit lowers exposure."""+ reason = rollback.get("rollback_reason")+ if not rollback.get("ask_rollback_reason") and reason is None:+ return None++ stored_filters = self._normalized_stored_filters(locked_instance)+ change = classify_exposure_change(+ before=FlagExposureConfig(+ active=locked_instance.active,+ deleted=locked_instance.deleted,+ filters=stored_filters,+ key=locked_instance.key,+ bucketing_identifier=locked_instance.bucketing_identifier,+ ensure_experience_continuity=locked_instance.ensure_experience_continuity,+ ),+ after=FlagExposureConfig(+ active=validated_data.get("active", locked_instance.active),+ deleted=validated_data.get("deleted", locked_instance.deleted),+ filters=validated_data.get("filters", stored_filters),+ key=validated_data.get("key", locked_instance.key),+ bucketing_identifier=validated_data.get("bucketing_identifier", locked_instance.bucketing_identifier),+ ensure_experience_continuity=validated_data.get(+ "ensure_experience_continuity", locked_instance.ensure_experience_continuity+ ),+ ),+ )+ if reason is None:+ if change.direction == ExposureDirection.LOWERS:+ raise Conflict(+ detail="This edit lowers the flag's exposure. Send it again with a rollback_reason, or without "+ "ask_rollback_reason to save it without one.",+ code="rollback_reason_required",+ )+ return None+ return change++ @staticmethod+ def _normalized_stored_filters(locked_instance: FeatureFlag) -> dict:+ """The stored filters, normalized the way `validate_filters` normalizes the request's, so a shape the+ serializer rewrites (a condition without a `properties` key, an operator alias) does not read as an edit.+ Payloads are left out because the classifier does not read them and stored ones can be ciphertext."""+ stored = flag_filters.without_payloads(locked_instance.filters)+ structural = FeatureFlagFiltersSerializer(+ data=stored,+ context={FLAG_ID_CONTEXT_KEY: locked_instance.id, PRESERVE_UNKNOWN_KEYS_CONTEXT_KEY: True},+ )+ return structural.validated_data if structural.is_valid() else stored+def _discard_unchanged_stale_fields(self, validated_data: dict, original_flag: dict | None) -> dict:if not original_flag:return validated_datadiff --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.pyindex d281f3e35b0b..21e9a2603729 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@@ -273,6 +273,15 @@ class TestAdmittedV2Updates(AdmittedV2TestCase):assert flag.filters == {"groups": [{"properties": [], "rollout_percentage": 25}]}assert flag.version == 4+ def test_rollback_reason_fields_do_not_block_a_v2_update(self) -> None:+ flag = self.flag(active=True)+ response = self.patch_flag(+ flag, {"version": 3, "active": False, "ask_rollback_reason": True, "rollback_reason": "errors"}+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert not flag.active+def test_v2_create_stays_reserved_while_creation_is_closed(self) -> None:response = self.post_flag({"key": "new-v2", "filters": config()})assert response.status_code == status.HTTP_400_BAD_REQUESTdiff --git a/products/feature_flags/backend/api/test/test_feature_flag_rollback_reason.py b/products/feature_flags/backend/api/test/test_feature_flag_rollback_reason.pynew file mode 100644index 000000000000..8265d747a31f--- /dev/null+++ b/products/feature_flags/backend/api/test/test_feature_flag_rollback_reason.py@@ -0,0 +1,120 @@+from typing import Any++from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from parameterized import parameterized+from rest_framework import status++from posthog.constants import AvailableFeature+from posthog.models.activity_logging.activity_log import ActivityLog++from products.approvals.backend.models import ApprovalPolicy, ChangeRequest+from products.approvals.backend.services import ChangeRequestService+from products.feature_flags.backend.models.feature_flag import FeatureFlag+++def _rollout(percentage: int) -> dict[str, Any]:+ return {"filters": {"groups": [{"properties": [], "rollout_percentage": percentage}]}}+++class TestFeatureFlagRollbackReason(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.flag = FeatureFlag.objects.create(+ team=self.team, created_by=self.user, key="checkout", filters=_rollout(50)["filters"]+ )++ def _patch(self, body: dict[str, Any]) -> Any:+ return self.client.patch(f"/api/projects/{self.team.id}/feature_flags/{self.flag.pk}", body, format="json")++ @parameterized.expand(+ [+ ("lower_rollout", _rollout(10), True, status.HTTP_409_CONFLICT),+ ("disable", {"active": False}, True, status.HTTP_409_CONFLICT),+ ("delete", {"deleted": True}, True, status.HTTP_409_CONFLICT),+ ("higher_rollout", _rollout(80), True, status.HTTP_200_OK),+ ("lower_rollout_sent_again_without_asking", _rollout(10), False, status.HTTP_200_OK),+ (+ "note_without_reason",+ {**_rollout(10), "rollback_reason_note": "Checkout 500s"},+ False,+ status.HTTP_400_BAD_REQUEST,+ ),+ ("unknown_reason", {**_rollout(10), "rollback_reason": "bogus"}, False, status.HTTP_400_BAD_REQUEST),+ ]+ )+ def test_asks_for_a_reason_only_when_the_edit_lowers_exposure(+ self, _name: str, edit: dict[str, Any], ask: bool, expected_status: int+ ) -> None:+ version = self.flag.version or 0++ response = self._patch({**edit, "ask_rollback_reason": ask})++ assert response.status_code == expected_status+ self.flag.refresh_from_db()+ if expected_status == status.HTTP_409_CONFLICT:+ assert response.json()["code"] == "rollback_reason_required"+ assert self.flag.version == (version + 1 if expected_status == status.HTTP_200_OK else version)++ def test_asks_for_a_reason_when_the_stored_condition_has_no_properties_key(self) -> None:+ FeatureFlag.objects.filter(pk=self.flag.pk).update(filters={"groups": [{"rollout_percentage": 50}]})++ response = self._patch({**_rollout(10), "ask_rollback_reason": True})++ assert response.status_code == status.HTTP_409_CONFLICT+ assert response.json()["code"] == "rollback_reason_required"++ @patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)+ def test_an_edit_that_needs_approval_applies_without_asking_for_a_reason(self, _mock_enabled: MagicMock) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}+ ]+ self.organization.save()+ ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key="feature_flag.disable",+ conditions={},+ approver_config={"quorum": 1, "users": [self.user.id]},+ created_by=self.user,+ )++ response = self._patch({"active": False, "ask_rollback_reason": True})++ assert response.status_code == status.HTTP_409_CONFLICT+ assert response.json()["code"] == "approval_required"+ change_request = ChangeRequest.objects.get(team=self.team)+ assert ChangeRequestService(change_request, self.user).approve().status == "applied"+ self.flag.refresh_from_db()+ assert self.flag.active is False++ @parameterized.expand([("lowering_edit", 10, "lowers"), ("raising_edit", 80, "raises")])+ @patch("products.feature_flags.backend.api.feature_flag.report_user_action")+ def test_stores_the_reason_on_the_activity_log_entry_of_the_edit(+ self, _name: str, rollout: int, direction: str, mock_report_user_action: MagicMock+ ) -> None:+ response = self._patch(+ {**_rollout(rollout), "rollback_reason": "errors", "rollback_reason_note": "Checkout 500s"}+ )++ assert response.status_code == status.HTTP_200_OK+ entry = ActivityLog.objects.filter(scope="FeatureFlag", item_id=str(self.flag.pk)).latest("created_at")+ assert entry.detail is not None+ assert entry.detail["context"] == {+ "rollback_reason": "errors",+ "rollback_reason_note": "Checkout 500s",+ "exposure_direction": direction,+ }+ (properties,) = [+ call.args[2]+ for call in mock_report_user_action.call_args_list+ if call.args[1] == "feature flag rollback reason given"+ ]+ assert properties == {+ "feature_flag_id": self.flag.pk,+ "feature_flag_version": (self.flag.version or 0) + 1,+ "rollback_reason": "errors",+ "has_note": True,+ "exposure_direction": direction,+ }diff --git a/products/feature_flags/backend/facade/filters.py b/products/feature_flags/backend/facade/filters.pyindex dd747e7893c0..c72dead420d1 100644--- a/products/feature_flags/backend/facade/filters.py+++ b/products/feature_flags/backend/facade/filters.py@@ -224,6 +224,12 @@ def replace_release_conditions(current_filters: dict, groups: list[dict]) -> dicreturn {**current_filters, "groups": deepcopy(groups)}+def without_payloads(current_filters: Mapping[str, Any] | None) -> dict:+ """Every key but ``payloads``, for a reader of who gets which value. Stored payloads can be ciphertext."""+ require_v1_config(current_filters)+ return {key: value for key, value in (current_filters or {}).items() if key != "payloads"}++def set_holdout(current_filters: dict, *, holdout_id: int | None, exclusion_percentage: float | None) -> dict:"""Set (or clear) the flag-level ``holdout`` object on the filters.diff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.pyindex f835e7637e7e..b106e106b5ea 100644--- a/products/feature_flags/backend/models/feature_flag.py+++ b/products/feature_flags/backend/models/feature_flag.py@@ -29,7 +29,7 @@ from products.feature_flags.backend.variant_rollout import format_variant_rollouif TYPE_CHECKING:from django.db.models.fields.related_descriptors import RelatedManager- from posthog.models.activity_logging.activity_log import Trigger+ from posthog.models.activity_logging.activity_log import ActivityContextBase, Triggerfrom posthog.models.team import Teamfrom products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContext@@ -154,6 +154,9 @@ class FeatureFlag(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMix# (for example the experiment exposure freeze) sets this before the gated write; the# activity-log receiver reads it so the entry does not render as a manual edit._activity_trigger: "Trigger | None" = None+ # Never persisted. The update serializer sets this before the write when the request carries a rollback reason,+ # so the reason lands on the activity log entry of the same edit.+ _activity_context: "ActivityContextBase | None" = None# When adding new fields, make sure to update organization_feature_flags.py::copy_flagskey = models.CharField(max_length=400)diff --git a/products/feature_flags/backend/rollback_reason.py b/products/feature_flags/backend/rollback_reason.pynew file mode 100644index 000000000000..3d3e8e04644f--- /dev/null+++ b/products/feature_flags/backend/rollback_reason.py@@ -0,0 +1,29 @@+"""The reason a person gives for an edit that lowers the exposure of a flag.++Flag rollback suggestions learn from these answers which rollbacks followed errors. The answer is stored on the+activity log entry of the edit.+"""++from django.db import models++from posthog.dataclasses import frozen+from posthog.models.activity_logging.activity_log import ActivityContextBase++from products.feature_flags.backend.exposure_change import ExposureDirection+++class RollbackReason(models.TextChoices):+ ERRORS = "errors", "Errors or bugs"+ METRICS = "metrics", "Metrics got worse"+ PLANNED = "planned", "It was planned"+ WRONG_CONFIGURATION = "wrong_configuration", "Wrong configuration"+ OTHER = "other", "Other"+++@frozen(slots=False) # The activity log encoder writes a context out through __dict__.+class RollbackReasonContext(ActivityContextBase):+ rollback_reason: RollbackReason+ rollback_reason_note: str | None+ # A client can send a reason with any edit, so the direction that the server classified tells a reason for a+ # rollback from a reason for another edit.+ exposure_direction: ExposureDirectiondiff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.pyindex 2833e8f0b98c..29cd5b8c32b5 100644--- a/products/feature_flags/backend/test/test_facade.py+++ b/products/feature_flags/backend/test/test_facade.py@@ -42,6 +42,7 @@ from products.feature_flags.backend.facade.filters import (set_holdout,set_release_condition_rollout,strip_group_cohort_restriction,+ without_payloads,)from products.feature_flags.backend.facade.rules import ExperimentRuleConfig, HoldoutRef, experiment_rule_from_filtersfrom products.feature_flags.backend.models.feature_flag import FeatureFlag, build_scheduled_change_serializer_data@@ -1222,6 +1223,7 @@ TRANSFORMS = [("set_release_condition_rollout", lambda filters: set_release_condition_rollout(filters, 0, 10)),("_leads_with_unconditional_rollout", _leads_with_unconditional_rollout),("roll_out_to_everyone", roll_out_to_everyone),+ ("without_payloads", without_payloads),]diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex 80506014fab7..3f61a7539e29 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -1178,7 +1178,40 @@ export interface FeatureFlagCreateRequestSchemaApi {bucketing_identifier?: BucketingIdentifierEnumApi | null}+/**+ * * `errors` - Errors or bugs+ * * `metrics` - Metrics got worse+ * * `planned` - It was planned+ * * `wrong_configuration` - Wrong configuration+ * * `other` - Other+ */+export type RollbackReasonEnumApi = (typeof RollbackReasonEnumApi)[keyof typeof RollbackReasonEnumApi]++export const RollbackReasonEnumApi = {+ Errors: 'errors',+ Metrics: 'metrics',+ Planned: 'planned',+ WrongConfiguration: 'wrong_configuration',+ Other: 'other',+} as const+export interface PatchedFeatureFlagPartialUpdateRequestSchemaApi {+ /** When true, the edit lowers the flag's exposure, and the request sends no `rollback_reason`, the flag is not saved and the response is a 409 with the code `rollback_reason_required`. Send the edit again without this field to save it, with or without a `rollback_reason`. Ignored for an edit that needs approval and for a config version 2 flag. */+ ask_rollback_reason?: boolean+ /** Why this edit lowers the flag's exposure, for example a rollback after errors. Stored on the activity log entry of the edit. Not stored for an edit that needs approval or for a config version 2 flag.+ *+ * * `errors` - Errors or bugs+ * * `metrics` - Metrics got worse+ * * `planned` - It was planned+ * * `wrong_configuration` - Wrong configuration+ * * `other` - Other */+ rollback_reason?: RollbackReasonEnumApi | null+ /**+ * A free-text note for `rollback_reason`. Requires `rollback_reason`.+ * @maxLength 1000+ * @nullable+ */+ rollback_reason_note?: string | null/** Feature flag key. */key?: string/** Feature flag description (stored in the `name` field for backwards compatibility). */diff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.tsindex 224d6b488d2b..2c91b25c55b0 100644--- a/products/feature_flags/frontend/generated/api.zod.ts+++ b/products/feature_flags/frontend/generated/api.zod.ts@@ -672,10 +672,37 @@ export const FeatureFlagsUpdateBody = /* @__PURE__ */ zod** If you're looking to use feature flags on your application, you can either use our JavaScript Library or our dedicated endpoint to check if feature flags are enabled for a given user.*/+export const featureFlagsPartialUpdateBodyAskRollbackReasonDefault = false+export const featureFlagsPartialUpdateBodyRollbackReasonNoteMax = 1000+export const featureFlagsPartialUpdateBodyFiltersOneEarlyExitDefault = falseexport const featureFlagsPartialUpdateBodyVersionMin = 0export const FeatureFlagsPartialUpdateBody = /* @__PURE__ */ zod.object({+ ask_rollback_reason: zod+ .boolean()+ .default(featureFlagsPartialUpdateBodyAskRollbackReasonDefault)+ .describe(+ "When true, the edit lowers the flag's exposure, and the request sends no `rollback_reason`, the flag is not saved and the response is a 409 with the code `rollback_reason_required`. Send the edit again without this field to save it, with or without a `rollback_reason`. Ignored for an edit that needs approval and for a config version 2 flag."+ ),+ rollback_reason: zod+ .union([+ zod+ .enum(['errors', 'metrics', 'planned', 'wrong_configuration', 'other'])+ .describe(+ '\* `errors` - Errors or bugs\n\* `metrics` - Metrics got worse\n\* `planned` - It was planned\n\* `wrong_configuration` - Wrong configuration\n\* `other` - Other'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ "Why this edit lowers the flag's exposure, for example a rollback after errors. Stored on the activity log entry of the edit. Not stored for an edit that needs approval or for a config version 2 flag.\n\n\* `errors` - Errors or bugs\n\* `metrics` - Metrics got worse\n\* `planned` - It was planned\n\* `wrong_configuration` - Wrong configuration\n\* `other` - Other"+ ),+ rollback_reason_note: zod+ .string()+ .max(featureFlagsPartialUpdateBodyRollbackReasonNoteMax)+ .nullish()+ .describe('A free-text note for `rollback_reason`. Requires `rollback_reason`.'),key: zod.string().optional().describe('Feature flag key.'),name: zod.string()diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f535c018cadc..09910cf8c034 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -87990,7 +87990,41 @@ export namespace Schemas {readonly connection_warning?: string | null;}+ /**+ * * `errors` - Errors or bugs+ * * `metrics` - Metrics got worse+ * * `planned` - It was planned+ * * `wrong_configuration` - Wrong configuration+ * * `other` - Other+ */+ export type RollbackReasonEnum = typeof RollbackReasonEnum[keyof typeof RollbackReasonEnum];+++ export const RollbackReasonEnum = {+ Errors: 'errors',+ Metrics: 'metrics',+ Planned: 'planned',+ WrongConfiguration: 'wrong_configuration',+ Other: 'other',+ } as const;+export interface PatchedFeatureFlagPartialUpdateRequestSchema {+ /** When true, the edit lowers the flag's exposure, and the request sends no `rollback_reason`, the flag is not saved and the response is a 409 with the code `rollback_reason_required`. Send the edit again without this field to save it, with or without a `rollback_reason`. Ignored for an edit that needs approval and for a config version 2 flag. */+ ask_rollback_reason?: boolean;+ /** Why this edit lowers the flag's exposure, for example a rollback after errors. Stored on the activity log entry of the edit. Not stored for an edit that needs approval or for a config version 2 flag.+ *+ * * `errors` - Errors or bugs+ * * `metrics` - Metrics got worse+ * * `planned` - It was planned+ * * `wrong_configuration` - Wrong configuration+ * * `other` - Other */+ rollback_reason?: RollbackReasonEnum | null;+ /**+ * A free-text note for `rollback_reason`. Requires `rollback_reason`.+ * @maxLength 1000+ * @nullable+ */+ rollback_reason_note?: string | null;/** Feature flag key. */key?: string;/** Feature flag description (stored in the `name` field for backwards compatibility). */diff --git a/services/mcp/src/generated/feature_flags/api.ts b/services/mcp/src/generated/feature_flags/api.tsindex de51cee687ae..e99b09b77719 100644--- a/services/mcp/src/generated/feature_flags/api.ts+++ b/services/mcp/src/generated/feature_flags/api.ts@@ -540,10 +540,36 @@ export const FeatureFlagsPartialUpdateParams = () => zod.object({),})+export const featureFlagsPartialUpdateBodyRollbackReasonNoteMax = 1000+export const featureFlagsPartialUpdateBodyFiltersOneEarlyExitDefault = falseexport const featureFlagsPartialUpdateBodyVersionMin = 0export const FeatureFlagsPartialUpdateBody = () => zod.object({+ ask_rollback_reason: zod+ .boolean()+ .optional()+ .describe(+ "When true, the edit lowers the flag's exposure, and the request sends no `rollback_reason`, the flag is not saved and the response is a 409 with the code `rollback_reason_required`. Send the edit again without this field to save it, with or without a `rollback_reason`. Ignored for an edit that needs approval and for a config version 2 flag."+ ),+ rollback_reason: zod+ .union([+ zod+ .enum(['errors', 'metrics', 'planned', 'wrong_configuration', 'other'])+ .describe(+ '\* `errors` - Errors or bugs\n\* `metrics` - Metrics got worse\n\* `planned` - It was planned\n\* `wrong_configuration` - Wrong configuration\n\* `other` - Other'+ ),+ zod.null(),+ ])+ .optional()+ .describe(+ "Why this edit lowers the flag's exposure, for example a rollback after errors. Stored on the activity log entry of the edit. Not stored for an edit that needs approval or for a config version 2 flag.\n\n\* `errors` - Errors or bugs\n\* `metrics` - Metrics got worse\n\* `planned` - It was planned\n\* `wrong_configuration` - Wrong configuration\n\* `other` - Other"+ ),+ rollback_reason_note: zod+ .string()+ .max(featureFlagsPartialUpdateBodyRollbackReasonNoteMax)+ .nullish()+ .describe('A free-text note for `rollback_reason`. Requires `rollback_reason`.'),key: zod.string().optional().describe('Feature flag key.'),name: zod.string()diff --git a/services/mcp/src/tools/generated/feature_flags.ts b/services/mcp/src/tools/generated/feature_flags.tsindex 10b9e63ef8af..7b7921be3241 100644--- a/services/mcp/src/tools/generated/feature_flags.ts+++ b/services/mcp/src/tools/generated/feature_flags.ts@@ -98,6 +98,9 @@ const DeleteFeatureFlagSchema = () => {FeatureFlagsPartialUpdateParams.omit({ project_id: true }).extend(FeatureFlagsPartialUpdateBody.omit({+ ask_rollback_reason: true,+ rollback_reason: true,+ rollback_reason_note: true,key: true,name: true,filters: true,@@ -1055,7 +1058,13 @@ const UpdateFeatureFlagSchema = () => {return z.preprocess(normalizeParamAliases({ id: ['flagId', 'flag_id', 'feature_flag_id', 'featureFlagId'] }),FeatureFlagsPartialUpdateParams.omit({ project_id: true })- .extend(FeatureFlagsPartialUpdateBody.shape)+ .extend(+ FeatureFlagsPartialUpdateBody.omit({+ ask_rollback_reason: true,+ rollback_reason: true,+ rollback_reason_note: true,+ }).shape+ ).extend({id: z.preprocess(castStringToInt, FeatureFlagsPartialUpdateParams.shape['id']),filters: UpdateFeatureFlagFiltersSchema.optional(),