: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
refactor(flags): read cohort and dependency references through one seam (#109446)
Anders517d8310e49d
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.pyindex 69d7f1d49bfe..84336af85e81 100644--- a/posthog/api/cohort.py+++ b/posthog/api/cohort.py@@ -112,7 +112,8 @@ from products.cohorts.backend.realtime_state import (has_realtime_state,resolve_realtime_readiness,)-from products.feature_flags.backend.facade.config import ConfigFormatError, is_v1_config+from products.feature_flags.backend.facade.config import ConfigFormatError, UnsupportedConfig, decode_config+from products.feature_flags.backend.facade.references import referencesfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.team_feature_flags_config import (PropertyMatchingVersion,@@ -1407,7 +1408,8 @@ class CohortSerializer(SearchMatchTypeSerializerMixin, serializers.ModelSerializflags = FeatureFlag.objects.filter(team__project_id=self.context["project_id"], active=True)cohort_used_in_flags = any(- cohort_id in flag.get_cohort_ids(stop_traversal_at_static=True) for flag in _v1_flags(flags)+ cohort_id in flag.get_cohort_ids(stop_traversal_at_static=True)+ for flag in _flags_with_readable_config(flags))if not cohort_used_in_flags:@@ -1645,29 +1647,22 @@ def _flags_with_cohort_filters(cohort: Cohort) -> QuerySet[FeatureFlag]:)-def _v1_flags(flags: Iterable[FeatureFlag]) -> Iterator[FeatureFlag]:- """Rows whose document carries the v1 release groups the cohort walks below read.+def _flags_with_readable_config(flags: Iterable[FeatureFlag]) -> Iterator[FeatureFlag]:+ """Rows whose stored config the cohort walks below can read: config version 1 or 2.- A flag in another config format references cohorts in its own shape; until those reads- exist it is skipped here rather than read as a flag with no conditions. Lazy, so a caller- that short-circuits stops at the first match.+ A document in no readable format is skipped rather than read as a flag with no+ conditions. Lazy, so a caller that short-circuits stops at the first match."""- return (flag for flag in flags if is_v1_config(flag.filters))+ return (flag for flag in flags if not isinstance(decode_config(flag.filters), UnsupportedConfig))def _directly_referenced_cohort_ids(flags: list[FeatureFlag]) -> set[int]:- """Cohort ids each flag references directly in its filter conditions.+ """Cohort ids each flag references directly, the ones ``FeatureFlag.get_cohort_ids`` starts from.- Mirrors the cohort-property walk in ``FeatureFlag.get_cohort_ids``, used to bulk-load- those cohorts so the expansion doesn't point-query them one at a time.+ Used to bulk-load those cohorts so the expansion doesn't point-query them one at a time.+ An id that is not an integer is left to the expansion, which rejects it in v1 and skips it in v2."""- return {- int(prop["value"])- for flag in flags- for condition in flag.conditions- for prop in condition.get("properties", [])- if prop.get("type") == "cohort" and str(prop.get("value")).lstrip("-").isdigit()- }+ return {cohort_id for flag in flags for cohort_id in references(decode_config(flag.filters)).cohort_ids}def _filter_flags_referencing_cohort(@@ -1681,7 +1676,7 @@ def _filter_flags_referencing_cohort(target still resolves: ``used_in`` reports flags referencing a deleted cohort, whichmatches the insights and cohorts blocks (neither checks the target's deleted state)."""- flag_list = list(_v1_flags(flags))+ flag_list = list(_flags_with_readable_config(flags))seen_cohorts_cache: dict[int, CohortOrEmpty] = {cohort.id: cohort}direct_ids = _directly_referenced_cohort_ids(flag_list) - seen_cohorts_cache.keys()if direct_ids:diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.pyindex a4aa97641b11..9d083d67bba8 100644--- a/posthog/api/test/test_cohort.py+++ b/posthog/api/test/test_cohort.py@@ -5326,12 +5326,14 @@ [email protected],@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")- def test_flags_in_another_config_format_are_skipped_by_the_flag_checks(self, patch_calculate_cohort, patch_capture):+ def test_config_version_2_flags_use_the_cohorts_their_rules_target(self, patch_calculate_cohort, patch_capture):response = self.client.post(f"/api/projects/{self.team.id}/cohorts",data={"name": "Test Cohort", "groups": [{"properties": {"team_id": 5}}]},)cohort_id = response.json()["id"]+ cohort_property = {"key": "id", "value": cohort_id, "type": "cohort"}+ # Written past the validator, which does not admit cohort targeting yet.FeatureFlag.objects.create(team=self.team,filters={@@ -5342,47 +5344,56 @@ [email protected],{"id": "11111111-1111-4111-8111-111111111111","rule_type": "targeted_release",- "targeting": {"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]},+ "targeting": {"properties": [cohort_property]},"value": True,}],},- name="Other format flag",- key="other-format",+ name="Rules flag using cohort",+ key="rules-flag",created_by=self.user,active=True,)+ FeatureFlag.objects.create(+ team=self.team,+ filters={"version": 3, "groups": [{"properties": [cohort_property]}]},+ name="Unreadable flag",+ key="unreadable-flag",+ created_by=self.user,+ active=True,+ )++ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort_id}/used_in")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([flag["key"] for flag in response.json()["feature_flags"]["results"]], ["rules-flag"])+response = self.client.patch(f"/api/projects/{self.team.id}/cohorts/{cohort_id}",data={"filters": {"properties": {"type": "OR",- "values": [{"key": "$some_prop", "value": "x", "type": "person", "operator": "exact"}],+ "values": [+ {+ "key": "$pageview",+ "event_type": "events",+ "time_value": 1,+ "time_interval": "day",+ "value": "performed_event",+ "type": "behavioral",+ }+ ],}}},format="json",)- self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())- FeatureFlag.objects.create(- team=self.team,- filters={"groups": [{"properties": [{"key": "id", "value": cohort_id, "type": "cohort"}]}]},- name="Flag using cohort",- key="cohort-flag",- created_by=self.user,- active=True,- )-- response = self.client.patch(- f"/api/projects/{self.team.id}/cohorts/{cohort_id}",- data={"groups": [{"properties": {"team_id": 6}}]},- )- self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["code"], "behavioral_cohort_found")response = self.client.patch(f"/api/projects/{self.team.id}/cohorts/{cohort_id}", data={"deleted": True})self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("used in 1 active feature flag(s): Flag using cohort", response.json()["detail"])+ self.assertIn("used in 1 active feature flag(s): Rules flag using cohort", response.json()["detail"])@patch("posthog.api.cohort.report_user_action")@patch("posthog.tasks.calculate_cohort.calculate_cohort_ch.delay")diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 2ab033ee1d40..e22cab059a43 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -131,8 +131,16 @@ from products.feature_flags.backend.facade import (config_writes,filters as flag_filters,)-from products.feature_flags.backend.facade.config import ConfigFormatError, detect_config_format, require_v1_config+from products.feature_flags.backend.facade.config import (+ ConfigFormatError,+ ConfigV1,+ UnsupportedConfig,+ decode_config,+ detect_config_format,+ require_v1_config,+)from products.feature_flags.backend.facade.config_validation import ConfigValidationError, ValidationLimits+from products.feature_flags.backend.facade.references import InvalidIds, referencesfrom products.feature_flags.backend.filters_validation import collect_cross_field_violations, flatten_structural_errorsfrom products.feature_flags.backend.flag_analytics import increment_request_countfrom products.feature_flags.backend.flag_limits import get_max_feature_flags_for_team@@ -2829,15 +2837,15 @@ class FeatureFlagSerializer(def _find_disabled_dependencies(self, flag_to_check: FeatureFlag) -> list[FeatureFlag]:"""Find all disabled flags that the given flag depends on."""- dependency_ids = []-- # Extract flag dependencies from filters- filters = flag_to_check.filters or {}- for group in filters.get("groups", []):- for prop in group.get("properties", []):- if prop.get("type") == "flag":- dependency_ids.append(int(prop.get("key")))-+ config = decode_config(flag_to_check.filters)+ if isinstance(config, UnsupportedConfig):+ # validate() rejected every other unsupported format, so this is a v2 document parse_v2_config+ # cannot read. Under the row lock _apply_v2_update rejects it through config_writes.validate_stored,+ # or, when the request also sends filters, _resolve_v2_document validates the replacement.+ return []+ # A non-integer flag id raises in v1, as it always did; v2 skips it and leaves the 400 to the validator.+ invalid_ids: InvalidIds = "raise" if isinstance(config, ConfigV1) else "skip"+ dependency_ids = references(config, invalid_flag_ids=invalid_ids).flag_idsif not dependency_ids:return []diff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.pyindex 29ef50a044c9..39ba7a858261 100644--- a/products/feature_flags/backend/api/organization_feature_flag.py+++ b/products/feature_flags/backend/api/organization_feature_flag.py@@ -41,7 +41,7 @@ from products.feature_flags.backend.encrypted_flag_payloads import (get_decrypted_flag_payloads_protected,)from products.feature_flags.backend.facade.api import create_flag, serialize_flags, update_flag-from products.feature_flags.backend.facade.config import ConfigFormatError+from products.feature_flags.backend.facade.config import ConfigFormatError, require_v1_configfrom products.feature_flags.backend.flag_analytics import get_cached_evaluations_7d_by_teamfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.scheduled_change import ScheduledChange@@ -1144,6 +1144,7 @@ class OrganizationFeatureFlagView(def _get_feature_flag_copy_source_context(self, source_flag: FeatureFlag, copy_schedule: bool, user: User) -> FeatureFlagCopySourceContext:+ require_v1_config(source_flag.get_filters())source_dependency_keys, disabled_source_dependency_keys = self._get_source_dependency_context(source_flag, user=user)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.pyindex 11449c0708e8..beb3345729f4 100644--- 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@@ -398,6 +398,27 @@ class TestAdmittedV2Enabling(AdmittedV2TestCase):assert (flag.active, flag.version) == (False, 5)assert [entry.activity for entry in self.activity(flag)] == ["updated", "updated"]+ def test_enabling_reports_a_disabled_flag_the_rule_targeting_depends_on(self) -> None:+ dependency = FeatureFlag.objects.create(team=self.team, key="base-flag", active=False, created_by=self.user)+ # Stored past the validator, which does not admit flag targeting yet. The non-integer key is skipped.+ targeting = {+ "properties": [+ {"key": str(dependency.id), "type": "flag", "value": True, "operator": "flag_evaluates_to"},+ {"key": "checkout-flow", "type": "flag", "value": True, "operator": "flag_evaluates_to"},+ ]+ }+ stored = config(targeted(targeting=targeting))+ flag = self.flag(stored, active=False)++ response = self.patch_flag(flag, {"version": 3, "active": True})++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ detail = response.json()["detail"]+ assert "Cannot enable this feature flag because it depends on disabled flags" in detail+ assert f"base-flag (ID: {dependency.id})" in detail+ flag.refresh_from_db()+ assert (flag.active, flag.version, flag.filters) == (False, 3, stored)+@parameterized.expand([("malformed", {"version": 2, "rules": "broken"}, settings.MAX_FEATURE_FLAG_FILTER_SIZE_BYTES),diff --git a/products/feature_flags/backend/facade/config.py b/products/feature_flags/backend/facade/config.pyindex 668a148cc852..a0de6edd62ca 100644--- a/products/feature_flags/backend/facade/config.py+++ b/products/feature_flags/backend/facade/config.py@@ -13,11 +13,15 @@ A JSON string or boolean never selects a version, and a stored value that is notreader 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 and values, experiment identity) and nothing-else. The full v2 schema lives in the contract; do not grow this module into a second copy of it.+route on (return type, ordered rule identities and values, experiment identity, and the cohort+and flag targeting predicates) 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 modelmodules import this at module level.++``decode_config`` is the read entry point for a reader that handles more than one format: it+returns one arm per format, and ``facade.references`` reads the cohorts and flags each arm names."""from collections.abc import Mapping@@ -25,11 +29,15 @@ from typing import Any, Literal, get_argsfrom posthog.dataclasses import frozen+from products.feature_flags.backend.types import PropertyFilterType+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]+_REFERENCE_PREDICATE_TYPES = (PropertyFilterType.COHORT, PropertyFilterType.FLAG)+@frozenclass ConfigFormat:@@ -80,6 +88,8 @@ def is_v1_config(filters: object) -> bool:@frozenclass RuleV2:id: str+ # The targeting predicates that name a cohort or another flag, as stored.+ reference_predicates: tuple[Mapping[str, Any], ...] = ()rule_type: RuleTypeexperiment_id: int | None# None for an experiment rule, whose values sit on its variants.@@ -102,6 +112,38 @@ class ConfigV2:raise ValueError("Unsupported feature flag return type")+@frozen+class ConfigV1:+ # The stored document. Its v1 keys are read where they are needed; no v1 type is built here.+ filters: Mapping[str, Any]+++@frozen+class UnsupportedConfig:+ config_format: ConfigFormat+++DecodedConfig = ConfigV1 | ConfigV2 | UnsupportedConfig+++def decode_config(document: object) -> DecodedConfig:+ """Read a stored ``filters`` document into the arm for its format.++ Decoding is structural. It does not run the writer's validator, so a decoded v2 document+ can still hold shapes the writer does not admit yet. A v2 document that the structural+ read cannot take decodes as unsupported, so no reader acts on part of it.+ """+ config_format = detect_config_format(document)+ if config_format.kind == "v1":+ return ConfigV1(filters=document if isinstance(document, Mapping) else {})+ if config_format.kind == "v2" and isinstance(document, Mapping):+ try:+ return parse_v2_config(document)+ except (KeyError, TypeError, ValueError, AttributeError):+ config_format = ConfigFormat(kind="unsupported", raw_version=config_format.raw_version)+ return UnsupportedConfig(config_format=config_format)++def parse_v2_config(filters: Mapping[str, Any]) -> ConfigV2:"""Structural read of a stored v2 document.@@ -124,6 +166,9 @@ def _rule_v2(rule: Mapping[str, Any]) -> RuleV2:rule_type = rule["rule_type"]return RuleV2(id=rule["id"],+ reference_predicates=tuple(+ prop for prop in rule["targeting"]["properties"] if prop.get("type") in _REFERENCE_PREDICATE_TYPES+ ),rule_type=rule_type,experiment_id=rule["experiment_id"] if rule_type == "experiment" else None,value=None if rule_type == "experiment" else rule["value"],diff --git a/products/feature_flags/backend/facade/references.py b/products/feature_flags/backend/facade/references.pyindex 1ea3ddab37c3..662df8caa28d 100644--- a/products/feature_flags/backend/facade/references.py+++ b/products/feature_flags/backend/facade/references.py@@ -1,29 +1,83 @@"""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.+``references`` reads a decoded config of either format and returns identities only: cohort+ids and flag ids, never the stored dicts. Config version 1 holds cohort and flag references+as ``groups[*].properties`` with ``type == "cohort"`` or ``type == "flag"``. Config version 2+holds the same property shapes in each rule's targeting. An unsupported document raises+``ConfigFormatError``; it is never read as a flag with no references.++``referenced_cohort_ids`` and ``flag_dependency_properties`` serve the SDK definitions+payload, which carries v1 documents only. It rewrites flag references from ids to keys and+annotates them with a dependency chain, so ``flag_dependency_properties`` returns the+caller's own property dicts and those in-place rewrites keep working. Both raise+``ConfigFormatError`` for any other format, because a producer that silently dropped the+references would publish an unsupported document into a feed built for v1 readers.Deliberately free of Django/DRF imports (same reason as ``facade.filters``)."""-from collections.abc import Mapping-from typing import Any+from collections.abc import Iterable, Mapping+from typing import Any, Literal++from posthog.dataclasses import frozen-from products.feature_flags.backend.facade.config import ConfigFormatError, detect_config_format+from products.feature_flags.backend.facade.config import (+ ConfigFormatError,+ ConfigV1,+ DecodedConfig,+ UnsupportedConfig,+ decode_config,+ require_v1_config,+)from products.feature_flags.backend.types import FlagProperty, PropertyFilterType+# "skip" drops a reference whose id is not an integer; "raise" lets int()'s error out.+InvalidIds = Literal["skip", "raise"]+++@frozen+class FlagReferences:+ cohort_ids: tuple[int, ...] = () # first-seen order+ flag_ids: tuple[int, ...] = () # first-seen order+++def references(+ config: DecodedConfig, *, invalid_cohort_ids: InvalidIds = "skip", invalid_flag_ids: InvalidIds = "skip"+) -> FlagReferences:+ """The cohorts and flags a decoded config names.++ A v1 document whose groups or properties are not lists of objects raises AttributeError or+ TypeError, as the v1 readers always did; the caller decides whether that skips the row or+ fails.+ """+ if isinstance(config, UnsupportedConfig):+ raise ConfigFormatError(config.config_format)+ if isinstance(config, ConfigV1):+ groups = config.filters.get("groups") or []+ predicates = [prop for group in groups for prop in group.get("properties") or []]+ else:+ predicates = [prop for rule in config.rules for prop in rule.reference_predicates]+ return FlagReferences(+ cohort_ids=_ids(predicates, PropertyFilterType.COHORT, "value", invalid_cohort_ids),+ flag_ids=_ids(predicates, PropertyFilterType.FLAG, "key", invalid_flag_ids),+ )+++def _ids(+ predicates: Iterable[Mapping[str, Any]], property_type: PropertyFilterType, field: str, invalid_ids: InvalidIds+) -> tuple[int, ...]:+ ids: dict[int, None] = {}+ for prop in predicates:+ if prop.get("type") != property_type:+ continue+ value: Any = prop.get(field)+ try:+ ids[int(value)] = None+ except (TypeError, ValueError, OverflowError):+ if invalid_ids == "raise":+ raise+ return tuple(ids)+def referenced_cohort_ids(filters: Mapping[str, Any] | None) -> set[int]:"""Cohort ids the release conditions of a v1 document reference.@@ -32,16 +86,8 @@ def referenced_cohort_ids(filters: Mapping[str, Any] | None) -> set[int]:integer is skipped, the same tolerance every producer already applied; a consumerthat 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+ require_v1_config(filters)+ return set(references(decode_config(filters)).cohort_ids)def flag_dependency_properties(filters: Mapping[str, Any] | None) -> list[FlagProperty]:@@ -55,9 +101,7 @@ def flag_dependency_properties(filters: Mapping[str, Any] | None) -> list[FlagPrdef _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)+ require_v1_config(filters)# 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 datadiff --git a/products/feature_flags/backend/flag_version_sync.py b/products/feature_flags/backend/flag_version_sync.pyindex f4f13b757030..9f2154cb8ada 100644--- a/products/feature_flags/backend/flag_version_sync.py+++ b/products/feature_flags/backend/flag_version_sync.py@@ -44,7 +44,8 @@ from posthog.models.activity_logging.activity_log import Change, Detail, LogActifrom posthog.models.activity_logging.utils import activity_storagefrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty-from products.feature_flags.backend.facade.config import ConfigFormatError+from products.feature_flags.backend.facade.config import ConfigFormatError, decode_config+from products.feature_flags.backend.facade.references import referencesfrom products.feature_flags.backend.field_snapshots import capture_fields_before_save, snapshot_if_changedfrom products.feature_flags.backend.models.feature_flag import FeatureFlag@@ -252,7 +253,7 @@ def _flag_version_bump_entry(flag: FeatureFlag, old_version: int | None, triggerdef direct_flag_dependency_ids(flag: FeatureFlag) -> set[int]:- """Flag ids this flag has a ``flag_evaluates_to`` release condition on.+ """Flag ids this flag's release conditions (v1) or rule targeting (v2) depend on.Same parse as ``flags_cache._extract_direct_dependency_ids`` (a dependency is keyed bythe referenced flag's id in ``key``), minus its inactive/deleted short-circuit: a@@ -261,27 +262,15 @@ def direct_flag_dependency_ids(flag: FeatureFlag) -> set[int]:sibling flag can't break the save that triggered this. Read by the version-bump pathbelow and by the stale-flags health check."""- dependency_ids: set[int] = set()try:- conditions = flag.conditions+ return set(references(decode_config(flag.filters)).flag_ids)except ConfigFormatError:- # Only a v1 document carries release groups, so a row in another format has no v1 edges.- return dependency_ids- except Exception:- # A sibling flag with malformed filters must neither break the save nor suppress- # the bump for healthy flags.+ return set()+ except (AttributeError, TypeError):+ # references() raises these for v1 groups or properties that are not lists of objects.logger.exception("flag_version_sync_dependency_parse_failed", flag_id=flag.pk, team_id=flag.team_id)capture_exception()- return dependency_ids- for condition in conditions:- for prop in condition.get("properties") or []:- if prop.get("type") != "flag":- continue- try:- dependency_ids.add(int(prop["key"]))- except (ValueError, KeyError, TypeError):- continue- return dependency_ids+ return set()def flags_with_flag_dependencies(project_ids: Collection[int]) -> QuerySet[FeatureFlag]:@@ -366,10 +355,7 @@ def _flags_referencing_cohort(cohort: Cohort) -> list[FeatureFlag]:direct_ids: set[int] = set()for flag in candidate_flags:try:- for condition in flag.conditions:- for prop in condition.get("properties", []):- if prop.get("type") == "cohort" and str(prop.get("value")).lstrip("-").isdigit():- direct_ids.add(int(prop["value"]))+ direct_ids.update(references(decode_config(flag.filters)).cohort_ids)except Exception:continuedirect_ids -= seen_cohorts_cache.keys()diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex 7bc3c405f69c..1300bfd36c52 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -72,12 +72,16 @@ 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.config import detect_config_format-from products.feature_flags.backend.facade.references import flag_dependency_properties, referenced_cohort_ids+from products.feature_flags.backend.facade.config import (+ ConfigFormatError,+ UnsupportedConfig,+ decode_config,+ detect_config_format,+)+from products.feature_flags.backend.facade.references import FlagReferences, referencesfrom 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-from products.feature_flags.backend.types import FlagPropertylogger = structlog.get_logger(__name__)@@ -102,15 +106,17 @@ def _is_unevaluable(flag_data: dict[str, Any]) -> bool:return not flag_data.get("active", True) or flag_data.get("deleted", False)-def _parse_dependency_ids(properties: list[FlagProperty]) -> set[int]:- """The integer flag ids the flag-reference properties name; any other ``key`` is skipped."""- dep_ids: set[int] = set()- for prop in properties:- try:- dep_ids.add(int(prop["key"]))- except (ValueError, KeyError, TypeError):- continue- return dep_ids+def _evaluated_references(flag_data: dict[str, Any]) -> FlagReferences:+ """The references of a serialized flag the matcher reads, and none for an unevaluable+ flag, whose filters it skips.++ Only flags that passed ``_omit_unsupported_flags`` are serialized, so the document is+ a readable config version 1 or a supported v2 document.+ """+ if _is_unevaluable(flag_data):+ return FlagReferences()+ config = decode_config(flag_data.get("filters", {}))+ return FlagReferences() if isinstance(config, UnsupportedConfig) else references(config)def _extract_direct_dependency_ids(flag_data: dict[str, Any]) -> set[int]:@@ -118,19 +124,9 @@ def _extract_direct_dependency_ids(flag_data: dict[str, Any]) -> set[int]:Extract direct flag dependency IDs from a serialized flag's filters.Inactive/deleted flags return empty deps before their filters are read, to- match Rust's extract_dependencies behavior. Only flags that passed- ``_omit_unsupported_flags`` are serialized, so every other document here is a- readable config version 1 or a supported v2 document, which has no dependencies.+ match Rust's extract_dependencies behavior. A ``key`` that is not an integer id is skipped."""- if not _reads_v1_conditions(flag_data):- return set()- return _parse_dependency_ids(flag_dependency_properties(flag_data.get("filters", {})))---def _reads_v1_conditions(flag_data: dict[str, Any]) -> bool:- """Whether a serialized flag's release conditions are read: evaluable, and a v1- document (a kept v2 document has no cohort or flag references)."""- return not _is_unevaluable(flag_data) and detect_config_format(flag_data.get("filters", {})).kind == "v1"+ return set(_evaluated_references(flag_data).flag_ids)def _validates_v2(filters: Mapping[str, Any]) -> bool:@@ -161,25 +157,26 @@ def _stored_dependency_ids(flag: FeatureFlag) -> set[int] | None:cache cannot carry the row.A non-object document and an unsupported discriminator are rejected whatever the- row's lifecycle. A v2 document is carried verbatim, with no dependencies, only when- the row is active and ``_validates_v2`` admits it. Any other v2 row is rejected, so an- inactive v2 row is never blanked into a v1-shaped entry. An unevaluable v1 object is- not read, since ``_blank_inactive_filters`` empties it; an evaluable one whose- conditions cannot be read is rejected instead of failing the team.+ row's lifecycle. A v2 document is carried verbatim only when the row is active and+ ``_validates_v2`` admits it. Any other v2 row is rejected, so an inactive v2 row is+ never blanked into a v1-shaped entry. An unevaluable v1 object is not read, since+ ``_blank_inactive_filters`` empties it; an evaluable one whose conditions cannot be+ read is rejected instead of failing the team."""filters = flag.filtersif not isinstance(filters, Mapping):return Nonekind = detect_config_format(filters).kindif kind == "v2":- return set() if flag.active and not flag.deleted and _validates_v2(filters) else None- if kind != "v1":+ if not (flag.active and not flag.deleted and _validates_v2(filters)):+ return None+ elif kind != "v1":return None- if not flag.active or flag.deleted:+ elif not flag.active or flag.deleted:return set()try:- return _parse_dependency_ids(flag_dependency_properties(filters))- except (AttributeError, TypeError):+ return set(references(decode_config(filters)).flag_ids)+ except (AttributeError, TypeError, ConfigFormatError):return None@@ -257,9 +254,7 @@ def _extract_cohort_ids_from_flag_filters(flags_data: list[dict[str, Any]]) -> s"""cohort_ids: set[int] = set()for flag in flags_data:- if not _reads_v1_conditions(flag):- continue- cohort_ids |= referenced_cohort_ids(flag.get("filters", {}))+ cohort_ids.update(_evaluated_references(flag).cohort_ids)return cohort_idsdiff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.pyindex f78488851478..65264dd01b09 100644--- a/products/feature_flags/backend/models/feature_flag.py+++ b/products/feature_flags/backend/models/feature_flag.py@@ -22,7 +22,8 @@ from posthog.models.utils import RootTeamManager, RootTeamMixin, RootTeamQuerySefrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmptyfrom products.experiments.backend.models.experiment import live_experiment_exists-from products.feature_flags.backend.facade.config import ConfigFormatError, require_v1_config+from products.feature_flags.backend.facade.config import ConfigFormatError, ConfigV1, decode_config, require_v1_config+from products.feature_flags.backend.facade.references import InvalidIds, referencesfrom products.feature_flags.backend.variant_rollout import format_variant_rollout_sum, variant_rollout_sum_is_100if TYPE_CHECKING:@@ -434,39 +435,39 @@ class FeatureFlag(Taggable, FileSystemSyncMixin, ModelActivityMixin, RootTeamMixseen_cohorts_cache = {}cohort_ids = set()- for condition in self.conditions:- props = condition.get("properties", [])- for prop in props:- if prop.get("type") == "cohort":- cohort_id = int(prop.get("value"))- try:- if cohort_id in seen_cohorts_cache:- cohort: CohortOrEmpty = seen_cohorts_cache[cohort_id]- if not cohort:- continue- else:- cohort = Cohort.objects.db_manager(using_database).get(- pk=cohort_id,- team__project_id=self.team.project_id,- deleted=False,- )- seen_cohorts_cache[cohort_id] = cohort-- cohort_ids.add(cohort.pk)- cohort_ids.update(- [- dependency_cohort.pk- for dependency_cohort in get_all_cohort_dependencies(- cohort,- using_database=using_database,- seen_cohorts_cache=seen_cohorts_cache,- stop_traversal_at_static=stop_traversal_at_static,- )- ]- )- except Cohort.DoesNotExist:- seen_cohorts_cache[cohort_id] = ""+ # Unreadable formats raise. A non-integer id raises in v1, as it always did; v2 skips it, as Rust does.+ config = decode_config(self.get_filters())+ invalid_ids: InvalidIds = "raise" if isinstance(config, ConfigV1) else "skip"+ direct_ids = references(config, invalid_cohort_ids=invalid_ids).cohort_ids+ for cohort_id in direct_ids:+ try:+ if cohort_id in seen_cohorts_cache:+ cohort: CohortOrEmpty = seen_cohorts_cache[cohort_id]+ if not cohort:continue+ else:+ cohort = Cohort.objects.db_manager(using_database).get(+ pk=cohort_id,+ team__project_id=self.team.project_id,+ deleted=False,+ )+ seen_cohorts_cache[cohort_id] = cohort++ cohort_ids.add(cohort.pk)+ cohort_ids.update(+ [+ dependency_cohort.pk+ for dependency_cohort in get_all_cohort_dependencies(+ cohort,+ using_database=using_database,+ seen_cohorts_cache=seen_cohorts_cache,+ stop_traversal_at_static=stop_traversal_at_static,+ )+ ]+ )+ except Cohort.DoesNotExist:+ seen_cohorts_cache[cohort_id] = ""+ continueif sort_by_topological_order:return sort_cohorts_topologically(cohort_ids, seen_cohorts_cache)diff --git a/products/feature_flags/backend/test/test_facade.py b/products/feature_flags/backend/test/test_facade.pyindex b0157670373d..f610e91b2f62 100644--- a/products/feature_flags/backend/test/test_facade.py+++ b/products/feature_flags/backend/test/test_facade.py@@ -1071,8 +1071,6 @@ class TestModelAccessorsRequireV1:getattr(flag, accessor)with pytest.raises(ConfigFormatError):flag.get_payload("true")- with pytest.raises(ConfigFormatError):- flag.get_cohort_ids()assert flag.is_eligible_for_experiment is Falseassert flag.get_analytics_metadata() == {"created_at": flag.created_at,@@ -1116,6 +1114,30 @@ class TestModelAccessorsRequireV1:assert flag.get_analytics_metadata()["groups_count"] == len(conditions)+class TestGetCohortIdsReadsEitherFormat:+ @parameterized.expand([(name, filters) for name, filters in UNSUPPORTED_DOCUMENTS if name != "v2_document"])+ def test_rejects_documents_in_no_readable_format(self, _name, filters):+ with pytest.raises(ConfigFormatError):+ FeatureFlag(filters=filters).get_cohort_ids()++ def test_reads_a_v2_document(self):+ filters = {"version": 2, "return_type": "boolean", "default_value": False, "rules": []}+ assert FeatureFlag(filters=filters).get_cohort_ids() == []++ def test_a_non_integer_cohort_id_raises_in_v1_and_is_skipped_in_v2(self):+ prop = {"key": "id", "type": "cohort", "value": "abc"}+ with pytest.raises(ValueError):+ FeatureFlag(filters={"groups": [{"properties": [prop]}]}).get_cohort_ids()+ rule = {+ "id": "11111111-1111-4111-8111-111111111111",+ "rule_type": "targeted_release",+ "targeting": {"properties": [prop]},+ "value": True,+ }+ filters = {"version": 2, "return_type": "boolean", "default_value": False, "rules": [rule]}+ assert FeatureFlag(filters=filters).get_cohort_ids() == []++class TestScheduledChangeBuilderRequiresV1:@parameterized.expand(UNSUPPORTED_DOCUMENTS)def test_v1_merges_fail_closed_and_status_changes_do_not_read_the_document(self, _name, filters):diff --git a/products/feature_flags/backend/test/test_facade_config.py b/products/feature_flags/backend/test/test_facade_config.pyindex 7f5fe9414eff..7e2bd2bdc07b 100644--- a/products/feature_flags/backend/test/test_facade_config.py+++ b/products/feature_flags/backend/test/test_facade_config.py@@ -8,8 +8,11 @@ from parameterized import parameterizedfrom products.feature_flags.backend.facade.config import (ConfigFormat,ConfigFormatError,+ ConfigV1,ConfigV2,RuleV2,+ UnsupportedConfig,+ decode_config,detect_config_format,parse_v2_config,)@@ -221,3 +224,67 @@ class TestParseV2Config:with pytest.raises(ValueError, match=message):parse_v2_config(filters)+++COHORT_PREDICATE: dict[str, Any] = {"key": "id", "type": "cohort", "value": 12}+FLAG_PREDICATE: dict[str, Any] = {"key": "34", "type": "flag", "operator": "flag_evaluates_to", "value": True}+++class TestDecodeConfig:+ @parameterized.expand(+ [+ ("absent_version", {"groups": []}, {"groups": []}),+ ("explicit_version_1", {"version": 1, "groups": []}, {"version": 1, "groups": []}),+ ("none_document", None, {}),+ ]+ )+ def test_v1_documents_decode_to_the_v1_arm(self, _name: str, document: Any, filters: dict) -> None:+ assert decode_config(document) == ConfigV1(filters=filters)++ def test_v2_rules_carry_their_cohort_and_flag_predicates(self) -> None:+ document = deepcopy(V2_STRING_GROUP_ASSIGNMENT)+ group_predicate = document["rules"][0]["targeting"]["properties"][0]+ document["rules"][0]["targeting"]["properties"] = [COHORT_PREDICATE, group_predicate, FLAG_PREDICATE]++ decoded = decode_config(document)++ assert isinstance(decoded, ConfigV2)+ assert decoded.aggregation_group_type_index == 0+ assert decoded.rules[0].reference_predicates == (COHORT_PREDICATE, FLAG_PREDICATE)++ @parameterized.expand(+ [+ ("unknown_future_version", {"version": 3}, 3),+ ("string_version", {"version": "2"}, "2"),+ ("list_document", [], None),+ ("v2_discriminator_over_v1_keys", {"version": 2, "groups": []}, 2),+ (+ "v2_rule_without_targeting",+ {**V2_BOOLEAN_ALL_RULE_TYPES, "rules": [{"id": "r", "rule_type": "targeted_release"}]},+ 2,+ ),+ ("v2_rules_not_a_list", {**V2_BOOLEAN_ALL_RULE_TYPES, "rules": 7}, 2),+ (+ "v2_unknown_rule_type",+ {+ **V2_BOOLEAN_ALL_RULE_TYPES,+ "rules": [{"id": "r", "rule_type": "variant_rollout", "targeting": {"properties": []}}],+ },+ 2,+ ),+ (+ "v2_predicate_not_an_object",+ {+ **V2_BOOLEAN_ALL_RULE_TYPES,+ "rules": [{"id": "r", "rule_type": "targeted_release", "targeting": {"properties": ["cohort"]}}],+ },+ 2,+ ),+ ]+ )+ def test_other_documents_decode_to_the_unsupported_arm(+ self, _name: str, document: Any, raw_version: object+ ) -> None:+ assert decode_config(document) == UnsupportedConfig(+ config_format=ConfigFormat(kind="unsupported", raw_version=raw_version)+ )diff --git a/products/feature_flags/backend/test/test_facade_references.py b/products/feature_flags/backend/test/test_facade_references.pyindex 458b4dd90285..937a339a79a5 100644--- a/products/feature_flags/backend/test/test_facade_references.py+++ b/products/feature_flags/backend/test/test_facade_references.py@@ -5,19 +5,32 @@ import pytestfrom 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+from products.feature_flags.backend.facade.config import ConfigFormatError, decode_config+from products.feature_flags.backend.facade.references import (+ FlagReferences,+ InvalidIds,+ flag_dependency_properties,+ referenced_cohort_ids,+ references,+)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.+# A stored v2 document in the contract's shape, 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}],+ "rules": [+ {+ "id": "11111111-1111-4111-8111-111111111111",+ "rule_type": "targeted_release",+ "targeting": {"properties": []},+ "value": True,+ }+ ],}UNSUPPORTED_DOCUMENTS = [@@ -127,3 +140,131 @@ class TestUnsupportedFormatRejection: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"+++def _v2_document(*rules: list[dict[str, Any]]) -> dict[str, Any]:+ return {+ "version": 2,+ "return_type": "boolean",+ "default_value": False,+ "rules": [+ {+ "id": f"00000000-0000-4000-8000-00000000000{index}",+ "rule_type": "targeted_release",+ "targeting": {"properties": properties},+ "value": True,+ }+ for index, properties in enumerate(rules)+ ],+ }+++def _cohort(value: object) -> dict[str, Any]:+ return {"key": "id", "type": "cohort", "value": value}+++def _flag(key: object) -> dict[str, Any]:+ return {"key": key, "type": "flag", "operator": "flag_evaluates_to", "value": True}+++class TestReferences:+ @parameterized.expand(+ [+ ("none_document", None, FlagReferences()),+ ("null_groups", {"groups": None}, FlagReferences()),+ ("null_properties", {"groups": [{"properties": None}]}, FlagReferences()),+ ("fixture_groups", {"groups": V1_GROUPS}, FlagReferences(cohort_ids=(42,), flag_ids=(7,))),+ (+ "first_seen_order_without_duplicates",+ {+ "groups": [+ {"properties": [_cohort(5), _flag("9"), _cohort("3")]},+ {"properties": [_cohort(5), _flag(9), _flag("2")]},+ ]+ },+ FlagReferences(cohort_ids=(5, 3), flag_ids=(9, 2)),+ ),+ (+ "v2_rule_targeting",+ _v2_document([_cohort(5), {"key": "email", "type": "person", "value": "a"}], [_flag("9"), _cohort(3)]),+ FlagReferences(cohort_ids=(5, 3), flag_ids=(9,)),+ ),+ ]+ )+ def test_reads_identities_from_either_format(self, _name: str, document: Any, expected: FlagReferences) -> None:+ assert references(decode_config(document)) == expected++ @parameterized.expand(+ [+ ("v1", {"groups": [{"properties": [_cohort(5), _flag("9")]}]}),+ ("v2", _v2_document([_cohort(5), _flag("9")])),+ ]+ )+ def test_returns_identities_not_the_stored_dicts(self, _name: str, document: dict[str, Any]) -> None:+ result = references(decode_config(document))++ properties = (+ document["groups"][0]["properties"]+ if "groups" in document+ else document["rules"][0]["targeting"]["properties"]+ )+ properties[0]["value"] = 6+ properties[1]["key"] = "10"++ assert result == FlagReferences(cohort_ids=(5,), flag_ids=(9,))++ @parameterized.expand(+ [+ (f"{version}_{name}", document)+ for name, invalid in (("string", "not-an-id"), ("null", None), ("object", {"id": 1}))+ for version, document in (+ ("v1", {"groups": [{"properties": [_cohort(invalid), _flag(invalid), _cohort(5), _flag("9")]}]}),+ ("v2", _v2_document([_cohort(invalid), _flag(invalid), _cohort(5), _flag("9")])),+ )+ ]+ )+ def test_invalid_ids_are_skipped_or_raised_per_reference_kind(self, _name: str, document: dict[str, Any]) -> None:+ config = decode_config(document)++ assert references(config) == FlagReferences(cohort_ids=(5,), flag_ids=(9,))+ with pytest.raises((TypeError, ValueError)):+ references(config, invalid_cohort_ids="raise")+ with pytest.raises((TypeError, ValueError)):+ references(config, invalid_flag_ids="raise")++ @parameterized.expand(+ [+ ("strict_cohorts", [_cohort(5), _flag("a-flag-key")], "raise", "skip", FlagReferences(cohort_ids=(5,))),+ ("strict_flags", [_cohort("not-an-id"), _flag("9")], "skip", "raise", FlagReferences(flag_ids=(9,))),+ ]+ )+ def test_a_strict_kind_ignores_invalid_ids_of_the_other_kind(+ self,+ _name: str,+ properties: list[dict[str, Any]],+ invalid_cohort_ids: InvalidIds,+ invalid_flag_ids: InvalidIds,+ expected: FlagReferences,+ ) -> None:+ config = decode_config({"groups": [{"properties": properties}]})++ result = references(config, invalid_cohort_ids=invalid_cohort_ids, invalid_flag_ids=invalid_flag_ids)++ assert result == expected++ @parameterized.expand(+ [+ ("group_not_an_object", {"groups": ["junk"]}, AttributeError),+ ("property_not_an_object", {"groups": [{"properties": ["junk"]}]}, AttributeError),+ ("groups_not_a_list", {"groups": 5}, TypeError),+ ]+ )+ def test_malformed_v1_structure_raises(self, _name: str, document: dict[str, Any], error: type[Exception]) -> None:+ with pytest.raises(error):+ references(decode_config(document))++ @parameterized.expand([(name, document) for name, document in UNSUPPORTED_DOCUMENTS if name != "v2_document"])+ def test_rejects_documents_in_no_readable_format(self, _name: str, document: dict[str, Any]) -> None:+ with pytest.raises(ConfigFormatError) as exc_info:+ references(decode_config(document))+ assert exc_info.value.config_format.kind == "unsupported"diff --git a/products/feature_flags/backend/test/test_flag_version_sync.py b/products/feature_flags/backend/test/test_flag_version_sync.pyindex 254e96fbcfd0..fb534cbaf453 100644--- a/products/feature_flags/backend/test/test_flag_version_sync.py+++ b/products/feature_flags/backend/test/test_flag_version_sync.py@@ -44,8 +44,8 @@ def _flag_dependency_filters(dependency_flag_id: int | str) -> dict:}-def _other_format_filters(referenced: dict) -> dict:- # A v2 document whose predicate matches the receivers' jsonb prefilters, so it reaches the v1 reads.+def _rules_filters(referenced: dict) -> dict:+ # Cohort and flag targeting is written past the validator, which does not admit it yet.return {"version": 2,"return_type": "boolean",@@ -147,25 +147,37 @@ class TestFlagVersionSync(BaseTest):assert entry.user is Noneassert entry.is_system is True- def test_a_flag_in_another_config_format_is_skipped_by_the_cohort_walk(self):+ def test_cohort_walk_reads_rule_targeting_and_skips_unreadable_formats(self):edited = self._create_cohort("edited", _person_filters("[email protected]"))+ parent = self._create_cohort("parent", _cohort_filters(edited.pk))flag_direct = self._create_flag("direct", edited.pk)- other_format = FeatureFlag.objects.create(+ rules_direct = FeatureFlag.objects.create(+ team=self.team,+ key="rules-direct",+ created_by=self.user,+ filters=_rules_filters({"key": "id", "type": "cohort", "value": edited.pk}),+ )+ rules_nested = FeatureFlag.objects.create(team=self.team,- key="other-format",+ key="rules-nested",created_by=self.user,- filters=_other_format_filters({"key": "id", "type": "cohort", "value": edited.pk}),+ filters=_rules_filters({"key": "id", "type": "cohort", "value": parent.pk}),+ )+ unreadable = FeatureFlag.objects.create(+ team=self.team,+ key="unreadable",+ created_by=self.user,+ filters={"version": 3, "groups": [{"properties": [{"key": "id", "type": "cohort", "value": edited.pk}]}]},)with capture_logs() as logs:edited.filters = _person_filters("[email protected]")edited.save()- flag_direct.refresh_from_db()- other_format.refresh_from_db()- assert flag_direct.version == 2- assert other_format.version == 1- assert _updated_entries(other_format) == []+ for flag, version in ((flag_direct, 2), (rules_direct, 2), (rules_nested, 2), (unreadable, 1)):+ flag.refresh_from_db()+ assert flag.version == version, flag.key+ assert _updated_entries(unreadable) == []assert [log for log in logs if log["event"] == "flag_version_sync_cohort_expansion_failed"] == []def test_flag_history_entry_attributes_the_cohort_editor(self):@@ -316,25 +328,25 @@ class TestFlagDependencyVersionSync(BaseTest):transitive = self._create_flag("transitive", _flag_dependency_filters(dependent.pk))return base, dependent, transitive- def test_a_flag_in_another_config_format_is_skipped_by_the_dependency_walk(self):+ def test_dependency_walk_reads_rule_targeting_and_skips_unreadable_formats(self):base, dependent, _transitive = self._create_chain()- other_format = self._create_flag(- "other-format",- _other_format_filters(- {"key": str(base.pk), "type": "flag", "operator": "flag_evaluates_to", "value": True}- ),+ dependency = {"key": str(base.pk), "type": "flag", "operator": "flag_evaluates_to", "value": True}+ rules_dependent = self._create_flag("rules-dependent", _rules_filters(dependency))+ rules_transitive = self._create_flag(+ "rules-transitive", _rules_filters(dependency | {"key": str(rules_dependent.pk)}))+ unreadable = self._create_flag("unreadable", {"version": 3, "groups": [{"properties": [dependency]}]})- with capture_logs() as logs:- base.filters = {"groups": [{"properties": [], "rollout_percentage": 25}]}- base.save()+ base.filters = {"groups": [{"properties": [], "rollout_percentage": 25}]}+ base.save()- dependent.refresh_from_db()- other_format.refresh_from_db()- assert dependent.version == 2- assert other_format.version == 1- assert _updated_entries(other_format) == []- assert [log for log in logs if log["event"] == "flag_version_sync_dependency_parse_failed"] == []+ for flag, version in ((dependent, 2), (rules_dependent, 2), (rules_transitive, 2), (unreadable, 1)):+ flag.refresh_from_db()+ assert flag.version == version, flag.key+ (entry,) = _updated_entries(rules_transitive)+ assert entry.detail is not None+ assert entry.detail["trigger"]["payload"] == {"flag_id": base.pk, "flag_key": "base"}+ assert _updated_entries(unreadable) == []def test_flag_definition_change_bumps_versions_of_flags_depending_on_it(self):base, dependent, transitive = self._create_chain()@@ -471,14 +483,20 @@ class TestFlagDependencyVersionSync(BaseTest):transitions.append((change["before"], change["after"]))assert sorted(transitions) == [(1, 2), (2, 3)]- def test_sibling_flag_with_non_dict_filters_does_not_block_save_or_bump(self):+ @parameterized.expand(+ [+ ("non_dict_filters", [{"properties": []}, {"type": "flag"}]),+ ("groups_not_a_list", {"groups": {"type": "flag"}}),+ ("properties_not_a_list", {"groups": [{"properties": {"dependency": {"type": "flag", "key": "1"}}}]}),+ ("properties_not_iterable", {"groups": [{"properties": 5, "note": {"type": "flag"}}]}),+ ]+ )+ def test_sibling_flag_with_malformed_filters_does_not_block_save_or_bump(self, _name, filters):base, dependent, _ = self._create_chain()- # filters is a JSONField with no shape validation, so a row can hold a non-dict;- # FeatureFlag.conditions calls .get() on it and raises. That must not abort the- # save being made to an unrelated flag. The malformed-key case in the chain test- # can't reach this: a bad key inside a well-shaped dict is caught further in.+ # filters is a JSONField with no shape validation, so a row can hold any JSON the+ # dependency prefilter matches.broken = self._create_flag("broken", _flag_dependency_filters(base.pk))- FeatureFlag.objects.filter(pk=broken.pk).update(filters=[{"properties": []}, {"type": "flag"}])+ FeatureFlag.objects.filter(pk=broken.pk).update(filters=filters)base.filters = {"groups": [{"properties": [], "rollout_percentage": 25}]}base.save()diff --git a/products/feature_flags/backend/test/test_flags_cache.py b/products/feature_flags/backend/test/test_flags_cache.pyindex 17ecf0d7138a..6beb47486373 100644--- a/products/feature_flags/backend/test/test_flags_cache.py+++ b/products/feature_flags/backend/test/test_flags_cache.py@@ -708,6 +708,42 @@ class TestOmitUnsupportedFlags(BaseTest):with override_settings(MAX_FEATURE_FLAG_FILTER_SIZE_BYTES=32):assert _get_feature_flags_for_service(self.team)["flags"] == []+ def test_rule_targeting_references_reach_the_builders(self):+ cohort = Cohort.objects.create(+ team=self.team,+ name="targeted",+ filters={"properties": {"type": "OR", "values": [{"key": "email", "value": "a", "type": "person"}]}},+ )+ unsupported = FeatureFlag.objects.create(+ team=self.team, key="unsupported", created_by=self.user, filters={"version": 3}+ )+ rows = {+ "rules-cohort": _rules_filters({"key": "id", "type": "cohort", "value": cohort.id}),+ "rules-dependent": _rules_filters(+ {"key": str(unsupported.id), "type": "flag", "operator": "flag_evaluates_to", "value": True}+ ),+ }+ created: dict[str, FeatureFlag] = {}+ for key, filters in rows.items():+ created[key] = FeatureFlag.objects.create(team=self.team, key=key, created_by=self.user, filters={})+ FeatureFlag.objects.filter(id=created[key].id).update(filters=filters)++ # Admitted here because the validator does not admit cohort or flag targeting yet.+ with (+ patch("products.feature_flags.backend.flags_cache._validates_v2", return_value=True),+ capture_logs() as log_events,+ ):+ single = _get_feature_flags_for_service(self.team)+ batch = _get_feature_flags_for_teams_batch([self.team])[self.team.id]++ for payload in (single, batch):+ assert [f["key"] for f in payload["flags"]] == ["rules-cohort"]+ assert [c["id"] for c in payload["cohorts"]] == [cohort.id]+ # Omitted as a dependent, which only a read of its flag reference can decide.+ expected = {"unsupported_flag_ids": [unsupported.id], "dependent_flag_ids": [created["rules-dependent"].id]}+ omissions = [e for e in log_events if e["event"] == "Omitted flags the service cache cannot carry"]+ assert [{k: e[k] for k in expected} for e in omissions] == [expected, expected]+def test_unsupported_flag_in_one_team_leaves_other_teams_in_the_batch_intact(self):other_team = Team.objects.create(organization=self.organization, name="other")FeatureFlag.objects.create(@@ -3759,6 +3795,23 @@ def _make_flag(id: int, key: str, deps: list[int] | None = None, active: bool =}+def _rules_filters(*properties: dict) -> dict:+ # Cohort and flag targeting is written past the validator, which does not admit it yet.+ return {+ "version": 2,+ "return_type": "boolean",+ "default_value": False,+ "rules": [+ {+ "id": "11111111-1111-4111-8111-111111111111",+ "rule_type": "targeted_release",+ "targeting": {"properties": list(properties)},+ "value": True,+ }+ ],+ }++class TestExtractDirectDependencyIds:@parameterized.expand([@@ -3772,6 +3825,17 @@ class TestExtractDirectDependencyIds:{**_make_flag(1, "flag_a", active=False), "filters": {"version": 2, **_dependency_filters(2)}},set(),),+ (+ "rule_targeting",+ {+ **_make_flag(1, "flag_a"),+ "filters": _rules_filters(+ {"type": "cohort", "key": "id", "value": 9},+ {"type": "flag", "key": "2", "value": True, "operator": "flag_evaluates_to"},+ ),+ },+ {2},+ ),("non_flag_properties_ignored",{@@ -4272,6 +4336,18 @@ class TestExtractCohortIdsFromFlagFilters(BaseTest):]assert _extract_cohort_ids_from_flag_filters(flags_data) == set()+ def test_extracts_cohort_ids_from_rule_targeting(self):+ flags_data = [+ {+ "active": True,+ "filters": _rules_filters(+ {"type": "cohort", "key": "id", "value": 42},+ {"type": "flag", "key": "7", "value": True, "operator": "flag_evaluates_to"},+ ),+ }+ ]+ assert _extract_cohort_ids_from_flag_filters(flags_data) == {42}+def test_handles_string_cohort_value(self):flags_data = [{