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.

chore(flags): add config format accessors (#96175)

Andersb9351db3f88e
diff --git a/docs/internal/feature-flags/django-api-endpoints.md b/docs/internal/feature-flags/django-api-endpoints.md
index 356ee5c6ed60..39eb6690e2b5 100644
--- a/docs/internal/feature-flags/django-api-endpoints.md
+++ b/docs/internal/feature-flags/django-api-endpoints.md
@@ -49,6 +49,15 @@ All in `posthog/api/feature_flag.py` unless noted otherwise.
Standard REST on `/api/projects/{id}/feature_flags/`. Hard `DELETE` is blocked — use `PATCH` with `deleted: true` for soft delete.
+The v1 write API rejects an incoming `filters.version` key with HTTP 400 and code
+`reserved_config_version`, regardless of `FEATURE_FLAG_FILTERS_ENFORCED_RULES`.
+Omit that key when creating or updating targeting. The top-level `version` field
+still provides optimistic concurrency control.
+
+This check does not migrate existing filters with a stray `version` key. Reads and
+updates that omit filters keep their existing behavior. The experiment-rule accessor
+rejects stored filters whose config discriminator is v2 or unsupported.
+
### Custom actions
| Method | URL | Description |
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index 4605260e8dd9..b0429e4c4da0 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -1601,6 +1601,13 @@ class FeatureFlagSerializer(
raise
def _validate_filters_inner(self, filters, operation: str):
+ # Unknown keys survive normalization during the validation rollout. Reserve the
+ # config discriminator before that path can store an unsupported format.
+ if "version" in filters:
+ raise serializers.ValidationError(
+ "filters.version is reserved. Remove it from the request.", code="reserved_config_version"
+ )
+
# An empty filters dict on an update carries no instruction, so the merged state is
# the stored state and there is nothing to validate. Returning it untouched also
# keeps normalization off flags the request never addressed: DRF hands DictField an
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
new file mode 100644
index 000000000000..64c56ee4daef
--- /dev/null
+++ b/products/feature_flags/backend/api/test/test_feature_flag_config_version.py
@@ -0,0 +1,54 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+
+from django.test import SimpleTestCase, override_settings
+
+from parameterized import parameterized
+from rest_framework import status
+
+from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer
+from products.feature_flags.backend.models import FeatureFlag
+
+
+class TestFeatureFlagConfigVersionValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (f"{mode}_{index}", enforced_rules, version)
+ for mode, enforced_rules in [
+ ("log_only", set()),
+ ("partial", {"cross_field.variant_rollout_sum_not_100"}),
+ ("full", {"*"}),
+ ]
+ for index, version in enumerate([1, 2, "1", True, None, 3])
+ ]
+ )
+ def test_config_version_is_reserved(self, _name: str, enforced_rules: set[str], version: Any) -> None:
+ with override_settings(FEATURE_FLAG_FILTERS_ENFORCED_RULES=enforced_rules):
+ serializer = FeatureFlagSerializer(data={"filters": {"version": version}}, partial=True)
+ assert not serializer.is_valid()
+ assert serializer.errors["filters"][0].code == "reserved_config_version"
+
+
+@override_settings(FEATURE_FLAG_FILTERS_ENFORCED_RULES={"cross_field.variant_rollout_sum_not_100"})
+class TestFeatureFlagConfigVersionWrites(APIBaseTest):
+ @parameterized.expand([("create",), ("update",)])
+ def test_config_version_cannot_reach_storage(self, operation: str) -> None:
+ filters = {"groups": [{"properties": [], "rollout_percentage": 40}]}
+ url = f"/api/projects/{self.team.id}/feature_flags/"
+ if operation == "update":
+ flag = FeatureFlag.objects.create(team=self.team, key="reserved-version", filters=filters)
+ response = self.client.patch(f"{url}{flag.id}/", {"filters": {"version": "1"}}, format="json")
+ else:
+ response = self.client.post(
+ url, {"key": "reserved-version", "filters": {**filters, "version": "1"}}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["code"] == "reserved_config_version"
+ assert response.json()["attr"] == "filters"
+ if operation == "update":
+ flag.refresh_from_db()
+ assert flag.filters == filters
+ else:
+ assert not FeatureFlag.objects.filter(team=self.team, key="reserved-version").exists()
diff --git a/products/feature_flags/backend/facade/config.py b/products/feature_flags/backend/facade/config.py
new file mode 100644
index 000000000000..cdf3f42ad1dc
--- /dev/null
+++ b/products/feature_flags/backend/facade/config.py
@@ -0,0 +1,109 @@
+"""Format detection and structural read DTOs for stored feature flag ``filters``.
+
+A flag's ``filters`` JSON is one of two stored config formats. Config version 1 is the shape
+every current reader knows: ``groups``, ``multivariate``, ``payloads`` and friends. Config
+version 2 is a separate document selected by ``filters.version == 2``. One document is
+entirely v1 or entirely v2. ``FeatureFlag.version``, the row's concurrency counter, is
+unrelated to ``filters.version``.
+
+Detection follows the Feature Flag Rules v2 contract: an absent ``version`` or a number that
+equals 1 selects v1, a number that equals 2 selects v2, and everything else is unsupported.
+A JSON string or boolean never selects a version. An unsupported document is never read as
+v1, so a reader with only a v1 branch checks the format before it touches any v1 key.
+
+The v2 DTOs are structural reads of a stored document. They carry the fields later consumers
+route on (return type, ordered rule identities, experiment identity) and nothing else. The
+full v2 schema lives in the contract; do not grow this module into a second copy of it.
+
+Deliberately free of Django/DRF imports (same reason as ``facade.filters``): consumer model
+modules import this at module level.
+"""
+
+from collections.abc import Mapping
+from typing import Any, Literal, get_args
+
+from posthog.dataclasses import frozen
+
+ConfigFormatKind = Literal["v1", "v2", "unsupported"]
+FlagReturnType = Literal["boolean", "string", "number", "object"]
+RuleType = Literal["targeted_release", "percentage_rollout", "experiment"]
+FlagValue = bool | str | int | float | dict[str, Any]
+
+
+@frozen
+class ConfigFormat:
+ kind: ConfigFormatKind
+ # The stored ``version`` as read, kept for diagnostics. None when absent or stored as null.
+ raw_version: object
+
+
+class ConfigFormatError(ValueError):
+ """A reader received a stored config in a format it does not support."""
+
+ def __init__(self, config_format: ConfigFormat) -> None:
+ super().__init__(f"config format {config_format.kind!r} is not handled here")
+ self.config_format = config_format
+
+
+def detect_config_format(filters: Mapping[str, Any] | None) -> ConfigFormat:
+ if not filters or "version" not in filters:
+ return ConfigFormat(kind="v1", raw_version=None)
+ version = filters["version"]
+ # bool is an int subclass, so ``True == 1`` would read as v1 without this guard.
+ if isinstance(version, bool) or not isinstance(version, int | float):
+ return ConfigFormat(kind="unsupported", raw_version=version)
+ if version == 1:
+ return ConfigFormat(kind="v1", raw_version=version)
+ if version == 2:
+ return ConfigFormat(kind="v2", raw_version=version)
+ return ConfigFormat(kind="unsupported", raw_version=version)
+
+
+@frozen
+class RuleV2:
+ id: str
+ rule_type: RuleType
+ experiment_id: int | None
+
+ def __post_init__(self) -> None:
+ if self.rule_type not in get_args(RuleType):
+ raise ValueError("Unsupported feature flag rule type")
+
+
+@frozen
+class ConfigV2:
+ return_type: FlagReturnType
+ default_value: FlagValue | None
+ rules: tuple[RuleV2, ...] # stored order, which is evaluation order
+ aggregation_group_type_index: int | None
+
+ def __post_init__(self) -> None:
+ if self.return_type not in get_args(FlagReturnType):
+ raise ValueError("Unsupported feature flag return type")
+
+
+def parse_v2_config(filters: Mapping[str, Any]) -> ConfigV2:
+ """Structural read of a stored v2 document.
+
+ Checks the return type and rule types so consumers can dispatch on their closed sets.
+ The write boundary owns full schema validation. Missing required keys raise KeyError
+ instead of being coerced into a partial read.
+ """
+ config_format = detect_config_format(filters)
+ if config_format.kind != "v2":
+ raise ConfigFormatError(config_format)
+ return ConfigV2(
+ return_type=filters["return_type"],
+ default_value=filters["default_value"],
+ rules=tuple(_rule_v2(rule) for rule in filters["rules"]),
+ aggregation_group_type_index=filters.get("aggregation_group_type_index"),
+ )
+
+
+def _rule_v2(rule: Mapping[str, Any]) -> RuleV2:
+ rule_type = rule["rule_type"]
+ return RuleV2(
+ id=rule["id"],
+ rule_type=rule_type,
+ experiment_id=rule["experiment_id"] if rule_type == "experiment" else None,
+ )
diff --git a/products/feature_flags/backend/facade/rules.py b/products/feature_flags/backend/facade/rules.py
index 2fa1d8704b4f..dfbb6b319e6c 100644
--- a/products/feature_flags/backend/facade/rules.py
+++ b/products/feature_flags/backend/facade/rules.py
@@ -3,8 +3,9 @@
A v1 flag hosting an experiment is a single implicit experiment rule: the flag-wide
``multivariate`` variants, the first release group's rollout percentage, and the
flag-level holdout/aggregation settings. This module derives that normalized rule
-config from today's ``filters`` format; when the rule-level flag model lands, the
-derivation becomes a read off the rule itself and consumers are untouched.
+config from the v1 ``filters`` format behind a format check, so a document in another
+config format is never read as v1. When the rule-level flag model lands, the
+derivation gains a v2 branch and consumers are untouched.
The DTO stays deliberately minimal while the rule-level model is being designed:
no seed handling, no reason mapping. It is the seam for the format swap — do not
@@ -17,6 +18,8 @@ consumer model modules import this at module level.
from dataclasses import dataclass
+from products.feature_flags.backend.facade.config import ConfigFormatError, detect_config_format
+
@dataclass(frozen=True)
class HoldoutRef:
@@ -33,7 +36,20 @@ class ExperimentRuleConfig:
def experiment_rule_from_filters(current_filters: dict) -> ExperimentRuleConfig:
- """Derive the implicit experiment rule from a v1 flag's ``filters`` dict.
+ """Derive the implicit experiment rule from a flag's ``filters`` dict.
+
+ Only config version 1 carries an implicit rule. Any other format raises
+ ``ConfigFormatError`` before any v1 key is read. Legacy filters can carry stray
+ ``version`` keys, so an unsupported discriminator does not imply a v2 shape.
+ """
+ config_format = detect_config_format(current_filters)
+ if config_format.kind != "v1":
+ raise ConfigFormatError(config_format)
+ return _v1_experiment_rule(current_filters)
+
+
+def _v1_experiment_rule(current_filters: dict) -> ExperimentRuleConfig:
+ """Derive the implicit experiment rule from a v1 ``filters`` dict.
Tolerant of legacy null/partial shapes: an explicit null ``multivariate`` reads as no
variants, and a holdout without an ``id`` reads as no holdout.
diff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.py
index 3683d7d1975d..c5cc0c1984d4 100644
--- a/products/feature_flags/backend/test/test_facade.py
+++ b/products/feature_flags/backend/test/test_facade.py
@@ -26,6 +26,7 @@ from products.feature_flags.backend.facade.api import (
ship_variant,
update_flag,
)
+from products.feature_flags.backend.facade.config import ConfigFormatError
from products.feature_flags.backend.facade.filters import (
group_cohort_restriction_blocker,
groups_carry_restriction_marker,
@@ -762,6 +763,20 @@ class TestExperimentRuleFromFilters:
holdout=HoldoutRef(id=7, exclusion_percentage=10),
),
),
+ (
+ "explicit_version_1",
+ {
+ "version": 1,
+ "groups": [{"properties": [], "rollout_percentage": 40}],
+ "multivariate": {"variants": [{"key": "control", "rollout_percentage": 100}]},
+ },
+ ExperimentRuleConfig(
+ variants=[{"key": "control", "rollout_percentage": 100}],
+ rollout_percentage=40,
+ assign_variant_by=None,
+ holdout=None,
+ ),
+ ),
(
"empty_filters",
{},
@@ -801,3 +816,28 @@ class TestExperimentRuleFromFilters:
)
def test_derivation(self, _name, filters, expected):
assert experiment_rule_from_filters(filters) == expected
+
+ @parameterized.expand(
+ [
+ ("v2_document", {"version": 2, "return_type": "boolean", "default_value": False, "rules": []}, "v2"),
+ (
+ "version_string",
+ {"version": "1", "groups": [{"properties": [], "rollout_percentage": 40}]},
+ "unsupported",
+ ),
+ (
+ "version_boolean",
+ {"version": True, "groups": [{"properties": [], "rollout_percentage": 40}]},
+ "unsupported",
+ ),
+ (
+ "unknown_future_version",
+ {"version": 3, "groups": [{"properties": [], "rollout_percentage": 40}]},
+ "unsupported",
+ ),
+ ]
+ )
+ def test_non_v1_formats_do_not_enter_the_v1_branch(self, _name, filters, expected_kind):
+ with pytest.raises(ConfigFormatError) as exc_info:
+ experiment_rule_from_filters(filters)
+ assert exc_info.value.config_format.kind == expected_kind
diff --git a/products/feature_flags/backend/test/test_facade_config.py b/products/feature_flags/backend/test/test_facade_config.py
new file mode 100644
index 000000000000..ae76cba39ffb
--- /dev/null
+++ b/products/feature_flags/backend/test/test_facade_config.py
@@ -0,0 +1,204 @@
+from copy import deepcopy
+from typing import Any
+
+import pytest
+
+from parameterized import parameterized
+
+from products.feature_flags.backend.facade.config import (
+ ConfigFormat,
+ ConfigFormatError,
+ ConfigV2,
+ RuleV2,
+ detect_config_format,
+ parse_v2_config,
+)
+
+# Shapes from the Feature Flag Rules v2 contract fixtures; identifiers are invented.
+V2_BOOLEAN_ALL_RULE_TYPES: dict[str, Any] = {
+ "version": 2,
+ "return_type": "boolean",
+ "default_value": False,
+ "rules": [
+ {
+ "id": "11111111-1111-4111-8111-111111111111",
+ "rule_type": "targeted_release",
+ "targeting": {
+ "properties": [
+ {
+ "key": "account_tier",
+ "type": "person",
+ "operator": "exact",
+ "value": "preview",
+ "label": "Account tier",
+ }
+ ]
+ },
+ "description": "Enable the preview for selected accounts.",
+ "metadata": {"display_color": "blue"},
+ "value": True,
+ },
+ {
+ "id": "22222222-2222-4222-8222-222222222222",
+ "rule_type": "percentage_rollout",
+ "targeting": {"properties": []},
+ "value": True,
+ "rollout_percentage": 25.5,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "release-preview",
+ "assign_by": "person",
+ },
+ {
+ "id": "44444444-4444-4444-8444-444444444444",
+ "rule_type": "experiment",
+ "targeting": {"properties": []},
+ "experiment_id": 42,
+ "paused": False,
+ "rollout_percentage": 100,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "experiment-preview",
+ "assign_by": "person",
+ "variants": [
+ {"key": "control", "weight": 50, "value": True},
+ {"key": "test", "weight": 50, "value": True},
+ ],
+ "holdout": {"id": 7, "seed": "holdout-", "exclusion_percentage": 5},
+ },
+ ],
+}
+
+V2_STRING_GROUP_ASSIGNMENT: dict[str, Any] = {
+ "version": 2,
+ "return_type": "string",
+ "default_value": "standard",
+ "aggregation_group_type_index": 0,
+ "rules": [
+ {
+ "id": "55555555-5555-4555-8555-555555555555",
+ "rule_type": "percentage_rollout",
+ "targeting": {
+ "properties": [
+ {
+ "key": "region",
+ "type": "group",
+ "operator": "exact",
+ "value": "north",
+ "group_type_index": 0,
+ "group_key_names": {"organization": "Organization"},
+ }
+ ]
+ },
+ "value": "compact",
+ "rollout_percentage": 50,
+ "on_rollout_miss": "continue",
+ "assignment_algorithm": "sha1_60_v1",
+ "seed": "group-release",
+ }
+ ],
+}
+
+
+class TestDetectConfigFormat:
+ @parameterized.expand(
+ [
+ ("absent_version", {"groups": []}, ConfigFormat(kind="v1", raw_version=None)),
+ ("empty_filters", {}, ConfigFormat(kind="v1", raw_version=None)),
+ ("none_filters", None, ConfigFormat(kind="v1", raw_version=None)),
+ ("version_1", {"version": 1}, ConfigFormat(kind="v1", raw_version=1)),
+ ("version_1_float", {"version": 1.0}, ConfigFormat(kind="v1", raw_version=1.0)),
+ ("version_2", {"version": 2}, ConfigFormat(kind="v2", raw_version=2)),
+ ("version_2_float", {"version": 2.0}, ConfigFormat(kind="v2", raw_version=2.0)),
+ ("version_true_is_not_1", {"version": True}, ConfigFormat(kind="unsupported", raw_version=True)),
+ ("version_string", {"version": "2"}, ConfigFormat(kind="unsupported", raw_version="2")),
+ ("version_null", {"version": None}, ConfigFormat(kind="unsupported", raw_version=None)),
+ ("unknown_future_version", {"version": 3}, ConfigFormat(kind="unsupported", raw_version=3)),
+ ("fractional_version", {"version": 1.5}, ConfigFormat(kind="unsupported", raw_version=1.5)),
+ ]
+ )
+ def test_detection(self, _name, filters, expected):
+ assert detect_config_format(filters) == expected
+
+
+class TestParseV2Config:
+ def test_boolean_document_with_every_rule_type(self):
+ assert parse_v2_config(V2_BOOLEAN_ALL_RULE_TYPES) == ConfigV2(
+ return_type="boolean",
+ default_value=False,
+ rules=(
+ RuleV2(id="11111111-1111-4111-8111-111111111111", rule_type="targeted_release", experiment_id=None),
+ RuleV2(id="22222222-2222-4222-8222-222222222222", rule_type="percentage_rollout", experiment_id=None),
+ RuleV2(
+ id="44444444-4444-4444-8444-444444444444",
+ rule_type="experiment",
+ experiment_id=42,
+ ),
+ ),
+ aggregation_group_type_index=None,
+ )
+
+ def test_string_group_document(self):
+ assert parse_v2_config(V2_STRING_GROUP_ASSIGNMENT) == ConfigV2(
+ return_type="string",
+ default_value="standard",
+ rules=(
+ RuleV2(id="55555555-5555-4555-8555-555555555555", rule_type="percentage_rollout", experiment_id=None),
+ ),
+ aggregation_group_type_index=0,
+ )
+
+ def test_float_version_literal_selects_v2(self):
+ assert parse_v2_config(
+ {"version": 2.0, "return_type": "boolean", "default_value": None, "rules": []}
+ ) == ConfigV2(return_type="boolean", default_value=None, rules=(), aggregation_group_type_index=None)
+
+ @parameterized.expand(
+ [
+ ("v1_document", {"groups": [{"properties": [], "rollout_percentage": 100}]}, "v1"),
+ ("version_string", {**V2_BOOLEAN_ALL_RULE_TYPES, "version": "2"}, "unsupported"),
+ ("unknown_future_version", {**V2_BOOLEAN_ALL_RULE_TYPES, "version": 3}, "unsupported"),
+ ("untrusted_version", {**V2_BOOLEAN_ALL_RULE_TYPES, "version": "<untrusted-version>"}, "unsupported"),
+ ]
+ )
+ def test_non_v2_formats_are_rejected(self, _name, filters, expected_kind):
+ with pytest.raises(ConfigFormatError) as exc_info:
+ parse_v2_config(filters)
+ assert exc_info.value.config_format.kind == expected_kind
+ assert exc_info.value.config_format.raw_version == filters.get("version")
+ assert str(exc_info.value) == f"config format {expected_kind!r} is not handled here"
+
+ @parameterized.expand(
+ [
+ ("return_type", None, "return_type"),
+ ("default_value", None, "default_value"),
+ ("rules", None, "rules"),
+ ("rule_id", 0, "id"),
+ ("rule_type", 0, "rule_type"),
+ ("experiment_id", 2, "experiment_id"),
+ ]
+ )
+ def test_missing_required_keys_are_rejected(self, _name: str, rule_index: int | None, key: str) -> None:
+ filters = deepcopy(V2_BOOLEAN_ALL_RULE_TYPES)
+ target = filters if rule_index is None else filters["rules"][rule_index]
+ del target[key]
+
+ with pytest.raises(KeyError) as exc_info:
+ parse_v2_config(filters)
+ assert exc_info.value.args == (key,)
+
+ @parameterized.expand(
+ [
+ ("unknown_return_type", "return_type", "future_return_type", "Unsupported feature flag return type"),
+ ("null_return_type", "return_type", None, "Unsupported feature flag return type"),
+ ("removed_rule_type", "rule_type", "variant_rollout", "Unsupported feature flag rule type"),
+ ("null_rule_type", "rule_type", None, "Unsupported feature flag rule type"),
+ ]
+ )
+ def test_unsupported_types_are_rejected(self, _name: str, key: str, value: object, message: str) -> None:
+ filters = deepcopy(V2_BOOLEAN_ALL_RULE_TYPES)
+ target = filters if key == "return_type" else filters["rules"][0]
+ target[key] = value
+
+ with pytest.raises(ValueError, match=message):
+ parse_v2_config(filters)