Skip to content

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

feat(flags): add the pilot config version 2 writer path (#105889)

Anders4cc6bdf018d9
diff --git a/docs/internal/feature-flags/api-writes.md b/docs/internal/feature-flags/api-writes.md
index 599adfbabb1e..61dec8b157e4 100644
--- a/docs/internal/feature-flags/api-writes.md
+++ b/docs/internal/feature-flags/api-writes.md
@@ -10,8 +10,8 @@ The serializer owns request validation, approvals, persistence, tags, evaluation
The facade's serializer dependency is legacy; this path does not establish a pattern for new facade contracts or product isolation.
Stored configurations with an absent `filters.version` or a numeric value equal to 1 use v1 validation.
-Other stored formats fail with `unsupported_config_version` before v1 normalization, including updates that omit filters or supply `{}`.
-Every incoming `filters.version`, including numeric 1, still fails with `reserved_config_version`.
+Other stored formats fail with `unsupported_config_version` before v1 normalization, including updates that omit filters or supply `{}`; stored version 2 rows take the separate path described under "Config version 2 writes".
+Every incoming `filters.version`, including numeric 1, still fails with `reserved_config_version`, except a version 2 document sent to a project the writer policy admits.
Supplied top-level v1 filter keys replace those keys in the stored state; `{}` retains targeting and `groups: []` clears it.
The existing validation rollout controls normalization and unknown-key preservation.
@@ -28,12 +28,12 @@ Metadata-only and empty-filter updates retain their existing no-op targeting sem
Restoring a deleted flag that stays disabled does not require repairing its dependencies.
Disabling, archival, and deletion retain their existing dependent-flag protections.
-| Source configuration | Target configuration | Write behavior |
-| -------------------- | ----------------------------------------- | --------------------------------------------------- |
-| V1 | Absent version, numeric 1, or numeric 1.0 | Existing dependency validation |
-| V1 | Numeric 2 or 2.0 | Reject the dependency |
-| V1 | Null, string, boolean, or another version | Reject the dependency |
-| V2 | Any flag dependency | Unsupported by the dormant validator; no write path |
+| Source configuration | Target configuration | Write behavior |
+| -------------------- | ----------------------------------------- | ----------------------------------- |
+| V1 | Absent version, numeric 1, or numeric 1.0 | Existing dependency validation |
+| V1 | Numeric 2 or 2.0 | Reject the dependency |
+| V1 | Null, string, boolean, or another version | Reject the dependency |
+| V2 | Any flag dependency | Rejected by the strict v2 validator |
The row's `FeatureFlag.version` remains an independent concurrency counter.
Conversion attempts remain blocked by incoming-version rejection and the stored-format write guard.
@@ -53,25 +53,37 @@ 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)
+## Config version 2 writes
-`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`.
+Two internal feature flags form the writer policy, evaluated by `facade.config_writes` for the `project` group (targeted by project `id`) with local evaluation only, so an unresolved flag reads as off:
-When the policy admits updates, a stored v2 row that is not remote-configured and carries no encrypted payloads takes a separate path:
+- `feature-flag-rules-v2-writes`: the projects whose flags may be created, updated and enabled with config version 2.
+- `feature-flag-rules-v2-creation`: whether an admitted project may create a new version 2 flag. Turning it off leaves existing rows updatable, enableable and disableable.
+Nothing else grants admission: no request field, serializer context flag, staff status, internal team or missing user.
+`FEATURE_FLAG_RULES_V2_MAX_METADATA_BYTES` bounds one rule's opaque `metadata` object in an admitted write; the default is pilot scope and is revisited before users author documents through the editor or broader API use.
+The deployment filter-size limit (`MAX_FEATURE_FLAG_FILTER_SIZE_BYTES`) bounds the whole document, as it does for v1.
+
+| Operation | Requires | Closed |
+| ----------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
+| Create (`POST` with `filters.version` 2) | Admitted project, creation enabled, no `active: true` | Every other project keeps `reserved_config_version`; `active: true` is rejected rather than downgraded |
+| Full-document update (`filters`) | Admitted project, current `version` | |
+| Metadata update (`name`, `key`, `tags`) | Admitted project, current `version` | Every other field, including `archived`, remote config and payload fields |
+| Enable (`active: true`) | Admitted project, current `version`, stored document valid under current limits | |
+| Disable (`active: false`) | Current `version` only | An enabled flag-write approval policy, like every other row here |
+| Delete (`deleted: true`, the soft delete) | Current `version` only; disables an enabled row in the same write | Restore (`deleted: false`); the separate `archived` field and the `/archive/` action; an enabled policy |
+
+A stored version 2 row that is not remote-configured and carries no encrypted payloads always takes this path, whatever its project: disabling and soft-deleting are the pilot's incident controls and do not depend on either writer flag.
+
+- A new row is created disabled with server-owned rule IDs and seeds; the request document is resolved against an empty stored document and validated strictly before it is persisted exactly. No v1 row is converted.
- 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.
+- `FeatureFlag.version` is required on every update 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. The token applies to disabling and deleting too.
+- Identity resolution, validation and the enable check run against the locked row inside the existing update transaction. A stored document with an unsupported shape or semantics is rejected rather than replaced or enabled. Configuration and metadata byte limits apply to a replacement, so an oversized stored document can be edited back under a lowered limit; enabling requires the stored document to fit the current limits.
- 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.
+- An enabled flag-write approval policy (`feature_flag.enable`, `feature_flag.disable` or `feature_flag.update`, on the team or its organization) denies every version 2 write, disable and delete included, and an approved change cannot be applied to a version 2 row: PH-WRITE-APPROVAL owns that path. Nothing here creates a pending change request; to disable a version 2 flag under such a policy, disable the policy first.
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.
+- Each accepted write saves once, increments `version` once, runs the existing cache invalidation and produces one activity log entry through the existing receiver. The entry carries the generic field diff; canonical version 2 summaries and version-history reconstruction are later work.
-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.
+Rollback turns both flags off. Existing version 2 rows stay readable, disableable and deletable; there is no data conversion, and v1-to-v2 dependency protection is not removed.
diff --git a/posthog/settings/feature_flags.py b/posthog/settings/feature_flags.py
index e123023a7c9d..2925872f1cbe 100644
--- a/posthog/settings/feature_flags.py
+++ b/posthog/settings/feature_flags.py
@@ -2,6 +2,8 @@ import os
import json
from contextlib import suppress
+from django.core.exceptions import ImproperlyConfigured
+
from posthog.settings.access import SECRET_KEY
from posthog.settings.base_variables import TEST
from posthog.settings.utils import get_from_env, get_list, get_set, str_to_bool
@@ -172,6 +174,20 @@ MAX_FEATURE_FLAG_FILTER_SIZE_BYTES: int = get_from_env(
type_cast=int, # 512KB
)
+# Bounds one rule's opaque metadata object in an admitted config version 2 write (admission itself
+# is by internal feature flag, see facade/config_writes.py). The default is sized for the pilot's documents;
+# revisit it before users can author v2 documents through the editor or the wider API.
+FEATURE_FLAG_RULES_V2_MAX_METADATA_BYTES: int = get_from_env(
+ "FEATURE_FLAG_RULES_V2_MAX_METADATA_BYTES", 2048, type_cast=int
+)
+
+# Both feed the v2 validator's limits, which reject a non-positive value. Fail the deploy rather than
+# the first v2 write, which may be the incident disable.
+if MAX_FEATURE_FLAG_FILTER_SIZE_BYTES <= 0 or FEATURE_FLAG_RULES_V2_MAX_METADATA_BYTES <= 0:
+ raise ImproperlyConfigured(
+ "MAX_FEATURE_FLAG_FILTER_SIZE_BYTES and FEATURE_FLAG_RULES_V2_MAX_METADATA_BYTES must be positive integers"
+ )
+
# Staged rollout for feature flag filters validation (#50084). Rule ids to reject on, comma
# separated, matching the ids in the violation metrics and in the `code` of each error this
# returns (e.g. "cross_field.variant_rollout_sum_not_100").
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index b0b90554cecd..037bce5cb5c7 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -7,6 +7,7 @@ import math
import logging
import functools
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
+from contextlib import nullcontext
from dataclasses import asdict
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, Literal, NoReturn, Optional, cast
@@ -97,7 +98,8 @@ from products.access_control.backend.presentation.access_control import (
)
from products.approvals.backend.decorators import approval_gate
from products.approvals.backend.mixins import ApprovalHandlingMixin
-from products.approvals.backend.policies import PolicyEngine, lock_approval_policies
+from products.approvals.backend.models import ApprovalPolicy
+from products.approvals.backend.policies import lock_approval_policies
from products.cohorts.backend.models.cohort import Cohort, CohortType
from products.cohorts.backend.models.util import get_all_cohort_dependencies
from products.dashboards.backend.api.dashboard import Dashboard
@@ -265,6 +267,12 @@ def _count_filters_write_success(serializer: serializers.Serializer, operation:
_count_filters_write(operation, outcome, request)
+def _cache_json_body(request: request.Request) -> None:
+ """Read the raw bytes before DRF consumes the stream, so validation can check them for duplicate keys."""
+ if request.content_type.startswith("application/json"):
+ _ = request.body
+
+
def _mirror_stored_fields(source: FeatureFlag, target: FeatureFlag) -> None:
"""Bring a stale copy of a flag up to date with the row that was just written."""
for field in source._meta.concrete_fields:
@@ -302,14 +310,15 @@ 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"})
+# What a config version 2 write may change, in request-field names; everything else stays unsupported
+# until the task that owns it lands. Disabling and soft-deleting are incident controls and need no admission.
+V2_SAFETY_FIELDS = frozenset({"version", "active", "deleted"})
+V2_UPDATE_FIELDS = V2_SAFETY_FIELDS | {"filters", "name", "key", "tags"}
+V2_CREATE_FIELDS = V2_UPDATE_FIELDS - {"deleted"}
V2_APPROVAL_ACTIONS = ("feature_flag.enable", "feature_flag.disable", "feature_flag.update")
+_MISSING: Any = object()
+
def parse_created_by_ids(value: Any) -> list[int]:
"""Parse a `created_by_id` filter value into a list of user IDs.
@@ -1432,7 +1441,9 @@ class FeatureFlagSerializer(
Treat them as omitted so enabling or restoring an active flag still checks its dependencies.
"""
- if self.instance is None or self.initial_data.get("filters"):
+ # A v2 document cannot be walked as v1; enabling one validates the stored document
+ # strictly under the lock instead, and that validator admits no flag or cohort reference.
+ if self.instance is None or self.initial_data.get("filters") or self._v2_write:
return
enabling = attrs.get("active") is True and not self.instance.active
@@ -1451,16 +1462,22 @@ class FeatureFlagSerializer(
"""Validate feature flag creation/update including evaluation tag requirements."""
# `filters` is declared with source="get_filters", so its absence means the request
# omitted filters. A supplied-filters request runs the same check in _validate_filters_inner.
- if self.instance is not None and "get_filters" not in attrs:
+ if self.instance is not None and "get_filters" not in attrs and not self._v2_write:
try:
self._validate_stored_config_format()
except serializers.ValidationError as exc:
raise serializers.ValidationError({"filters": exc.detail}) from exc
attrs = super().validate(attrs)
- if self._v2_update_limits is not None:
+ if self._v2_write:
self._reject_lossy_v2_request_json()
- self._reject_unsupported_v2_operations(attrs)
+ if self.instance is None:
+ self._validate_v2_create(attrs)
+ else:
+ echoed = self._drop_echoed_v2_fields(attrs)
+ self._reject_unsupported_v2_operations(attrs, echoed)
+ if attrs.get("deleted") is True:
+ attrs["active"] = False # soft-deleting disables in the same write; no second step to forget
# Run universal validations before any early returns so they always apply,
# regardless of creation_context (surveys, etc.) or evaluation contexts.
@@ -1569,7 +1586,6 @@ class FeatureFlagSerializer(
# distinguish "field absent from PATCH" from "field explicitly set to null". A bare
# `attrs.get(...) is None` fallback would otherwise treat an explicit null as missing
# and validate against the stale instance value.
- _MISSING: Any = object()
bucketing_identifier = attrs.get("bucketing_identifier", _MISSING)
ensure_experience_continuity = attrs.get("ensure_experience_continuity", _MISSING)
@@ -1690,9 +1706,7 @@ class FeatureFlagSerializer(
This avoids a potentially expensive feature_enabled() call for flags that don't
reference any cohort properties.
"""
- get_team = self.context.get("get_team")
- team = get_team() if get_team else Team.objects.get(pk=self.context["team_id"])
- return is_realtime_cohort_flag_targeting_enabled(self.context["request"], team=team)
+ return is_realtime_cohort_flag_targeting_enabled(self.context["request"], team=self._write_team)
def validate_filters(self, filters):
# Metrics wrapper: one increment per rejected write. `rejected` means a switch-gated
@@ -1711,7 +1725,7 @@ class FeatureFlagSerializer(
raise
def _validate_stored_config_format(self) -> None:
- if self.instance is None or self._v2_update_limits is not None:
+ if self.instance is None:
return
if detect_config_format(self.instance.filters).kind != "v1":
raise serializers.ValidationError(
@@ -1720,39 +1734,135 @@ class FeatureFlagSerializer(
)
@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.
+ def _v2_write(self) -> bool:
+ """Whether this write takes the config version 2 path.
+
+ Every stored v2 row in the admitted family takes it (no encrypted payloads, no remote
+ config), whatever its team: disabling and soft-deleting are the pilot's incident controls
+ and must not depend on a writer flag. A create takes it only when its team is admitted with
+ creation enabled and the request document says version 2, so a request that merely
+ contains numeric 2 cannot reach it elsewhere. Which operations the path then accepts
+ is decided by `_v2_limits`.
"""
- limits = config_writes.v2_update_limits()
- if limits is None or self.instance is None:
- return None
+ if self.instance is None:
+ filters = self.initial_data.get("filters") if isinstance(self.initial_data, Mapping) else None
+ team_id = self.context.get("team_id")
+ return (
+ isinstance(filters, Mapping)
+ and team_id is not None
+ and detect_config_format(filters).kind == "v2"
+ and config_writes.v2_creation_enabled(team_id)
+ )
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 (
+ detect_config_format(self.instance.filters).kind == "v2"
+ and not self.instance.has_encrypted_payloads
+ and not self.instance.is_remote_configuration
+ )
+
+ @functools.cached_property
+ def _v2_limits(self) -> ValidationLimits | None:
+ """Trusted limits when this v2 write's team is admitted, else None.
+
+ None on a stored v2 row means only the safety fields are open; None on a create means
+ the v1 path and its reserved-discriminator rejection apply. Admission is the project's
+ internal writes flag, evaluated once per serializer.
+ """
+ if not self._v2_write:
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))
+ team_id = self.instance.team_id if self.instance is not None else self.context["team_id"]
+ return config_writes.v2_write_limits(team_id)
+
+ @functools.cached_property
+ def _write_team(self) -> Team:
+ # Derived like the approval gate, instance fallback included, so a caller with no get_team context cannot skip the policy check.
+ get_team = self.context.get("get_team")
+ team = get_team() if get_team else None
+ if team is not None:
+ return team
+ if self.instance is not None:
+ return self.instance.team
+ return Team.objects.get(pk=self.context["team_id"])
+
+ 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"}
+
+ def _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."""
+ limits = self._v2_limits
+ assert limits is not None # the caller admitted this write
+ try:
+ document = config_writes.resolve_identity(submitted, 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_write_warnings",
+ extra={"flag_id": flag_id, "codes": [warning.code for warning in warnings]},
+ )
+ return document
+
+ def _validate_v2_create(self, attrs: dict) -> None:
+ """Resolve and validate an admitted v2 create. The row is born disabled."""
+ if attrs.get("active") is True:
+ raise serializers.ValidationError(
+ {
+ "active": "A flag with this configuration format is created disabled. Enable it in a separate request."
+ },
+ code="unsupported_config_version",
+ )
+ unsupported = self._unsupported_v2_fields(attrs, V2_CREATE_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"
+ f"These fields cannot be set when creating this flag: {', '.join(sorted(unsupported))}.",
+ code="unsupported_config_version",
)
+ self._reject_v2_approval_operations()
+ attrs["active"] = False
+ attrs["get_filters"] = self._resolve_v2_document(attrs["get_filters"], stored={}, flag_id=None)
+
+ def _drop_echoed_v2_fields(self, attrs: dict) -> set[str]:
+ """Remove every submitted value equal to the stored one and return their names.
+
+ An echo is neither judged nor written: PUT must repeat `key`, and a bulk delete does not
+ bump `version`, so a written `deleted: false` could undo one.
+ """
+ assert isinstance(self.instance, FeatureFlag)
+ echoed = {
+ field
+ for field in attrs
+ if field != "get_filters" and attrs[field] == getattr(self.instance, field, _MISSING)
+ }
+ for field in echoed:
+ del attrs[field]
+ return echoed
+
+ def _reject_unsupported_v2_operations(self, attrs: dict, echoed: set[str]) -> None:
+ """Deny everything about a v2 update that this milestone does not own.
+
+ Disabling and soft-deleting need no admission; every other change needs the project's writes flag.
+ Restoring a deleted row stays closed until a later task owns it.
+ """
+ admitted = self._v2_limits is not None
+ unsupported = self._unsupported_v2_fields(attrs, V2_UPDATE_FIELDS if admitted else V2_SAFETY_FIELDS) - echoed
+ if attrs.get("deleted") is False:
+ unsupported.add("deleted")
+ if attrs.get("active") is True and not admitted:
+ unsupported.add("active")
+ if unsupported:
+ raise serializers.ValidationError(
+ f"These fields cannot be updated on this flag: {', '.join(sorted(unsupported))}.",
+ code="unsupported_config_version",
+ )
+ self._reject_v2_approval_operations()
+
+ def _reject_v2_approval_operations(self) -> None:
# 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.
@@ -1760,24 +1870,20 @@ class FeatureFlagSerializer(
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)
+ self._reject_v2_approval_policy(self._write_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
+ # this team or its organization denies the write, because a v2 change that needs
+ # approval has nowhere to go. Existence only, so PolicyEngine's precedence is irrelevant.
+ if (
+ ApprovalPolicy.objects.enabled()
+ .filter(organization_id=team.organization_id, action_key__in=V2_APPROVAL_ACTIONS)
+ .filter(Q(team=team) | Q(team__isnull=True))
+ .exists()
):
raise serializers.ValidationError(
- "This flag cannot be updated while an approval policy is enabled.",
+ "This flag cannot be written while an approval policy is enabled.",
code="unsupported_config_version",
)
@@ -1817,9 +1923,7 @@ class FeatureFlagSerializer(
[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:
+ def _apply_v2_update(self, locked_instance: FeatureFlag, validated_data: dict, locked_version: int) -> 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
@@ -1836,22 +1940,18 @@ class FeatureFlagSerializer(
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]},
+ if "filters" in validated_data:
+ validated_data["filters"] = self._resolve_v2_document(
+ validated_data["filters"], stored=stored, flag_id=locked_instance.pk
)
- validated_data["filters"] = document
+ elif validated_data.get("active") is True and not locked_instance.active:
+ limits = self._v2_limits
+ assert limits is not None # enabling was admitted in validate()
+ try:
+ config_writes.validate_stored(stored, limits=limits)
+ except ConfigValidationError as exc:
+ raise self._v2_validation_error(exc) from exc
def _validate_filters_inner(self, filters, operation: str):
if _uses_reserved_variant_key(filters):
@@ -1860,10 +1960,9 @@ class FeatureFlagSerializer(
code="reserved_variant_key",
)
- 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.
+ if self._v2_limits is not None:
+ # An admitted v2 document passes through untouched (no v1 merge or normalization): a
+ # create resolves and validates it in validate(), an update in update() under the lock.
return filters
# Unknown keys survive normalization during the validation rollout. Reserve the
@@ -2422,9 +2521,13 @@ class FeatureFlagSerializer(
analytics_dashboards = validated_data.pop("analytics_dashboards", None)
try:
- self._free_key_held_by_soft_deleted_flags(validated_data["key"])
-
- with ImpersonatedContext(request):
+ with ImpersonatedContext(request), transaction.atomic() if self._v2_write else nullcontext():
+ if self._v2_write:
+ # Same lock as update(): a policy enabled after validate() must still deny the write.
+ lock_approval_policies(self._write_team.organization_id, shared=True)
+ self._reject_v2_approval_policy(self._write_team)
+ # After the policy check, so a denied v2 create does not leave a tombstone renamed or removed.
+ self._free_key_held_by_soft_deleted_flags(validated_data["key"])
instance: FeatureFlag = super().create(validated_data)
except IntegrityError as e:
self._reraise_duplicate_key_violation(e)
@@ -2539,9 +2642,8 @@ 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)
+ if self._v2_write:
+ lock_approval_policies(self._write_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.
@@ -2549,13 +2651,13 @@ class FeatureFlagSerializer(
locked_version = locked_instance.version or 0
# V1 cleanup must not strip unknown keys from a v2 document before validation.
- if v2_limits is None:
+ if not self._v2_write:
self._apply_stored_filter_rules(validated_data, locked_instance, request)
# NOW check for conflicts after all transformations
- 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)
+ if self._v2_write:
+ self._reject_v2_approval_policy(self._write_team)
+ self._apply_v2_update(locked_instance, validated_data, locked_version)
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
@@ -3823,6 +3925,7 @@ class FeatureFlagViewSet(
# The facade is imported inside the method because it imports this module's serializer.
from products.feature_flags.backend.facade.api import create_flag
+ _cache_json_body(request)
flag = create_flag(
request.data,
team=self.team,
@@ -3843,14 +3946,7 @@ class FeatureFlagViewSet(
from products.feature_flags.backend.facade.api import update_flag
instance = 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.body
+ _cache_json_body(request)
flag = update_flag(
instance,
request.data,
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py
new file mode 100644
index 000000000000..c8c0477fdab1
--- /dev/null
+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_lifecycle.py
@@ -0,0 +1,350 @@
+"""Disabling and soft-deleting a stored v2 row are the pilot's incident controls, so they must
+work with both writer flags off; creating and enabling need the project's flags on.
+"""
+
+from django.conf import settings
+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.models import 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.api.test.test_feature_flag_config_v2_updates import (
+ AdmittedV2TestCase,
+ V2UpdateTestCase,
+ admit_v2,
+ config,
+ rollout,
+ targeted,
+)
+from products.feature_flags.backend.facade import api as flag_facade
+from products.feature_flags.backend.flags_cache import _get_feature_flags_for_service
+from products.feature_flags.backend.local_evaluation import _get_flags_response_for_local_evaluation_batch
+from products.feature_flags.backend.models import FeatureFlag
+
+
+class TestV2SafetyWritesNeedNoAdmission(V2UpdateTestCase):
+ """Disabling and soft-deleting are the pilot's incident controls: they work with both writer flags off."""
+
+ @parameterized.expand(["patch", "put"])
+ def test_disabling_needs_only_the_row_version(self, method: str) -> None:
+ flag = self.flag(active=True)
+ response = self.patch_flag(flag, {"key": flag.key, "version": 3, "active": False}, method=method)
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ flag.refresh_from_db()
+ assert (flag.active, flag.version) == (False, 4)
+ (entry,) = self.activity(flag)
+ assert entry.activity == "updated"
+ assert self.changed_fields(entry) == {"active", "version"}
+
+ def test_an_echoed_deleted_false_does_not_undo_a_concurrent_bulk_delete(self) -> None:
+ flag = self.flag(active=True)
+ stale = FeatureFlag.objects.get(pk=flag.pk)
+ FeatureFlag.objects.filter(pk=flag.pk).update(deleted=True) # a bulk delete does not bump version
+ updated = flag_facade.update_flag(
+ stale, {"version": 3, "deleted": False, "active": False}, team=self.team, user=self.user
+ )
+ assert (updated.deleted, updated.active, updated.version) == (True, False, 4)
+
+ def test_soft_deleting_disables_an_enabled_row_in_the_same_write(self) -> None:
+ flag = self.flag(active=True)
+ response = self.patch_flag(flag, {"version": 3, "deleted": True})
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ flag.refresh_from_db()
+ assert (flag.deleted, flag.active, flag.version) == (True, False, 4)
+ (entry,) = self.activity(flag)
+ assert entry.activity == "deleted"
+
+ @parameterized.expand(
+ [
+ ("missing_token", {"active": False}, status.HTTP_400_BAD_REQUEST),
+ ("stale_token", {"version": 2, "active": False}, status.HTTP_409_CONFLICT),
+ ("stale_delete", {"version": 2, "deleted": True}, status.HTTP_409_CONFLICT),
+ ("restore", {"version": 3, "deleted": False}, status.HTTP_400_BAD_REQUEST),
+ ("archived_flag_field", {"version": 3, "archived": True, "active": False}, status.HTTP_400_BAD_REQUEST),
+ ("rename", {"version": 3, "active": False, "name": "Renamed"}, status.HTTP_400_BAD_REQUEST),
+ ]
+ )
+ def test_everything_else_stays_closed(self, _name: str, data: dict, expected: int) -> None:
+ flag = self.flag(active=True, deleted=data.get("deleted") is False)
+ response = self.patch_flag(flag, data)
+ assert response.status_code == expected, response.json()
+ flag.refresh_from_db()
+ assert flag.active
+ assert flag.version == 3
+ assert self.activity(flag) == []
+
+ @parameterized.expand(
+ [
+ ("enable", False, "unsupported_config_version"),
+ ("disable", True, "required"),
+ ("archive", True, "unsupported_config_version"),
+ ]
+ )
+ def test_body_less_lifecycle_actions_reject_v2_rows_explicitly(self, action: str, active: bool, code: str) -> None:
+ flag = self.flag(active=active)
+ response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/{action}/")
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["code"] == code
+ flag.refresh_from_db()
+ assert (flag.active, flag.archived, flag.version) == (active, False, 3)
+
+
+class TestAdmittedV2Creation(AdmittedV2TestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.enterContext(admit_v2(self.team.id, creation=True))
+
+ def test_create_is_disabled_with_server_identity_and_round_trips(self) -> None:
+ submitted = config(targeted(rule_id=None), rollout(rule_id=None, seed=None))
+ response = self.post_flag({"key": "new-v2", "name": "Pilot", "filters": submitted})
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ flag = FeatureFlag.objects.get(team=self.team, key="new-v2")
+ assert (flag.active, flag.version, flag.name) == (False, 1, "Pilot")
+ rules = flag.filters["rules"]
+ assert [rule["rule_type"] for rule in rules] == ["targeted_release", "percentage_rollout"]
+ assert len({rule["id"] for rule in rules}) == 2 and rules[1]["seed"]
+ assert {
+ **flag.filters,
+ "rules": [{k: v for k, v in r.items() if k not in ("id", "seed")} for r in rules],
+ } == submitted
+ assert response.json()["filters"] == flag.filters
+ read = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/")
+ assert read.status_code == status.HTTP_200_OK
+ assert (read.json()["filters"], read.json()["active"]) == (flag.filters, False)
+ (entry,) = self.activity(flag)
+ assert entry.activity == "created"
+
+ def test_active_on_create_is_rejected_not_downgraded(self) -> None:
+ response = self.post_flag({"key": "new-v2", "filters": config(targeted(rule_id=None)), "active": True})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert (response.json()["code"], response.json()["attr"]) == ("unsupported_config_version", "active")
+ assert not FeatureFlag.objects.filter(team=self.team, key="new-v2").exists()
+
+ @parameterized.expand(
+ [
+ ("client_id", {"filters": config(targeted())}, "invalid_input"),
+ ("fragment", {"filters": {"version": 2, "rules": []}}, "required"),
+ ("remote_config", {"filters": config(), "is_remote_configuration": True}, "unsupported_config_version"),
+ ("encrypted", {"filters": config(), "has_encrypted_payloads": True}, "unsupported_config_version"),
+ ("archived", {"filters": config(), "archived": True}, "unsupported_config_version"),
+ ("deleted", {"filters": config(), "deleted": True}, "unsupported_config_version"),
+ ("continuity", {"filters": config(), "ensure_experience_continuity": True}, "unsupported_config_version"),
+ ("unknown", {"filters": config(), "naem": "x"}, "unsupported_config_version"),
+ ]
+ )
+ def test_invalid_documents_and_unsupported_fields_are_rejected(self, _name: str, data: dict, code: str) -> None:
+ response = self.post_flag({"key": "new-v2", **data})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["code"] == code, response.json()
+ assert not FeatureFlag.objects.filter(team=self.team, key="new-v2").exists()
+
+ def test_v1_creates_and_version_1_stay_as_before(self) -> None:
+ response = self.post_flag(
+ {"key": "v1-flag", "filters": {"groups": [{"properties": [], "rollout_percentage": 50}]}}
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ assert FeatureFlag.objects.get(team=self.team, key="v1-flag").active
+ response = self.post_flag({"key": "reserved", "filters": {"version": 1, "groups": []}})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["code"] == "reserved_config_version"
+
+ def test_another_team_stays_reserved_while_this_one_creates(self) -> None:
+ other = Team.objects.create(organization=self.organization, name="not admitted")
+ response = self.client.post(
+ f"/api/projects/{other.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"
+
+ def test_an_enabled_approval_policy_denies_the_create(self) -> None:
+ ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="feature_flag.update",
+ approver_config={},
+ enabled=True,
+ )
+ response = self.post_flag({"key": "new-v2", "filters": config()})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["code"] == "unsupported_config_version"
+ assert not FeatureFlag.objects.filter(team=self.team, key="new-v2").exists()
+ assert not ChangeRequest.objects.filter(organization=self.organization).exists()
+
+ def test_a_policy_enabled_after_validation_denies_the_create(self) -> None:
+ tombstone = self.flag(key="new-v2", deleted=True)
+ serializer = FeatureFlagSerializer(
+ data={"key": "new-v2", "filters": config()},
+ context={
+ "request": ServiceRequest(self.user),
+ "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)
+
+ with self.assertRaises(ValidationError) as error:
+ serializer.save()
+
+ assert error.exception.get_codes() == ["unsupported_config_version"]
+ assert not FeatureFlag.objects.filter(team=self.team, key="new-v2").exists()
+ tombstone.refresh_from_db()
+ assert (tombstone.key, tombstone.deleted) == ("new-v2", True)
+
+ def test_approval_replay_cannot_create(self) -> None:
+ serializer = FeatureFlagSerializer(
+ data={"key": "new-v2", "filters": config()},
+ context={
+ "request": ServiceRequest(self.user),
+ "team_id": self.team.id,
+ "project_id": self.team.project_id,
+ "approval_apply": True,
+ },
+ )
+ assert not serializer.is_valid()
+ assert "unsupported_config_version" in str(serializer.errors)
+
+ @override_settings(MIDDLEWARE=[])
+ def test_duplicate_keys_in_the_create_bytes_are_rejected(self) -> None:
+ self.client.force_authenticate(user=self.user)
+ body = '{"key": "new-v2", "filters": {"version": 2, "version": 2, "return_type": "boolean", "default_value": false, "rules": []}}'
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/feature_flags/", body, content_type="application/json"
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert '"version"' in response.json()["detail"]
+ assert not FeatureFlag.objects.filter(team=self.team, key="new-v2").exists()
+
+
+class TestAdmittedV2Enabling(AdmittedV2TestCase):
+ def test_enable_and_disable_are_one_version_checked_toggle(self) -> None:
+ flag = self.flag(active=False)
+ response = self.patch_flag(flag, {"version": 3, "active": True})
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ flag.refresh_from_db()
+ assert (flag.active, flag.version) == (True, 4)
+ assert self.patch_flag(flag, {"version": 3, "active": False}).status_code == status.HTTP_409_CONFLICT
+ assert self.patch_flag(flag, {"version": 4, "active": False}).status_code == status.HTTP_200_OK
+ flag.refresh_from_db()
+ assert (flag.active, flag.version) == (False, 5)
+ assert [entry.activity for entry in self.activity(flag)] == ["updated", "updated"]
+
+ @parameterized.expand(
+ [
+ ("malformed", {"version": 2, "rules": "broken"}, settings.MAX_FEATURE_FLAG_FILTER_SIZE_BYTES),
+ (
+ "flag_reference",
+ config(
+ targeted(
+ targeting={
+ "properties": [{"key": "1", "type": "flag", "value": True, "operator": "flag_evaluates_to"}]
+ }
+ )
+ ),
+ settings.MAX_FEATURE_FLAG_FILTER_SIZE_BYTES,
+ ),
+ ("over_the_current_limit", config(targeted(description="x" * 400)), 200),
+ ]
+ )
+ def test_enabling_rechecks_the_stored_document(
+ self, _name: str, stored: dict, max_config_bytes: int | None
+ ) -> None:
+ flag = self.flag(stored, active=False)
+ with override_settings(
+ MAX_FEATURE_FLAG_FILTER_SIZE_BYTES=max_config_bytes or settings.MAX_FEATURE_FLAG_FILTER_SIZE_BYTES
+ ):
+ response = self.patch_flag(flag, {"version": 3, "active": True})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ flag.refresh_from_db()
+ assert (flag.active, flag.version, flag.filters) == (False, 3, stored)
+ assert self.activity(flag) == []
+
+ def test_an_enabled_approval_policy_denies_enabling(self) -> None:
+ ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key="feature_flag.enable",
+ approver_config={},
+ enabled=True,
+ )
+ flag = self.flag(active=False)
+ response = self.patch_flag(flag, {"version": 3, "active": True})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["code"] == "unsupported_config_version"
+ flag.refresh_from_db()
+ assert not flag.active
+ assert not ChangeRequest.objects.filter(organization=self.organization).exists()
+
+
+class TestV2PilotLifecycle(AdmittedV2TestCase):
+ """Create, read, enable, replace, stale write, disable, re-enable, delete through the public API:
+ one activity entry and one version step per write.
+ """
+
+ def check(self, response, flag_id: int, *, version: int, entries: int, expected: int = status.HTTP_200_OK):
+ assert response.status_code == expected, response.json()
+ flag = FeatureFlag.objects_including_soft_deleted.get(pk=flag_id)
+ assert flag.version == version
+ assert len(self.activity(flag)) == entries
+ return flag
+
+ def test_create_read_enable_update_close_disable_recover_delete(self) -> None:
+ initial = config(targeted(rule_id=None), rollout(rule_id=None, seed=None))
+ with admit_v2(self.team.id, creation=True):
+ response = self.post_flag({"key": "pilot-flag", "filters": initial})
+ flag = self.check(response, response.json()["id"], version=1, entries=1, expected=status.HTTP_201_CREATED)
+ assert not flag.active
+ stored = flag.filters
+ read = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/").json()
+ assert (read["filters"], read["active"], read["version"]) == (stored, False, 1)
+
+ flag = self.check(self.patch_flag(flag, {"version": 1, "active": True}), flag.id, version=2, entries=2)
+ assert flag.active
+ assert "pilot-flag" not in {
+ f["key"] for f in _get_flags_response_for_local_evaluation_batch([self.team])[self.team.id]["flags"]
+ }
+ assert "pilot-flag" not in {f["key"] for f in _get_feature_flags_for_service(self.team)["flags"]}
+
+ replacement = config(
+ targeted(rule_id=stored["rules"][0]["id"], value=False),
+ rollout(rule_id=None, seed=None, rollout_percentage=50),
+ )
+ flag = self.check(self.patch_flag(flag, {"version": 2, "filters": replacement}), flag.id, version=3, entries=3)
+ assert flag.filters["rules"][0] == replacement["rules"][0]
+ assert flag.filters["rules"][1]["rollout_percentage"] == 50 and flag.filters["rules"][1]["seed"]
+ stale = self.patch_flag(flag, {"version": 2, "filters": config()})
+ flag = self.check(stale, flag.id, version=3, entries=3, expected=status.HTTP_409_CONFLICT)
+
+ flag = self.check(self.patch_flag(flag, {"version": 3, "active": False}), flag.id, version=4, entries=4)
+ assert not flag.active
+ flag = self.check(self.patch_flag(flag, {"version": 4, "active": True}), flag.id, version=5, entries=5)
+ assert flag.active
+ flag = self.check(self.patch_flag(flag, {"version": 5, "active": False}), flag.id, version=6, entries=6)
+ flag = self.check(self.patch_flag(flag, {"version": 6, "deleted": True}), flag.id, version=7, entries=7)
+ assert (flag.deleted, flag.active) == (True, False)
+ assert not FeatureFlag.objects.filter(pk=flag.id).exists()
+
+ entries = self.activity(flag)
+ assert [entry.activity for entry in entries] == ["created", *["updated"] * 5, "deleted"]
+ assert [self.changed_fields(entry) for entry in entries[1:]] == [
+ {"active", "version"},
+ {"filters", "version"},
+ {"active", "version"},
+ {"active", "version"},
+ {"active", "version"},
+ {"deleted", "version"},
+ ]
+ history = self.client.get(f"/api/projects/{self.team.id}/feature_flags/{flag.id}/versions/1/")
+ assert history.status_code == status.HTTP_200_OK, history.json()
+ assert (history.json()["filters"]["rules"], history.json()["active"]) == (stored["rules"], False)
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py b/products/feature_flags/backend/api/test/test_feature_flag_config_v2_updates.py
index 680716886de9..455b6eda7508 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
@@ -1,9 +1,8 @@
-"""Config version 2 update path: closed in production, exercised through a test-only admission.
+"""Config version 2 update path: full-document replacement, identity, concurrency and 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.
+Both writer flags are off in tests, so the closed-path tests run as production does and the
+admitted ones stub the flag client for one project. Create, enable, disable and soft delete are
+covered in test_feature_flag_config_v2_lifecycle. These flags are invented test rows.
"""
import copy
@@ -15,7 +14,7 @@ from unittest.mock import patch
from django.conf import settings
from django.db import OperationalError, connection, transaction
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
from rest_framework import status
@@ -24,6 +23,7 @@ from rest_framework.exceptions import ValidationError
from posthog.api.utils import ServiceRequest
from posthog.constants import AvailableFeature
from posthog.models import Organization, Team
+from posthog.models.activity_logging.activity_log import ActivityLog
from products.approvals.backend.models import ApprovalPolicy, ChangeRequest
from products.approvals.backend.serializers import ApprovalPolicySerializer
@@ -32,21 +32,22 @@ 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 admit_v2(team_id: int, *, creation: bool = False):
+ """Turn the writer flags on for one project the way the local flag client would answer."""
+ enabled = {config_writes.V2_WRITES_FLAG} | ({config_writes.V2_CREATION_FLAG} if creation else set())
+
+ def evaluate(key: str, distinct_id: str, **kwargs: Any) -> bool:
+ return key in enabled and kwargs.get("groups", {}).get("project") == str(team_id)
+
+ return patch("posthoganalytics.feature_enabled", side_effect=evaluate)
def targeted(rule_id: str | None = RULE_A, **extra: Any) -> dict:
@@ -75,9 +76,30 @@ def config(*rules: dict, **extra: Any) -> dict:
return {"version": 2, "return_type": "boolean", "default_value": False, "rules": list(rules), **extra}
+class TestWriterAdmission(SimpleTestCase):
+ def test_the_gate_evaluates_locally_for_the_project_and_captures_nothing(self) -> None:
+ with patch("posthoganalytics.feature_enabled", return_value=True) as feature_enabled:
+ assert config_writes.v2_write_limits(42) is not None
+ kwargs = feature_enabled.call_args.kwargs
+ assert kwargs["only_evaluate_locally"] is True
+ assert kwargs["send_feature_flag_events"] is False
+ assert kwargs["groups"] == {"project": "42"}
+ assert kwargs["group_properties"] == {"project": {"id": "42"}}
+
+ def test_a_broken_client_reads_closed_and_is_logged(self) -> None:
+ with (
+ patch("posthoganalytics.feature_enabled", side_effect=RuntimeError("boom")),
+ patch.object(config_writes, "logger") as logger,
+ ):
+ assert config_writes.v2_write_limits(42) is None
+ assert config_writes.v2_creation_enabled(42) is False
+ assert logger.warning.call_args.args[0] == "feature_flag_rules_v2_flag_evaluation_failed"
+ assert logger.warning.call_args.kwargs["team_id"] == 42
+
+
class V2UpdateTestCase(APIBaseTest):
def flag(self, filters: dict | None = None, **extra: Any) -> FeatureFlag:
- return FeatureFlag.objects.create(
+ flag = FeatureFlag.objects.create(
team=self.team,
key=extra.pop("key", "v2-flag"),
filters=filters if filters is not None else config(targeted(), rollout()),
@@ -85,15 +107,30 @@ class V2UpdateTestCase(APIBaseTest):
created_by=self.user,
**extra,
)
+ self._activity_qs(flag).delete()
+ return flag
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"
)
+ def post_flag(self, data: dict):
+ return self.client.post(f"/api/projects/{self.team.id}/feature_flags/", data, format="json")
+
+ def _activity_qs(self, flag: FeatureFlag):
+ return ActivityLog.objects.filter(team_id=self.team.id, scope="FeatureFlag", item_id=str(flag.id))
+
+ def activity(self, flag: FeatureFlag) -> list[ActivityLog]:
+ return list(self._activity_qs(flag).order_by("created_at"))
+
+ @staticmethod
+ def changed_fields(entry: ActivityLog) -> set[str]:
+ return {change["field"] for change in (entry.detail or {})["changes"]}
-class TestV2UpdatesAreClosed(V2UpdateTestCase):
- """With production settings nothing reaches the v2 path, through any entrypoint."""
+
+class TestV2WritesAreClosed(V2UpdateTestCase):
+ """With production settings no create, replacement or enable 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:
@@ -159,12 +196,33 @@ class TestV2UpdatesAreClosed(V2UpdateTestCase):
assert not serializer.is_valid()
assert serializer.errors["filters"][0].code == "reserved_config_version"
+ def test_facade_and_direct_serializer_creates_are_reserved(self) -> None:
+ with self.assertRaises(ValidationError) as caught:
+ flag_facade.create_flag({"key": "new-v2", "filters": config()}, team=self.team, user=self.user)
+ assert caught.exception.get_codes() == {"filters": ["reserved_config_version"]}
+ serializer = FeatureFlagSerializer(
+ data={"key": "new-v2", "filters": config()},
+ context={"request": ServiceRequest(self.user), "team_id": self.team.id, "project_id": self.team.project_id},
+ )
+ assert not serializer.is_valid()
+ assert serializer.errors["filters"][0].code == "reserved_config_version"
+ assert not FeatureFlag.objects.filter(key="new-v2").exists()
+
+ def test_enabling_is_rejected_without_admission(self) -> None:
+ flag = self.flag(active=False)
+ response = self.patch_flag(flag, {"version": 3, "active": True})
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["code"] == "unsupported_config_version"
+ flag.refresh_from_db()
+ assert not flag.active
+ assert flag.version == 3
+
@override_settings(FEATURE_FLAG_FILTERS_ENFORCED_RULES={"*"})
class AdmittedV2TestCase(V2UpdateTestCase):
def setUp(self) -> None:
super().setUp()
- self.enterContext(admit_v2_updates())
+ self.enterContext(admit_v2(self.team.id))
class TestAdmittedV2Updates(AdmittedV2TestCase):
@@ -177,10 +235,8 @@ class TestAdmittedV2Updates(AdmittedV2TestCase):
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"
- )
+ 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_REQUEST
assert response.json()["code"] == "reserved_config_version"
assert not FeatureFlag.objects.filter(team=self.team, key="new-v2").exists()
@@ -417,7 +473,7 @@ class TestV2ApprovalPolicyLocking(NonAtomicBaseTest):
finally:
connection.close()
- with admit_v2_updates(), transaction.atomic():
+ with admit_v2(self.team.id), 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)
@@ -475,7 +531,7 @@ class TestV2ApprovalPolicyLocking(NonAtomicBaseTest):
assert getattr(error.exception.__cause__, "sqlstate", None) == "55P03"
with (
- admit_v2_updates(),
+ admit_v2(self.team.id),
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)
@@ -516,9 +572,7 @@ class TestV2AdmissionBoundary(AdmittedV2TestCase):
@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}),
@@ -669,7 +723,7 @@ class TestV2RequestBytes(AdmittedV2TestCase):
@parameterized.expand(
[
("config", config(targeted(description="x" * 400)), 200),
- ("metadata", config(targeted(metadata={"note": "x" * 4000})), ADMITTED_LIMITS.max_config_bytes),
+ ("metadata", config(targeted(metadata={"note": "x" * 4000})), settings.MAX_FEATURE_FLAG_FILTER_SIZE_BYTES),
]
)
def test_an_oversized_stored_document_can_be_replaced_within_the_limits(
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_config_version.py b/products/feature_flags/backend/api/test/test_feature_flag_config_version.py
index 0f6153660bdd..f3a4871665b1 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag_config_version.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_version.py
@@ -26,6 +26,8 @@ class TestFeatureFlagConfigVersionValidation(SimpleTestCase):
("empty", {"filters": {}}),
("supplied", {"filters": {"groups": "invalid"}}),
]
+ # A filters-less update of a stored v2 row takes the v2 path, which needs the database.
+ if not (version == 2 and shape == "omitted")
]
)
def test_stored_config_rejected_before_v1_validation(
@@ -64,8 +66,14 @@ class TestFeatureFlagConfigVersionValidation(SimpleTestCase):
@override_settings(FEATURE_FLAG_FILTERS_ENFORCED_RULES={"cross_field.variant_rollout_sum_not_100"})
class TestFeatureFlagConfigVersionWrites(APIBaseTest):
- @parameterized.expand([("patch", {}), ("patch", {"filters": {}}), ("put", {"filters": {"groups": []}})])
- def test_unsupported_stored_config_is_not_rewritten(self, method: str, data: dict) -> None:
+ @parameterized.expand(
+ [
+ ("patch", {}, None),
+ ("patch", {"filters": {}}, "filters"),
+ ("put", {"filters": {"groups": []}}, "filters"),
+ ]
+ )
+ def test_unsupported_stored_config_is_not_rewritten(self, method: str, data: dict, attr: str | None) -> None:
filters = {"version": 2, "return_type": "boolean", "default_value": False, "rules": []}
flag = FeatureFlag.objects.create(team=self.team, key="stored-config", filters=filters, version=7)
response = getattr(self.client, method)(
@@ -75,7 +83,7 @@ class TestFeatureFlagConfigVersionWrites(APIBaseTest):
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert response.json()["code"] == "unsupported_config_version"
- assert response.json()["attr"] == "filters"
+ assert response.json()["attr"] == attr
flag.refresh_from_db()
assert flag.filters == filters
assert flag.version == 7
diff --git a/products/feature_flags/backend/facade/config_writes.py b/products/feature_flags/backend/facade/config_writes.py
index f3da72c3e5de..a55bc1f0030e 100644
--- a/products/feature_flags/backend/facade/config_writes.py
+++ b/products/feature_flags/backend/facade/config_writes.py
@@ -1,11 +1,11 @@
-"""Writer admission and server-owned identity for config version 2 updates.
+"""Writer admission and server-owned identity for config version 2 writes.
-Three things a v2 update needs that the pure validator deliberately does not do:
+Three things a v2 write 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``.
+- **Admission.** ``v2_write_limits`` and ``v2_creation_enabled`` are the writer policy: two
+ internal feature flags evaluated for the project, both off by default. Nothing else grants
+ admission. Disabling and soft-deleting an existing v2 row need neither, which the serializer
+ decides; the operation matrix is 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.
@@ -25,40 +25,72 @@ from uuid import uuid4
from django.conf import settings
+import structlog
+
+from posthog.ph_client import feature_enabled_or_false
+
from products.feature_flags.backend.facade.config_validation import (
ConfigError,
ConfigValidationError,
+ ValidatedConfig,
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
+logger = structlog.get_logger(__name__)
_SEEDED_RULE_TYPE = "percentage_rollout"
+# Internal feature flags, targeted at the ``project`` group by id. Both off means closed.
+V2_WRITES_FLAG = "feature-flag-rules-v2-writes"
+V2_CREATION_FLAG = "feature-flag-rules-v2-creation"
+
+
+def _flag_enabled(key: str, team_id: int) -> bool:
+ # Local evaluation only, so a write never waits on a remote call; an unresolved flag reads as closed.
+ try:
+ return feature_enabled_or_false(
+ key,
+ f"team-{team_id}",
+ groups={"project": str(team_id)},
+ group_properties={"project": {"id": str(team_id)}},
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ logger.warning("feature_flag_rules_v2_flag_evaluation_failed", flag=key, team_id=team_id, exc_info=True)
+ return False
+
+
+def v2_write_limits(team_id: int) -> ValidationLimits | None:
+ """Trusted limits for a v2 write on ``team_id``'s flags, or ``None`` when the project is not admitted.
-def v2_update_limits() -> ValidationLimits | None:
- """Trusted limits for an admitted v2 update, or ``None`` when the write is denied.
+ Admission is the ``feature-flag-rules-v2-writes`` flag for the project alone: no request
+ field, serializer context flag, staff status or missing user opens it.
- 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.
+ ``max_config_bytes`` is the deployment filter-size limit the v1 write path and the Rust
+ reader both enforce. ``max_metadata_bytes`` is pilot scope: its default is sized for the
+ known pilot documents; revisit it before users can author v2 documents through the editor
+ or the wider API.
"""
- limits = V2_UPDATE_LIMITS
- if limits is None:
+ if not _flag_enabled(V2_WRITES_FLAG, team_id):
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,
+ max_config_bytes=settings.MAX_FEATURE_FLAG_FILTER_SIZE_BYTES,
+ max_metadata_bytes=settings.FEATURE_FLAG_RULES_V2_MAX_METADATA_BYTES,
)
+def v2_creation_enabled(team_id: int) -> bool:
+ """Whether ``team_id`` may create a new v2 flag: both the writes and the creation flag are on.
+
+ Turning the creation flag off leaves existing rows updatable and enableable in admitted projects.
+ """
+ return _flag_enabled(V2_CREATION_FLAG, team_id) and _flag_enabled(V2_WRITES_FLAG, team_id)
+
+
def reject_duplicate_json_keys(body: bytes) -> None:
"""Reject request bytes that carry the same key twice at any depth.
@@ -179,22 +211,27 @@ def review_update(
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.
+ can judge. An empty ``stored`` is a create, which has no current document to compare.
"""
+ # Stored rows may predate lower byte caps; validate their semantics without
+ # preventing a replacement that brings them back within the write limits.
+ unbounded = ValidationLimits(max_config_bytes=sys.maxsize, max_metadata_bytes=sys.maxsize)
+ current = _validated_stored(stored, limits=unbounded, operation="updated") if stored else None
+ return review_config(document, limits=limits, current=current).warnings
+
+
+def validate_stored(stored: Mapping[str, Any], *, limits: ValidationLimits) -> None:
+ """Reject enabling a stored document that no longer validates under the current limits.
+
+ Enabling is what makes the document reachable by evaluation, so a row written under an
+ older contract or a larger byte limit must be edited back into validity first.
+ """
+ _validated_stored(stored, limits=limits, operation="enabled")
+
+
+def _validated_stored(stored: Mapping[str, Any], *, limits: ValidationLimits, operation: str) -> ValidatedConfig:
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)
- )
+ return validate_config(stored, limits=limits)
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
+ detail = f"This flag's stored configuration cannot be {operation} through this API."
+ raise ConfigValidationError([ConfigError(code="unsupported", detail=detail, attr="filters")]) from exc
diff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.py
index 3d3ffd1801be..8b30580d42ae 100644
--- a/products/feature_flags/backend/test/test_facade.py
+++ b/products/feature_flags/backend/test/test_facade.py
@@ -45,17 +45,18 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlag
class TestFeatureFlagFacadeGatedWrites(APIBaseTest):
@parameterized.expand([("user", False), ("system", True)])
- def test_unsupported_stored_config_cannot_be_updated(self, _name: str, system: bool) -> None:
+ def test_stored_v2_config_can_only_be_disabled_with_its_row_version(self, _name: str, system: bool) -> None:
filters = {"version": 2, "return_type": "boolean", "default_value": False, "rules": []}
flag = self._create_flag(filters=filters)
- original_version = flag.version
+ user = None if system else self.user
with self.assertRaises(ValidationError) as exc:
- update_flag(flag, {"active": False}, team=self.team, user=None if system else self.user)
- assert exc.exception.get_codes() == {"filters": ["unsupported_config_version"]}
+ update_flag(flag, {"active": False}, team=self.team, user=user)
+ assert exc.exception.get_codes() == {"version": "required"}
flag.refresh_from_db()
- assert flag.active is True
- assert flag.filters == filters
- assert flag.version == original_version
+ assert (flag.active, flag.version) == (True, 1)
+ update_flag(flag, {"version": 1, "active": False}, team=self.team, user=user)
+ flag.refresh_from_db()
+ assert (flag.active, flag.version, flag.filters) == (False, 2, filters)
def _create_flag(self, *, active: bool = True, filters: dict | None = None) -> FeatureFlag:
return FeatureFlag.objects.create(