: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 a closed config version 2 update path (#102958)
Andersa03d7504819c
diff --git a/docs/internal/feature-flags/api-writes.md b/docs/internal/feature-flags/api-writes.mdindex 38c0764dbcb9..599adfbabb1e 100644--- a/docs/internal/feature-flags/api-writes.md+++ b/docs/internal/feature-flags/api-writes.md@@ -52,3 +52,26 @@ Empty-filter updates preserve the stored ciphertext without encrypting it again.A rollback restores ordinary HTTP routing to the previous serializer path.Keep any format rejection or reader capability required by configuration data that exists at rollback time.In particular, retain v1-to-v2 dependency protection once v2 targets can exist; rollback does not convert stored configurations to v1.++## Config version 2 updates (closed)++`facade.config_writes.V2_UPDATE_LIMITS` is the writer policy for config version 2 updates.+It is `None` in every deployed configuration, so no entrypoint — HTTP, facade, system write, direct serializer, or approval replay — can accept a v2 write, and the behavior described above is the only behavior production has.+Before any production v2 row can exist, including an inactive row, the common safety gate must establish that deployed readers and dependent write paths can handle it safely.+The closed policy does not establish that safety; a trusted per-team admission policy must replace it before writes open.+Admission also requires an agreed production byte limit for each rule's opaque `metadata` object and matching configuration-size limits in writers and readers.+The metadata limit has no production value yet, so `V2_UPDATE_LIMITS` remains `None`.++When the policy admits updates, a stored v2 row that is not remote-configured and carries no encrypted payloads takes a separate path:++- A supplied `filters` object replaces the whole configuration. There is no top-level merge, no rule merge by index, no filling of omitted fields from the stored document, and no v1 normalization. `{}`, `null`, a list, and an incomplete object are invalid; a complete document with `rules: []` is valid.+- A PATCH that omits `filters` updates `name`, `key`, and `tags` without rewriting the stored configuration. Every other field, including activation, archival, deletion, remote config, and payload fields, is rejected with `unsupported_config_version`.+- Rule IDs and percentage-rollout seeds are server-owned and identify rules rather than list positions. An echoed ID keeps its seed through reordering and unrelated edits; a rule that omits its ID is new and receives fresh identity. An unknown ID, an ID used twice, a client-chosen seed, and a changed seed are all rejected.+- `FeatureFlag.version` is required and must equal the locked row's value. Unlike v1 there is no `original_flag` merge: a stale token is a conflict even when no individual field clashes, because the document replaces everything. The token applies to metadata-only updates too.+- Identity resolution and validation both run against the locked row inside the existing update transaction, so warnings describe the real before/proposed pair. A stored document with an unsupported shape or semantics is rejected rather than replaced. Configuration and metadata byte limits apply to the replacement, so an oversized stored document can be edited back under a lowered limit.+- Request bytes that repeat a JSON key are rejected before normalization can hide the duplicate. Non-finite numbers and percentages with more than two decimal places are rejected by the validator itself.+- An enabled flag-write approval policy denies the update, and an approved change cannot be applied to a v2 row: PH-WRITE-APPROVAL owns that path. Nothing here creates a pending v2 change request.+ The final policy lookup and flag mutation share an organization-scoped transaction lock with policy creation and updates, so a policy cannot be enabled between that lookup and commit.+ Flag writes take the lock in shared mode so different flags can update concurrently; policy writes take it in exclusive mode.++Rollback closes the policy and reverts the update routing. Format guards and readers stay in place for whatever data exists at that point; there is no automatic v2-to-v1 conversion, and v1-to-v2 dependency protection is not removed.diff --git a/products/approvals/backend/policies.py b/products/approvals/backend/policies.pyindex 477c9628e6ec..650c1b6a3502 100644--- a/products/approvals/backend/policies.py+++ b/products/approvals/backend/policies.py@@ -1,10 +1,32 @@from typing import Any, Literal+from uuid import UUID++from django.db import connection, transactionfrom posthog.dataclasses import frozenfrom products.access_control.backend.models.role import RoleMembership+def lock_approval_policies(organization_id: UUID, *, shared: bool = False) -> None:+ """Prevent policy changes between a flag's final policy lookup and its commit.++ FeatureFlagSerializer.update holds a shared lock through lookup and mutation.+ ApprovalPolicySerializer.create/update hold the exclusive lock, so different flag+ writes can proceed together while policy creation and enablement wait for them.+ """+ # Org scope covers both team policies and the org fallback, including policies not yet created.+ if not connection.in_atomic_block:+ raise transaction.TransactionManagementError("Approval policy locks require an atomic block")+ with connection.cursor() as cursor:+ cursor.execute(+ "SELECT pg_advisory_xact_lock_shared(hashtextextended(%s, 0))"+ if shared+ else "SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))",+ [f"approval-policies:{organization_id}"],+ )++@frozenclass PolicyDecision:"""Result of policy evaluation"""diff --git a/products/approvals/backend/serializers.py b/products/approvals/backend/serializers.pyindex 40076965a853..1115f681c7c7 100644--- a/products/approvals/backend/serializers.py+++ b/products/approvals/backend/serializers.py@@ -1,3 +1,5 @@+from django.db import transaction+from drf_spectacular.utils import extend_schema_fieldfrom rest_framework import serializers@@ -6,6 +8,7 @@ from posthog.api.shared import UserBasicSerializerfrom products.access_control.backend.models.role import Rolefrom products.approvals.backend.experiment_policy_sync import SYNCED_ACTION_KEYSfrom products.approvals.backend.models import Approval, ApprovalPolicy, ChangeRequest, ChangeRequestState+from products.approvals.backend.policies import lock_approval_policiesclass ChangeRequestSummarySerializer(serializers.ModelSerializer):@@ -292,14 +295,18 @@ class ApprovalPolicySerializer(serializers.ModelSerializer):return value+ @transaction.atomicdef create(self, validated_data):+ lock_approval_policies(validated_data["organization"].id)bypass_role_ids = validated_data.pop("bypass_roles", [])instance = super().create(validated_data)if bypass_role_ids:instance.set_bypass_roles([str(rid) for rid in bypass_role_ids])return instance+ @transaction.atomicdef update(self, instance, validated_data):+ lock_approval_policies(instance.organization_id)bypass_role_ids = validated_data.pop("bypass_roles", None)instance = super().update(instance, validated_data)if bypass_role_ids is not None:diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex fff61ceea713..508c71d85013 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -15,6 +15,7 @@ from django.conf import settingsfrom django.contrib.postgres.aggregates import ArrayAggfrom django.db import IntegrityError, transactionfrom django.db.models import Count, Prefetch, Q, QuerySet, deletion+from django.http.request import RawPostDataExceptionimport grpcimport requests@@ -94,6 +95,7 @@ from products.access_control.backend.presentation.access_control import ()from products.approvals.backend.decorators import approval_gatefrom products.approvals.backend.mixins import ApprovalHandlingMixin+from products.approvals.backend.policies import PolicyEngine, lock_approval_policiesfrom products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.cohorts.backend.models.util import get_all_cohort_dependenciesfrom products.dashboards.backend.api.dashboard import Dashboard@@ -125,8 +127,12 @@ from products.feature_flags.backend.encrypted_flag_payloads import (get_decrypted_flag_payloads_protected,restore_redacted_flag_payloads,)-from products.feature_flags.backend.facade import filters as flag_filters+from products.feature_flags.backend.facade import (+ config_writes,+ filters as flag_filters,+)from products.feature_flags.backend.facade.config import ConfigFormatError, detect_config_format+from products.feature_flags.backend.facade.config_validation import ConfigValidationError, ValidationLimitsfrom products.feature_flags.backend.filters_validation import collect_cross_field_violations, flatten_structural_errorsfrom products.feature_flags.backend.flag_analytics import increment_request_countfrom products.feature_flags.backend.flag_limits import get_max_feature_flags_for_team@@ -294,6 +300,14 @@ ENFORCE_FEATURE_FLAG_WRITE_SCOPE_FLAG = "enforce-feature-flag-write-scope-cross-ENCRYPTED_VERSION_HISTORY_UNAVAILABLE = "Version history is not available for flags with encrypted payloads."+# What an admitted config version 2 update may change, beside a full-document `filters`+# replacement. Everything else on such a row — activation, archival, deletion, remote+# config, payloads, aggregation, experiment and lifecycle fields — stays unsupported+# until the task that owns it lands, so a permissive metadata route cannot stand in for+# the emergency write path (PH-WRITE-SAFETY) or approval application (PH-WRITE-APPROVAL).+V2_UPDATE_FIELDS = frozenset({"get_filters", "name", "key", "tags", "version"})+V2_APPROVAL_ACTIONS = ("feature_flag.enable", "feature_flag.disable", "feature_flag.update")+def parse_created_by_ids(value: Any) -> list[int]:"""Parse a `created_by_id` filter value into a list of user IDs.@@ -1425,6 +1439,10 @@ class FeatureFlagSerializer(raise serializers.ValidationError({"filters": exc.detail}) from excattrs = super().validate(attrs)+ if self._v2_update_limits is not None:+ self._reject_lossy_v2_request_json()+ self._reject_unsupported_v2_operations(attrs)+# Run universal validations before any early returns so they always apply,# regardless of creation_context (surveys, etc.) or evaluation contexts.self._validate_device_bucketing_with_persist_auth(attrs)@@ -1674,13 +1692,155 @@ class FeatureFlagSerializer(raisedef _validate_stored_config_format(self) -> None:- if self.instance is not None and detect_config_format(self.instance.filters).kind != "v1":+ if self.instance is None or self._v2_update_limits is not None:+ return+ if detect_config_format(self.instance.filters).kind != "v1":raise serializers.ValidationError("This flag's stored configuration cannot be updated through this API. Contact support.",code="unsupported_config_version",)+ @functools.cached_property+ def _v2_update_limits(self) -> ValidationLimits | None:+ """Trusted limits when this write is an admitted config version 2 update, else None.++ `config_writes.v2_update_limits` is closed in every deployed configuration, so this is+ None on every production path — creates, v1 rows, unsupported stored formats and v2+ rows alike — and the unchanged v1/closed handling applies. Admission never reads the+ request: it needs an existing row whose stored config is v2 and a family this+ milestone can own, so a request that merely contains numeric 2 cannot reach it.+ """+ limits = config_writes.v2_update_limits()+ if limits is None or self.instance is None:+ return None+ assert isinstance(self.instance, FeatureFlag)+ if detect_config_format(self.instance.filters).kind != "v2":+ return None+ # Encrypted payloads and remote config are v1-only features; a row carrying either is+ # not in the admitted family, whatever its discriminator says.+ if self.instance.has_encrypted_payloads or self.instance.is_remote_configuration:+ return None+ return limits++ def _reject_unsupported_v2_operations(self, attrs: dict) -> None:+ """Deny everything about an admitted v2 update that this milestone does not own."""+ submitted_fields = set(self.initial_data) if isinstance(self.initial_data, Mapping) else set()+ # DRF drops unknown and read-only input fields. original_flag remains an ignored+ # v1 compatibility field; the required row-version token still forbids merging.+ allowed_input_fields = (V2_UPDATE_FIELDS - {"get_filters"}) | {"filters", "original_flag"}+ unsupported = sorted((set(attrs) - V2_UPDATE_FIELDS) | (submitted_fields - allowed_input_fields))+ if unsupported:+ names = ", ".join("filters" if field == "get_filters" else field for field in unsupported)+ raise serializers.ValidationError(+ f"These fields cannot be updated on this flag: {names}.", code="unsupported_config_version"+ )+ # PH-WRITE-APPROVAL owns approval application for v2. Until it exists, reject the+ # operation outright rather than let the gate create a pending request whose apply+ # path (replayed through this serializer with approval_apply set) is unsupported.+ if self.context.get("approval_apply"):+ raise serializers.ValidationError(+ "Approved changes cannot be applied to this flag.", code="unsupported_config_version"+ )+ # Derived the way the approval gate derives it, including its instance fallback: a+ # caller that builds no get_team context (internal service paths, organization copy)+ # must not skip this check, or an enabled policy would be bypassed rather than denied.+ get_team = self.context.get("get_team")+ assert isinstance(self.instance, FeatureFlag)+ team = (get_team() if get_team else None) or self.instance.team+ self._reject_v2_approval_policy(team)++ def _reject_v2_approval_policy(self, team: Team) -> None:+ engine = PolicyEngine()+ # Deliberately broader than the gate's own detect(): any enabled flag-write policy on+ # this team denies the write, because a v2 change that needs approval has nowhere to go.+ if any(+ engine.get_policy(action_key=action, team=team, organization=team.organization) is not None+ for action in V2_APPROVAL_ACTIONS+ ):+ raise serializers.ValidationError(+ "This flag cannot be updated while an approval policy is enabled.",+ code="unsupported_config_version",+ )++ def _reject_lossy_v2_request_json(self) -> None:+ """Reject request bytes that repeat a key, before JSON normalization hides it.++ `json.loads` keeps the last of two duplicate keys, so bytes the Rust parser rejects+ would otherwise be validated and stored as a clean document. Scoped to the v2 path:+ v1 parsing, coercion and error behavior are untouched. Non-finite numbers and excess+ percentage precision need no ingress handling — the strict validator rejects both.+ """+ request = self.context.get("request")+ if not str(getattr(request, "content_type", "") or "").startswith("application/json"):+ return+ try:+ body = getattr(request, "body", b"")+ except (AttributeError, RawPostDataException):+ # A caller that already consumed the stream, or a request shim with no bytes at+ # all. Direct Python callers pass a parsed dict and cannot carry a duplicate key.+ return+ if not body:+ return+ try:+ config_writes.reject_duplicate_json_keys(body)+ except ConfigValidationError as exc:+ raise self._v2_validation_error(exc) from exc++ @staticmethod+ def _v2_validation_error(exc: ConfigValidationError) -> serializers.ValidationError:+ """Translate pure validation errors into this endpoint's error envelope.++ Same shape as the v1 structural tier: one detail per field error, prefixed with its+ `filters....` path and carrying the validator's code. The validator's details never+ echo config values, seeds or metadata.+ """+ return serializers.ValidationError(+ [ErrorDetail(f"{error.attr}: {error.detail}", code=error.code) for error in exc.errors]+ )++ def _apply_v2_update(+ self, locked_instance: FeatureFlag, validated_data: dict, locked_version: int, limits: ValidationLimits+ ) -> None:+ """Enforce the v2 row-version token and resolve the final document under the lock.++ `FeatureFlag.version` is the row's concurrency counter, unrelated to+ `filters.version`. Unlike v1 it is required here and never merged: a stale v2+ replacement is a conflict even when its individual fields do not clash, because the+ document replaces the whole configuration.+ """+ # Use the submitted token: IntegerField coerces strings and defaults missing PUT+ # values, while facade callers' ServiceRequest.data contains no submitted fields.+ token = self.initial_data.get("version") if isinstance(self.initial_data, dict) else None+ if token is None:+ raise serializers.ValidationError({"version": "This field is required for this flag."}, code="required")+ if isinstance(token, bool) or not isinstance(token, int):+ raise serializers.ValidationError({"version": "Must be an integer."})+ if token != locked_version:+ raise Conflict(flag_version_conflict_message(token, locked_version))+ if "filters" not in validated_data:+ return # a metadata update; the stored config is not rewritten or normalized+ stored = locked_instance.filters or {}+ try:+ document = config_writes.resolve_identity(validated_data["filters"], stored=stored)+ warnings = config_writes.review_update(document, stored=stored, limits=limits)+ except ConfigValidationError as exc:+ raise self._v2_validation_error(exc) from exc+ if warnings:+ # No response field carries these yet; the editor preview (PH-UI-FLAG) owns+ # surfacing them. Recording the codes keeps the detectors exercised meanwhile.+ logger.info(+ "feature_flag_v2_update_warnings",+ extra={"flag_id": locked_instance.pk, "codes": [warning.code for warning in warnings]},+ )+ validated_data["filters"] = document+def _validate_filters_inner(self, filters, operation: str):+ if self._v2_update_limits is not None:+ # An admitted v2 replacement passes through untouched — no v1 merge, no+ # normalization. It is resolved and validated in update(), against the locked+ # state it actually replaces; nothing this side of the lock can decide it.+ return filters+# Unknown keys survive normalization during the validation rollout. Reserve the# config discriminator before that path can store an unsupported format.if "version" in filters:@@ -2267,7 +2427,7 @@ class FeatureFlagSerializer(return instance- @approval_gate(["feature_flag.enable", "feature_flag.disable", "feature_flag.update"])+ @approval_gate(list(V2_APPROVAL_ACTIONS))def update(self, instance: FeatureFlag, validated_data: dict, *args: Any, **kwargs: Any) -> FeatureFlag:request = self.context["request"]# Service-layer callers may carry no body, and an endpoint that declares no request schema@@ -2354,16 +2514,24 @@ class FeatureFlagSerializer(try:with transaction.atomic():+ v2_limits = self._v2_update_limits+ if v2_limits is not None:+ lock_approval_policies(instance.team.organization_id, shared=True)# select_for_update locks the database row so we ensure version updates are atomic.# Uses objects_including_soft_deleted so that restoring a soft-deleted flag# (setting deleted=False) can acquire the lock.locked_instance = FeatureFlag.objects_including_soft_deleted.select_for_update().get(pk=instance.pk)locked_version = locked_instance.version or 0- self._apply_stored_filter_rules(validated_data, locked_instance, request)+ # V1 cleanup must not strip unknown keys from a v2 document before validation.+ if v2_limits is None:+ self._apply_stored_filter_rules(validated_data, locked_instance, request)# NOW check for conflicts after all transformations- if version != -1 and version != locked_version:+ if v2_limits is not None:+ self._reject_v2_approval_policy(locked_instance.team)+ self._apply_v2_update(locked_instance, validated_data, locked_version, v2_limits)+ elif version != -1 and version != locked_version:if getattr(request, "strict_version_precondition", False):# The default check below needs the caller's `original_flag` and only# refuses a write whose own fields collide. A caller that sends a version@@ -3650,6 +3818,14 @@ class FeatureFlagViewSet(from products.feature_flags.backend.facade.api import update_flaginstance = self.get_object()+ if (+ config_writes.v2_update_limits() is not None+ and detect_config_format(instance.filters).kind == "v2"+ and request.content_type.startswith("application/json")+ ):+ # Cache the bytes before DRF consumes the stream, so validation can detect+ # duplicate keys even when middleware has not already read the body.+ _ = request.bodyflag = update_flag(instance,request.data,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.pynew file mode 100644index 000000000000..680716886de9--- /dev/null+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py@@ -0,0 +1,713 @@+"""Config version 2 update path: closed in production, exercised through a test-only admission.++`config_writes.V2_UPDATE_LIMITS` is None in every deployed configuration, so the closed-path+tests here run with production settings and the admitted ones patch that one attribute.+Admitting updates is not PH-GATE-001 and not the common safety gate: no production v2 row may+exist, and these flags are invented test rows.+"""++import copy+from concurrent.futures import ThreadPoolExecutor+from typing import Any++from posthog.test.base import APIBaseTest, NonAtomicBaseTest+from unittest.mock import patch++from django.conf import settings+from django.db import OperationalError, connection, transaction+from django.test import override_settings++from parameterized import parameterized+from rest_framework import status+from rest_framework.exceptions import ValidationError++from posthog.api.utils import ServiceRequest+from posthog.constants import AvailableFeature+from posthog.models import Organization, Team++from products.approvals.backend.models import ApprovalPolicy, ChangeRequest+from products.approvals.backend.serializers import ApprovalPolicySerializer+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer+from products.feature_flags.backend.facade import (+ api as flag_facade,+ config_writes,+)+from products.feature_flags.backend.facade.config_validation import ValidationLimits+from products.feature_flags.backend.models import FeatureFlag++ADMITTED_LIMITS = ValidationLimits(+ max_config_bytes=settings.MAX_FEATURE_FLAG_FILTER_SIZE_BYTES, max_metadata_bytes=2048+)++RULE_A = "3f3b7a9e-8f2e-4f4b-9c7d-2a1e5b6c8d90"+RULE_B = "b1c2d3e4-f5a6-4b7c-8d9e-0f1a2b3c4d5e"+SEED_B = "7c9e6f82-1a2b-4c3d-9e8f-5a6b7c8d9e0f"+UNKNOWN_RULE = "00000000-0000-4000-8000-000000000000"+++def admit_v2_updates():+ return patch.object(config_writes, "V2_UPDATE_LIMITS", ADMITTED_LIMITS)+++def targeted(rule_id: str | None = RULE_A, **extra: Any) -> dict:+ rule = {"rule_type": "targeted_release", "targeting": {"properties": []}, "value": True, **extra}+ return {"id": rule_id, **rule} if rule_id is not None else rule+++def rollout(rule_id: str | None = RULE_B, seed: str | None = SEED_B, **extra: Any) -> dict:+ rule: dict[str, Any] = {+ "rule_type": "percentage_rollout",+ "targeting": {"properties": []},+ "value": True,+ "rollout_percentage": 25,+ "on_rollout_miss": "continue",+ "assignment_algorithm": "sha1_60_v1",+ **extra,+ }+ if rule_id is not None:+ rule = {"id": rule_id, **rule}+ if seed is not None:+ rule["seed"] = seed+ return rule+++def config(*rules: dict, **extra: Any) -> dict:+ return {"version": 2, "return_type": "boolean", "default_value": False, "rules": list(rules), **extra}+++class V2UpdateTestCase(APIBaseTest):+ def flag(self, filters: dict | None = None, **extra: Any) -> FeatureFlag:+ return FeatureFlag.objects.create(+ team=self.team,+ key=extra.pop("key", "v2-flag"),+ filters=filters if filters is not None else config(targeted(), rollout()),+ version=3,+ created_by=self.user,+ **extra,+ )++ def patch_flag(self, flag: FeatureFlag, data: dict, method: str = "patch"):+ return getattr(self.client, method)(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", data, format="json"+ )+++class TestV2UpdatesAreClosed(V2UpdateTestCase):+ """With production settings nothing reaches the v2 path, through any entrypoint."""++ @parameterized.expand(["patch", "put"])+ def test_http_v2_replacement_is_rejected_and_writes_nothing(self, method: str) -> None:+ flag = self.flag()+ stored = copy.deepcopy(flag.filters)+ response = self.patch_flag(flag, {"key": flag.key, "version": 3, "filters": config(targeted())}, method=method)+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ # A supplied discriminator is refused before the stored format is read: unchanged+ # precedence, unchanged code.+ assert response.json()["code"] == "reserved_config_version"+ flag.refresh_from_db()+ assert flag.filters == stored+ assert flag.version == 3++ def test_http_metadata_only_update_is_rejected(self) -> None:+ flag = self.flag()+ response = self.patch_flag(flag, {"version": 3, "name": "Renamed"})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "unsupported_config_version"+ flag.refresh_from_db()+ assert flag.version == 3++ def test_http_v2_create_is_reserved(self) -> None:+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/", {"key": "new-v2", "filters": config()}, format="json"+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "reserved_config_version"+ assert not FeatureFlag.objects.filter(key="new-v2").exists()++ def test_facade_update_is_rejected(self) -> None:+ flag = self.flag()+ with self.assertRaises(Exception) as caught:+ flag_facade.update_flag(flag, {"version": 3, "filters": config(targeted())}, team=self.team, user=self.user)+ assert "reserved_config_version" in str(caught.exception.detail) # type: ignore[attr-defined]+ flag.refresh_from_db()+ assert flag.version == 3++ def test_system_write_is_rejected(self) -> None:+ flag = self.flag()+ stored = copy.deepcopy(flag.filters)+ with self.assertRaises(ValidationError) as caught:+ flag_facade.update_flag(flag, {"version": 3, "filters": config(targeted())}, team=self.team, user=None)+ assert caught.exception.get_codes() == {"filters": ["reserved_config_version"]}+ flag.refresh_from_db()+ assert flag.filters == stored+ assert flag.version == 3++ def test_direct_serializer_is_rejected(self) -> None:+ flag = self.flag()+ serializer = FeatureFlagSerializer(flag, data={"filters": config(targeted())}, partial=True)+ assert not serializer.is_valid()+ assert serializer.errors["filters"][0].code == "reserved_config_version"++ def test_approval_replay_is_rejected(self) -> None:+ flag = self.flag()+ serializer = FeatureFlagSerializer(+ flag,+ data={"filters": config(targeted())},+ partial=True,+ context={"request": ServiceRequest(self.user, method="PATCH"), "approval_apply": True},+ )+ assert not serializer.is_valid()+ assert serializer.errors["filters"][0].code == "reserved_config_version"+++@override_settings(FEATURE_FLAG_FILTERS_ENFORCED_RULES={"*"})+class AdmittedV2TestCase(V2UpdateTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.enterContext(admit_v2_updates())+++class TestAdmittedV2Updates(AdmittedV2TestCase):+ def test_v1_update_keeps_v1_behavior_when_v2_is_admitted(self) -> None:+ flag = self.flag({"groups": [{"properties": [], "rollout_percentage": 25}]}, active=True)+ response = self.patch_flag(flag, {"active": False})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert not flag.active+ assert flag.filters == {"groups": [{"properties": [], "rollout_percentage": 25}]}+ assert flag.version == 4++ def test_v2_create_stays_reserved_when_updates_are_admitted(self) -> None:+ response = self.client.post(+ f"/api/projects/{self.team.id}/feature_flags/", {"key": "new-v2", "filters": config()}, format="json"+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "reserved_config_version"+ assert not FeatureFlag.objects.filter(team=self.team, key="new-v2").exists()++ def test_full_document_replaces_and_saves_once(self) -> None:+ flag = self.flag()+ replacement = config(targeted(description="Kept", metadata={"owner": "growth"}))+ response = self.patch_flag(flag, {"version": 3, "filters": replacement})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert flag.filters == replacement # the removed rollout rule is gone, nothing merged back+ assert flag.version == 4++ def test_empty_rules_list_is_a_valid_document(self) -> None:+ flag = self.flag()+ response = self.patch_flag(flag, {"version": 3, "filters": config()})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert flag.filters == config()++ def test_optional_fields_omitted_by_the_replacement_are_removed(self) -> None:+ flag = self.flag(config(targeted(description="Old", metadata={"a": 1})))+ response = self.patch_flag(flag, {"version": 3, "filters": config(targeted())})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert flag.filters["rules"][0] == targeted()++ @parameterized.expand(+ [+ ("empty", {}),+ ("fragment", {"version": 2, "rules": []}),+ ("v1_shape", {"version": 2, "return_type": "boolean", "default_value": False, "groups": []}),+ ("downgrade", {"version": 1, "groups": []}),+ ("no_discriminator", {"return_type": "boolean", "default_value": False, "rules": []}),+ ]+ )+ def test_incomplete_or_reshaped_documents_are_rejected(self, _name: str, filters: dict) -> None:+ flag = self.flag()+ stored = copy.deepcopy(flag.filters)+ response = self.patch_flag(flag, {"version": 3, "filters": filters})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ flag.refresh_from_db()+ assert flag.filters == stored+ assert flag.version == 3++ @parameterized.expand([("null", None), ("list", []), ("string", "x")])+ def test_non_object_filters_are_rejected(self, _name: str, filters: Any) -> None:+ flag = self.flag()+ response = self.patch_flag(flag, {"version": 3, "filters": filters})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ flag.refresh_from_db()+ assert flag.version == 3++ def test_omitted_filters_preserves_the_config_exactly(self) -> None:+ flag = self.flag()+ stored = copy.deepcopy(flag.filters)+ response = self.patch_flag(flag, {"version": 3, "name": "Renamed"})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert flag.filters == stored+ assert flag.name == "Renamed"+ assert flag.version == 4++ @parameterized.expand(+ [+ ("false_default", {"default_value": False}),+ ("null_default", {"default_value": None}),+ ("true_default", {"default_value": True}),+ ]+ )+ def test_document_level_values_round_trip(self, _name: str, extra: dict) -> None:+ flag = self.flag()+ document = config(targeted(), **extra)+ response = self.patch_flag(flag, {"version": 3, "filters": document})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert flag.filters == document++ @parameterized.expand([("zero", 0), ("hundred", 100), ("two_decimals", 33.33)])+ def test_percentages_round_trip(self, _name: str, percentage: Any) -> None:+ flag = self.flag()+ response = self.patch_flag(flag, {"version": 3, "filters": config(rollout(rollout_percentage=percentage))})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert flag.filters["rules"][0]["rollout_percentage"] == percentage+++class TestServerOwnedIdentity(AdmittedV2TestCase):+ def test_new_rules_get_server_identity(self) -> None:+ flag = self.flag(config())+ submitted = config(targeted(rule_id=None), rollout(rule_id=None, seed=None))+ sent = copy.deepcopy(submitted)+ response = self.patch_flag(flag, {"version": 3, "filters": submitted})+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert submitted == sent # the request document is never mutated in place+ flag.refresh_from_db()+ ids = [rule["id"] for rule in flag.filters["rules"]]+ assert len(set(ids)) == 2+ assert flag.filters["rules"][1]["seed"] not in (None, "")++ def test_identity_survives_reorder_and_unrelated_edits(self) -> None:+ flag = self.flag()+ response = self.patch_flag(+ flag,+ {"version": 3, "filters": config(rollout(rollout_percentage=90), targeted(value=False))},+ )+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert [rule["id"] for rule in flag.filters["rules"]] == [RULE_B, RULE_A]+ assert flag.filters["rules"][0]["seed"] == SEED_B++ def test_an_omitted_seed_is_taken_from_the_locked_row(self) -> None:+ flag = self.flag()+ response = self.patch_flag(flag, {"version": 3, "filters": config(rollout(seed=None))})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert flag.filters["rules"][0]["seed"] == SEED_B++ def test_a_rule_that_becomes_randomized_gets_a_fresh_seed(self) -> None:+ flag = self.flag(config(targeted()))+ response = self.patch_flag(flag, {"version": 3, "filters": config(rollout(rule_id=RULE_A, seed=None))})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert flag.filters["rules"][0]["id"] == RULE_A+ assert flag.filters["rules"][0]["seed"] not in (None, "", SEED_B)++ @parameterized.expand(+ [+ ("unknown_id", config(targeted(rule_id=UNKNOWN_RULE))),+ ("hijacked_id", config(targeted(), targeted(rule_id=RULE_A, value=False))),+ ("null_id", config(targeted(rule_id=None) | {"id": None})),+ ("chosen_seed", config(rollout(rule_id=None, seed="chosen-by-client"))),+ ("changed_seed", config(rollout(seed="chosen-by-client"))),+ ]+ )+ def test_client_chosen_identity_is_rejected(self, _name: str, filters: dict) -> None:+ flag = self.flag()+ stored = copy.deepcopy(flag.filters)+ response = self.patch_flag(flag, {"version": 3, "filters": filters})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ flag.refresh_from_db()+ assert flag.filters == stored+ assert flag.version == 3+++class TestV2Concurrency(AdmittedV2TestCase):+ @parameterized.expand([("missing", {}), ("null", {"version": None}), ("string", {"version": "3"})])+ def test_an_absent_or_malformed_token_is_rejected(self, _name: str, data: dict) -> None:+ flag = self.flag()+ response = self.patch_flag(flag, {"filters": config(targeted()), **data})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ flag.refresh_from_db()+ assert flag.version == 3++ def test_a_stale_token_conflicts_even_without_conflicting_fields(self) -> None:+ flag = self.flag()+ response = self.patch_flag(+ flag,+ {+ "version": 2,+ "filters": config(targeted()),+ # v1 would accept this as a non-conflicting stale update; a v2 replacement+ # rewrites the whole document, so the stale token alone is the conflict.+ "original_flag": {"name": flag.name},+ },+ )+ assert response.status_code == status.HTTP_409_CONFLICT+ assert response.json()["detail"] == (+ "This feature flag has changed since version 2; it is now at version 3. "+ "Nothing was written. Read the flag again and decide the change against its current definition."+ )+ flag.refresh_from_db()+ assert flag.version == 3++ def test_the_token_applies_to_metadata_only_updates(self) -> None:+ flag = self.flag()+ assert self.patch_flag(flag, {"name": "No token"}).status_code == status.HTTP_400_BAD_REQUEST+ assert self.patch_flag(flag, {"version": 1, "name": "Stale"}).status_code == status.HTTP_409_CONFLICT+ flag.refresh_from_db()+ assert flag.version == 3++ def test_a_second_writer_on_a_stale_instance_cannot_reuse_a_version(self) -> None:+ flag = self.flag()+ stale = FeatureFlag.objects.get(pk=flag.pk)+ assert self.patch_flag(flag, {"version": 3, "filters": config(targeted())}).status_code == 200+ response = self.patch_flag(stale, {"version": 3, "filters": config(rollout())})+ assert response.status_code == status.HTTP_409_CONFLICT+ flag.refresh_from_db()+ assert flag.version == 4+ assert flag.filters == config(targeted())++ @parameterized.expand([("team", True), ("organization", False)])+ def test_a_policy_enabled_after_validation_denies_the_update(self, _name: str, team_policy: bool) -> None:+ flag = self.flag()+ serializer = FeatureFlagSerializer(+ flag,+ data={"version": 3, "name": "Renamed"},+ partial=True,+ context={+ "request": ServiceRequest(self.user, method="PATCH"),+ "team_id": self.team.id,+ "project_id": self.team.project_id,+ },+ )+ serializer.is_valid(raise_exception=True)+ policy = ApprovalPolicySerializer(+ data={"action_key": "feature_flag.update", "approver_config": {"quorum": 1}, "enabled": True}+ )+ policy.is_valid(raise_exception=True)+ policy.save(organization=self.organization, team=self.team if team_policy else None)++ with self.assertRaises(ValidationError) as error:+ serializer.save()++ assert error.exception.get_codes() == ["unsupported_config_version"]+ flag.refresh_from_db()+ assert flag.name != "Renamed"+ assert flag.version == 3+++class TestV2ApprovalPolicyLocking(NonAtomicBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def test_different_flags_in_an_organization_can_update_concurrently(self) -> None:+ first = FeatureFlag.objects.create(team=self.team, key="v2-first", filters=config(), version=3)+ second = FeatureFlag.objects.create(team=self.team, key="v2-second", filters=config(), version=3)++ def update_second_flag() -> None:+ try:+ with transaction.atomic():+ with connection.cursor() as cursor:+ cursor.execute("SET LOCAL lock_timeout = '100ms'")+ flag_facade.update_flag(second, {"version": 3, "name": "Second"}, team=self.team, user=self.user)+ finally:+ connection.close()++ with admit_v2_updates(), transaction.atomic():+ flag_facade.update_flag(first, {"version": 3, "name": "First"}, team=self.team, user=self.user)+ with ThreadPoolExecutor(max_workers=1) as executor:+ executor.submit(update_second_flag).result(timeout=10)++ first.refresh_from_db()+ second.refresh_from_db()+ assert (first.name, first.version) == ("First", 4)+ assert (second.name, second.version) == ("Second", 4)++ @parameterized.expand(+ [+ ("team_create", True, False),+ ("org_create", False, False),+ ("team_enable", True, True),+ ("org_enable", False, True),+ ]+ )+ def test_policy_write_waits_for_flag_commit(self, _name: str, team_policy: bool, existing_policy: bool) -> None:+ team = self.team if team_policy else None+ policy = (+ ApprovalPolicy.objects.create(+ organization=self.organization,+ team=team,+ action_key="feature_flag.update",+ approver_config={"quorum": 1},+ enabled=False,+ )+ if existing_policy+ else None+ )+ flag = FeatureFlag.objects.create(team=self.team, key="v2-policy-lock", filters=config(), version=3)++ def enable_policy() -> None:+ try:+ with transaction.atomic():+ with connection.cursor() as cursor:+ cursor.execute("SET LOCAL lock_timeout = '100ms'")+ serializer = ApprovalPolicySerializer(+ policy,+ data={"action_key": "feature_flag.update", "approver_config": {"quorum": 1}, "enabled": True},+ partial=existing_policy,+ )+ serializer.is_valid(raise_exception=True)+ serializer.save(organization=self.organization, team=team)+ finally:+ connection.close()++ save_flag = FeatureFlag.save++ def save_with_concurrent_policy(instance: FeatureFlag, *args: Any, **kwargs: Any) -> None:+ save_flag(instance, *args, **kwargs)+ with ThreadPoolExecutor(max_workers=1) as executor:+ with self.assertRaises(OperationalError) as error:+ executor.submit(enable_policy).result(timeout=10)+ assert getattr(error.exception.__cause__, "sqlstate", None) == "55P03"++ with (+ admit_v2_updates(),+ patch.object(FeatureFlag, "save", autospec=True, side_effect=save_with_concurrent_policy),+ ):+ flag_facade.update_flag(flag, {"version": 3, "name": "Renamed"}, team=self.team, user=self.user)++ flag.refresh_from_db()+ assert (flag.name, flag.version) == ("Renamed", 4)+ assert not ApprovalPolicy.objects.filter(organization=self.organization, enabled=True).exists()+ with ThreadPoolExecutor(max_workers=1) as executor:+ executor.submit(enable_policy).result(timeout=10)+ assert ApprovalPolicy.objects.filter(organization=self.organization, team=team, enabled=True).exists()+++class TestV2AdmissionBoundary(AdmittedV2TestCase):+ @parameterized.expand(+ [+ ("malformed", {"version": 2, "rules": "broken"}),+ ("deferred_experiment", config({"id": RULE_A, "rule_type": "experiment", "targeting": {}})),+ ("deferred_string", config(return_type="string")),+ ]+ )+ def test_unsupported_stored_configs_are_not_replaced(self, _name: str, stored: dict) -> None:+ flag = self.flag(stored)+ response = self.patch_flag(flag, {"version": 3, "filters": config(targeted(rule_id=None))})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ flag.refresh_from_db()+ assert flag.filters == stored+ assert flag.version == 3++ def test_an_experiment_rule_cannot_be_written(self) -> None:+ flag = self.flag()+ response = self.patch_flag(+ flag,+ {"version": 3, "filters": config({"id": RULE_A, "rule_type": "experiment", "targeting": {}})},+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ flag.refresh_from_db()+ assert flag.version == 3++ @parameterized.expand(+ [+ ("active", {"active": False}),+ ("archived", {"archived": True, "active": False}),+ ("deleted", {"deleted": True}),+ ("remote_config", {"is_remote_configuration": True}),+ ("encrypted", {"has_encrypted_payloads": True}),+ ("continuity", {"ensure_experience_continuity": True}),+ ("runtime", {"evaluation_runtime": "server"}),+ ("unknown", {"naem": "Renamed"}),+ ("read_only", {"created_at": "2026-01-01T00:00:00Z"}),+ ]+ )+ def test_unsupported_metadata_operations_are_rejected(self, _name: str, data: dict) -> None:+ flag = self.flag()+ response = self.patch_flag(flag, {"version": 3, **data})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "unsupported_config_version"+ flag.refresh_from_db()+ assert flag.version == 3++ def test_supported_metadata_operations_work(self) -> None:+ flag = self.flag()+ response = self.patch_flag(flag, {"version": 3, "name": "Renamed", "key": "v2-renamed", "tags": []})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert (flag.name, flag.key, flag.version) == ("Renamed", "v2-renamed", 4)++ @parameterized.expand(["has_encrypted_payloads", "is_remote_configuration"])+ def test_unsupported_flag_families_are_not_admitted(self, field: str) -> None:+ # Not in the admitted family, so the write falls back to the closed path rather+ # than gaining a v2 route through it.+ flag = self.flag(+ has_encrypted_payloads=field == "has_encrypted_payloads",+ is_remote_configuration=field == "is_remote_configuration",+ )+ response = self.patch_flag(flag, {"version": 3, "filters": config(targeted())})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "reserved_config_version"+ flag.refresh_from_db()+ assert flag.version == 3++ def test_an_enabled_approval_policy_denies_the_update(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.APPROVALS, "name": AvailableFeature.APPROVALS}+ ]+ self.organization.save()+ ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key="feature_flag.update",+ approver_config={"quorum": 1, "users": [self.user.id]},+ enabled=True,+ )+ flag = self.flag()+ response = self.patch_flag(flag, {"version": 3, "filters": config(targeted())})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "unsupported_config_version"+ flag.refresh_from_db()+ assert flag.version == 3+ assert not ChangeRequest.objects.filter(organization=self.organization).exists()++ def test_a_context_less_caller_cannot_skip_the_approval_check(self) -> None:+ # A serializer built without a get_team context must still see the policy: the+ # approval gate derives the team from the instance for exactly these callers, so+ # returning early here would bypass an enabled policy rather than deny it.+ ApprovalPolicy.objects.create(+ organization=self.organization,+ team=self.team,+ action_key="feature_flag.update",+ approver_config={},+ enabled=True,+ )+ flag = self.flag()+ serializer = FeatureFlagSerializer(flag, data={"version": 3, "name": "Renamed"}, partial=True)+ assert not serializer.is_valid()+ assert "unsupported_config_version" in str(serializer.errors)+ flag.refresh_from_db()+ assert flag.version == 3++ def test_approval_replay_is_rejected_even_when_admitted(self) -> None:+ flag = self.flag()+ serializer = FeatureFlagSerializer(+ flag,+ data={"version": 3, "filters": config(targeted())},+ partial=True,+ context={"request": ServiceRequest(self.user, method="PATCH"), "approval_apply": True},+ )+ assert not serializer.is_valid()+ assert "unsupported_config_version" in str(serializer.errors)++ def test_the_facade_reaches_the_admitted_path(self) -> None:+ flag = self.flag()+ updated = flag_facade.update_flag(+ flag, {"version": 3, "filters": config(targeted())}, team=self.team, user=self.user+ )+ assert updated.filters == config(targeted())+ assert updated.version == 4++ def test_another_team_cannot_reach_the_flag(self) -> None:+ other = FeatureFlag.objects.create(+ team=Team.objects.create(organization=Organization.objects.create(name="other org")),+ key="other-v2",+ filters=config(targeted()),+ version=1,+ )+ response = self.patch_flag(other, {"version": 1, "filters": config()})+ assert response.status_code == status.HTTP_404_NOT_FOUND+++class TestV2RequestBytes(AdmittedV2TestCase):+ def post_bytes(self, flag: FeatureFlag, body: str):+ return self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/", body, content_type="application/json"+ )++ @parameterized.expand(+ [+ (+ "filters",+ '{"version": 3, "filters": {"version": 1, "version": 2, "return_type": "boolean", "default_value": false, "rules": []}}',+ "version",+ ),+ ("metadata", '{"version": 3, "name": "First", "name": "Second"}', "name"),+ ]+ )+ @override_settings(MIDDLEWARE=[])+ def test_duplicate_keys_in_the_request_bytes_are_rejected(self, _name: str, body: str, key: str) -> None:+ self.client.force_authenticate(user=self.user)+ flag = self.flag()+ stored = copy.deepcopy(flag.filters)+ response = self.post_bytes(flag, body)+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert f'"{key}"' in response.json()["detail"]+ flag.refresh_from_db()+ assert flag.filters == stored+ assert flag.version == 3++ @parameterized.expand([("nan", "NaN"), ("infinity", "Infinity"), ("precision", "33.333")])+ def test_lossy_numbers_never_become_valid(self, _name: str, literal: str) -> None:+ flag = self.flag()+ body = (+ '{"version": 3, "filters": {"version": 2, "return_type": "boolean", "default_value": false, '+ '"rules": [{"rule_type": "percentage_rollout", "targeting": {"properties": []}, "value": true, '+ f'"rollout_percentage": {literal}, "on_rollout_miss": "continue", '+ '"assignment_algorithm": "sha1_60_v1"}]}}'+ )+ response = self.post_bytes(flag, body)+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ flag.refresh_from_db()+ assert flag.version == 3++ @parameterized.expand(+ [+ ("config", config(targeted(description="x" * 400)), 200),+ ("metadata", config(targeted(metadata={"note": "x" * 4000})), ADMITTED_LIMITS.max_config_bytes),+ ]+ )+ def test_an_oversized_stored_document_can_be_replaced_within_the_limits(+ self, _name: str, stored: dict, max_config_bytes: int+ ) -> None:+ flag = self.flag(stored)+ replacement = config(targeted())+ with override_settings(MAX_FEATURE_FLAG_FILTER_SIZE_BYTES=max_config_bytes):+ response = self.patch_flag(flag, {"version": 3, "filters": replacement})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert flag.filters == replacement+ assert flag.version == 4++ def test_the_deployment_byte_limit_applies(self) -> None:+ flag = self.flag()+ with override_settings(MAX_FEATURE_FLAG_FILTER_SIZE_BYTES=200):+ response = self.patch_flag(flag, {"version": 3, "filters": config(targeted(description="x" * 400))})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["code"] == "limit_exceeded"+ assert "configuration is too large" in response.json()["detail"]+ flag.refresh_from_db()+ assert flag.version == 3++ def test_the_metadata_byte_limit_applies(self) -> None:+ flag = self.flag()+ response = self.patch_flag(flag, {"version": 3, "filters": config(targeted(metadata={"note": "x" * 4000}))})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ flag.refresh_from_db()+ assert flag.version == 3++ def test_v1_only_keys_are_not_stripped_into_validity(self) -> None:+ # The v1 write path opportunistically drops these keys on save; doing that to a v2+ # document would turn a request the validator rejects into an accepted one.+ flag = self.flag()+ response = self.patch_flag(+ flag, {"version": 3, "filters": config(targeted(), super_groups=[], holdout_groups=[])}+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ flag.refresh_from_db()+ assert flag.version == 3diff --git a/products/feature_flags/backend/facade/config_writes.py b/products/feature_flags/backend/facade/config_writes.pynew file mode 100644index 000000000000..f3da72c3e5de--- /dev/null+++ b/products/feature_flags/backend/facade/config_writes.py@@ -0,0 +1,200 @@+"""Writer admission and server-owned identity for config version 2 updates.++Three things a v2 update needs that the pure validator deliberately does not do:++- **Admission.** ``v2_update_limits`` is the closed seam the writer asks before it looks at+ a request. It answers ``None`` in every deployed configuration, so no v2 write is+ reachable in production through any entrypoint. The production admission requirements+ are documented in ``docs/internal/feature-flags/api-writes.md``.+- **Identity.** Rule ids and assignment seeds are server-owned and identify rules, not+ list positions. ``resolve_identity`` echoes back existing identity, allocates it for+ genuinely new rules, and rejects a client that tries to choose it.+- **Comparison.** ``review_update`` validates both documents' shape and semantics, so+ warnings describe the real before/proposed pair and unsupported stored families are+ rejected. Byte limits apply only to the candidate so oversized rows can be reduced.++Deliberately free of Django ORM and DRF imports: the endpoint owns HTTP error shapes and+the row lock, this module owns the document.+"""++import sys+import json+from collections.abc import Mapping+from typing import Any+from uuid import uuid4++from django.conf import settings++from products.feature_flags.backend.facade.config_validation import (+ ConfigError,+ ConfigValidationError,+ ValidationLimits,+ validate_config,+)+from products.feature_flags.backend.facade.rule_warnings import review_config+from products.feature_flags.backend.facade.warnings import ManagementWarning++# The trusted writer policy for admitted v2 updates. ``None`` denies every one of them and+# is the only value any deployed configuration has: per-team admission is not implemented,+# and the per-rule metadata byte bound has no agreed production value (see api-writes.md).+# Tests patch this attribute to exercise the dormant path; nothing reads a request field,+# a serializer context flag, staff status or a missing user as permission to write v2.+V2_UPDATE_LIMITS: ValidationLimits | None = None++_SEEDED_RULE_TYPE = "percentage_rollout"+++def v2_update_limits() -> ValidationLimits | None:+ """Trusted limits for an admitted v2 update, or ``None`` when the write is denied.++ A lower deployment filter-size limit always wins over the policy's, matching the cap+ the v1 write path and the Rust reader both enforce.+ """+ limits = V2_UPDATE_LIMITS+ if limits is None:+ return None+ return ValidationLimits(+ max_config_bytes=min(limits.max_config_bytes, settings.MAX_FEATURE_FLAG_FILTER_SIZE_BYTES),+ max_metadata_bytes=limits.max_metadata_bytes,+ )+++def reject_duplicate_json_keys(body: bytes) -> None:+ """Reject request bytes that carry the same key twice at any depth.++ ``json.loads`` keeps the last of two duplicate keys, so a body the Rust parser rejects+ would otherwise reach the validator as a clean document and be persisted. Only the v2+ path calls this; v1 parsing, coercion and error behavior are untouched.+ """++ def object_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]:+ result: dict[str, Any] = {}+ for key, value in pairs:+ if key in result:+ raise ConfigValidationError(+ [ConfigError(code="invalid", detail=f"Must not repeat the key {json.dumps(key)}.", attr="filters")]+ )+ result[key] = value+ return result++ try:+ json.loads(body, object_pairs_hook=object_pairs)+ except ConfigValidationError:+ raise+ except ValueError as exc:+ raise ConfigValidationError(+ [ConfigError(code="invalid", detail="Must not repeat a key.", attr="filters")]+ ) from exc+++def resolve_identity(submitted: object, *, stored: Mapping[str, Any]) -> dict[str, Any]:+ """Return ``submitted`` with server-owned rule ids and seeds resolved against ``stored``.++ An echoed id keeps its rule's stored seed through reordering and unrelated edits; a+ rule that omits its id is new and gets fresh identity. Clients may round-trip identity+ but never choose it, so an unknown id, an id claimed twice, or a changed seed is+ rejected here rather than silently honoured — the last of those is an assignment reset,+ which is a separate operation nobody owns yet.++ The input is not modified, and nothing else is filled in: the result is the exact+ document that both the validator and the row will see.+ """+ if not isinstance(submitted, Mapping):+ raise ConfigValidationError([ConfigError(code="invalid", detail="Must be an object.", attr="filters")])+ rules = submitted.get("rules")+ if not isinstance(rules, list):+ return dict(submitted) # not a document shape this module can resolve; the validator reports it++ stored_rules = {+ rule["id"]: rule+ for rule in (stored.get("rules") or [])+ if isinstance(rule, Mapping) and isinstance(rule.get("id"), str)+ }+ errors: list[ConfigError] = []+ claimed: set[str] = set()+ resolved = [+ _resolve_rule(rule, f"filters.rules[{index}]", stored_rules, claimed, errors)+ if isinstance(rule, Mapping)+ else rule+ for index, rule in enumerate(rules)+ ]+ if errors:+ raise ConfigValidationError(errors)+ return {**submitted, "rules": resolved}+++def _resolve_rule(+ rule: Mapping[str, Any],+ path: str,+ stored_rules: Mapping[str, Mapping[str, Any]],+ claimed: set[str],+ errors: list[ConfigError],+) -> dict[str, Any]:+ resolved = dict(rule)+ current: Mapping[str, Any] | None = None+ if "id" not in rule:+ resolved["id"] = str(uuid4())+ elif not isinstance(rule["id"], str) or rule["id"] not in stored_rules:+ errors.append(+ ConfigError(+ code="invalid",+ detail="Rule ids are server-assigned; echo one this flag already has or omit the field.",+ attr=f"{path}.id",+ )+ )+ elif rule["id"] in claimed:+ errors.append(ConfigError(code="not_unique", detail="Used by another rule.", attr=f"{path}.id"))+ else:+ claimed.add(rule["id"])+ current = stored_rules[rule["id"]]++ if rule.get("rule_type") != _SEEDED_RULE_TYPE:+ # A rule that is not randomized carries no seed; changing type away from a rollout+ # drops it, and changing type towards one allocates a fresh one below.+ return resolved+ stored_seed = current.get("seed") if current is not None and current.get("rule_type") == _SEEDED_RULE_TYPE else None+ if not isinstance(stored_seed, str):+ if "seed" in rule:+ errors.append(+ ConfigError(code="invalid", detail="Assignment seeds are server-assigned.", attr=f"{path}.seed")+ )+ resolved["seed"] = str(uuid4())+ elif "seed" not in rule or rule["seed"] == stored_seed:+ resolved["seed"] = stored_seed+ else:+ errors.append(+ ConfigError(+ code="invalid",+ detail="Cannot be changed; resetting assignment is a separate operation.",+ attr=f"{path}.seed",+ )+ )+ return resolved+++def review_update(+ document: object, *, stored: Mapping[str, Any], limits: ValidationLimits+) -> tuple[ManagementWarning, ...]:+ """Validate the candidate against the stored document it replaces; raise on either.++ A stored document this milestone cannot validate is rejected rather than overwritten:+ replacing it with a generic admitted document would erase semantics no detector here+ can judge.+ """+ try:+ # Stored rows may predate lower byte caps; validate their semantics without+ # preventing a replacement that brings them back within the write limits.+ current = validate_config(+ stored, limits=ValidationLimits(max_config_bytes=sys.maxsize, max_metadata_bytes=sys.maxsize)+ )+ except ConfigValidationError as exc:+ raise ConfigValidationError(+ [+ ConfigError(+ code="unsupported",+ detail="This flag's stored configuration cannot be updated through this API.",+ attr="filters",+ )+ ]+ ) from exc+ return review_config(document, limits=limits, current=current).warnings