:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(flags): align the rules v2 validator with the flags service parser (#109427)
Anders97baa110a1e4
diff --git a/docs/internal/feature-flags/api-writes.md b/docs/internal/feature-flags/api-writes.mdindex 711c97c22e4c..7cd091d84aa1 100644--- a/docs/internal/feature-flags/api-writes.md+++ b/docs/internal/feature-flags/api-writes.md@@ -78,6 +78,7 @@ A stored version 2 row that is not remote-configured and carries no encrypted pa- 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.- `return_type` is `boolean`, `string`, `number` or `object` and cannot change after creation. `default_value` is null or the declared type; every rule `value` is the declared type. Strings are non-empty and not `$false`, the event-storage sentinel that v1 also reserves as a variant key; numbers lie within ±(2^53 − 1); objects nest at most 20 object or array levels with numbers in the same range.+- Writer-only rules (`check_writer_rules` in `facade/config_writes.py`, currently the `$false` reservation) apply to a created or replacing document and to the stored document being enabled. The shared validator, and with it the flags caches and the stored side of an update, does not apply them: tightening a writer rule never hides a stored row from evaluation or blocks replacing it.- 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 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.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.pyindex 906a238aa22f..4d8fac01379c 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@@ -725,6 +725,65 @@ class TestV2AdmissionBoundary(AdmittedV2TestCase):assert response.status_code == status.HTTP_404_NOT_FOUND+def string_config(value: str, default: str | None, rule_id: str | None = RULE_A) -> dict:+ return config(targeted(rule_id=rule_id, value=value), return_type="string", default_value=default)+++RESERVED_STRING_VALUES = [+ ("rule_value", "$false", None, "filters.rules[0].value: Must be a non-empty string other than $false."),+ (+ "default_value",+ "compact",+ "$false",+ "filters.default_value: Must be a non-empty string other than $false, or null.",+ ),+]+++class TestWriterOnlyRules(AdmittedV2TestCase):+ """The writer reserves `$false` as a string value; the caches accept it, so a stored one stays replaceable."""++ @parameterized.expand(RESERVED_STRING_VALUES)+ def test_create_rejects_a_reserved_value(self, _name: str, value: str, default: str | None, detail: str) -> None:+ with admit_v2(self.team.id, creation=True):+ response = self.post_flag({"key": "new-v2", "filters": string_config(value, default, rule_id=None)})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert (response.json()["code"], response.json()["detail"]) == ("invalid_input", detail)+ assert not FeatureFlag.objects.filter(team=self.team, key="new-v2").exists()++ @parameterized.expand(RESERVED_STRING_VALUES)+ def test_update_rejects_a_reserved_value(self, _name: str, value: str, default: str | None, detail: str) -> None:+ flag = self.flag(string_config("compact", None))+ response = self.patch_flag(flag, {"version": 3, "filters": string_config(value, default)})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert (response.json()["code"], response.json()["detail"]) == ("invalid_input", detail)+ flag.refresh_from_db()+ assert (flag.filters, flag.version) == (string_config("compact", None), 3)++ def test_a_stored_reserved_value_is_not_enabled_but_can_be_replaced(self) -> None:+ stored = string_config("$false", "$false")+ flag = self.flag(stored, active=False)+ response = self.patch_flag(flag, {"version": 3, "active": True})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["detail"] == (+ "filters: This flag's stored configuration cannot be enabled through this API."+ )+ flag.refresh_from_db()+ assert (flag.active, flag.filters, flag.version) == (False, stored, 3)++ response = self.patch_flag(flag, {"version": 3, "filters": string_config("compact", None)})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert (flag.filters, flag.version) == (string_config("compact", None), 4)++ def test_a_stored_reserved_value_can_be_disabled(self) -> None:+ flag = self.flag(string_config("$false", None), active=True)+ response = self.patch_flag(flag, {"version": 3, "active": False})+ assert response.status_code == status.HTTP_200_OK, response.json()+ flag.refresh_from_db()+ assert (flag.active, flag.version) == (False, 4)++class TestV2RequestBytes(AdmittedV2TestCase):def post_bytes(self, flag: FeatureFlag, body: str):return self.client.patch(diff --git a/products/feature_flags/backend/facade/config_validation.py b/products/feature_flags/backend/facade/config_validation.pyindex 333ab7bca9a8..5ec97f7c216d 100644--- a/products/feature_flags/backend/facade/config_validation.py+++ b/products/feature_flags/backend/facade/config_validation.py@@ -7,7 +7,9 @@ detectors read, or ``ConfigValidationError`` carrying every field error in a fix(root fields, then each rule's fields in rule order), so the same document always yieldsthe same list. Nothing here reads or writes the database, assigns ids or seeds, checkspermissions, or mutates the input: a validated config says the document is well formed-and admitted, not that the caller may store it. The later trusted write path resolves+and admitted, not that the caller may store it. The cache builders call this too, so it+should admit exactly what the flags service's parser admits; restrictions on what a writer+may store live in ``config_writes.check_writer_rules``. The later trusted write path resolvesrequest input into the final document, calls ``rule_warnings.review_config`` (whichvalidates through this module and reports warnings) and persists under the existing rowlock. No production caller exists yet.@@ -30,7 +32,6 @@ from dataclasses import fieldfrom decimal import Decimalfrom typing import Any, Literal, TypeGuard, get_args-from posthog.hogql.constants import FEATURE_FLAG_FALSE_VARIANT_SENTINELfrom posthog.hogql.property import parse_semverfrom posthog.dataclasses import frozen@@ -130,6 +131,14 @@ _PROPERTY_FIELDS = frozenset({"key", "value", "type", "operator", "group_type_index", "negation", "cohort_name", "group_key_names", "label"})_UUID = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")+_SEMVER_PRERELEASE_ID = r"(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)"+# SemVer 2.0.0, as the flags service's semver parser reads it; numbers are unsigned 64-bit.+_STRICT_SEMVER = re.compile(+ r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"+ rf"(?:-{_SEMVER_PRERELEASE_ID}(?:\.{_SEMVER_PRERELEASE_ID})*)?"+ r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"+)+_MAX_SEMVER_NUMBER = 2**64 - 1@frozen@@ -457,16 +466,30 @@ def _property_value_error(operator: str, value: Any) -> str | None:return "Must be a number or a string."if operator in _LIST_VALUE_OPERATORS and not isinstance(value, list):return "Must be an array."- if operator in _SEMVER_OPERATORS:- if not isinstance(value, str):- return "Must be a semver string."- try:- parse_semver(value.rstrip(".*") if operator == "semver_wildcard" else value)- except (ValueError, IndexError):- return "Must be a semver string."+ if operator in _SEMVER_OPERATORS and not (+ isinstance(value, str) and _is_semver(value.rstrip(".*") if operator == "semver_wildcard" else value)+ ):+ return "Must be a semver string."return None+def _is_semver(value: str) -> bool:+ """The flags service's check: numeric major, minor and patch, and a version its semver+ parser reads once missing components are padded and leading zeros stripped. ``parse_semver``+ alone also admits values that parser rejects, such as ``1.2.3.4`` and ``1.2.3-``.+ """+ try:+ parse_semver(value)+ except (ValueError, IndexError):+ return False+ version = value.strip()+ core_end = next((index for index, char in enumerate(version) if char in "-+"), len(version))+ core = version[:core_end].split(".")+ parts = [(part.lstrip("0") or "0") if part.isascii() and part.isdigit() else part for part in core]+ match = _STRICT_SEMVER.fullmatch(".".join(parts + ["0"] * (3 - len(parts))) + version[core_end:])+ return match is not None and all(int(number) <= _MAX_SEMVER_NUMBER for number in match.groups())++def _validate_metadata(metadata: object, path: str, limits: ValidationLimits, errors: list[ConfigError]) -> None:if not isinstance(metadata, Mapping):errors.append(ConfigError(code="invalid", detail="Must be an object.", attr=path))@@ -550,11 +573,7 @@ def _is_nested_value(value: object, *, depth: int) -> bool:_VALUE_CHECKS: dict[str, _Check] = {"boolean": (lambda v: isinstance(v, bool), "Must be true or false."),- # A string is served as the variant, and `$false` is the event-storage sentinel that v1 reserves as a variant key.- "string": (- lambda v: isinstance(v, str) and v not in ("", FEATURE_FLAG_FALSE_VARIANT_SENTINEL),- f"Must be a non-empty string other than {FEATURE_FLAG_FALSE_VARIANT_SENTINEL}.",- ),+ "string": (lambda v: isinstance(v, str) and v != "", "Must be a non-empty string."),"number": (_is_safe_number, f"Must be a number from -{MAX_SAFE_INTEGER} to {MAX_SAFE_INTEGER}."),"object": (_is_object_value,diff --git a/products/feature_flags/backend/facade/config_writes.py b/products/feature_flags/backend/facade/config_writes.pyindex 4219cb2450a8..e75069df1470 100644--- a/products/feature_flags/backend/facade/config_writes.py+++ b/products/feature_flags/backend/facade/config_writes.py@@ -1,6 +1,6 @@"""Writer admission and server-owned identity for config version 2 writes.-Three things a v2 write needs that the pure validator deliberately does not do:+Four things a v2 write needs that the pure validator deliberately does not do:- **Admission.** ``v2_write_limits`` and ``v2_creation_enabled`` are the writer policy: twointernal feature flags evaluated for the project, both off by default. Nothing else grants@@ -12,6 +12,9 @@ Three things a v2 write needs that the pure validator deliberately does not do:- **Comparison.** ``review_update`` validates both documents' shape and semantics, sowarnings describe the real before/proposed pair and unsupported stored families arerejected. Byte limits apply only to the candidate so oversized rows can be reduced.+- **Writer-only rules.** ``check_writer_rules`` rejects what readers accept but a writer may+ not store. It runs on the submitted document and on a stored one being enabled, never on+ the stored side of an update, so tightening a rule never blocks replacing a stored row.Deliberately free of Django ORM and DRF imports: the endpoint owns HTTP error shapes andthe row lock, this module owns the document.@@ -19,7 +22,7 @@ the row lock, this module owns the document.import sysimport json-from collections.abc import Mapping+from collections.abc import Callable, Iterator, Mappingfrom typing import Anyfrom uuid import uuid4@@ -27,6 +30,8 @@ from django.conf import settingsimport structlog+from posthog.hogql.constants import FEATURE_FLAG_FALSE_VARIANT_SENTINEL+from posthog.ph_client import feature_enabled_or_falsefrom products.feature_flags.backend.facade.config_validation import (@@ -231,21 +236,55 @@ def review_update()])- return review_config(document, limits=limits, current=current).warnings+ warnings = review_config(document, limits=limits, current=current).warnings+ assert isinstance(document, Mapping) # review_config rejects anything else+ check_writer_rules(document)+ return warningsdef validate_stored(stored: Mapping[str, Any], *, limits: ValidationLimits) -> None:- """Reject enabling a stored document that no longer validates under the current limits.+ """Reject enabling a stored document that no longer validates under the current limits or writer rules.Enabling is what makes the document reachable by evaluation, so a row written under anolder contract or a larger byte limit must be edited back into validity first."""- _validated_stored(stored, limits=limits, operation="enabled")+ _validated_stored(stored, limits=limits, operation="enabled", writer_rules=True)-def _validated_stored(stored: Mapping[str, Any], *, limits: ValidationLimits, operation: str) -> ValidatedConfig:+def _validated_stored(+ stored: Mapping[str, Any], *, limits: ValidationLimits, operation: str, writer_rules: bool = False+) -> ValidatedConfig:try:- return validate_config(stored, limits=limits)+ config = validate_config(stored, limits=limits)+ if writer_rules:+ check_writer_rules(stored)+ return configexcept ConfigValidationError as exc:detail = f"This flag's stored configuration cannot be {operation} through this API."raise ConfigValidationError([ConfigError(code="unsupported", detail=detail, attr="filters")]) from exc+++def check_writer_rules(document: Mapping[str, Any]) -> None:+ """Reject a document ``validate_config`` admitted that a writer still may not store.++ Readers never apply these. Each entry in ``_WRITER_RULES`` reads the validated document+ and yields its field errors.+ """+ errors = [error for rule in _WRITER_RULES for error in rule(document)]+ if errors:+ raise ConfigValidationError(errors)+++def _reserved_string_values(document: Mapping[str, Any]) -> Iterator[ConfigError]:+ # A string value is served as the variant, and `$false` is the event-storage sentinel that v1 reserves as a variant key.+ if document["return_type"] != "string":+ return+ detail = f"Must be a non-empty string other than {FEATURE_FLAG_FALSE_VARIANT_SENTINEL}"+ if document["default_value"] == FEATURE_FLAG_FALSE_VARIANT_SENTINEL:+ yield ConfigError(code="invalid", detail=f"{detail}, or null.", attr="filters.default_value")+ for index, rule in enumerate(document["rules"]):+ if rule.get("value") == FEATURE_FLAG_FALSE_VARIANT_SENTINEL:+ yield ConfigError(code="invalid", detail=f"{detail}.", attr=f"filters.rules[{index}].value")+++_WRITER_RULES: tuple[Callable[[Mapping[str, Any]], Iterator[ConfigError]], ...] = (_reserved_string_values,)diff --git a/products/feature_flags/backend/test/test_facade_config_validation.py b/products/feature_flags/backend/test/test_facade_config_validation.pyindex 215b968eb443..8b008aad29da 100644--- a/products/feature_flags/backend/test/test_facade_config_validation.py+++ b/products/feature_flags/backend/test/test_facade_config_validation.py@@ -178,6 +178,8 @@ VALID_DOCUMENTS: list[tuple[str, dict[str, Any]]] = [config(targeted(value="compact"), rollout(value="wide"), return_type="string", default_value="standard"),),("string_null_default", config(targeted(value="compact"), return_type="string", default_value=None)),+ # Readers accept the event-storage sentinel; only the writer reserves it.+ ("string_false_sentinel", config(targeted(value="$false"), return_type="string", default_value="$false")),("number_values", config(targeted(value=1.25), rollout(value=-40), return_type="number", default_value=0)),("number_safe_integer_bounds",@@ -236,11 +238,6 @@ INVALID_DOCUMENTS: list[tuple[str, object, list[tuple[str, str]]]] = [config(targeted(value=True), return_type="string", default_value=None),[("invalid", "filters.rules[0].value")],),- (- "string_reserved_false_sentinel",- config(targeted(value="$false"), return_type="string", default_value="$false"),- [("invalid", "filters.default_value"), ("invalid", "filters.rules[0].value")],- ),("number_bool_default", config(return_type="number", default_value=False), [("invalid", "filters.default_value")]),("number_string_value",@@ -748,7 +745,7 @@ class TestValidateConfig:@parameterized.expand([("boolean", 1, "Must be true or false"),- ("string", "$false", "Must be a non-empty string other than $false"),+ ("string", "", "Must be a non-empty string"),("number", "1", "Must be a number from -9007199254740991 to 9007199254740991"),("object",@@ -768,6 +765,50 @@ class TestValidateConfig:("filters.rules[0].value", f"{message}."),]+ @parameterized.expand(+ [+ # Mirrors the semver cases of the flags service's parser test in rust/feature-flags/tests/test_config_v2.rs.+ *[+ (operator, value, True)+ for operator, value in [+ ("semver_eq", "1.2.3"),+ ("semver_eq", " 1.2.3 "),+ ("semver_tilde", "1.2"),+ ("semver_wildcard", "1.2.*"),+ ("semver_eq", "01.2.3-rc.1"),+ ("semver_eq", "1.2.3-alpha+build.01"),+ ("semver_eq", "18446744073709551615.0.0"),+ ]+ ],+ *[+ (operator, value, False)+ for operator, value in [+ ("semver_eq", "1.2.3.4"),+ ("semver_tilde", "1.2.3.4"),+ ("semver_wildcard", "1.2.3.4.*"),+ ("semver_eq", "1.2.3-"),+ ("semver_eq", "1.2.3-01"),+ ("semver_eq", "1.2.3-a_b"),+ ("semver_eq", "1_0.2.3"),+ ("semver_eq", "18446744073709551616.0.0"),+ ("semver_eq", "1.2.3+meta"),+ ("semver_eq", "v1.2.3"),+ ("semver_eq", "+1.2.3"),+ ("semver_eq", "1. 2.3"),+ ("semver_eq", "1.+2.3"),+ ]+ ],+ ]+ )+ def test_semver_values_are_the_ones_the_flags_service_parses(+ self, operator: str, value: str, accepted: bool+ ) -> None:+ document = config(targeted(targeting={"properties": [person(operator=operator, value=value)]}))+ if accepted:+ validate_config(document, limits=LIMITS)+ else:+ assert errors_of(document) == [("invalid", "filters.rules[0].targeting.properties[0].value")]+def test_v1_only_fields_name_the_format_clash(self) -> None:with pytest.raises(ConfigValidationError) as exc_info:validate_config(config(groups=[], future=1), limits=LIMITS)diff --git a/rust/feature-flags/tests/fixtures/flags_cache_config_formats.json b/rust/feature-flags/tests/fixtures/flags_cache_config_formats.jsonindex 3b30eb738cba..624ad4fcbb9b 100644--- a/rust/feature-flags/tests/fixtures/flags_cache_config_formats.json+++ b/rust/feature-flags/tests/fixtures/flags_cache_config_formats.json@@ -140,6 +140,55 @@},"expect": "unsupported"},+ {+ "key": "v2-string-false-sentinel-active",+ "active": true,+ "filters": {+ "version": 2,+ "return_type": "string",+ "default_value": "$false",+ "rules": [{ "id": "c3c3c3c3-c3c3-4c3c-8c3c-c3c3c3c3c3c3", "rule_type": "targeted_release", "targeting": { "properties": [] }, "value": "$false" }]+ },+ "expect": "kept",+ "reason": "only the writer reserves the event-storage sentinel; readers accept it"+ },+ {+ "key": "v2-semver-padded-active",+ "active": true,+ "filters": {+ "version": 2,+ "return_type": "boolean",+ "default_value": null,+ "rules": [+ {+ "id": "d4d4d4d4-d4d4-4d4d-8d4d-d4d4d4d4d4d4",+ "rule_type": "targeted_release",+ "targeting": { "properties": [{ "key": "app_version", "type": "person", "operator": "semver_gte", "value": "01.2-rc.1" }] },+ "value": true+ }+ ]+ },+ "expect": "kept"+ },+ {+ "key": "v2-semver-four-part-active",+ "active": true,+ "filters": {+ "version": 2,+ "return_type": "boolean",+ "default_value": null,+ "rules": [+ {+ "id": "d4d4d4d4-d4d4-4d4d-8d4d-d4d4d4d4d4d4",+ "rule_type": "targeted_release",+ "targeting": { "properties": [{ "key": "app_version", "type": "person", "operator": "semver_eq", "value": "1.2.3.4" }] },+ "value": true+ }+ ]+ },+ "expect": "unsupported",+ "reason": "a four-part version is not semver, so the flags service parser rejects it"+ },{"key": "v2-malformed-active","active": true,diff --git a/rust/feature-flags/tests/test_config_v2.rs b/rust/feature-flags/tests/test_config_v2.rsindex fb19fe9b4d13..70180eed3829 100644--- a/rust/feature-flags/tests/test_config_v2.rs+++ b/rust/feature-flags/tests/test_config_v2.rs@@ -472,6 +472,9 @@ fn person_property_cases() -> Vec<(&'static str, Value)> {("semver_tilde", json!("1.2")),("semver_caret", json!("1.2.3")),("semver_wildcard", json!("1.2.*")),+ ("semver_eq", json!("01.2.3-rc.1")),+ ("semver_eq", json!("1.2.3-alpha+build.01")),+ ("semver_eq", json!("18446744073709551615.0.0")),]}@@ -549,6 +552,14 @@ fn person_properties_are_closed_before_reusing_operator_types() {("semver_eq", json!("+1.2.3")),("semver_eq", json!("1. 2.3")),("semver_eq", json!("1.+2.3")),+ ("semver_eq", json!("1.2.3.4")),+ ("semver_tilde", json!("1.2.3.4")),+ ("semver_wildcard", json!("1.2.3.4.*")),+ ("semver_eq", json!("1.2.3-")),+ ("semver_eq", json!("1.2.3-01")),+ ("semver_eq", json!("1.2.3-a_b")),+ ("semver_eq", json!("1_0.2.3")),+ ("semver_eq", json!("18446744073709551616.0.0")),] {let mut document = config();document["rules"][0]["targeting"]["properties"] =