: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
chore(flags): remove unread legacy team_feature_flags cache writer (#82180)
Phil Haack4c8f84f404cf
diff --git a/docs/internal/feature-flags/django-api-endpoints.md b/docs/internal/feature-flags/django-api-endpoints.mdindex 50bbc5584641..13d5464296ab 100644--- a/docs/internal/feature-flags/django-api-endpoints.md+++ b/docs/internal/feature-flags/django-api-endpoints.md@@ -96,7 +96,7 @@ Key things to know:- `evaluation_runtime` controls whether a flag is evaluated client-side, server-side, or both- The `@approval_gate` decorator on updates can require approval before changes take effect-**Cache invalidation**: The `refresh_flag_cache_on_updates` signal handler fires on save/delete, calling `set_feature_flags_for_team_in_cache()` via `transaction.on_commit()`.+**Cache invalidation**: The `feature_flag_changed_flags_cache` (`flags_cache.py`) and `feature_flag_changed` (`local_evaluation.py`) signal handlers fire on save/delete, scheduling cache rebuilds via `transaction.on_commit()`.### Related models (same file)diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.mdindex 1ffcf202bae9..1e593821e288 100644--- a/docs/internal/feature-flags/hypercache-system.md+++ b/docs/internal/feature-flags/hypercache-system.md@@ -356,28 +356,8 @@ The feature-flags Rust service can use a separate Redis instance for caching, isFLAGS_REDIS_URL=redis://flags-redis:6379 # Separate instance for flags```-When `FLAGS_REDIS_URL` is set, the system uses a dual-write pattern:--```python-# posthog/caching/flags_redis_cache.py-def write_flags_to_cache(key: str, value: Any, timeout: Optional[int] = None) -> None:- # Always write to shared cache (Django reads from here)- cache.set(key, value, timeout)-- # Also write to dedicated cache if configured (Rust service reads from here)- if has_dedicated_cache:- dedicated_cache = caches[FLAGS_DEDICATED_CACHE_ALIAS]- dedicated_cache.set(key, value, timeout)-```--### Why dual-write?--| Consumer | Reads from | Purpose |-| ------------ | --------------- | ------------------------------- |-| Django | Shared cache | Local evaluation, SDK endpoints |-| Rust service | Dedicated cache | High-throughput flag evaluation |--The dual-write pattern is temporary while the Rust port is being completed. Once the Rust service handles all flag evaluation, Django will stop writing to the shared cache for local evaluation, and only the dedicated cache will be used.+When `FLAGS_REDIS_URL` is set, Django registers it as the `flags_dedicated` cache alias (`FLAGS_DEDICATED_CACHE_ALIAS` in `posthog/caching/flags_redis_cache.py`, wired up in `posthog/settings/data_stores.py`).+Three HyperCache instances bind that alias: flags (`products/feature_flags/backend/flags_cache.py`), remote config, and team metadata. Django writes those to the dedicated instance and the Rust service reads them from it. The SDK-facing flag-definitions cache (`local_evaluation.py`) stays on the shared default cache on both the Django write side and the Rust read side.The Rust service only operates when `FLAGS_REDIS_URL` is configured. All cache update functions check this setting and skip operations if not set.@@ -475,7 +455,7 @@ The local evaluation cache (for SDKs) also invalidates when cohorts change. See# RequiredREDIS_URL=redis://localhost:6379-# Dedicated flags Redis (optional, enables dual-write)+# Dedicated flags Redis (optional)FLAGS_REDIS_URL=redis://flags-redis:6379# Cache TTL settings@@ -500,13 +480,13 @@ REMOTE_CONFIG_CDN_PURGE_DOMAINS=["cdn.example.com"]## Related files- `posthog/storage/hypercache.py` - Core HyperCache implementation-- `posthog/models/feature_flag/local_evaluation.py` - Local evaluation caching-- `posthog/models/feature_flag/flags_cache.py` - Flags cache, signal handlers, verification, dependency computation+- `products/feature_flags/backend/local_evaluation.py` - Local evaluation caching+- `products/feature_flags/backend/flags_cache.py` - Flags cache, signal handlers, verification, dependency computation- `posthog/storage/hypercache_manager.py` - Batch management operations (warm, invalidate, stats)-- `posthog/caching/flags_redis_cache.py` - Dual-write pattern for dedicated Redis+- `posthog/caching/flags_redis_cache.py` - `FLAGS_DEDICATED_CACHE_ALIAS` constant for the dedicated flags Redis- `posthog/models/remote_config.py` - Remote config caching- `posthog/models/team/team_caching.py` - Team authentication caching-- `posthog/tasks/feature_flags.py` - Cache update and refresh Celery tasks+- `products/feature_flags/backend/tasks.py` - Cache update and refresh Celery tasks- `posthog/tasks/hypercache_verification.py` - Cache verification task- `posthog/tasks/remote_config.py` - Remote config sync tasks- `posthog/tasks/scheduled.py` - Task schedule definitionsdiff --git a/posthog/caching/flags_redis_cache.py b/posthog/caching/flags_redis_cache.pyindex 87bab8ee6d20..36706c9a4f1e 100644--- a/posthog/caching/flags_redis_cache.py+++ b/posthog/caching/flags_redis_cache.py@@ -1,40 +1 @@-import logging-from typing import Any, Optional--from django.conf import settings-from django.core.cache import cache, caches--from posthog.exceptions_capture import capture_exception--logger = logging.getLogger(__name__)-FLAGS_DEDICATED_CACHE_ALIAS = "flags_dedicated"---def write_flags_to_cache(key: str, value: Any, timeout: Optional[int] = None) -> None:- """Write feature flags to the appropriate cache(s).-- - FLAGS_REDIS_URL not set: writes to shared cache only- - FLAGS_REDIS_URL set: dual-writes to both shared and dedicated- (Django reads from shared, Rust service reads from dedicated)- """- has_dedicated_cache = FLAGS_DEDICATED_CACHE_ALIAS in settings.CACHES-- try:- # Always write to shared cache. If it fails, let the caller handle the error.- cache.set(key, value, timeout)-- if has_dedicated_cache:- try:- dedicated_cache = caches[FLAGS_DEDICATED_CACHE_ALIAS]- dedicated_cache.set(key, value, timeout)- except Exception as e:- logger.warning(- "Dedicated cache write failed",- extra={"key": key},- exc_info=True,- )- capture_exception(e)- except Exception as e:- logger.exception("Failed to write to cache", extra={"key": key})- capture_exception(e)diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex aa12da50ae4e..163fad0084af 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -94,7 +94,6 @@ post_delete:products.feature_flags.backend.local_evaluation.cohort_changedpost_delete:products.feature_flags.backend.local_evaluation.evaluation_context_changedpost_delete:products.feature_flags.backend.local_evaluation.experiment_changedpost_delete:products.feature_flags.backend.local_evaluation.feature_flag_changed-post_delete:products.feature_flags.backend.models.feature_flag.refresh_flag_cache_on_updatespost_delete:products.signals.backend.receivers.reconcile_report_embedding_on_verdict_deletedpost_delete:products.signals.backend.receivers.tombstone_report_embedding_on_hard_deletepost_delete:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_change@@ -194,7 +193,6 @@ post_save:products.feature_flags.backend.local_evaluation.evaluation_context_chapost_save:products.feature_flags.backend.local_evaluation.evaluation_context_name_changedpost_save:products.feature_flags.backend.local_evaluation.experiment_changedpost_save:products.feature_flags.backend.local_evaluation.feature_flag_changed-post_save:products.feature_flags.backend.models.feature_flag.refresh_flag_cache_on_updatespost_save:products.review_hog.backend.receivers.handle_task_run_savedpost_save:products.signals.backend.receivers.capture_status_change_analyticspost_save:products.signals.backend.receivers.close_pr_when_report_dismisseddiff --git a/posthog/test/test_flags_redis_cache.py b/posthog/test/test_flags_redis_cache.pydeleted file mode 100644index 80a8b4a8523a..000000000000--- a/posthog/test/test_flags_redis_cache.py+++ /dev/null@@ -1,154 +0,0 @@-"""-Tests for flags Redis cache dual-write functionality.--Tests the write_flags_to_cache() function which handles writing feature flags-to both shared and dedicated Redis caches when configured.-"""--import json--from posthog.test.base import BaseTest-from unittest.mock import MagicMock, patch--from django.core.cache import cache-from django.test import override_settings--from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIAS, write_flags_to_cache--from products.feature_flags.backend.models.feature_flag import FeatureFlag, set_feature_flags_for_team_in_cache---class TestFlagsRedisCache(BaseTest):- def setUp(self):- super().setUp()- cache.clear()-- def test_writes_to_shared_cache_only_when_no_dedicated(self):- """No dedicated cache configured - writes to shared cache only"""- test_data = {"test": "data"}-- write_flags_to_cache("test-key", test_data, timeout=300)-- # Verify data was written to shared cache- cached_value = cache.get("test-key")- self.assertEqual(cached_value, test_data)-- @override_settings(- CACHES={- "default": {- "BACKEND": "django.core.cache.backends.locmem.LocMemCache",- },- FLAGS_DEDICATED_CACHE_ALIAS: {- "BACKEND": "django.core.cache.backends.locmem.LocMemCache",- },- }- )- def test_dual_writes_when_dedicated_configured(self):- """Dedicated cache configured - dual-writes to both shared and dedicated"""- from django.core.cache import caches-- caches["default"].clear()- caches[FLAGS_DEDICATED_CACHE_ALIAS].clear()-- test_data = {"test": "data"}-- write_flags_to_cache("test-key", test_data, timeout=300)-- # Verify data was written to both caches- shared_value = caches["default"].get("test-key")- dedicated_value = caches[FLAGS_DEDICATED_CACHE_ALIAS].get("test-key")-- self.assertEqual(shared_value, test_data)- self.assertEqual(dedicated_value, test_data)-- @override_settings(- CACHES={- "default": {- "BACKEND": "django.core.cache.backends.locmem.LocMemCache",- },- FLAGS_DEDICATED_CACHE_ALIAS: {- "BACKEND": "django.core.cache.backends.locmem.LocMemCache",- },- }- )- def test_continues_on_dedicated_cache_failure(self):- """Dedicated cache write failure - continues successfully, writes to shared"""- from django.core.cache import caches-- test_data = {"test": "data"}-- # Create a mock for the dedicated cache that fails on set- mock_dedicated_cache = MagicMock()- mock_dedicated_cache.set.side_effect = Exception("Redis connection failed")-- shared_cache = caches["default"]- shared_cache.clear()-- # Patch cache, caches, and settings to return our mocks- with (- patch("posthog.caching.flags_redis_cache.cache", shared_cache),- patch("posthog.caching.flags_redis_cache.caches") as mock_caches,- patch("posthog.caching.flags_redis_cache.settings") as mock_settings,- ):-- def get_cache(name):- if name == "default":- return shared_cache- elif name == FLAGS_DEDICATED_CACHE_ALIAS:- return mock_dedicated_cache- raise KeyError(f"Unknown cache: {name}")-- mock_caches.__getitem__.side_effect = get_cache- mock_settings.CACHES = {"default": {}, FLAGS_DEDICATED_CACHE_ALIAS: {}}-- write_flags_to_cache("test-key", test_data, timeout=300)-- # Shared cache should still have the data- shared_value = shared_cache.get("test-key")- self.assertEqual(shared_value, test_data)-- # Dedicated cache set should have been attempted- mock_dedicated_cache.set.assert_called_once_with("test-key", test_data, 300)-- @override_settings(- CACHES={- "default": {- "BACKEND": "django.core.cache.backends.locmem.LocMemCache",- },- FLAGS_DEDICATED_CACHE_ALIAS: {- "BACKEND": "django.core.cache.backends.locmem.LocMemCache",- },- }- )- def test_integration_with_set_feature_flags_for_team(self):- """Integration test: set_feature_flags_for_team_in_cache uses write_flags_to_cache"""- from django.core.cache import caches-- caches["default"].clear()- caches[FLAGS_DEDICATED_CACHE_ALIAS].clear()-- # Create a feature flag- FeatureFlag.objects.create(- team=self.team,- created_by=self.user,- key="test-flag",- active=True,- filters={"groups": [{"rollout_percentage": 100}]},- )-- # Call the integration point- set_feature_flags_for_team_in_cache(self.team.project_id)-- # Verify both caches received the data- shared_data = caches["default"].get(f"team_feature_flags_{self.team.project_id}")- dedicated_data = caches[FLAGS_DEDICATED_CACHE_ALIAS].get(f"team_feature_flags_{self.team.project_id}")-- self.assertIsNotNone(shared_data)- self.assertIsNotNone(dedicated_data)-- # Verify the data is identical and correct- self.assertEqual(shared_data, dedicated_data)- flags = json.loads(shared_data)- self.assertEqual(len(flags), 1)- self.assertEqual(flags[0]["key"], "test-flag")- self.assertTrue(flags[0]["active"])diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.pyindex 6d76282762c6..02b35033f556 100644--- a/products/experiments/backend/test/test_presentation_api.py+++ b/products/experiments/backend/test/test_presentation_api.py@@ -8,7 +8,6 @@ from freezegun import freeze_timefrom posthog.test.base import ClickhouseTestMixin, FuzzyInt, _create_event, _create_person, flush_persons_and_eventsfrom unittest.mock import ANY, MagicMock, patch-from django.core.cache import cachefrom django.db import connectionfrom django.db.models import Ffrom django.test.utils import CaptureQueriesContext@@ -47,7 +46,7 @@ from products.experiments.backend.models.web_experiment import WebExperimentfrom products.experiments.backend.presentation.serializers import ExperimentSerializerfrom products.experiments.backend.presentation.views import LIST_DEFERRED_FIELDS, EnterpriseExperimentsViewSetfrom products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContext-from products.feature_flags.backend.models.feature_flag import FeatureFlag, get_feature_flags_for_team_in_cache+from products.feature_flags.backend.models.feature_flag import FeatureFlagfrom ee.api.test.base import APILicensedTestfrom ee.clickhouse.views.experiment_saved_metrics import ExperimentToSavedMetricSerializer@@ -3359,147 +3358,6 @@ class TestExperimentCRUD(_HoistFlagConfigClientMixin, APILicensedTest):[("flag_0", []), (ff_key, [created_experiment])],)- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())- def test_create_experiment_updates_feature_flag_cache(self, mock_on_commit):- cache.clear()-- initial_cached_flags = get_feature_flags_for_team_in_cache(self.team.pk)- self.assertIsNone(initial_cached_flags)-- ff_key = "a-b-test"- response = self.client.post(- f"/api/projects/{self.team.id}/experiments/",- {- "name": "Test Experiment",- "description": "",- "start_date": None,- "end_date": None,- "feature_flag_key": ff_key,- "parameters": {- "feature_flag_variants": [- {- "key": "control",- "name": "Control Group",- "rollout_percentage": 33,- },- {- "key": "test_1",- "name": "Test Variant",- "rollout_percentage": 33,- },- {- "key": "test_2",- "name": "Test Variant",- "rollout_percentage": 34,- },- ]- },- "filters": {- "events": [- {"order": 0, "id": "$pageview"},- {"order": 1, "id": "$pageleave"},- ],- "properties": [],- },- },- )-- self.assertEqual(response.status_code, status.HTTP_201_CREATED)- self.assertEqual(response.json()["name"], "Test Experiment")- self.assertEqual(response.json()["feature_flag_key"], ff_key)-- # save was called, but no flags saved because experiment is in draft mode, so flag is not active- cached_flags = get_feature_flags_for_team_in_cache(self.team.pk)- assert cached_flags is not None- self.assertEqual(0, len(cached_flags))-- id = response.json()["id"]-- # launch experiment- response = self.client.patch(- f"/api/projects/{self.team.id}/experiments/{id}",- {- "start_date": "2021-12-01T10:23",- },- )-- cached_flags = get_feature_flags_for_team_in_cache(self.team.pk)- assert cached_flags is not None- self.assertEqual(1, len(cached_flags))- self.assertEqual(cached_flags[0].key, ff_key)- self.assertEqual(- cached_flags[0].filters,- {- "groups": [- {- "properties": [],- "rollout_percentage": 100,- "aggregation_group_type_index": None,- }- ],- "multivariate": {- "variants": [- {- "key": "control",- "name": "Control Group",- "rollout_percentage": 33,- },- {- "key": "test_1",- "name": "Test Variant",- "rollout_percentage": 33,- },- {- "key": "test_2",- "name": "Test Variant",- "rollout_percentage": 34,- },- ]- },- "holdout": None,- "aggregation_group_type_index": None,- },- )-- # On a running experiment, a flag-config change without the opt-in is rejected and must not- # touch the cached flag.- unchanged_filters: dict[str, Any] = {- "groups": [{"properties": [], "rollout_percentage": 100, "aggregation_group_type_index": None}],- "multivariate": {- "variants": [- {"key": "control", "name": "Control Group", "rollout_percentage": 33},- {"key": "test_1", "name": "Test Variant", "rollout_percentage": 33},- {"key": "test_2", "name": "Test Variant", "rollout_percentage": 34},- ]- },- "holdout": None,- "aggregation_group_type_index": None,- }- response = self.client.patch(- f"/api/projects/{self.team.id}/experiments/{id}",- {- "description": "Bazinga",- "feature_flag": {- "filters": {- "multivariate": {- "variants": [- {"key": "control", "name": "X", "rollout_percentage": 50},- {"key": "test", "name": "Y", "rollout_percentage": 50},- ]- }- }- },- },- )- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertIn("update_feature_flag_params", str(response.json()))-- cached_flags = get_feature_flags_for_team_in_cache(self.team.pk)- assert cached_flags is not None- self.assertEqual(1, len(cached_flags))- self.assertEqual(cached_flags[0].key, ff_key)- self.assertEqual(cached_flags[0].filters, unchanged_filters)-def test_create_draft_experiment_with_filters(self) -> None:ff_key = "a-b-tests"response = self.client.post(diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex b54053b07824..b0e058d451c1 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -100,11 +100,7 @@ from products.feature_flags.backend.flag_status import ()from products.feature_flags.backend.local_evaluation import _get_flag_properties_from_filtersfrom products.feature_flags.backend.models.evaluation_context import normalize_context_name-from products.feature_flags.backend.models.feature_flag import (- FeatureFlag,- FeatureFlagDashboards,- set_feature_flags_for_team_in_cache,-)+from products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagDashboardsfrom products.feature_flags.backend.session_recording_links import teams_linking_flagfrom products.feature_flags.backend.types import PropertyFilterTypefrom products.feature_flags.backend.user_blast_radius import get_user_blast_radius@@ -719,14 +715,7 @@ class EvaluationContextSerializerMixin(serializers.Serializer):FeatureFlagEvaluationContext,)- seen: set[str] = set()- deduped_names: list[str] = []- for t in evaluation_contexts or []:- name = normalize_context_name(t)- if name not in seen:- seen.add(name)- deduped_names.append(name)- deduped_set = seen+ deduped_set = {normalize_context_name(t) for t in evaluation_contexts or []}current_context_names = set(FeatureFlagEvaluationContext.objects.filter(feature_flag=obj)@@ -754,11 +743,6 @@ class EvaluationContextSerializerMixin(serializers.Serializer):after=sorted(deduped_set),)- try:- set_feature_flags_for_team_in_cache(obj.team.project_id)- except Exception as e:- capture_exception(e)-def _log_evaluation_context_change(self, obj: FeatureFlag, before: list[str], after: list[str]) -> None:from posthog.models.activity_logging.activity_log import Change, Detail@@ -3504,8 +3488,8 @@ class FeatureFlagViewSet(from posthog.rbac.user_access_control import access_level_satisfied_for_resourcefrom posthog.tasks.remote_config import update_team_remote_config- from products.feature_flags.backend.models.feature_flag import set_feature_flags_for_team_in_cache- from products.feature_flags.backend.tasks import update_team_flags_cache, update_team_service_flags_cache+ from products.feature_flags.backend.flags_cache import enqueue_evaluation_cache_invalidation+ from products.feature_flags.backend.tasks import update_team_flags_cachefilters = request.data.get("filters", {})explicit_ids = request.data.get("ids", [])@@ -3692,7 +3676,7 @@ class FeatureFlagViewSet(# Perform bulk database updates# Using queryset.update() instead of individual saves means Django signals don't fire.- # The signals (refresh_flag_cache_on_updates, feature_flag_changed_flags_cache, etc.)+ # The signals (feature_flag_changed_flags_cache, feature_flag_changed, etc.)# all do cache invalidation, which we handle manually below - once for all flags# instead of once per flag.now_timestamp = timezone.now()@@ -3700,7 +3684,6 @@ class FeatureFlagViewSet(if flags_to_delete_normal or flags_to_delete_with_rename:sample_flag = flags_to_delete_normal[0] if flags_to_delete_normal else flags_to_delete_with_rename[0]team_id = sample_flag.team_id- project_id = sample_flag.team.project_idwith transaction.atomic():if flags_to_delete_normal:@@ -3729,8 +3712,7 @@ class FeatureFlagViewSet(# Cache invalidation - same work the signals would do, but once instead of N timesdef invalidate_caches():- set_feature_flags_for_team_in_cache(project_id)- update_team_service_flags_cache.delay(team_id)+ enqueue_evaluation_cache_invalidation(team_id)update_team_flags_cache.delay(team_id)update_team_remote_config.delay(team_id)diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 4aed8ddc3ad0..59e20589edfd 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -61,11 +61,7 @@ from products.feature_flags.backend.encrypted_flag_payloads import (get_decrypted_flag_payload,)from products.feature_flags.backend.flag_status import FeatureFlagStatus-from products.feature_flags.backend.models.feature_flag import (- FeatureFlag,- FeatureFlagDashboards,- get_feature_flags_for_team_in_cache,-)+from products.feature_flags.backend.models.feature_flag import FeatureFlag, FeatureFlagDashboardsfrom products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfigfrom products.feature_flags.backend.user_blast_radius import get_user_blast_radius, get_user_blast_radius_personsfrom products.product_analytics.backend.models.insight import Insight@@ -7299,57 +7295,6 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):assert len(response["results"]) == 1assert response["results"][0]["key"] == "all_flag"- @patch("django.db.transaction.on_commit", side_effect=lambda func: func())- def test_flag_is_cached_on_create_and_update(self, mock_on_commit):- # Ensure empty feature flag list- FeatureFlag.objects.all().delete()-- feature_flag = self.client.post(- f"/api/projects/{self.team.id}/feature_flags/",- data={- "name": "Beta feature",- "key": "beta-feature",- "filters": {- "aggregation_group_type_index": 0,- "groups": [{"rollout_percentage": 65}],- },- },- format="json",- ).json()-- flags = get_feature_flags_for_team_in_cache(self.team.id)-- assert flags is not None- self.assertEqual(len(flags), 1)- self.assertEqual(flags[0].id, feature_flag["id"])- self.assertEqual(flags[0].key, "beta-feature")- self.assertEqual(flags[0].name, "Beta feature")-- response = self.client.patch(- f"/api/projects/{self.team.id}/feature_flags/{feature_flag['id']}",- {"name": "XYZ", "key": "red_button"},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- flags = get_feature_flags_for_team_in_cache(self.team.id)-- assert flags is not None- self.assertEqual(len(flags), 1)- self.assertEqual(flags[0].id, feature_flag["id"])- self.assertEqual(flags[0].key, "red_button")- self.assertEqual(flags[0].name, "XYZ")-- response = self.client.patch(- f"/api/projects/{self.team.id}/feature_flags/{feature_flag['id']}",- {"deleted": True},- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- flags = get_feature_flags_for_team_in_cache(self.team.id)-- assert flags is not None- self.assertEqual(len(flags), 0)-def test_feature_flag_dashboard(self):another_feature_flag = FeatureFlag.objects.create(team=self.team,@@ -11292,182 +11237,6 @@ class TestFeatureFlagEvaluationContexts(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)self.assertEqual(response.data["evaluation_contexts"], [])- @pytest.mark.ee- def test_evaluation_contexts_in_cache(self):- from products.feature_flags.backend.models.evaluation_context import (- EvaluationContext,- FeatureFlagEvaluationContext,- )- from products.feature_flags.backend.models.feature_flag import set_feature_flags_for_team_in_cache-- flag = FeatureFlag.objects.create(- team=self.team,- key="cached-flag",- name="Cached Flag",- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},- created_by=self.user,- )-- # Create evaluation context- ctx = EvaluationContext.objects.create(name="app", team=self.team)- FeatureFlagEvaluationContext.objects.create(feature_flag=flag, evaluation_context=ctx)-- # Set flags in cache- set_feature_flags_for_team_in_cache(self.team.project_id)-- # Get flags from cache- cached_flags = get_feature_flags_for_team_in_cache(self.team.project_id)- self.assertIsNotNone(cached_flags)- assert cached_flags is not None- self.assertEqual(len(cached_flags), 1)-- cached_flag = cached_flags[0]- self.assertEqual(cached_flag.key, "cached-flag")- # Evaluation tag names should be exposed via the property when populated from cache- self.assertIsNotNone(cached_flag.evaluation_tag_names)- self.assertEqual(cached_flag.evaluation_tag_names, ["app"])-- @parameterized.expand([("with_experiment", True), ("without_experiment", False)])- @pytest.mark.ee- def test_has_experiment_survives_cache_round_trip(self, _name: str, has_experiment: bool):- from products.feature_flags.backend.models.feature_flag import (- get_feature_flags_for_team_in_cache,- set_feature_flags_for_team_in_cache,- )-- flag = FeatureFlag.objects.create(- team=self.team,- key="round-trip-flag",- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},- created_by=self.user,- )- if has_experiment:- Experiment.objects.create(team=self.team, name="exp", feature_flag=flag)-- set_feature_flags_for_team_in_cache(self.team.project_id)- 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 == "round-trip-flag")- # The cached value is read back without a per-flag experiment query.- self.assertEqual(cached_flag._has_experiment, has_experiment)-- @pytest.mark.ee- def test_evaluation_contexts_cache_invalidation(self):- from products.feature_flags.backend.models.feature_flag import (- get_feature_flags_for_team_in_cache,- set_feature_flags_for_team_in_cache,- )-- flag = FeatureFlag.objects.create(- team=self.team,- key="cache-invalidation-test",- name="Cache Invalidation Test",- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},- created_by=self.user,- )-- set_feature_flags_for_team_in_cache(self.team.project_id)-- 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 == "cache-invalidation-test"), None)- assert cached_flag is not None- self.assertEqual(cached_flag.evaluation_tag_names, [])-- response = self.client.patch(- f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",- {- "tags": ["app", "docs"],- "evaluation_contexts": ["app"],- },- format="json",- )- self.assertEqual(response.status_code, status.HTTP_200_OK)-- # Cache should be automatically invalidated and refreshed- 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 == "cache-invalidation-test"), None)- assert cached_flag is not None- self.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 ActivityLog@@ -12939,6 +12708,7 @@ class TestFeatureFlagBulkDelete(APIBaseTest):assert flag.deleted is Trueassert flag.last_modified_by == self.user+ @override_settings(FLAGS_REDIS_URL="redis://test")def test_bulk_delete_invalidates_cache_efficiently(self):"""Test that cache invalidation happens once, not per flag."""flags = [@@ -12956,9 +12726,7 @@ class TestFeatureFlagBulkDelete(APIBaseTest):with patch("products.feature_flags.backend.api.feature_flag.transaction.on_commit", side_effect=lambda fn: fn()):- with patch(- "products.feature_flags.backend.models.feature_flag.set_feature_flags_for_team_in_cache"- ) as mock_cache:+ with patch("products.feature_flags.backend.tasks.update_team_service_flags_cache") as mock_cache_task:response = self.client.post(f"/api/projects/{self.team.id}/feature_flags/bulk_delete/",{"ids": [f.id for f in flags]},@@ -12968,7 +12736,7 @@ class TestFeatureFlagBulkDelete(APIBaseTest):assert len(response.json()["deleted"]) == 10# Cache should be invalidated only once, not 10 times- assert mock_cache.call_count == 1+ assert mock_cache_task.delay.call_count == 1def test_bulk_delete_handles_mixed_key_rename_scenarios(self):"""Test bulk delete correctly handles mix of flags needing key rename and not."""diff --git a/products/feature_flags/backend/flag_version_sync.py b/products/feature_flags/backend/flag_version_sync.pyindex ee535d4e68ef..4daa58d6bd59 100644--- a/products/feature_flags/backend/flag_version_sync.py+++ b/products/feature_flags/backend/flag_version_sync.py@@ -22,9 +22,9 @@ definition change. The same goes for flag edits that leave the flag's conditionscomparison below guarantees only real definition changes bump.The bumps run synchronously inside the triggering save's transaction rather than on-commit: ``refresh_flag_cache_on_updates`` connects at model-import time, i.e. before-this module is wired in ``apps.ready()``, so its own ``on_commit`` callback runs first-and would rebuild the flag cache with the pre-bump versions.+commit: the flag-change signals schedule cache rebuilds via ``on_commit`` callbacks,+so a bump deferred to commit time could run after a rebuild has already read the+pre-bump versions."""from collections import defaultdictdiff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex ebbea41fc506..ee815d3ffc2d 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -353,10 +353,6 @@ def _blank_inactive_filters(flags_data: list[dict[str, Any]]) -> None:Order-independent: dependency and cohort extraction guard on ``_is_unevaluable``themselves.-- Not folded into ``serialize_feature_flags``, which- ``set_feature_flags_for_team_in_cache`` also uses to populate the separate- legacy ``team_feature_flags_{project_id}`` cache."""for flag in flags_data:if _is_unevaluable(flag):diff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.pyindex 6d7299e4be26..2e990746d2f1 100644--- a/products/feature_flags/backend/models/feature_flag.py+++ b/products/feature_flags/backend/models/feature_flag.py@@ -1,40 +1,28 @@import copy-import json-from functools import lru_cachefrom typing import TYPE_CHECKING, Any, Optionalfrom django.contrib.auth.base_user import AbstractBaseUserfrom django.contrib.postgres.aggregates import ArrayAgg-from django.core.cache import cachefrom django.core.exceptions import ValidationError-from django.db import DatabaseError, models, transaction+from django.db import DatabaseError, modelsfrom django.db.models import Func, IntegerField, Q, QuerySetfrom django.db.models.fields.json import KeyTransform-from django.db.models.signals import post_delete, post_savefrom django.http import HttpRequestfrom django.utils import timezone-import structlogfrom django_deprecate_fields import deprecate_field-from posthog.caching.flags_redis_cache import write_flags_to_cachefrom posthog.constants import ENRICHED_DASHBOARD_INSIGHT_IDENTIFIER-from posthog.exceptions_capture import capture_exceptionfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.file_system.constants import DEFAULT_SURFACEfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixinfrom posthog.models.file_system.file_system_representation import FileSystemRepresentationfrom posthog.models.property import GroupTypeIndex-from posthog.models.signals import mutable_receiverfrom posthog.models.utils import RootTeamManager, RootTeamMixin, RootTeamQuerySetfrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmptyfrom products.experiments.backend.models.experiment import live_experiment_exists-FIVE_DAYS = 60 * 60 * 24 * 5 # 5 days in seconds--logger = structlog.get_logger(__name__)-if TYPE_CHECKING:from django.db.models.fields.related_descriptors import RelatedManager@@ -509,13 +497,6 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, modelsreturn False-@mutable_receiver([post_save, post_delete], sender=FeatureFlag)-def refresh_flag_cache_on_updates(sender, instance, **kwargs):- # Defer cache update until after the transaction commits- # This ensures the database has the new data before we query it- transaction.on_commit(lambda: set_feature_flags_for_team_in_cache(instance.team.project_id))--class FeatureFlagHashKeyOverride(models.Model):# Can't use a foreign key to feature_flag_key directly, since# the unique constraint is on (team_id+key), and not just key.@@ -559,19 +540,17 @@ class FeatureFlagOverride(models.Model):def get_feature_flags(- team: Optional["Team"] = None,- project_id: Optional[int] = None,+ team: "Team",exclude_encrypted_payloads: bool = False,) -> list[FeatureFlag]:"""- Fetch FeatureFlag objects for a team or project.+ Fetch FeatureFlag objects for a team.Evaluation tags are always aggregated using ArrayAgg for performance.This avoids N+1 queries when serializing flags with evaluation tags.Args:- team: Team to get flags for (mutually exclusive with project_id)- project_id: Project ID to get flags for (mutually exclusive with team)+ team: Team to get flags forexclude_encrypted_payloads: If True, exclude flags withhas_encrypted_payloads=True. These flags can only be accessedvia the /remote_config endpoint, which handles decryption.@@ -581,21 +560,12 @@ def get_feature_flags(Returns:List of FeatureFlag model instances with evaluation tags pre-loaded"""- # Build query filter- filter_kwargs: dict[str, Any]- if team is not None:- filter_kwargs = {"team": team}- elif project_id is not None:- filter_kwargs = {"team__project_id": project_id}- else:- raise ValueError("Either team or project_id must be provided")-# Include disabled flags (active=False) so flag dependencies can reference them# and evaluate them as false, rather than raising DependencyNotFound errors.# Aggregate evaluation context names into a string array per flag in one query,# avoiding N+1 queries when serializing many flags.- qs = FeatureFlag.objects.filter(**filter_kwargs)+ qs = FeatureFlag.objects.filter(team=team)# Use .exclude() (not .filter(=False)) so legacy rows with NULL# has_encrypted_payloads remain included, matching prior behavior.@@ -644,78 +614,6 @@ def serialize_feature_flags(flags: list[FeatureFlag]) -> list[dict[str, Any]]:return list(serialized_data)-def set_feature_flags_for_team_in_cache(- project_id: int,-) -> list[FeatureFlag]:- # Fetch flags once (with evaluation contexts pre-loaded)- all_feature_flags = get_feature_flags(project_id=project_id)-- # Serialize for cache storage- serialized_flags = serialize_feature_flags(all_feature_flags)-- # Write to Redis cache- write_flags_to_cache(f"team_feature_flags_{project_id}", json.dumps(serialized_flags), FIVE_DAYS)-- return all_feature_flags---def get_feature_flags_for_team_in_cache(project_id: int) -> Optional[list[FeatureFlag]]:- try:- flag_data = cache.get(f"team_feature_flags_{project_id}")- except Exception:- logger.exception("Redis is unavailable")- return None-- if flag_data is not None:- try:- parsed_data = json.loads(flag_data)- 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.- return [f for f in flags if f.active]- except Exception as e:- logger.exception("Error parsing flags from cache")- capture_exception(e)- return None-- return 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 EvaluationFeatureFlagSerializer, which emits- SerializerMethodFields (e.g. `evaluation_contexts`, `has_experiment`) 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"))- # Preserve has_experiment so a cache-read flag answers without a per-flag experiment query.- flag._has_experiment = entry.get("has_experiment")- return flag--class FeatureFlagDashboards(models.Model):feature_flag = models.ForeignKey("FeatureFlag", on_delete=models.CASCADE)dashboard = models.ForeignKey("dashboards.Dashboard", on_delete=models.CASCADE)