: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): make flags cache read-back resilient to non-model keys (#65319)
Phil Haack09a12120c106
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex ecf3b49fde69..72165e4fc3b2 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -10103,6 +10103,82 @@ class TestFeatureFlagEvaluationContexts(APIBaseTest):assert cached_flag is not Noneself.assertEqual(cached_flag.evaluation_tag_names, ["app"])+ @pytest.mark.ee+ def test_cache_read_back_ignores_unknown_non_model_key(self):+ from posthog.caching.flags_redis_cache import write_flags_to_cache++ from products.feature_flags.backend.models.feature_flag import FIVE_DAYS, serialize_feature_flags++ flag = FeatureFlag.objects.create(+ team=self.team,+ key="unknown-key-flag",+ name="Unknown Key Flag",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ created_by=self.user,+ )++ [serialized] = serialize_feature_flags([flag])+ # A future SDK-only serializer field that is not a model field must not break read-back.+ serialized["some_future_sdk_field"] = {"anything": True}+ write_flags_to_cache(+ f"team_feature_flags_{self.team.project_id}",+ json.dumps([serialized]),+ FIVE_DAYS,+ )++ cached_flags = get_feature_flags_for_team_in_cache(self.team.project_id)+ assert cached_flags is not None+ self.assertEqual(len(cached_flags), 1)+ self.assertEqual(cached_flags[0].key, "unknown-key-flag")++ @parameterized.expand(+ [+ # (name, evaluation_contexts value, evaluation_tags value, expected)+ ("current_key", ["app", "docs"], None, ["app", "docs"]),+ ("legacy_key", None, ["app", "docs"], ["app", "docs"]),+ # When both keys are present, the current `evaluation_contexts` key wins.+ ("both_keys_current_wins", ["app", "docs"], ["legacy"], ["app", "docs"]),+ ]+ )+ @pytest.mark.ee+ def test_cache_read_back_accepts_evaluation_context_keys(+ self,+ _name: str,+ contexts_value: Optional[list[str]],+ tags_value: Optional[list[str]],+ expected: list[str],+ ):+ from posthog.caching.flags_redis_cache import write_flags_to_cache++ from products.feature_flags.backend.models.feature_flag import FIVE_DAYS, serialize_feature_flags++ flag = FeatureFlag.objects.create(+ team=self.team,+ key=f"eval-context-key-{_name}",+ name="Eval Context Key Flag",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ created_by=self.user,+ )++ [serialized] = serialize_feature_flags([flag])+ # Exercise the current `evaluation_contexts` key, the legacy `evaluation_tags`+ # key, and entries that carry both (where the current key must take precedence).+ serialized.pop("evaluation_contexts", None)+ if contexts_value is not None:+ serialized["evaluation_contexts"] = contexts_value+ if tags_value is not None:+ serialized["evaluation_tags"] = tags_value+ write_flags_to_cache(+ f"team_feature_flags_{self.team.project_id}",+ json.dumps([serialized]),+ FIVE_DAYS,+ )++ cached_flags = get_feature_flags_for_team_in_cache(self.team.project_id)+ assert cached_flags is not None+ cached_flag = next(f for f in cached_flags if f.key == flag.key)+ self.assertEqual(cached_flag.evaluation_tag_names, expected)+def _get_eval_context_activity_entries(self, flag_id: int, activity: str = "updated") -> list:from posthog.models.activity_logging.activity_log import ActivityLogdiff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.pyindex 508b96ea24f0..0e5bfb0da071 100644--- a/products/feature_flags/backend/models/feature_flag.py+++ b/products/feature_flags/backend/models/feature_flag.py@@ -1,4 +1,5 @@import json+from functools import lru_cachefrom typing import TYPE_CHECKING, Any, Optional, castfrom django.contrib.auth.base_user import AbstractBaseUser@@ -707,19 +708,7 @@ def get_feature_flags_for_team_in_cache(project_id: int) -> Optional[list[Featurif flag_data is not None:try:parsed_data = json.loads(flag_data)- flags = []- for flag_data in parsed_data:- # Extract evaluation contexts before creating the model instance since- # it's not a DB field. Accept both old and new key names for cache- # entries written before or after the rename.- contexts_list = flag_data.pop("evaluation_contexts", None)- if contexts_list is None:- contexts_list = flag_data.pop("evaluation_tags", None)- else:- flag_data.pop("evaluation_tags", None) # discard legacy key if present- flag = FeatureFlag(**flag_data)- flag._evaluation_tag_names = contexts_list- flags.append(flag)+ flags = [_feature_flag_from_cache_entry(entry) for entry in parsed_data]# Filter to only return active flags. The cache includes inactive flags# for dependency resolution (used by the Rust service), but Python callers# expect only active flags for backward compatibility.@@ -732,6 +721,37 @@ def get_feature_flags_for_team_in_cache(project_id: int) -> Optional[list[Featurreturn None+@lru_cache(maxsize=1)+def _feature_flag_model_field_names() -> frozenset[str]:+ """Names accepted by the FeatureFlag constructor (concrete fields only), used to+ separate real model fields from serializer-only extras in cached payloads. The+ field set is constant for the process, so it's computed once and cached."""+ names: set[str] = set()+ for field in FeatureFlag._meta.concrete_fields:+ names.add(field.name)+ names.add(field.attname) # FK attnames like `team_id`+ return frozenset(names)+++def _feature_flag_from_cache_entry(entry: dict[str, Any]) -> FeatureFlag:+ """Reconstruct a FeatureFlag from one cached payload entry.++ The cache payload comes from MinimalFeatureFlagSerializer, which emits+ SerializerMethodFields (e.g. `evaluation_contexts`) that are not model fields.+ Keep only real model fields so unknown extras are ignored rather than crashing+ the FeatureFlag(**...) constructor; known extras are then assigned onto the instance.+ """+ model_field_names = _feature_flag_model_field_names()+ model_fields = {key: value for key, value in entry.items() if key in model_field_names}++ flag = FeatureFlag(**model_fields)+ # Evaluation contexts are derived data, not a DB field. Accept both the current+ # `evaluation_contexts` key and the legacy `evaluation_tags` key for entries+ # written before the rename.+ flag._evaluation_tag_names = entry.get("evaluation_contexts", entry.get("evaluation_tags"))+ return flag++class FeatureFlagDashboards(models.Model):feature_flag = models.ForeignKey("FeatureFlag", on_delete=models.CASCADE)dashboard = models.ForeignKey("dashboards.Dashboard", on_delete=models.CASCADE)