Skip to content

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

fix(flags): exclude unsupported flags and dependents from legacy definitions (#104948)

Anders72fb7e553aa9
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.md
index ae9ff843e1cc..20c37e26eea7 100644
--- a/docs/internal/feature-flags/hypercache-system.md
+++ b/docs/internal/feature-flags/hypercache-system.md
@@ -180,8 +180,27 @@ 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.
+The builder classifies stored filters before reading cohort references, transforming dependencies, or serializing flags.
+Only absent or numeric version 1 configurations enter the legacy feed.
+Classification includes inactive and deleted targets before existing lifecycle filtering omits them.
+Unsupported formats are expected exclusions; malformed flags increment `posthog_flag_definitions_processing_error`.
+A malformed flag or reachable cohort removes the affected flag and its transitive dependents while independent flags remain available.
+Direct and nested cohort references must be integers or strings that parse as integers; booleans, floats, and unparseable values are rejected before serialization.
+Legacy cohort property dictionaries can use `type` or `values` as property names; a grouped expression requires both keys.
+Dependencies on excluded targets are omitted even when the condition expects false.
+An inconclusive dependency does not always force an SDK to use server evaluation: a later condition can return a different variant.
+For example, if the first condition selects `blue` when the target is true and the next always selects `green`, omitting only the target can make the SDK return `green` instead of `blue`.
+Removing the dependent prevents that local answer, at the cost of sending the whole flag to server evaluation or the caller's local-only default.
+Supported v1 missing targets, inactive targets, cycles, cohort scoping, mappings, and metadata retain their existing behavior.
+The internal `flags.json` producer keeps its separate rejection and inactive-filter behavior.
+
+Readers serve cached bodies and answer 304s without re-checking them, so the exclusion relies on deployment order.
+For well-formed v1 data with string dependency references, this builder preserves the older builder's definitions.
+Integer dependency references now resolve to flag keys and populated dependency chains.
+Malformed flags and reachable cohorts now exclude affected flags and their transitive dependents.
+These cases can change cached bodies and ETags even before an unsupported configuration exists, including during a rollback.
+Deploy this builder to every region before storing an unsupported configuration, and never deploy an older builder after one exists.
+Tightening these exclusion rules later requires rebuilding existing cache entries.
### Cache invalidation
diff --git a/products/feature_flags/backend/legacy_definitions.py b/products/feature_flags/backend/legacy_definitions.py
new file mode 100644
index 000000000000..b5fc83f44fe7
--- /dev/null
+++ b/products/feature_flags/backend/legacy_definitions.py
@@ -0,0 +1,112 @@
+from collections import defaultdict, deque
+from collections.abc import Mapping
+from typing import Any
+
+from rest_framework.exceptions import ValidationError
+
+from posthog.models.property import Property
+
+from products.feature_flags.backend.facade.config import ConfigFormatError, detect_config_format
+from products.feature_flags.backend.facade.references import flag_dependency_properties
+
+
+def _parse_cohort_reference(value: object) -> int:
+ if isinstance(value, bool) or not isinstance(value, str | int):
+ raise ValueError("Invalid legacy cohort reference")
+ return int(value)
+
+
+def validate_legacy_filters(filters: object) -> None:
+ if filters is not None and not isinstance(filters, Mapping):
+ raise ValueError("Invalid legacy flag filters")
+ config_format = detect_config_format(filters)
+ if config_format.kind != "v1":
+ raise ConfigFormatError(config_format)
+ if filters is None:
+ return
+ groups = filters.get("groups")
+ if groups is not None:
+ if not isinstance(groups, list):
+ raise ValueError("Invalid legacy flag groups")
+ for group in groups:
+ if not isinstance(group, dict):
+ raise ValueError("Invalid legacy flag group")
+ properties = group.get("properties")
+ if properties is not None:
+ if not isinstance(properties, list) or any(not isinstance(prop, dict) for prop in properties):
+ raise ValueError("Invalid legacy flag properties")
+ for prop in properties:
+ if prop.get("type") == "flag":
+ key = prop.get("key")
+ if isinstance(key, bool) or not isinstance(key, str | int):
+ raise ValueError("Invalid legacy flag dependency")
+ elif prop.get("type") == "cohort":
+ _parse_cohort_reference(prop.get("value"))
+ for field in ("payloads", "holdout"):
+ if filters.get(field) is not None and not isinstance(filters[field], dict):
+ raise ValueError("Invalid legacy flag configuration")
+ multivariate = filters.get("multivariate")
+ if multivariate is not None:
+ if not isinstance(multivariate, dict):
+ raise ValueError("Invalid legacy flag variants")
+ variants = multivariate.get("variants")
+ if variants is not None and (
+ not isinstance(variants, list) or any(not isinstance(variant, dict) for variant in variants)
+ ):
+ raise ValueError("Invalid legacy flag variants")
+
+
+def drop_legacy_dependents(flags: list[dict[str, Any]], excluded: Mapping[str, str]) -> list[dict[str, Any]]:
+ """Drop flags that depend, directly or transitively, on an excluded flag, without modifying the input.
+
+ ``excluded`` maps each excluded flag's ID to its key. The ID lookup also covers these
+ flags, which are already left out of ``flags``, so a dependency written as an ID
+ resolves to that flag's key before it is treated as a key. A flag whose key is "7"
+ is then not mistaken for the flag with ID 7.
+ """
+ if not excluded:
+ return flags
+ id_to_key = {**excluded, **{str(flag["id"]): flag["key"] for flag in flags}}
+ dependents: dict[str, set[int]] = defaultdict(set)
+ for index, flag in enumerate(flags):
+ for prop in flag_dependency_properties(flag["filters"]):
+ reference = str(prop["key"])
+ dependents[id_to_key.get(reference, reference)].add(index)
+ dropped: set[int] = set()
+ queue = deque(excluded.values())
+ while queue:
+ for index in dependents.get(queue.popleft(), ()):
+ if index not in dropped:
+ dropped.add(index)
+ queue.append(flags[index]["key"])
+ return [flag for index, flag in enumerate(flags) if index not in dropped]
+
+
+def cohort_references(properties: object) -> set[str]:
+ references: set[str] = set()
+ pending = [properties]
+ while pending:
+ node = pending.pop()
+ if not isinstance(node, dict):
+ raise ValueError("Invalid legacy cohort properties")
+ if not node:
+ continue
+ if "values" in node:
+ values = node["values"]
+ group_type = node.get("type")
+ if (
+ not isinstance(values, list)
+ or not isinstance(group_type, str)
+ or group_type.upper() not in ("AND", "OR")
+ ):
+ raise ValueError("Invalid legacy cohort group")
+ pending.extend(values)
+ continue
+ try:
+ # Filter silently drops properties that fail construction.
+ Property(**node)
+ except (TypeError, ValueError, ValidationError) as error:
+ raise ValueError("Invalid legacy cohort property") from error
+ if node.get("type") == "cohort":
+ references.add(str(_parse_cohort_reference(node.get("value"))))
+ return references
diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.py
index 128af11cc218..35efad8c1cb8 100644
--- a/products/feature_flags/backend/local_evaluation.py
+++ b/products/feature_flags/backend/local_evaluation.py
@@ -28,10 +28,13 @@ from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
import structlog
+from celery.exceptions import SoftTimeLimitExceeded
from posthoganalytics import capture_exception
from prometheus_client import Counter
+from rest_framework.exceptions import ValidationError
from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS
+from posthog.dataclasses import frozen
from posthog.models.group_type_mapping import (
GROUP_TYPES_STALE_CACHE_KEY_PREFIX,
GroupTypesUnavailable,
@@ -47,10 +50,9 @@ from posthog.storage.hypercache import (
emit_cache_sync_metrics,
)
from posthog.storage.hypercache_manager import HyperCacheManagementConfig
-from posthog.utils import capture_exception_throttled, get_safe_cache
+from posthog.utils import capture_exception_throttled, get_safe_cache, safe_int
-from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty, is_cohort_recalculation_only_save
-from products.cohorts.backend.models.util import get_nested_cohort_ids
+from products.cohorts.backend.models.cohort import Cohort, is_cohort_recalculation_only_save
from products.experiments.backend.models.experiment import Experiment, live_experiment_exists
from products.feature_flags.backend.cache_keys import EU_CROSS_REGION_MIRROR_CACHE_KEY
from products.feature_flags.backend.facade.config import ConfigFormatError
@@ -60,6 +62,11 @@ from products.feature_flags.backend.flags_cache import (
get_team_ids_with_recently_updated_flags,
get_teams_with_flags_queryset,
)
+from products.feature_flags.backend.legacy_definitions import (
+ cohort_references,
+ drop_legacy_dependents,
+ validate_legacy_filters,
+)
from products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.feature_flags.backend.models.team_feature_flags_config import (
@@ -97,7 +104,7 @@ def _resolve_flag_dependency_key(flag_prop: FlagProperty, flag_id_to_key: dict[s
Convert flag property reference to flag key.
Handles both flag IDs and flag keys as references.
"""
- flag_reference = flag_prop.get("key", "")
+ flag_reference = str(flag_prop.get("key", ""))
return flag_id_to_key.get(flag_reference, flag_reference)
@@ -132,12 +139,8 @@ class _DependencyChainBuilder:
self.memo[flag_key] = []
return []
- # Build the chain using DFS
- visited: set[str] = set()
- temp_visited: set[str] = set()
- chain: list[str] = []
-
- if not self._dfs(flag_key, visited, temp_visited, chain):
+ chain = self._dfs(flag_key)
+ if chain is None:
logger.warning(
"Flag cannot be evaluated due to circular dependencies or missing dependencies",
extra={"flag_key": flag_key},
@@ -161,34 +164,42 @@ class _DependencyChainBuilder:
return True
return False
- def _dfs(self, current_key: str, visited: set[str], temp_visited: set[str], chain: list[str]) -> bool:
- """
- Depth-first search to build dependency chain with cycle detection.
-
- Returns False if a cycle or missing dependency is detected, True otherwise.
- """
- if current_key in temp_visited:
- logger.warning(
- "Circular dependency detected in feature flags",
- extra={"circular_at": current_key},
- )
- return False
-
- if current_key in visited:
- return True
-
- temp_visited.add(current_key)
-
- if not self._validate_flag_exists(current_key):
- return False
-
- if not self._validate_all_dependencies_for_flag(current_key, visited, temp_visited, chain):
- return False
-
- temp_visited.remove(current_key)
- visited.add(current_key)
- chain.append(current_key)
- return True
+ def _dfs(self, root_key: str) -> list[str] | None:
+ """Return the evaluation order for ``root_key``, or None for a cycle or missing dependency."""
+ visited: set[str] = set()
+ temp_visited: set[str] = set()
+ chain: list[str] = []
+ # Iterative DFS keeps a deep dependency chain from exhausting Python's call stack.
+ pending = [(root_key, False)]
+ while pending:
+ key, leaving = pending.pop()
+ if leaving:
+ temp_visited.remove(key)
+ visited.add(key)
+ chain.append(key)
+ continue
+ if key in temp_visited:
+ logger.warning("Circular dependency detected in feature flags", extra={"circular_at": key})
+ return None
+ if key in visited:
+ continue
+ if not self._validate_flag_exists(key):
+ return None
+ temp_visited.add(key)
+ pending.append((key, True))
+ dependencies = flag_dependency_properties(self.all_flags[key].get("filters", {}))
+ for prop in reversed(dependencies):
+ dependency = prop["key"]
+ if dependency == key:
+ continue
+ if dependency not in self.all_flags:
+ logger.warning(
+ "Flag dependency references non-existent flag",
+ extra={"flag": key, "missing_dependency": dependency},
+ )
+ return None
+ pending.append((dependency, False))
+ return chain
def _validate_flag_exists(self, flag_key: str) -> bool:
"""Validate that a flag exists in the flags collection."""
@@ -200,40 +211,6 @@ class _DependencyChainBuilder:
return False
return True
- def _validate_all_dependencies_for_flag(
- self, current_key: str, visited: set[str], temp_visited: set[str], chain: list[str]
- ) -> bool:
- """Validates all dependencies of the current flag."""
- current_flag = self.all_flags.get(current_key)
- if not current_flag:
- return False
-
- filters = current_flag.get("filters", {})
- for flag_prop in flag_dependency_properties(filters):
- dep_flag_key = flag_prop["key"] # Already normalized to key
- if dep_flag_key != current_key: # Avoid self-dependency
- if not self._validate_dependency(dep_flag_key, current_key, visited, temp_visited, chain):
- return False
- return True
-
- def _validate_dependency(
- self, dep_flag_key: str, current_key: str, visited: set[str], temp_visited: set[str], chain: list[str]
- ) -> bool:
- """Validates the dependency exists and recursively checks for cycles"""
- # Validate the dependency exists
- if dep_flag_key not in self.all_flags:
- logger.warning(
- "Flag dependency references non-existent flag",
- extra={"flag": current_key, "missing_dependency": dep_flag_key},
- )
- return False
-
- # Recursively process the dependency
- if not self._dfs(dep_flag_key, visited, temp_visited, chain):
- return False
-
- return True
-
def _normalize_and_collect_dependency_target_keys(
flags_data: list[dict[str, Any]], flag_id_to_key: dict[str, str]
@@ -333,18 +310,9 @@ def _apply_flag_dependency_transformation(
Returns:
New response data dictionary with transformed flags
"""
- try:
- flags_list = cast(list[dict[str, Any]], response_data["flags"])
- transformed_flags = _transform_flag_property_dependencies(flags_list, flag_id_to_key)
-
- logger.debug("Flag dependency transformation completed")
- return {**response_data, "flags": transformed_flags}
- except Exception as e:
- logger.warning(
- "Flag dependency transformation failed, proceeding without transformation",
- extra={"error": str(e)},
- )
- return response_data
+ flags_list = cast(list[dict[str, Any]], response_data["flags"])
+ transformed_flags = _transform_flag_property_dependencies(flags_list, flag_id_to_key)
+ return {**response_data, "flags": transformed_flags}
DATABASE_FOR_LOCAL_EVALUATION = (
@@ -540,25 +508,87 @@ def _local_eval_response(
def _get_flags_response_for_local_evaluation(team: Team) -> dict[str, Any]:
"""Build the local-evaluation response for a single team."""
results = _get_flags_response_for_local_evaluation_batch([team])
- return results.get(
- team.id,
- _local_eval_response(
- flags=[],
- group_type_mapping={},
- cohorts={},
- minimal_flag_called_events=False,
- property_matching_version=PropertyMatchingVersion.LEGACY,
- ),
- )
+ if team.id not in results:
+ raise RuntimeError(f"Flag definitions build failed for team {team.id}")
+ return results[team.id]
+
+
+# Errors that mean a stored flag or cohort definition is malformed.
+_MALFORMED_DEFINITION_ERRORS = (AttributeError, TypeError, ValueError, KeyError, RecursionError, ValidationError)
+
+
+def _is_supported_legacy_flag(flag: FeatureFlag) -> bool:
+ try:
+ validate_legacy_filters(flag.filters)
+ return True
+ except ConfigFormatError:
+ return False
+ except (TypeError, ValueError):
+ logger.warning(
+ "Malformed feature flag omitted from legacy definitions",
+ extra={"team_id": flag.team_id, "flag_id": flag.pk},
+ exc_info=True,
+ )
+ FLAG_PROCESSING_ERROR_COUNTER.inc()
+ return False
+
+
+@frozen
+class _LegacyCohortDefinition:
+ properties: dict[str, Any]
+ dependencies: set[int]
+
+
+def _serialize_legacy_cohort(cohort: Cohort) -> _LegacyCohortDefinition:
+ """Validate raw properties because Filter can turn untyped groups into empty
+ AND groups and drop unparseable properties, hiding malformed cohort data.
+
+ Keep the serialized properties with their references so all flags sharing a
+ cohort use the same validated definition without repeating model conversion.
+ """
+ if cohort.filters is not None and not isinstance(cohort.filters, dict):
+ raise ValueError("Invalid legacy cohort filters")
+ references = None
+ if cohort.filters and cohort.filters.get("properties") is not None:
+ properties = cohort.filters["properties"]
+ if isinstance(properties, list):
+ properties = {"type": "AND", "values": properties}
+ # Filter keeps every entry of a flat {property: value} dictionary, so its serialized form can be validated.
+ is_flat_legacy_dict = isinstance(properties, dict) and not ("type" in properties and "values" in properties)
+ if not is_flat_legacy_dict:
+ references = cohort_references(properties)
+ serialized = cohort.properties.to_dict()
+ if references is None:
+ references = cohort_references(serialized)
+ return _LegacyCohortDefinition(properties=serialized, dependencies={int(reference) for reference in references})
+
+
+def _flag_cohort_ids(
+ filters: dict[str, Any],
+ project_cohorts: dict[int, Cohort],
+ definitions: dict[int, _LegacyCohortDefinition],
+ malformed: set[int],
+) -> set[int]:
+ cohort_ids: set[int] = set()
+ pending = list(referenced_cohort_ids(filters))
+ while pending:
+ cid = pending.pop()
+ if cid not in project_cohorts or cid in cohort_ids:
+ continue
+ if cid in malformed:
+ raise ValueError("Malformed cohort in legacy flag definition")
+ cohort_ids.add(cid)
+ pending.extend(definitions[cid].dependencies)
+ return cohort_ids
def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[int, dict[str, Any]]:
"""
Build local-evaluation responses for multiple teams using bulk data loading.
- Loads survey flag IDs, flags, cohorts, and group type mappings in bulk (one
- query each regardless of team count), then iterates the materialized flag
- list with itertools.groupby to process one team at a time.
+ Loads survey flag IDs, eligible flags, excluded flag references, cohorts, and
+ group type mappings in bulk, then processes one team's flags at a time. A team
+ whose own build fails is left out, so callers keep its previous cache entry.
"""
from products.feature_flags.backend.api.feature_flag import EvaluationFeatureFlagSerializer
@@ -593,14 +623,16 @@ def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[in
):
survey_flag_ids.update(fid for fid in row if fid is not None)
- # Load all eligible flags once, ordered for groupby and ETag stability.
+ flag_queryset = FeatureFlag.objects_including_soft_deleted.db_manager(DATABASE_FOR_LOCAL_EVALUATION).filter(
+ team_id__in=team_ids
+ )
+ ineligible = Q(deleted=True) | Q(has_encrypted_payloads=True) | Q(pk__in=survey_flag_ids)
+ excluded_by_team: dict[int, dict[str, str]] = defaultdict(dict)
+ # Preserve ordering for groupby and ETag stability.
# Materializing allows two passes: first to extract cohort IDs, then to
# serialize — one DB round trip instead of two.
all_flags = list(
- FeatureFlag.objects.db_manager(DATABASE_FOR_LOCAL_EVALUATION)
- .filter(team_id__in=team_ids)
- .exclude(has_encrypted_payloads=True)
- .exclude(id__in=survey_flag_ids)
+ flag_queryset.exclude(ineligible)
.annotate(
evaluation_tag_names_agg=ArrayAgg(
"flag_evaluation_contexts__evaluation_context__name",
@@ -613,15 +645,33 @@ def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[in
)
direct_cohort_ids: set[int] = set()
+ eligible_flags: list[FeatureFlag] = []
+ dependency_references: set[str] = set()
for flag in all_flags:
+ if not _is_supported_legacy_flag(flag):
+ excluded_by_team[flag.team_id][str(flag.pk)] = flag.key
+ continue
flag._evaluation_tag_names = flag.evaluation_tag_names_agg or []
flag._has_experiment = flag.has_experiment_agg
- 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
+ direct_cohort_ids.update(referenced_cohort_ids(flag.filters))
+ dependency_references.update(str(prop["key"]) for prop in flag_dependency_properties(flag.filters))
+ eligible_flags.append(flag)
+
+ if dependency_references:
+ dependency_ids = {
+ flag_id for reference in dependency_references if (flag_id := safe_int(reference)) is not None
+ }
+ # Ineligible targets still exclude dependents when their format is unsupported.
+ # They need no model instances, evaluation contexts, or experiment annotations.
+ for flag_id, key, team_id, filters in (
+ flag_queryset.filter(ineligible)
+ .filter(Q(pk__in=dependency_ids) | Q(key__in=dependency_references))
+ .values_list("id", "key", "team_id", "filters")
+ ):
+ try:
+ validate_legacy_filters(filters)
+ except (ConfigFormatError, TypeError, ValueError):
+ excluded_by_team[team_id][str(flag_id)] = key
# Load only the referenced cohorts and resolve nested dependencies
# iteratively. Each iteration loads newly discovered nested cohort IDs
@@ -630,6 +680,8 @@ def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[in
ids_to_load = direct_cohort_ids.copy()
loaded_ids: set[int] = set()
+ malformed_cohort_ids: set[int] = set()
+ cohort_definitions: dict[int, _LegacyCohortDefinition] = {}
while ids_to_load:
newly_loaded: list[Cohort] = []
cohort_qs = (
@@ -649,7 +701,17 @@ def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[in
# Extract nested cohort references from newly loaded cohorts
nested_ids: set[int] = set()
for cohort in newly_loaded:
- nested_ids.update(get_nested_cohort_ids(cohort))
+ try:
+ definition = _serialize_legacy_cohort(cohort)
+ cohort_definitions[cohort.pk] = definition
+ nested_ids.update(definition.dependencies)
+ except _MALFORMED_DEFINITION_ERRORS:
+ logger.warning(
+ "Malformed cohort omitted from legacy definitions",
+ extra={"team_id": cohort.team_id, "cohort_id": cohort.pk},
+ exc_info=True,
+ )
+ malformed_cohort_ids.add(cohort.pk)
ids_to_load = nested_ids - loaded_ids
@@ -660,75 +722,63 @@ def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[in
gtm_by_project[pid][str(m["group_type_index"])] = m["group_type"]
results: dict[int, dict[str, Any]] = {}
+ failed_team_ids: set[int] = set()
- for tid, team_flags_iter in groupby(all_flags, key=lambda f: f.team_id):
+ for tid, team_flags_iter in groupby(eligible_flags, key=lambda f: f.team_id):
team = team_by_id.get(tid)
if team is None:
continue
- project_cohorts = cohorts_by_project.get(team.project_id, {})
- # Build a seen_cohorts_cache compatible with FeatureFlag.get_cohort_ids
- seen_cohorts_cache: dict[int, CohortOrEmpty] = dict(project_cohorts)
-
- flags_data: list[dict[str, Any]] = []
- cohorts: dict[str, Any] = {}
- flag_id_to_key: dict[str, str] = {}
-
- for feature_flag in team_flags_iter:
- try:
- filters = feature_flag.get_filters()
-
- # 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 referenced_cohort_ids(filters):
- if cid not in seen_cohorts_cache:
- seen_cohorts_cache[cid] = ""
-
- cohort_ids = feature_flag.get_cohort_ids(
- using_database=DATABASE_FOR_LOCAL_EVALUATION,
- seen_cohorts_cache=seen_cohorts_cache,
- )
-
- flags_data.append(EvaluationFeatureFlagSerializer(feature_flag, context={}).data)
-
- for cohort_id in cohort_ids:
- str_id = str(cohort_id)
- if str_id not in cohorts:
- cohort = project_cohorts.get(cohort_id)
- if cohort is not None and not cohort.is_static:
- try:
- cohorts[str_id] = cohort.properties.to_dict()
- except Exception:
- logger.error(
- "Error processing cohort properties",
- extra={"cohort_id": cohort_id},
- exc_info=True,
- )
-
+ try:
+ project_cohorts = cohorts_by_project.get(team.project_id, {})
+
+ flags_data: list[dict[str, Any]] = []
+ flag_cohort_ids: dict[str, set[int]] = {}
+ flag_id_to_key: dict[str, str] = {}
+
+ for feature_flag in team_flags_iter:
+ try:
+ cohort_ids = _flag_cohort_ids(
+ feature_flag.get_filters(), project_cohorts, cohort_definitions, malformed_cohort_ids
+ )
+ flags_data.append(EvaluationFeatureFlagSerializer(feature_flag, context={}).data)
+ except _MALFORMED_DEFINITION_ERRORS:
+ excluded_by_team[tid][str(feature_flag.pk)] = feature_flag.key
+ logger.warning(
+ "Malformed feature flag omitted from legacy definitions",
+ extra={"team_id": tid, "flag_id": feature_flag.pk},
+ exc_info=True,
+ )
+ FLAG_PROCESSING_ERROR_COUNTER.inc()
+ continue
+ flag_cohort_ids[feature_flag.key] = cohort_ids
flag_id_to_key[str(feature_flag.id)] = feature_flag.key
- except Exception:
- logger.error("Error processing feature flag", extra={"flag_id": feature_flag.pk}, exc_info=True)
- FLAG_PROCESSING_ERROR_COUNTER.inc()
- continue
-
- minimal_flag_called_events, property_matching_version = team_config_by_team_id.get(
- tid, (False, PropertyMatchingVersion.LEGACY)
- )
- response_data = _local_eval_response(
- flags=flags_data,
- group_type_mapping=gtm_by_project.get(team.project_id, {}),
- cohorts=cohorts,
- minimal_flag_called_events=minimal_flag_called_events,
- property_matching_version=property_matching_version,
- )
-
- results[tid] = _apply_flag_dependency_transformation(response_data, flag_id_to_key)
+ flags_data = drop_legacy_dependents(flags_data, excluded_by_team[tid])
+ minimal_flag_called_events, property_matching_version = team_config_by_team_id.get(
+ tid, (False, PropertyMatchingVersion.LEGACY)
+ )
+ response_data = _local_eval_response(
+ flags=flags_data,
+ group_type_mapping=gtm_by_project.get(team.project_id, {}),
+ cohorts={
+ str(cohort_id): cohort_definitions[cohort_id].properties
+ for flag in flags_data
+ for cohort_id in flag_cohort_ids[flag["key"]]
+ },
+ minimal_flag_called_events=minimal_flag_called_events,
+ property_matching_version=property_matching_version,
+ )
+ results[tid] = _apply_flag_dependency_transformation(response_data, flag_id_to_key)
+ except SoftTimeLimitExceeded:
+ raise
+ except Exception:
+ logger.exception("Flag definitions build failed for team", team_id=tid)
+ failed_team_ids.add(tid)
# Ensure every requested team has a result, even if it had no flags
for tid in team_ids:
- if tid not in results:
+ if tid not in results and tid not in failed_team_ids:
minimal_flag_called_events, property_matching_version = team_config_by_team_id.get(
tid, (False, PropertyMatchingVersion.LEGACY)
)
diff --git a/products/feature_flags/backend/rebuild_queue.py b/products/feature_flags/backend/rebuild_queue.py
index 6fdeddb0ac20..014dda6f1e0b 100644
--- a/products/feature_flags/backend/rebuild_queue.py
+++ b/products/feature_flags/backend/rebuild_queue.py
@@ -226,7 +226,8 @@ def _rebuild_batch(redis: redis_lib.Redis, team_ids: list[int]) -> dict[int, boo
results: dict[int, bool] = {}
for team_id in team_ids:
team = teams_by_id.get(team_id)
- if team is None:
+ # batch_load leaves out a team whose own build failed.
+ if team is None or team_id not in payloads:
results[team_id] = _record_result(redis, team_id, ok=False)
continue
payload = payloads[team_id]
diff --git a/products/feature_flags/backend/test/test_legacy_definitions.py b/products/feature_flags/backend/test/test_legacy_definitions.py
new file mode 100644
index 000000000000..6b5e89874d6a
--- /dev/null
+++ b/products/feature_flags/backend/test/test_legacy_definitions.py
@@ -0,0 +1,140 @@
+import copy
+from itertools import count
+from typing import Any
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.feature_flags.backend.legacy_definitions import (
+ cohort_references,
+ drop_legacy_dependents,
+ validate_legacy_filters,
+)
+from products.feature_flags.backend.local_evaluation import _apply_flag_dependency_transformation
+
+_ids = count(1000)
+
+
+def definition(key: str, filters: dict[str, Any] | None = None, flag_id: int | None = None) -> dict[str, Any]:
+ return {"id": next(_ids) if flag_id is None else flag_id, "key": key, "filters": filters or {}}
+
+
+def depends_on(key: str, reference: str | int, value: bool = False) -> dict[str, Any]:
+ return definition(key, {"groups": [{"properties": [{"type": "flag", "key": reference, "value": value}]}]})
+
+
+def feed(flags: list[dict[str, Any]]) -> dict[str, Any]:
+ return {"flags": flags, "cohorts": {}, "group_type_mapping": {}, "minimal_flag_called_events": True}
+
+
+class TestLegacyDefinitions(SimpleTestCase):
+ @parameterized.expand(
+ [(str(value), {"version": value, "groups": []}) for value in (2, 2.0, 3, "1", "2", True, False, None)]
+ + [
+ ("root_list", []),
+ ("root_string", ""),
+ ("root_number", 0),
+ ("groups", {"groups": {}}),
+ ("group", {"groups": [None]}),
+ ("properties", {"groups": [{"properties": [None]}]}),
+ ("payloads", {"payloads": []}),
+ ("holdout", {"holdout": "control"}),
+ ("multivariate", {"multivariate": []}),
+ ("variants", {"multivariate": {"variants": [None]}}),
+ ]
+ + [
+ (f"dependency_{key}", {"groups": [{"properties": [{"type": "flag", "key": key}]}]})
+ for key in (None, True, False, 7.0, [7], {"id": 7})
+ ]
+ + [
+ (f"cohort_{value}", {"groups": [{"properties": [{"type": "cohort", "key": "id", "value": value}]}]})
+ for value in (None, "not-an-id", "", "7.5", True, False, 7.5, 7.0, [7], {"id": 7})
+ ]
+ )
+ def test_rejects_unsupported_and_malformed_filters(self, _name: str, filters: Any) -> None:
+ with self.assertRaises(ValueError):
+ validate_legacy_filters(filters)
+
+ @parameterized.expand(
+ [
+ ("absent", {}),
+ ("null", None),
+ ("integer", {"version": 1}),
+ ("float", {"version": 1.0}),
+ ("null_groups", {"groups": None}),
+ ("null_properties", {"groups": [{"properties": None}]}),
+ ("integer_cohort", {"groups": [{"properties": [{"type": "cohort", "key": "id", "value": 7}]}]}),
+ ("string_cohort", {"groups": [{"properties": [{"type": "cohort", "key": "id", "value": "7"}]}]}),
+ ]
+ )
+ def test_accepts_supported_filters(self, _name: str, filters: Any) -> None:
+ validate_legacy_filters(filters)
+
+ @parameterized.expand([("7",), (7,), ("excluded",)])
+ def test_drops_transitive_dependents_of_excluded_flags(self, reference: str | int) -> None:
+ flags = [
+ definition("healthy"),
+ depends_on("dependent", reference),
+ depends_on("transitive", "dependent", value=True),
+ ]
+ before = copy.deepcopy(flags)
+ assert drop_legacy_dependents(flags, {"7": "excluded"}) == [flags[0]]
+ assert flags == before
+
+ def test_without_exclusions_returns_the_same_list(self) -> None:
+ flags = [definition("healthy"), depends_on("dependent", "missing")]
+ assert drop_legacy_dependents(flags, {}) is flags
+
+ @parameterized.expand([("numeric_excluded_key", True), ("named_excluded_key", False)])
+ def test_exclusions_resolve_id_collisions_without_removing_independent_flags(
+ self, _name: str, excluded_numeric_key: bool
+ ) -> None:
+ excluded_key = "7" if excluded_numeric_key else "unsupported"
+ healthy = definition("healthy" if excluded_numeric_key else "8", flag_id=7)
+ flags = [
+ healthy,
+ *(
+ depends_on(f"dependent-{type(reference).__name__}-{reference}", reference)
+ for reference in (7, "7", 8, "8")
+ ),
+ depends_on("transitive", "dependent-int-8", value=True),
+ ]
+ result = drop_legacy_dependents(flags, {"8": excluded_key})
+ assert [flag["key"] for flag in result] == [healthy["key"], "dependent-int-7", "dependent-str-7"]
+
+ def test_deep_cycle_keeps_independent_definition_and_finishes_transformation(self) -> None:
+ flags = [depends_on(str(index), str((index + 1) % 400)) for index in range(400)]
+ independent = definition("healthy")
+ result = _apply_flag_dependency_transformation(feed([*flags, independent]), {})
+ assert result["flags"][-1] == independent
+ assert all(
+ flag["filters"]["groups"][0]["properties"][0]["dependency_chain"] == [] for flag in result["flags"][:-1]
+ )
+
+ @parameterized.expand(
+ [
+ ({"values": [None]},),
+ ({"type": "AND", "values": [{"values": [{"type": "person", "key": "tier", "value": "example"}]}]},),
+ ({"type": "AND", "values": [{"type": "person", "value": "example"}]},),
+ ({"type": "AND", "values": [{"type": "person", "key": "tier"}]},),
+ ]
+ + [
+ ({"type": "AND", "values": [{"type": "cohort", "key": "id", "value": value}]},)
+ for value in (None, "not-an-id", "", "7.5", True, False, 7.5, 7.0, [7], {"id": 7})
+ ]
+ )
+ def test_rejects_malformed_cohort_properties(self, properties: dict[str, Any]) -> None:
+ with self.assertRaises(ValueError):
+ cohort_references(properties)
+
+ def test_collects_nested_cohort_references(self) -> None:
+ properties = {
+ "type": "OR",
+ "values": [
+ {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": 2}]},
+ {"type": "cohort", "key": "id", "value": "3"},
+ {},
+ ],
+ }
+ assert cohort_references(properties) == {"2", "3"}
diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.py
index 1b6bad6f9b6a..bf4ea96d8745 100644
--- a/products/feature_flags/backend/test/test_local_evaluation.py
+++ b/products/feature_flags/backend/test/test_local_evaluation.py
@@ -1,3 +1,5 @@
+from typing import Any
+
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
@@ -28,6 +30,7 @@ from products.feature_flags.backend.local_evaluation import (
_build_flag_definitions_hypercache,
_get_flags_response_for_local_evaluation,
_get_flags_response_for_local_evaluation_batch,
+ _transform_flag_property_dependencies,
_update_flag_definitions,
clear_flag_definition_caches,
flag_definitions_hypercache,
@@ -974,7 +977,8 @@ class TestLocalEvaluationBatch(BaseTest):
assert results[team.id]["flags"] == []
assert results[team.id]["group_type_mapping"] == {"0": "company"}
- def test_batch_cohort_isolation_across_projects(self):
+ @parameterized.expand([("valid", False), ("malformed", True)])
+ def test_batch_cohort_isolation_across_projects(self, _name: str, malformed: bool) -> None:
team_a = self._create_team_with_project("Project A")
team_b = self._create_team_with_project("Project B")
@@ -999,10 +1003,22 @@ class TestLocalEvaluationBatch(BaseTest):
name="cohort-b",
)
+ if malformed:
+ Cohort.objects.filter(pk=cohort_b.pk).update(filters={"properties": {"type": "AND", "values": [None]}})
+
FeatureFlag.objects.create(
team=team_a,
key="flag-with-cohort-a",
- filters={"groups": [{"properties": [{"key": "id", "type": "cohort", "value": cohort_a.pk}]}]},
+ filters={
+ "groups": [
+ {
+ "properties": [
+ {"key": "id", "type": "cohort", "value": cohort_a.pk},
+ {"key": "id", "type": "cohort", "value": cohort_b.pk},
+ ]
+ }
+ ]
+ },
)
FeatureFlag.objects.create(
team=team_b,
@@ -1018,8 +1034,9 @@ class TestLocalEvaluationBatch(BaseTest):
assert str(cohort_a.pk) in cohort_ids_a
assert str(cohort_b.pk) not in cohort_ids_a
- assert str(cohort_b.pk) in cohort_ids_b
- assert str(cohort_a.pk) not in cohort_ids_b
+ assert [flag["key"] for flag in results[team_a.id]["flags"]] == ["flag-with-cohort-a"]
+ assert cohort_ids_b == (set() if malformed else {str(cohort_b.pk)})
+ assert [flag["key"] for flag in results[team_b.id]["flags"]] == ([] if malformed else ["flag-with-cohort-b"])
def test_batch_only_loads_referenced_cohorts(self):
"""Cohorts not referenced by any flag filter should not appear in the response."""
@@ -1097,7 +1114,8 @@ class TestLocalEvaluationBatch(BaseTest):
assert str(dynamic_cohort.pk) in results[team.id]["cohorts"]
assert str(static_cohort.pk) not in results[team.id]["cohorts"]
- def test_batch_loads_nested_cohort_dependencies(self):
+ @parameterized.expand([(False,), (True,)])
+ def test_batch_loads_nested_cohort_dependencies(self, string_reference: bool) -> None:
"""Cohorts referenced transitively through other cohorts should be loaded."""
team = self._create_team_with_project("Nested Cohort Team")
@@ -1117,7 +1135,16 @@ class TestLocalEvaluationBatch(BaseTest):
"properties": {
"type": "OR",
"values": [
- {"type": "OR", "values": [{"key": "id", "value": leaf_cohort.pk, "type": "cohort"}]},
+ {
+ "type": "OR",
+ "values": [
+ {
+ "key": "id",
+ "value": str(leaf_cohort.pk) if string_reference else leaf_cohort.pk,
+ "type": "cohort",
+ }
+ ],
+ },
],
}
},
@@ -1229,8 +1256,7 @@ class TestLocalEvaluationBatch(BaseTest):
assert str(cohort_a.pk) in cohort_ids
assert str(cohort_b.pk) in cohort_ids
- def test_batch_no_cohort_flags_skips_cohort_loading(self):
- """When no flags reference cohorts, the cohort query should be skipped entirely."""
+ def test_batch_flags_without_dependencies_skip_cohort_and_ineligible_loading(self) -> None:
team = self._create_team_with_project("No Cohort Team")
Cohort.objects.create(
@@ -1251,10 +1277,7 @@ class TestLocalEvaluationBatch(BaseTest):
)
with self.assertNumQueries(3):
- # Expected queries: the minimal_flag_called_events gate, survey flag
- # IDs, and flags (with evaluation tags via ArrayAgg). Group type
- # mappings are read from personhog, not SQL. No cohort query should
- # be issued.
+ # Group type mappings use personhog; SQL only loads team config, surveys, and eligible flags.
results = _get_flags_response_for_local_evaluation_batch([team])
assert results[team.id]["cohorts"] == {}
@@ -1305,7 +1328,8 @@ class TestLocalEvaluationBatch(BaseTest):
},
)
- def test_batch_reads_explicit_config_version_1_like_absent(self):
+ @parameterized.expand([("string", False), ("integer", True)])
+ def test_batch_reads_explicit_config_version_1_like_absent(self, _name: str, integer_reference: bool) -> None:
team = self._create_team_with_project("Explicit version 1")
cohort = self._create_cohort(team, "referenced")
target = FeatureFlag.objects.create(
@@ -1319,7 +1343,12 @@ class TestLocalEvaluationBatch(BaseTest):
{
"properties": [
{"key": "id", "type": "cohort", "value": cohort.pk},
- {"key": str(target.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"},
+ {
+ "key": target.pk if integer_reference else str(target.pk),
+ "type": "flag",
+ "value": True,
+ "operator": "flag_evaluates_to",
+ },
],
"rollout_percentage": 100,
}
@@ -1338,7 +1367,33 @@ class TestLocalEvaluationBatch(BaseTest):
flag.refresh_from_db()
assert flag.filters == stored_filters
- def test_batch_drops_unsupported_config_format_and_keeps_siblings(self):
+ @parameterized.expand(
+ [
+ ("v2_depends_true", 2, True, False, True),
+ ("v2_float_inactive_depends_false", 2.0, False, False, False),
+ ("v2_string_deleted_depends_false", "2", True, True, False),
+ ("null_version_inactive_deleted_depends_true", None, False, True, True),
+ ("bool_version_depends_false", True, True, False, False),
+ ("v3_depends_true", 3, True, False, True),
+ ("v2_encrypted_depends_false", 2, True, False, False, "encrypted"),
+ ("v2_survey_depends_true", 2, True, False, True, "survey"),
+ ("v1_deleted_depends_true", 1, True, True, True),
+ ("v1_encrypted_depends_true", 1, True, False, True, "encrypted"),
+ ("v1_survey_depends_false", 1, True, False, False, "survey"),
+ ("v2_deleted_key_reference", 2, True, True, True, None, "key"),
+ ("v2_deleted_integer_reference", 2, True, True, False, None, "integer"),
+ ]
+ )
+ def test_batch_excludes_unsupported_targets_and_preserves_supported_missing_dependencies(
+ self,
+ _name: str,
+ version: object,
+ active: bool,
+ deleted: bool,
+ dependency_value: bool,
+ exclusion: str | None = None,
+ reference_kind: str = "string",
+ ) -> None:
team = self._create_team_with_project("Unsupported format")
cohort = self._create_cohort(team, "sibling-cohort")
FeatureFlag.objects.create(
@@ -1349,12 +1404,21 @@ class TestLocalEvaluationBatch(BaseTest):
# 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,
+ "version": version,
"groups": [
{"properties": [{"key": "id", "type": "cohort", "value": cohort.pk}], "rollout_percentage": 100}
],
}
- unsupported = FeatureFlag.objects.create(team=team, key="unsupported-format", filters=unsupported_filters)
+ unsupported = FeatureFlag.objects.create(
+ team=team, key="unsupported-format", filters=unsupported_filters, active=active, deleted=deleted
+ )
+ if exclusion == "encrypted":
+ FeatureFlag.objects.filter(pk=unsupported.pk).update(
+ has_encrypted_payloads=True, is_remote_configuration=True
+ )
+ elif exclusion == "survey":
+ Survey.objects.create(team=team, name="Excluded survey", type="popover", targeting_flag=unsupported)
+ reference = {"string": str(unsupported.pk), "integer": unsupported.pk, "key": unsupported.key}[reference_kind]
FeatureFlag.objects.create(
team=team,
key="depends-on-unsupported",
@@ -1362,7 +1426,12 @@ class TestLocalEvaluationBatch(BaseTest):
"groups": [
{
"properties": [
- {"key": str(unsupported.pk), "type": "flag", "value": True, "operator": "flag_evaluates_to"}
+ {
+ "key": reference,
+ "type": "flag",
+ "value": dependency_value,
+ "operator": "flag_evaluates_to",
+ }
],
"rollout_percentage": 100,
}
@@ -1374,17 +1443,194 @@ class TestLocalEvaluationBatch(BaseTest):
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"}
+ expected = {"v1-sibling"}
+ if version == 1 and not isinstance(version, bool):
+ expected.add("depends-on-unsupported")
+ prop = flags_by_key["depends-on-unsupported"]["filters"]["groups"][0]["properties"][0]
+ assert prop["dependency_chain"] == []
+ assert set(flags_by_key) == expected
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"] == []
+ assert FLAG_PROCESSING_ERROR_COUNTER._value.get() == dropped_before
unsupported.refresh_from_db()
assert unsupported.filters == unsupported_filters
+ @parameterized.expand(
+ [
+ ([], False),
+ ([], True),
+ ({"groups": [None]}, False),
+ ({"groups": [None]}, True),
+ ({"groups": [{"properties": {}}]}, False),
+ ({"groups": [{"properties": {}}]}, True),
+ ]
+ + [
+ ({"groups": [{"properties": [{"type": "cohort", "key": "id", "value": value}]}]}, deleted)
+ for value in ("not-an-id", None, [7], True, False, 7.5, 7.0)
+ for deleted in (False, True)
+ ]
+ )
+ def test_batch_malformed_stored_config_keeps_other_teams(self, filters: Any, deleted: bool) -> None:
+ other = self._create_team_with_project("Independent")
+ bad = FeatureFlag.objects.create(team=self.team, key="malformed", filters={})
+ FeatureFlag.objects.filter(pk=bad.pk).update(filters=filters, deleted=deleted)
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="depends-on-malformed",
+ filters={"groups": [{"properties": [{"type": "flag", "key": bad.pk, "value": False}]}]},
+ )
+ FeatureFlag.objects.create(team=self.team, key="healthy", filters={"groups": []})
+ # The other team's healthy flag shares the malformed flag's key, and its dependent
+ # references it by key, so an exclusion leaking across teams would drop both.
+ FeatureFlag.objects.create(team=other, key="malformed", filters={"groups": []})
+ FeatureFlag.objects.create(
+ team=other,
+ key="other-dependent",
+ filters={"groups": [{"properties": [{"type": "flag", "key": "malformed", "value": True}]}]},
+ )
+ dropped_before = FLAG_PROCESSING_ERROR_COUNTER._value.get()
+ result = _get_flags_response_for_local_evaluation_batch([self.team, other])
+ assert [flag["key"] for flag in result[self.team.id]["flags"]] == ["healthy"]
+ assert [flag["key"] for flag in result[other.id]["flags"]] == ["malformed", "other-dependent"]
+ assert FLAG_PROCESSING_ERROR_COUNTER._value.get() == dropped_before + (not deleted)
+
+ @parameterized.expand([(False, False), (False, True), (True, False), (True, True)])
+ def test_batch_exclusions_distinguish_numeric_keys_from_ids(
+ self, deleted: bool, unsupported_numeric_key: bool
+ ) -> None:
+ healthy = FeatureFlag.objects.create(team=self.team, key="healthy", filters={"groups": []})
+ unsupported = FeatureFlag.objects.create(
+ team=self.team,
+ key=str(healthy.pk) if unsupported_numeric_key else "unsupported",
+ filters={"version": 2},
+ deleted=deleted,
+ )
+ if not unsupported_numeric_key:
+ healthy.key = str(unsupported.pk)
+ healthy.save()
+ for target, key in ((healthy, "healthy-dependent"), (unsupported, "unsupported-dependent")):
+ FeatureFlag.objects.create(
+ team=self.team,
+ key=key,
+ filters={"groups": [{"properties": [{"type": "flag", "key": target.pk, "value": False}]}]},
+ )
+ result = _get_flags_response_for_local_evaluation_batch([self.team])[self.team.id]
+ assert {flag["key"] for flag in result["flags"]} == {healthy.key, "healthy-dependent"}
+ dependent = next(flag for flag in result["flags"] if flag["key"] == "healthy-dependent")
+ prop = dependent["filters"]["groups"][0]["properties"][0]
+ assert prop["key"] == healthy.key
+ assert prop["dependency_chain"] == [healthy.key]
+
+ @parameterized.expand(
+ [
+ (None,),
+ ([],),
+ ({},),
+ ({"tier": "example"},),
+ ({"type": "paid"},),
+ ({"values": ["paid"]},),
+ ([{"type": "person", "key": "tier", "value": "example"}],),
+ ({"type": "and", "values": [{"type": "person", "key": "tier", "value": "example"}]},),
+ ({"type": "AND", "values": [{}]},),
+ ]
+ )
+ def test_batch_preserves_legacy_cohort_property_forms(
+ self, properties: list[dict[str, str]] | dict[str, Any] | None
+ ) -> None:
+ cohort = self._create_cohort(self.team, "Legacy properties")
+ Cohort.objects.filter(pk=cohort.pk).update(filters={"properties": properties})
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="healthy",
+ filters={"groups": [{"properties": [{"type": "cohort", "key": "id", "value": cohort.pk}]}]},
+ )
+ result = _get_flags_response_for_local_evaluation(self.team)
+ cohort.refresh_from_db()
+ assert [flag["key"] for flag in result["flags"]] == ["healthy"]
+ assert result["cohorts"][str(cohort.pk)] == cohort.properties.to_dict()
+
+ @parameterized.expand(
+ [
+ ("null_leaf", {"type": "AND", "values": [None]}),
+ (
+ "untyped_group",
+ {"type": "AND", "values": [{"values": [{"type": "person", "key": "tier", "value": "example"}]}]},
+ ),
+ ("invalid_group_type", {"type": "XOR", "values": []}),
+ ("missing_leaf_key", {"type": "AND", "values": [{"type": "person", "value": "example"}]}),
+ ("missing_leaf_value", {"type": "AND", "values": [{"type": "person", "key": "tier"}]}),
+ (
+ "invalid_leaf_type",
+ {"type": "AND", "values": [{"type": "unknown", "key": "tier", "value": "example"}]},
+ ),
+ (
+ "mixed_group",
+ {
+ "type": "AND",
+ "values": [
+ {"type": "AND", "values": []},
+ {"type": "person", "key": "tier", "value": "example"},
+ ],
+ },
+ ),
+ ]
+ + [
+ (f"cohort_{value}", {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": value}]})
+ for value in ("not-an-id", True, False, 7.5, 7.0)
+ ]
+ + [("list_missing_leaf_key", [{"type": "person", "value": "example"}])]
+ )
+ def test_batch_malformed_nested_cohort_keeps_independent_flags(
+ self, _name: str, properties: list[dict[str, Any]] | dict[str, Any]
+ ) -> None:
+ child = self._create_cohort(self.team, "Malformed child")
+ parent = Cohort.objects.create(
+ team=self.team,
+ name="Parent",
+ filters={"properties": {"type": "AND", "values": [{"type": "cohort", "key": "id", "value": child.pk}]}},
+ )
+ Cohort.objects.filter(pk=child.pk).update(filters={"properties": properties})
+ affected = FeatureFlag.objects.create(
+ team=self.team,
+ key="affected",
+ filters={"groups": [{"properties": [{"type": "cohort", "key": "id", "value": parent.pk}]}]},
+ )
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="dependent",
+ filters={"groups": [{"properties": [{"type": "flag", "key": affected.pk, "value": False}]}]},
+ )
+ valid = self._create_cohort(self.team, "Valid")
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="healthy",
+ filters={"groups": [{"properties": [{"type": "cohort", "key": "id", "value": valid.pk}]}]},
+ )
+ result = _get_flags_response_for_local_evaluation(self.team)
+ assert [flag["key"] for flag in result["flags"]] == ["healthy"]
+ assert result["cohorts"] == {str(valid.pk): valid.properties.to_dict()}
+
+ def test_batch_team_failure_keeps_other_teams(self) -> None:
+ other = self._create_team_with_project("Independent")
+ FeatureFlag.objects.create(team=self.team, key="poison", filters={"groups": []})
+ FeatureFlag.objects.create(team=other, key="other", filters={"groups": []})
+
+ def transform(flags: list[dict[str, Any]], flag_id_to_key: dict[str, str]) -> list[dict[str, Any]]:
+ if any(flag["key"] == "poison" for flag in flags):
+ raise RuntimeError("transformation failed")
+ return _transform_flag_property_dependencies(flags, flag_id_to_key)
+
+ with patch(
+ "products.feature_flags.backend.local_evaluation._transform_flag_property_dependencies",
+ side_effect=transform,
+ ):
+ results = _get_flags_response_for_local_evaluation_batch([self.team, other])
+ with self.assertRaises(RuntimeError):
+ _get_flags_response_for_local_evaluation(self.team)
+
+ # The failed team is left out rather than published empty.
+ assert self.team.id not in results
+ assert [flag["key"] for flag in results[other.id]["flags"]] == ["other"]
+
@override_settings(FLAGS_REDIS_URL="redis://test")
class TestFlagDefinitionsCache(BaseTest):
@@ -1507,6 +1753,20 @@ class TestFlagDefinitionsCache(BaseTest):
assert result is False
+ def test_update_flag_definitions_cache_keeps_previous_entry_when_transformation_fails(self) -> None:
+ FeatureFlag.objects.create(team=self.team, key="first", created_by=self.user, filters={"groups": []})
+ assert update_flag_definitions_cache(self.team) is True
+ previous = flag_definitions_hypercache.get_from_cache(self.team)
+ FeatureFlag.objects.create(team=self.team, key="second", created_by=self.user, filters={"groups": []})
+
+ with patch(
+ "products.feature_flags.backend.local_evaluation._transform_flag_property_dependencies",
+ side_effect=RuntimeError("transformation failed"),
+ ):
+ assert update_flag_definitions_cache(self.team) is False
+
+ assert flag_definitions_hypercache.get_from_cache(self.team) == previous
+
def test_update_flag_definitions_cache_passes_custom_ttl(self):
FeatureFlag.objects.create(
team=self.team,
diff --git a/products/feature_flags/backend/test/test_rebuild_queue.py b/products/feature_flags/backend/test/test_rebuild_queue.py
index f2d6b5bf6a07..af4ea69ea1c0 100644
--- a/products/feature_flags/backend/test/test_rebuild_queue.py
+++ b/products/feature_flags/backend/test/test_rebuild_queue.py
@@ -35,16 +35,17 @@ def fake_redis():
@contextmanager
-def _rebuilds(error=None, skip_write=False, load_error=None):
+def _rebuilds(error=None, skip_write=False, load_error=None, omit=()):
"""Patch the batch DB-load + cache-write seam so rebuilds succeed (error=None) or
fail with the given exception, without touching the DB or the real caches.
`skip_write=True` makes the group-mapping-emptied guard veto every write.
- `load_error` makes the batch DB load raise (simulating a DB/query failure)."""
+ `load_error` makes the batch DB load raise (simulating a DB/query failure).
+ `omit` leaves those team IDs out of the batch load, as a failed team build does."""
def _load(teams):
if load_error is not None:
raise load_error
- return {t.id: {} for t in teams}
+ return {t.id: {} for t in teams if t.id not in omit}
with (
patch.object(rebuild_queue, "Team") as team,
@@ -177,6 +178,17 @@ def test_batch_load_failure_counts_every_team_as_failure(fake_redis):
assert fake_redis.get(FAILURE_STREAK_KEY.format(team_id=team_id)) == b"1"
+def test_team_missing_from_batch_load_fails_alone(fake_redis):
+ for team_id in (21, 22):
+ _enqueue(fake_redis, team_id)
+ with _rebuilds(omit={22}):
+ stats = drain_rebuild_requests()
+
+ assert stats["success"] == 1 and stats["failure"] == 1
+ assert fake_redis.get(FAILURE_STREAK_KEY.format(team_id=21)) is None
+ assert fake_redis.get(FAILURE_STREAK_KEY.format(team_id=22)) == b"1"
+
+
def test_group_mapping_guard_skips_write_without_counting_failure(fake_redis):
_enqueue(fake_redis, 8)
with _rebuilds(skip_write=True) as set_cache: