: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): read definition references through the feature flag facade (#100066)
Anders1b255eacfa8e
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.mdindex 15a43ed5fd60..2de46b43a609 100644--- a/docs/internal/feature-flags/hypercache-system.md+++ b/docs/internal/feature-flags/hypercache-system.md@@ -115,6 +115,10 @@ flags_hypercache = HyperCache(The `_get_feature_flags_for_service` function fetches all flags for a team (including inactive, but excluding deleted and encrypted remote config flags), then returns a cache payload trimmed to the flags worth caching. The Rust service filters out inactive flags at request time via `filtered_out_flag_ids`.+Cohort references and flag dependencies are read from each flag's `filters` through `products/feature_flags/backend/facade/references.py`, which runs `detect_config_format` before it reads a v1 key.+A flag stored in any other config format raises `ConfigFormatError` rather than reading as a flag with no references; in this cache that fails the team's rebuild the way any malformed document does, and `HyperCache.update_cache` keeps the existing entry and ETag.+Inactive and deleted flags are skipped before that read (`_is_unevaluable`), so they are not classified.+Because that filtering happens before the matcher reads `filters`, an inactive flag can never affect a response, so the payload keeps only evaluable flags plus the inactive flags that another flag's dependency conditions reference.A referenced entry is load-bearing: the matcher pre-seeds its id as false, so a dependent with `flag_evaluates_to: false` on a disabled flag still matches instead of missing a dependency.`_drop_unreferenced_unevaluable_flags` removes the rest, `evaluation_metadata` is computed on the surviving set, and `_blank_inactive_filters` replaces the kept unevaluable flags' `filters` with an empty `{"groups": []}` before the payload is written.@@ -176,6 +180,9 @@ flag_definitions_hypercache = HyperCache(It includes full cohort definitions and group type mappings, since all current SDKs support cohort evaluation locally. A legacy `flag_definitions_without_cohorts_hypercache` variant — pre-flattened cohort filters for SDKs too old to evaluate cohorts locally — was removed once nothing served it to real clients anymore.+The builder reads cohort references and flag dependencies through the same `facade/references.py` accessors as the service cache.+A flag in an unsupported config format is dropped from the payload by the per-flag error handling (logged and counted in `posthog_flag_definitions_processing_error`), the team's other flags are published as before, and the cohort prepass skips that flag so one document cannot fail the whole batch.+### Cache invalidationDjango signals trigger cache updates when models change:diff --git a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt b/posthog/test/repo_invariants/database_free_test_classes_baseline.txtindex 06f8e72bccec..8bcfcd0031d8 100644--- a/posthog/test/repo_invariants/database_free_test_classes_baseline.txt+++ b/posthog/test/repo_invariants/database_free_test_classes_baseline.txt@@ -329,7 +329,6 @@ products/exports/backend/tasks/test/test_export_utils.py::TestSiteURLReachabilitproducts/feature_flags/backend/test/test_flag_definitions_cache_tasks.py::TestCleanupStaleFlagDefinitionsExpiryTrackingTaskproducts/feature_flags/backend/test/test_flag_definitions_cache_tasks.py::TestRefreshExpiringFlagDefinitionsCacheEntriesproducts/feature_flags/backend/test/test_flags_cache.py::TestExtractCohortIdsFromFlagFilters-products/feature_flags/backend/test/test_local_evaluation.py::TestExtractCohortIdsFromFiltersproducts/growth/backend/temporal/signup_enrichment/tests/test_harmonic_status_poll.py::TestReportStatusPollRunActivityproducts/legal_documents/backend/tests/test_admin.py::TestLegalDocumentInlineRegistrationproducts/logs/backend/test/test_logs_url_params.py::TestBuildLogsUrlParamsdiff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 1c0e4a453992..fded04d46382 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -120,7 +120,6 @@ from products.feature_flags.backend.flag_status import (exclude_archived_unless_requested,filter_flags_by_active_param,)-from products.feature_flags.backend.local_evaluation import _get_flag_properties_from_filtersfrom products.feature_flags.backend.models.evaluation_context import normalize_context_namefrom products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagDashboardsfrom products.feature_flags.backend.models.team_feature_flag_policy_config import team_requires_flag_tags@@ -1987,7 +1986,7 @@ class FeatureFlagSerializer(def _extract_flag_dependencies(self, filters):"""Extract flag dependencies from filters."""dependencies = set()- for flag_prop in _get_flag_properties_from_filters(filters):+ for flag_prop in self._get_properties_from_filters(filters, PropertyFilterType.FLAG):flag_reference = flag_prop.get("key")if flag_reference:flag_key = self._validate_flag_reference(flag_reference)diff --git a/products/feature_flags/backend/facade/references.py b/products/feature_flags/backend/facade/references.pynew file mode 100644index 000000000000..1ea3ddab37c3--- /dev/null+++ b/products/feature_flags/backend/facade/references.py@@ -0,0 +1,70 @@+"""The cohorts and flags a feature flag's stored config references.++The SDK definitions payload and the Rust service cache both need two reads of a+``filters`` document: which cohorts its release conditions reference, and which+properties make it depend on other flags. Both are config version 1 knowledge+(``groups[*].properties`` with ``type == "cohort"`` or ``type == "flag"``), so this+module owns them behind the format check. A document in any other format raises+``ConfigFormatError`` before a v1 key is read; it is never read as a flag with no+references, because a producer that silently dropped the references would publish an+unsupported document into a feed built for v1 readers.++Consumers keep their own meaning of a reference: the definitions payload rewrites flag+references from ids to keys and annotates them with a dependency chain, the service+cache parses them as integer ids, and the model resolves cohort ids against the+database. ``flag_dependency_properties`` therefore returns the caller's own property+dicts so those in-place rewrites keep working.++Deliberately free of Django/DRF imports (same reason as ``facade.filters``).+"""++from collections.abc import Mapping+from typing import Any++from products.feature_flags.backend.facade.config import ConfigFormatError, detect_config_format+from products.feature_flags.backend.types import FlagProperty, PropertyFilterType+++def referenced_cohort_ids(filters: Mapping[str, Any] | None) -> set[int]:+ """Cohort ids the release conditions of a v1 document reference.++ Raises ``ConfigFormatError`` for any other config format. A ``value`` that is not an+ integer is skipped, the same tolerance every producer already applied; a consumer+ that needs strictness resolves the ids itself.+ """+ cohort_ids: set[int] = set()+ for prop in _v1_properties(filters, PropertyFilterType.COHORT):+ value = prop.get("value")+ if value is None:+ continue+ try:+ cohort_ids.add(int(value))+ except (TypeError, ValueError):+ continue+ return cohort_ids+++def flag_dependency_properties(filters: Mapping[str, Any] | None) -> list[FlagProperty]:+ """The ``type == "flag"`` properties in the release conditions of a v1 document.++ Raises ``ConfigFormatError`` for any other config format. The returned dicts are the+ caller's own objects, so a consumer can rewrite them in place. ``key`` holds the+ referenced flag's id or key; the consumer decides which it accepts.+ """+ return _v1_properties(filters, PropertyFilterType.FLAG)+++def _v1_properties(filters: Mapping[str, Any] | None, property_type: PropertyFilterType) -> list[FlagProperty]:+ config_format = detect_config_format(filters)+ if config_format.kind != "v1":+ raise ConfigFormatError(config_format)+ # Only ``groups`` can hold cohort or flag properties: ``feature_enrollment`` is a+ # boolean gate evaluated against ``$feature_enrollment/*`` person properties, and+ # ``holdout`` carries no property filters. Explicit nulls occur in stored v1 data+ # (see FeatureFlag.conditions); read them as empty.+ return [+ prop+ for group in (filters or {}).get("groups") or []+ for prop in group.get("properties") or []+ if prop.get("type") == property_type+ ]diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex 7bd446cdd626..8f36091a189e 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -66,6 +66,7 @@ from posthog.storage.hypercache_manager import (from products.cohorts.backend.models.cohort import Cohortfrom products.cohorts.backend.models.dependencies import extract_cohort_dependenciesfrom products.experiments.backend.models.experiment import Experiment, live_experiment_exists+from products.feature_flags.backend.facade.references import flag_dependency_properties, referenced_cohort_idsfrom products.feature_flags.backend.flags_cache_messages import FlagsCacheInvalidationfrom products.feature_flags.backend.models.evaluation_context import FeatureFlagEvaluationContextfrom products.feature_flags.backend.models.feature_flag import FeatureFlag, get_feature_flags, serialize_feature_flags@@ -97,22 +98,21 @@ def _extract_direct_dependency_ids(flag_data: dict[str, Any]) -> set[int]:"""Extract direct flag dependency IDs from a serialized flag's filters.- Scans filters.groups[*].properties for type=="flag" properties and parses- their key as an integer flag ID. Inactive/deleted flags return empty deps- to match Rust's extract_dependencies behavior.+ Parses the ``key`` of each flag-reference property as an integer flag ID.+ Inactive/deleted flags return empty deps before their filters are read, to+ match Rust's extract_dependencies behavior. Any other flag stored in a config+ format other than version 1 raises ``ConfigFormatError``, which fails the whole+ team's rebuild; ``HyperCache.update_cache`` then keeps the previous entry and ETag."""if _is_unevaluable(flag_data):return set()dep_ids: set[int] = set()- filters = flag_data.get("filters", {})- for group in filters.get("groups") or []:- for prop in group.get("properties") or []:- if prop.get("type") == "flag":- try:- dep_ids.add(int(prop["key"]))- except (ValueError, KeyError, TypeError):- continue+ for prop in flag_dependency_properties(flag_data.get("filters", {})):+ try:+ dep_ids.add(int(prop["key"]))+ except (ValueError, KeyError, TypeError):+ continuereturn dep_ids@@ -147,24 +147,15 @@ _COHORT_RECALCULATION_FIELDS = frozenset(def _extract_cohort_ids_from_flag_filters(flags_data: list[dict[str, Any]]) -> set[int]:"""Extract cohort IDs directly referenced in active flag filters.- Only scans ``groups`` — the other filter sections cannot contain cohort- properties:- - ``feature_enrollment`` is a boolean gate for early-access features,- evaluated against person properties (``$feature_enrollment/*``).- - ``holdout`` uses a different schema for configuring experiment holdouts- with no property filters at all.+ Inactive/deleted flags are skipped before their filters are read. Any other flag+ stored in a config format other than version 1 raises ``ConfigFormatError``,+ which fails the whole team's rebuild."""cohort_ids: set[int] = set()for flag in flags_data:if _is_unevaluable(flag):continue- for group in flag.get("filters", {}).get("groups") or []:- for prop in group.get("properties") or []:- if prop.get("type") == "cohort":- try:- cohort_ids.add(int(prop["value"]))- except (ValueError, KeyError, TypeError):- continue+ cohort_ids |= referenced_cohort_ids(flag.get("filters", {}))return cohort_idsdiff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.pyindex f8e99761a532..c3575f1054d4 100644--- a/products/feature_flags/backend/local_evaluation.py+++ b/products/feature_flags/backend/local_evaluation.py@@ -17,9 +17,8 @@ Configuration:import timefrom collections import defaultdict-from collections.abc import Generatorfrom itertools import groupby-from typing import Any, Union, cast+from typing import Any, castfrom django.conf import settingsfrom django.contrib.postgres.aggregates import ArrayAgg@@ -54,6 +53,8 @@ from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty, is_cohfrom products.cohorts.backend.models.util import get_nested_cohort_idsfrom products.experiments.backend.models.experiment import Experiment, live_experiment_existsfrom products.feature_flags.backend.cache_keys import EU_CROSS_REGION_MIRROR_CACHE_KEY+from products.feature_flags.backend.facade.config import ConfigFormatError+from products.feature_flags.backend.facade.references import flag_dependency_properties, referenced_cohort_idsfrom products.feature_flags.backend.flags_cache import (_compare_flag_fields,get_team_ids_with_recently_updated_flags,@@ -65,7 +66,7 @@ from products.feature_flags.backend.models.team_feature_flags_config import (PropertyMatchingVersion,TeamFeatureFlagsConfig,)-from products.feature_flags.backend.types import FlagFilters, FlagProperty, PropertyFilterType+from products.feature_flags.backend.types import FlagPropertyfrom products.surveys.backend.models import Surveylogger = structlog.get_logger(__name__)@@ -91,43 +92,6 @@ HYPERCACHE_GROUP_MAPPING_EMPTIED_COUNTER = Counter()-def _get_properties_from_filters(- filters: Union[dict, FlagFilters], property_type: str | None = None-) -> Generator[FlagProperty]:- """- Extract properties from filters by iterating through groups.-- Args:- filters: The filters dictionary containing groups- property_type: Optional filter by property type (e.g., 'flag', 'cohort')-- Yields:- Property dictionaries matching the criteria- """- for group in filters.get("groups", []):- for prop in group.get("properties", []):- if property_type is None or prop.get("type") == property_type:- yield prop---def _extract_cohort_ids_from_filters(filters: Union[dict, FlagFilters]) -> set[int]:- """Extract cohort IDs directly referenced in flag filter properties."""- cohort_ids: set[int] = set()- for prop in _get_properties_from_filters(filters, "cohort"):- value = prop.get("value")- if value is not None:- try:- cohort_ids.add(int(value))- except (TypeError, ValueError):- continue- return cohort_ids---def _get_flag_properties_from_filters(filters: Union[dict, FlagFilters]) -> Generator[FlagProperty]:- """Extract flag properties from filters."""- return _get_properties_from_filters(filters, PropertyFilterType.FLAG)--def _resolve_flag_dependency_key(flag_prop: FlagProperty, flag_id_to_key: dict[str, str]) -> str:"""Convert flag property reference to flag key.@@ -191,7 +155,7 @@ class _DependencyChainBuilder:return Falsefilters = flag_data.get("filters", {})- for flag_prop in _get_flag_properties_from_filters(filters):+ for flag_prop in flag_dependency_properties(filters):dep_flag_key = flag_prop["key"] # Already normalized to keyif dep_flag_key == flag_key:return True@@ -245,7 +209,7 @@ class _DependencyChainBuilder:return Falsefilters = current_flag.get("filters", {})- for flag_prop in _get_flag_properties_from_filters(filters):+ for flag_prop in flag_dependency_properties(filters):dep_flag_key = flag_prop["key"] # Already normalized to keyif dep_flag_key != current_key: # Avoid self-dependencyif not self._validate_dependency(dep_flag_key, current_key, visited, temp_visited, chain):@@ -288,7 +252,7 @@ def _normalize_and_collect_dependency_target_keys(for flag_data in flags_data:filters = flag_data.get("filters", {})- for flag_prop in _get_flag_properties_from_filters(filters):+ for flag_prop in flag_dependency_properties(filters):# Transform flag ID to flag keyflag_key = _resolve_flag_dependency_key(flag_prop, flag_id_to_key)flag_prop["key"] = flag_key@@ -320,7 +284,7 @@ def _build_all_dependency_chains(for flag_data in flags_data:filters = flag_data.get("filters", {})- for flag_prop in _get_flag_properties_from_filters(filters):+ for flag_prop in flag_dependency_properties(filters):flag_key = flag_prop["key"]dependency_chain = builder.build_chain(flag_key)@@ -648,17 +612,22 @@ def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[in.order_by("team_id", "key"))- referenced_cohort_ids: set[int] = set()+ direct_cohort_ids: set[int] = set()for flag in all_flags:flag._evaluation_tag_names = flag.evaluation_tag_names_agg or []flag._has_experiment = flag.has_experiment_agg- referenced_cohort_ids.update(_extract_cohort_ids_from_filters(flag.filters or {}))+ try:+ direct_cohort_ids.update(referenced_cohort_ids(flag.filters))+ except ConfigFormatError:+ # The per-flag pass below drops this flag through its error handling; one+ # unsupported document must not fail the whole batch here.+ continue# Load only the referenced cohorts and resolve nested dependencies# iteratively. Each iteration loads newly discovered nested cohort IDs# until there are none left (typically 1-2 iterations).cohorts_by_project: dict[int, dict[int, Cohort]] = defaultdict(dict)- ids_to_load = referenced_cohort_ids.copy()+ ids_to_load = direct_cohort_ids.copy()loaded_ids: set[int] = set()while ids_to_load:@@ -712,7 +681,7 @@ def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[in# Pre-populate cache with empty entries for any referenced cohort_id# not already loaded, so get_cohort_ids doesn't make fallback DB queries# for deleted or cross-team cohorts.- for cid in _extract_cohort_ids_from_filters(filters):+ for cid in referenced_cohort_ids(filters):if cid not in seen_cohorts_cache:seen_cohorts_cache[cid] = ""diff --git a/products/feature_flags/backend/test/test_facade_references.py b/products/feature_flags/backend/test/test_facade_references.pynew file mode 100644index 000000000000..458b4dd90285--- /dev/null+++ b/products/feature_flags/backend/test/test_facade_references.py@@ -0,0 +1,129 @@+from collections.abc import Callable+from typing import Any++import pytest++from parameterized import parameterized++from products.feature_flags.backend.facade.config import ConfigFormatError+from products.feature_flags.backend.facade.references import flag_dependency_properties, referenced_cohort_ids++COHORT_PROPERTY: dict[str, Any] = {"key": "id", "type": "cohort", "value": 42}+FLAG_PROPERTY: dict[str, Any] = {"key": "7", "type": "flag", "value": ["true"], "operator": "exact"}+V1_GROUPS: list[dict[str, Any]] = [{"properties": [COHORT_PROPERTY, FLAG_PROPERTY], "rollout_percentage": 100}]++# A stored v2 document from the contract fixtures, with invented identifiers.+V2_DOCUMENT: dict[str, Any] = {+ "version": 2,+ "return_type": "boolean",+ "default_value": False,+ "rules": [{"id": "11111111-1111-4111-8111-111111111111", "rule_type": "targeted_release", "value": True}],+}++UNSUPPORTED_DOCUMENTS = [+ ("v2_document", V2_DOCUMENT),+ ("v2_discriminator_with_v1_looking_groups", {"version": 2, "groups": V1_GROUPS}),+ ("string_discriminator", {"version": "1", "groups": V1_GROUPS}),+ ("boolean_discriminator", {"version": True, "groups": V1_GROUPS}),+ ("null_discriminator", {"version": None, "groups": V1_GROUPS}),+ ("unknown_future_version", {"version": 3, "groups": V1_GROUPS}),+ ("untrusted_discriminator", {"version": "<untrusted-version>", "groups": V1_GROUPS}),+]+++class TestReferencedCohortIds:+ @parameterized.expand(+ [+ ("none_filters", None, set()),+ ("empty_filters", {}, set()),+ ("no_groups", {"multivariate": {}}, set()),+ ("empty_groups", {"groups": []}, set()),+ ("null_groups", {"groups": None}, set()),+ ("null_properties", {"groups": [{"properties": None, "rollout_percentage": 100}]}, set()),+ (+ "person_properties_only",+ {"groups": [{"properties": [{"type": "person", "key": "email", "value": "[email protected]"}]}]},+ set(),+ ),+ ("single_cohort", {"groups": [{"properties": [{"type": "cohort", "value": 123}]}]}, {123}),+ (+ "multiple_cohorts_same_group",+ {"groups": [{"properties": [{"type": "cohort", "value": 1}, {"type": "cohort", "value": 2}]}]},+ {1, 2},+ ),+ (+ "cohorts_across_groups",+ {+ "groups": [+ {"properties": [{"type": "cohort", "value": 10}]},+ {"properties": [{"type": "cohort", "value": 20}]},+ ]+ },+ {10, 20},+ ),+ ("string_value_coerced", {"groups": [{"properties": [{"type": "cohort", "value": "456"}]}]}, {456}),+ ("invalid_string_skipped", {"groups": [{"properties": [{"type": "cohort", "value": "bad"}]}]}, set()),+ ("none_value_skipped", {"groups": [{"properties": [{"type": "cohort", "value": None}]}]}, set()),+ ("missing_value_skipped", {"groups": [{"properties": [{"type": "cohort"}]}]}, set()),+ (+ "duplicates_collapsed",+ {+ "groups": [+ {"properties": [{"type": "cohort", "value": 5}]},+ {"properties": [{"type": "cohort", "value": 5}]},+ ]+ },+ {5},+ ),+ ("explicit_version_1", {"version": 1, "groups": V1_GROUPS}, {42}),+ ("explicit_version_1_float", {"version": 1.0, "groups": V1_GROUPS}, {42}),+ ]+ )+ def test_reads_v1_documents(self, _name: str, filters: dict | None, expected: set[int]) -> None:+ assert referenced_cohort_ids(filters) == expected+++class TestFlagDependencyProperties:+ @parameterized.expand(+ [+ ("absent_version", {"groups": V1_GROUPS}),+ ("explicit_version_1", {"version": 1, "groups": V1_GROUPS}),+ ]+ )+ def test_returns_the_callers_own_flag_properties(self, _name: str, filters: dict) -> None:+ flag_property = filters["groups"][0]["properties"][1]++ returned = flag_dependency_properties(filters)++ assert len(returned) == 1+ # Consumers annotate the property in place, so identity matters, not equality.+ assert returned[0] is flag_property++ @parameterized.expand(+ [+ ("none_filters", None),+ ("null_groups", {"groups": None}),+ ("null_properties", {"groups": [{"properties": None}]}),+ ("cohort_only", {"groups": [{"properties": [COHORT_PROPERTY]}]}),+ ]+ )+ def test_reads_empty_v1_documents(self, _name: str, filters: dict | None) -> None:+ assert flag_dependency_properties(filters) == []+++class TestUnsupportedFormatRejection:+ @parameterized.expand(+ [+ (f"{read.__name__}_{name}", read, filters)+ for read in (referenced_cohort_ids, flag_dependency_properties)+ for name, filters in UNSUPPORTED_DOCUMENTS+ ]+ )+ def test_rejects_before_reading_v1_keys(self, _name: str, read: Callable[[dict], Any], filters: dict) -> None:+ with pytest.raises(ConfigFormatError) as exc_info:+ read(filters)++ kind = exc_info.value.config_format.kind+ assert kind != "v1"+ # The message names the kind only, so a log line never carries the stored discriminator.+ assert str(exc_info.value) == f"config format {kind!r} is not handled here"diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.pyindex 317e138c0f0e..c32f907afc5e 100644--- a/products/feature_flags/backend/test/test_flags_cache.py+++ b/products/feature_flags/backend/test/test_flags_cache.py@@ -527,6 +527,79 @@ class TestServiceFlagsCache(BaseTest):assert len(result[other_team.id]["cohorts"]) == 1assert result[other_team.id]["cohorts"][0]["id"] == cohort_b.id+ def _create_cohort(self, name: str) -> Cohort:+ return Cohort.objects.create(+ team=self.team,+ name=name,+ filters={+ "properties": {+ "type": "OR",+ "values": [+ {"type": "OR", "values": [{"key": "email", "value": "[email protected]", "type": "person"}]}+ ],+ }+ },+ )++ def test_get_feature_flags_for_service_reads_explicit_config_version_1_like_absent(self):+ cohort = self._create_cohort("referenced")+ target = FeatureFlag.objects.create(+ team=self.team,+ key="dependency-target",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ stored_filters = {+ "version": 1,+ "groups": [+ {+ "properties": [+ {"type": "cohort", "value": cohort.id},+ {"type": "flag", "key": str(target.id), "value": ["true"], "operator": "exact"},+ ],+ "rollout_percentage": 100,+ }+ ],+ }+ flag = FeatureFlag.objects.create(+ team=self.team, key="explicit-version-1", created_by=self.user, filters=stored_filters+ )++ result = _get_feature_flags_for_service(self.team)++ assert {f["key"] for f in result["flags"]} == {"dependency-target", "explicit-version-1"}+ assert [c["id"] for c in result["cohorts"]] == [cohort.id]+ assert result["evaluation_metadata"]["dependency_stages"] == [[target.id], [flag.id]]+ assert result["evaluation_metadata"]["transitive_deps"][str(flag.id)] == [target.id]+ flag.refresh_from_db()+ assert flag.filters == stored_filters++ def test_update_flags_cache_keeps_existing_entry_when_a_flag_has_unsupported_format(self):+ FeatureFlag.objects.create(+ team=self.team,+ key="v1-flag",+ created_by=self.user,+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ assert update_flags_cache(self.team) is True+ etag_before = flags_hypercache.get_etag(self.team)++ # A v2 discriminator over v1-looking groups: reading it as v1 would publish the+ # document into the service payload instead of failing this team's rebuild.+ unsupported_filters = {"version": 2, "groups": [{"properties": [], "rollout_percentage": 100}]}+ unsupported = FeatureFlag.objects.create(+ team=self.team, key="unsupported-format", created_by=self.user, filters=unsupported_filters+ )++ assert update_flags_cache(self.team) is False++ cached = get_flags_from_cache(self.team)+ assert cached is not None+ assert [f["key"] for f in cached] == ["v1-flag"]+ assert flags_hypercache.get_etag(self.team) == etag_before+ unsupported.refresh_from_db()+ assert unsupported.filters == unsupported_filters+@override_settings(FLAGS_REDIS_URL="redis://test")class TestHasExperimentField(BaseTest):@@ -3405,6 +3478,11 @@ class TestExtractDirectDependencyIds:("multiple_dependencies", _make_flag(1, "flag_a", deps=[2, 3]), {2, 3}),("inactive_flag_returns_empty", _make_flag(1, "flag_a", deps=[2], active=False), set()),("deleted_flag_returns_empty", _make_flag(1, "flag_a", deps=[2], deleted=True), set()),+ (+ "inactive_unsupported_format_returns_empty",+ {**_make_flag(1, "flag_a", active=False), "filters": {"version": 2, **_dependency_filters(2)}},+ set(),+ ),("non_flag_properties_ignored",{@@ -3888,15 +3966,17 @@ class TestExtractCohortIdsFromFlagFilters(BaseTest):@parameterized.expand([- ("inactive", {"active": False}),- ("deleted", {"active": True, "deleted": True}),+ ("inactive", {"active": False}, {}),+ ("deleted", {"active": True, "deleted": True}, {}),+ ("inactive_unsupported_format", {"active": False}, {"version": 2}),])- def test_skips_excluded_flag(self, _name, flag_overrides):+ def test_skips_excluded_flag(self, _name, flag_overrides, filters_overrides):flags_data = [{**flag_overrides,"filters": {+ **filters_overrides,"groups": [{"properties": [{"type": "cohort", "value": 42}]}],},}diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.pyindex b92b7b132e72..1b6bad6f9b6a 100644--- a/products/feature_flags/backend/test/test_local_evaluation.py+++ b/products/feature_flags/backend/test/test_local_evaluation.py@@ -24,8 +24,8 @@ from products.feature_flags.backend.cache_keys import EU_CROSS_REGION_MIRROR_CACfrom products.feature_flags.backend.flags_cache import get_team_ids_with_recently_updated_flagsfrom products.feature_flags.backend.local_evaluation import (FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,+ FLAG_PROCESSING_ERROR_COUNTER,_build_flag_definitions_hypercache,- _extract_cohort_ids_from_filters,_get_flags_response_for_local_evaluation,_get_flags_response_for_local_evaluation_batch,_update_flag_definitions,@@ -832,52 +832,6 @@ class TestSurveyFlagExclusion(BaseTest):assert regular_flag.key in flag_keys-class TestExtractCohortIdsFromFilters(BaseTest):- @parameterized.expand(- [- ("empty_filters", {}, set()),- ("no_groups", {"multivariate": {}}, set()),- ("empty_groups", {"groups": []}, set()),- (- "person_properties_only",- {"groups": [{"properties": [{"type": "person", "key": "email", "value": "[email protected]"}]}]},- set(),- ),- ("single_cohort", {"groups": [{"properties": [{"type": "cohort", "value": 123}]}]}, {123}),- (- "multiple_cohorts_same_group",- {"groups": [{"properties": [{"type": "cohort", "value": 1}, {"type": "cohort", "value": 2}]}]},- {1, 2},- ),- (- "cohorts_across_groups",- {- "groups": [- {"properties": [{"type": "cohort", "value": 10}]},- {"properties": [{"type": "cohort", "value": 20}]},- ]- },- {10, 20},- ),- ("string_value_coerced", {"groups": [{"properties": [{"type": "cohort", "value": "456"}]}]}, {456}),- ("invalid_string_skipped", {"groups": [{"properties": [{"type": "cohort", "value": "bad"}]}]}, set()),- ("none_value_skipped", {"groups": [{"properties": [{"type": "cohort", "value": None}]}]}, set()),- (- "duplicates_collapsed",- {- "groups": [- {"properties": [{"type": "cohort", "value": 5}]},- {"properties": [{"type": "cohort", "value": 5}]},- ]- },- {5},- ),- ]- )- def test_extract_cohort_ids(self, _name: str, filters: dict, expected: set):- assert _extract_cohort_ids_from_filters(filters) == expected--class TestLocalEvaluationBatch(BaseTest):def _create_team_with_project(self, name: str) -> Team:project, team = Project.objects.create_with_team(@@ -1337,6 +1291,100 @@ class TestLocalEvaluationBatch(BaseTest):assert "flag-ref-deleted-cohort" in flag_keysassert str(cohort_id) not in results[team.id]["cohorts"]+ def _create_cohort(self, team: Team, name: str) -> Cohort:+ return Cohort.objects.create(+ team=team,+ name=name,+ filters={+ "properties": {+ "type": "OR",+ "values": [+ {"type": "OR", "values": [{"key": "email", "value": "[email protected]", "type": "person"}]}+ ],+ }+ },+ )++ def test_batch_reads_explicit_config_version_1_like_absent(self):+ team = self._create_team_with_project("Explicit version 1")+ cohort = self._create_cohort(team, "referenced")+ target = FeatureFlag.objects.create(+ team=team,+ key="dependency-target",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )+ stored_filters = {+ "version": 1,+ "groups": [+ {+ "properties": [+ {"key": "id", "type": "cohort", "value": cohort.pk},+ {"key": str(target.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"},+ ],+ "rollout_percentage": 100,+ }+ ],+ }+ flag = FeatureFlag.objects.create(team=team, key="explicit-version-1", filters=stored_filters)++ results = _get_flags_response_for_local_evaluation_batch([team])++ flags_by_key = {f["key"]: f for f in results[team.id]["flags"]}+ assert set(flags_by_key) == {"dependency-target", "explicit-version-1"}+ assert set(results[team.id]["cohorts"]) == {str(cohort.pk)}+ flag_property = flags_by_key["explicit-version-1"]["filters"]["groups"][0]["properties"][1]+ assert flag_property["key"] == "dependency-target"+ assert flag_property["dependency_chain"] == ["dependency-target"]+ flag.refresh_from_db()+ assert flag.filters == stored_filters++ def test_batch_drops_unsupported_config_format_and_keeps_siblings(self):+ team = self._create_team_with_project("Unsupported format")+ cohort = self._create_cohort(team, "sibling-cohort")+ FeatureFlag.objects.create(+ team=team,+ key="v1-sibling",+ filters={"groups": [{"properties": [{"key": "id", "type": "cohort", "value": cohort.pk}]}]},+ )+ # A v2 discriminator over v1-looking groups: reading the groups as v1 would leak the+ # cohort reference and the flag itself into the legacy payload.+ unsupported_filters = {+ "version": 2,+ "groups": [+ {"properties": [{"key": "id", "type": "cohort", "value": cohort.pk}], "rollout_percentage": 100}+ ],+ }+ unsupported = FeatureFlag.objects.create(team=team, key="unsupported-format", filters=unsupported_filters)+ FeatureFlag.objects.create(+ team=team,+ key="depends-on-unsupported",+ filters={+ "groups": [+ {+ "properties": [+ {"key": str(unsupported.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"}+ ],+ "rollout_percentage": 100,+ }+ ]+ },+ )+ dropped_before = FLAG_PROCESSING_ERROR_COUNTER._value.get()++ results = _get_flags_response_for_local_evaluation_batch([team])++ flags_by_key = {f["key"]: f for f in results[team.id]["flags"]}+ assert set(flags_by_key) == {"v1-sibling", "depends-on-unsupported"}+ assert set(results[team.id]["cohorts"]) == {str(cohort.pk)}+ assert FLAG_PROCESSING_ERROR_COUNTER._value.get() == dropped_before + 1+ # The dropped flag never reaches flag_id_to_key, so its dependent publishes the same+ # shape as a reference to a flag that never existed (see test_missing_dependency).+ flag_property = flags_by_key["depends-on-unsupported"]["filters"]["groups"][0]["properties"][0]+ assert flag_property["key"] == str(unsupported.pk)+ assert flag_property["dependency_chain"] == []+ unsupported.refresh_from_db()+ assert unsupported.filters == unsupported_filters+@override_settings(FLAGS_REDIS_URL="redis://test")class TestFlagDefinitionsCache(BaseTest):