: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
feat(flags): dual-write the flag definitions cache to the dedicated Redis (#95905)
James Gill8479995f15b2
diff --git a/docs/internal/feature-flags/hypercache-system.md b/docs/internal/feature-flags/hypercache-system.mdindex 3fc2b602df63..30b4677d0faf 100644--- a/docs/internal/feature-flags/hypercache-system.md+++ b/docs/internal/feature-flags/hypercache-system.md@@ -168,6 +168,9 @@ flag_definitions_hypercache = HyperCache(value="flags_with_cohorts.json",load_fn=lambda key: _get_flags_response_for_local_evaluation(HyperCache.team_from_key(key)),enable_etag=True,+ # Set only when FLAGS_REDIS_URL is configured. See "Dedicated flags Redis" below.+ cache_alias=FLAGS_DEDICATED_CACHE_ALIAS,+ secondary_cache_alias="default",)```@@ -324,6 +327,8 @@ redis-cli get "remote_config/{api_token}/config"redis-cli get "team_token:{api_token}"```+When `FLAGS_REDIS_URL` is set, the local-evaluation flags key is written to the dedicated instance and mirrored to the shared cache, so `redis-cli` returns whichever copy the cluster you point it at holds. The two can disagree. Read the flag-definitions notes under "Dedicated flags Redis" before you act on either copy.+### Check cache source in responsesLocal evaluation responses include cache source information via Prometheus metrics. Check the `posthog_hypercache_get_from_cache` metric with the appropriate labels.@@ -358,7 +363,9 @@ FLAGS_REDIS_URL=redis://flags-redis:6379 # Separate instance for flags```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.+Four HyperCache instances bind that alias. For flags (`products/feature_flags/backend/flags_cache.py`), remote config, and team metadata, Django writes to the dedicated instance and the Rust service reads them from it.++The SDK-facing flag-definitions cache (`local_evaluation.py`) is part-way through the same move, so its write side and read side currently point at different clusters. Django writes it to the dedicated instance and mirrors each write to the shared default cache, covering the payload, the ETag, and the cache-miss sentinel. Deletes mirror as well. The Rust `/flags/definitions` reader still reads the shared cache, so the shared copy is the one serving SDK traffic. A later change moves that reader to the dedicated instance, and the mirror is removed after it.The Rust service only operates when `FLAGS_REDIS_URL` is configured. All cache update functions check this setting and skip operations if not set.diff --git a/posthog/management/commands/verify_flag_definitions_cache.py b/posthog/management/commands/verify_flag_definitions_cache.pyindex d8fbca539b9b..d4b248354d1c 100644--- a/posthog/management/commands/verify_flag_definitions_cache.py+++ b/posthog/management/commands/verify_flag_definitions_cache.py@@ -4,6 +4,9 @@ Management command to verify flag definitions cache consistency.Compares cached flag definitions data against database to detect discrepancies.When --fix is used, the cache is updated to match the database.+IMPORTANT: This command requires FLAGS_REDIS_URL to be set. Without it, the command+prints an error and stops without verifying anything, to prevent misleading results.+Usage:# Verify all teamspython manage.py verify_flag_definitions_cache@@ -69,8 +72,10 @@ class Command(BaseHyperCacheCommand):self.stdout.write(f" Flag '{flag_key}': {diff_type}")def handle(self, *args, **options):- # No check_dedicated_cache_configured() needed — flag definitions use the- # default cache (REDIS_URL), not the dedicated flags cache (FLAGS_REDIS_URL).+ # Check if dedicated flags cache is configured (fail fast)+ if not self.check_dedicated_cache_configured():+ return+team_ids = options.get("team_ids")sample_size = options.get("sample")verbose = options.get("verbose", False)diff --git a/posthog/management/commands/warm_flag_definitions_cache.py b/posthog/management/commands/warm_flag_definitions_cache.pyindex 9a74242e4ace..432573d7c649 100644--- a/posthog/management/commands/warm_flag_definitions_cache.py+++ b/posthog/management/commands/warm_flag_definitions_cache.py@@ -1,6 +1,9 @@"""Management command to warm the flag definitions cache used for SDK local evaluation.+IMPORTANT: This command requires FLAGS_REDIS_URL to be set. It will error if the+dedicated flags cache is not configured to prevent warming the wrong cache.+Usage:# Initial cache warm (preserves existing caches)python manage.py warm_flag_definitions_cache@@ -25,8 +28,10 @@ class Command(BaseHyperCacheCommand):self.add_warm_arguments(parser)def handle(self, *args, **options):- # No check_dedicated_cache_configured() needed — flag definitions use the- # default cache (REDIS_URL), not the dedicated flags cache (FLAGS_REDIS_URL).+ # Check if dedicated flags cache is configured (fail fast)+ if not self.check_dedicated_cache_configured():+ return+team_ids = options.get("team_ids")batch_size = options["batch_size"]stagger_ttl = not options["no_stagger"]diff --git a/posthog/storage/hypercache.py b/posthog/storage/hypercache.pyindex ae85be7ca9a9..af6cbef38887 100644--- a/posthog/storage/hypercache.py+++ b/posthog/storage/hypercache.py@@ -87,6 +87,13 @@ HYPERCACHE_WRITE_SKIPPED_UNCHANGED_COUNTER = Counter(labelnames=["namespace", "value"],)+HYPERCACHE_MIRROR_FAILURE_COUNTER = Counter(+ "posthog_hypercache_mirror_failure",+ "Mirror operations to the secondary cache that failed. Mirror failures do not fail the "+ "write, so this counter is the only Prometheus signal that the secondary tier is drifting.",+ labelnames=["namespace", "value"],+)+CACHE_SYNC_DURATION_HISTOGRAM = Histogram("posthog_hypercache_sync_duration_seconds","Time taken to sync hypercache in seconds",@@ -210,7 +217,7 @@ class HyperCache:self.cache_client = cacheself.redis_url = settings.REDIS_URL- # Optional secondary cache; writes are mirrored on a best-effort basis.+ # Optional secondary cache; writes and deletes are mirrored on a best-effort basis.self.secondary_cache_client = (caches[secondary_cache_alias]if secondary_cache_alias and secondary_cache_alias in settings.CACHES@@ -396,6 +403,21 @@ class HyperCache:capture_exception(e)return None+ def _secondary_etag_matches(self, key: KeyType, etag: str) -> bool:+ """True when there is no secondary cache, or the secondary already holds this ETag.++ An unreadable secondary returns False so the caller writes instead of skipping;+ skipping on a failed read would leave a drifted mirror unrepaired.+ """+ if self.secondary_cache_client is None:+ return True+ try:+ return self.secondary_cache_client.get(self.get_etag_key(key)) == etag+ except _REDIS_READ_ERRORS as e:+ HYPERCACHE_MIRROR_FAILURE_COUNTER.labels(namespace=self.namespace, value=self.value).inc()+ capture_exception(e)+ return False+def get_if_none_match(self, key: KeyType, client_etag: str | None) -> tuple[dict | None, str | None, bool]:"""Check if client's ETag matches current cache, enabling HTTP 304 responses.@@ -529,7 +551,11 @@ class HyperCache:json_data: str | None = Noneif skip_if_unchanged and self.enable_etag and isinstance(data, dict):json_data = json.dumps(data, sort_keys=True)- if self._compute_etag(json_data) == self.get_etag(key):+ etag = self._compute_etag(json_data)+ # Skip only when every tier is current. A failed mirror write leaves the+ # secondary on the old payload, and a primary-only ETag comparison would then+ # skip every identical rebuild until the secondary's TTL expires.+ if etag == self.get_etag(key) and self._secondary_etag_matches(key, etag):HYPERCACHE_WRITE_SKIPPED_UNCHANGED_COUNTER.labels(namespace=self.namespace, value=self.value).inc()return len(json_data)size = self._set_cache_value_redis(key, data, ttl=ttl, json_data=json_data)@@ -581,24 +607,34 @@ class HyperCache:"""kinds = kinds or ["redis", "s3"]try:+ cache_key = self.get_cache_key(key)if "redis" in kinds:- self.cache_client.delete(self.get_cache_key(key))- # Always delete ETag key to clean up stale ETags from when enable_etag was True- self.cache_client.delete(self.get_etag_key(key))+ # One DEL per cache drops the payload and its ETag together. A reader that+ # checks the ETag first would otherwise answer 304 for a payload that is+ # already gone. The ETag key goes even when enable_etag is off, to clear a+ # stale ETag from when it was on.+ redis_keys = [cache_key, self.get_etag_key(key)]+ # Mirror the delete so the secondary never serves an entry the primary dropped,+ # and mirror first so a primary failure cannot block it.+ self._mirror_to_secondary(lambda c: c.delete_many(redis_keys))+ self.cache_client.delete_many(redis_keys)if "s3" in kinds and self.s3_enabled:- object_storage.delete(self.get_cache_key(key))+ object_storage.delete(cache_key)finally:self._remove_expiry_tracking(key)def _mirror_to_secondary(self, op: Callable[..., None]) -> None:- """Best-effort mirror write; failures are logged and captured, never propagated."""+ """Best-effort mirror op; failures are logged and captured, never propagated."""if self.secondary_cache_client is None:returntry:op(self.secondary_cache_client)except Exception as e:+ HYPERCACHE_MIRROR_FAILURE_COUNTER.labels(namespace=self.namespace, value=self.value).inc()+ # The traceback names the calling frame, which says whether a set or a+ # delete failed more precisely than a label could.logger.warning(- "HyperCache secondary cache write failed",+ "HyperCache secondary cache op failed",namespace=self.namespace,value=self.value,exc_info=True,@@ -622,12 +658,14 @@ class HyperCache:"""cache_key = self.get_cache_key(key)etag_key = self.get_etag_key(key)+ # Mirror before the primary write. During a dual-write migration the secondary can+ # be the tier the live reader serves from, so a primary failure must not block it.if data is None or isinstance(data, HyperCacheStoreMissing):- self.cache_client.set(cache_key, _HYPER_CACHE_EMPTY_VALUE, timeout=self.cache_miss_ttl)self._mirror_to_secondary(lambda c: c.set(cache_key, _HYPER_CACHE_EMPTY_VALUE, timeout=self.cache_miss_ttl))+ self._mirror_to_secondary(lambda c: c.delete(etag_key))+ self.cache_client.set(cache_key, _HYPER_CACHE_EMPTY_VALUE, timeout=self.cache_miss_ttl)# Always delete ETag key to clean up stale ETags from when enable_etag was Trueself.cache_client.delete(etag_key)- self._mirror_to_secondary(lambda c: c.delete(etag_key))return Noneelse:timeout = ttl if ttl is not None else self.cache_ttl@@ -636,16 +674,16 @@ class HyperCache:json_data = json.dumps(data, sort_keys=True)if self.enable_etag:etag = self._compute_etag(json_data)+ self._mirror_to_secondary(lambda c: c.set_many({cache_key: json_data, etag_key: etag}, timeout=timeout))# Write data and ETag via pipeline (single Redis round trip)# Note this is not strictly atomic, but good enough for our use caseself.cache_client.set_many({cache_key: json_data, etag_key: etag}, timeout=timeout)- self._mirror_to_secondary(lambda c: c.set_many({cache_key: json_data, etag_key: etag}, timeout=timeout))else:- self.cache_client.set(cache_key, json_data, timeout=timeout)self._mirror_to_secondary(lambda c: c.set(cache_key, json_data, timeout=timeout))+ self._mirror_to_secondary(lambda c: c.delete(etag_key))+ self.cache_client.set(cache_key, json_data, timeout=timeout)# Clean up stale ETag if ETags were previously enabledself.cache_client.delete(etag_key)- self._mirror_to_secondary(lambda c: c.delete(etag_key))return len(json_data)def _set_cache_value_s3(self, key: KeyType, data: dict | None | HyperCacheStoreMissing, ttl: Optional[int] = None):diff --git a/posthog/storage/test/test_hypercache.py b/posthog/storage/test/test_hypercache.pyindex 00802dfd2554..592570853198 100644--- a/posthog/storage/test/test_hypercache.py+++ b/posthog/storage/test/test_hypercache.py@@ -11,6 +11,7 @@ import redis.exceptionsfrom botocore.exceptions import BotoCoreError, ClientErrorfrom django_redis.exceptions import ConnectionInterruptedfrom parameterized import parameterized+from prometheus_client import REGISTRYfrom posthog.models.team.team import Teamfrom posthog.storage import object_storage@@ -729,9 +730,16 @@ class TestHyperCacheSecondaryCache(BaseTest):broken.set.side_effect = RuntimeError("secondary down")broken.set_many.side_effect = RuntimeError("secondary down")broken.delete.side_effect = RuntimeError("secondary down")+ broken.delete_many.side_effect = RuntimeError("secondary down")hc.secondary_cache_client = broken# Must not raise.+ failures_before = (+ REGISTRY.get_sample_value(+ "posthog_hypercache_mirror_failure_total", {"namespace": "test", "value": "value"}+ )+ or 0+ )hc.set_cache_value(team_id, self.sample_data)# Primary cache still got the write.@@ -742,6 +750,109 @@ class TestHyperCacheSecondaryCache(BaseTest):# The broken secondary received the write attempt.broken.set.assert_called()+ # A swallowed mirror failure must still be countable, or the secondary drifts silently.+ failures_after = REGISTRY.get_sample_value(+ "posthog_hypercache_mirror_failure_total", {"namespace": "test", "value": "value"}+ )+ assert failures_after is not None and failures_after > failures_before++ # The mirrored delete must also swallow the failure and still drop the primary entry.+ hc.delete_cache_entry(team_id, kinds=["redis"])+ broken.delete_many.assert_called()+ assert caches["flags_dedicated"].get(cache_key) is None++ @parameterized.expand([("etag", True), ("no_etag", False)])+ @override_settings(+ CACHES={+ "default": {+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",+ "LOCATION": "default-primary-failure-test-cache",+ },+ "flags_dedicated": {+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",+ "LOCATION": "flags-dedicated-primary-failure-test-cache",+ },+ }+ )+ def test_primary_failure_does_not_block_mirror(self, _name, enable_etag):+ from django.core.cache import caches++ caches["default"].clear()+ caches["flags_dedicated"].clear()++ hc = HyperCache(+ namespace="test",+ value="value",+ load_fn=lambda team: self.sample_data,+ cache_alias="flags_dedicated",+ secondary_cache_alias="default",+ enable_etag=enable_etag,+ )++ team_id = self.team.id++ # The mirror can be the tier the live reader serves from during a migration,+ # so a primary outage must not stop the mirror write or the mirror delete.+ broken_primary = Mock()+ broken_primary.set.side_effect = RuntimeError("primary down")+ broken_primary.set_many.side_effect = RuntimeError("primary down")+ broken_primary.delete.side_effect = RuntimeError("primary down")+ broken_primary.delete_many.side_effect = RuntimeError("primary down")+ hc.cache_client = broken_primary++ with pytest.raises(RuntimeError):+ hc.set_cache_value(team_id, self.sample_data)++ cache_key = hc.get_cache_key(team_id)+ assert caches["default"].get(cache_key) == json.dumps(self.sample_data, sort_keys=True)++ with pytest.raises(RuntimeError):+ hc.delete_cache_entry(team_id, kinds=["redis"])+ assert caches["default"].get(cache_key) is None+ assert caches["default"].get(hc.get_etag_key(team_id)) is None++ @override_settings(+ CACHES={+ "default": {+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",+ "LOCATION": "default-secondary-delete-test-cache",+ },+ "flags_dedicated": {+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",+ "LOCATION": "flags-dedicated-secondary-delete-test-cache",+ },+ }+ )+ def test_delete_removes_entry_from_both_caches(self):+ from django.core.cache import caches++ caches["default"].clear()+ caches["flags_dedicated"].clear()++ hc = HyperCache(+ namespace="test",+ value="value",+ load_fn=lambda team: self.sample_data,+ cache_alias="flags_dedicated",+ secondary_cache_alias="default",+ enable_etag=True,+ )++ team_id = self.team.id+ hc.set_cache_value(team_id, self.sample_data)++ cache_key = hc.get_cache_key(team_id)+ etag_key = hc.get_etag_key(team_id)+ assert caches["default"].get(cache_key) is not None+ assert caches["default"].get(etag_key) is not None++ hc.delete_cache_entry(team_id, kinds=["redis"])++ assert caches["flags_dedicated"].get(cache_key) is None+ assert caches["flags_dedicated"].get(etag_key) is None+ assert caches["default"].get(cache_key) is None+ assert caches["default"].get(etag_key) is None+def test_unknown_secondary_alias_falls_back_to_no_op(self):"""A secondary_cache_alias not in settings.CACHES is silently ignored."""@@ -1313,7 +1424,7 @@ class TestHyperCacheRemoveExpiryTracking(BaseTest):hc = self._make_hypercache(token_based=False)hc.cache_client = Mock()- hc.cache_client.delete.side_effect = ConnectionError("Redis unavailable")+ hc.cache_client.delete_many.side_effect = ConnectionError("Redis unavailable")with pytest.raises(ConnectionError):hc.clear_cache(42)@@ -1470,6 +1581,63 @@ class TestHyperCacheSkipIfUnchanged(BaseTest):# The stored ETag is untouched, so readers comparing ETags won't refetch.assert hc.get_etag(self.team.id) == etag_before+ @override_settings(+ CACHES={+ "default": {+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",+ "LOCATION": "skip-secondary-default-test-cache",+ },+ "flags_dedicated": {+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",+ "LOCATION": "skip-secondary-dedicated-test-cache",+ },+ }+ )+ def test_stale_secondary_defeats_the_skip_and_gets_repaired(self):+ from django.core.cache import caches++ caches["default"].clear()+ caches["flags_dedicated"].clear()++ hc = HyperCache(+ namespace="skip_ns",+ value="skip_value",+ load_fn=lambda team: {"default": "data"},+ enable_etag=True,+ expiry_sorted_set_key="skip_ns_expiry",+ cache_alias="flags_dedicated",+ secondary_cache_alias="default",+ )+ cache_key = hc.get_cache_key(self.team.id)+ etag_key = hc.get_etag_key(self.team.id)++ with patch.object(hc, "_set_cache_value_s3"):+ hc.set_cache_value(self.team.id, self.sample_data, skip_if_unchanged=True)++ # Simulate a mirror write that failed: the secondary is missing the entry+ # while the primary ETag matches the rebuild. The primary comparison alone+ # would skip here, and the secondary would stay un-repaired until its TTL.+ caches["default"].delete(cache_key)+ caches["default"].delete(etag_key)++ hc.set_cache_value(self.team.id, self.sample_data, skip_if_unchanged=True)+ assert caches["default"].get(cache_key) == json.dumps(self.sample_data, sort_keys=True)+ assert caches["default"].get(etag_key) is not None++ # With both tiers current again, the identical rebuild skips.+ with patch.object(hc, "_set_cache_value_redis", wraps=hc._set_cache_value_redis) as redis_write:+ hc.set_cache_value(self.team.id, self.sample_data, skip_if_unchanged=True)+ redis_write.assert_not_called()++ # An unreadable secondary must also defeat the skip: a failed read reports+ # False, so the rebuild writes instead of skipping past possible drift.+ with (+ patch.object(hc.secondary_cache_client, "get", side_effect=ConnectionError("secondary read down")),+ patch.object(hc, "_set_cache_value_redis", wraps=hc._set_cache_value_redis) as redis_write,+ ):+ hc.set_cache_value(self.team.id, self.sample_data, skip_if_unchanged=True)+ redis_write.assert_called_once()+def test_changed_write_reuses_serialization_correctly(self):"""When the content changed, the skip path's serialization is threaded into the Rediswrite instead of re-dumped; the stored value and ETag must still match the new payload."""diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.pyindex eaf507c18385..f8e99761a532 100644--- a/products/feature_flags/backend/local_evaluation.py+++ b/products/feature_flags/backend/local_evaluation.py@@ -32,6 +32,7 @@ import structlogfrom posthoganalytics import capture_exceptionfrom prometheus_client import Counter+from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIASfrom posthog.models.group_type_mapping import (GROUP_TYPES_STALE_CACHE_KEY_PREFIX,GroupTypesUnavailable,@@ -400,16 +401,25 @@ def _load_flag_definitions_with_cohorts(key: KeyType) -> dict[str, Any]:return _get_flags_response_for_local_evaluation(HyperCache.team_from_key(key))-flag_definitions_hypercache = HyperCache(- namespace="feature_flags",- value="flags_with_cohorts.json",- load_fn=_load_flag_definitions_with_cohorts,- cache_ttl=settings.FLAGS_CACHE_TTL,- cache_miss_ttl=settings.FLAGS_CACHE_MISS_TTL,- batch_load_fn=lambda teams: _get_flags_response_for_local_evaluation_batch(teams),- enable_etag=True,- expiry_sorted_set_key=FLAG_DEFINITIONS_CACHE_EXPIRY_SORTED_SET,-)+def _build_flag_definitions_hypercache() -> HyperCache:+ has_dedicated_cache = FLAGS_DEDICATED_CACHE_ALIAS in settings.CACHES+ return HyperCache(+ namespace="feature_flags",+ value="flags_with_cohorts.json",+ load_fn=_load_flag_definitions_with_cohorts,+ cache_ttl=settings.FLAGS_CACHE_TTL,+ cache_miss_ttl=settings.FLAGS_CACHE_MISS_TTL,+ batch_load_fn=lambda teams: _get_flags_response_for_local_evaluation_batch(teams),+ enable_etag=True,+ expiry_sorted_set_key=FLAG_DEFINITIONS_CACHE_EXPIRY_SORTED_SET,+ cache_alias=FLAGS_DEDICATED_CACHE_ALIAS if has_dedicated_cache else None,+ # Mirror to the shared Redis while the /flags/definitions reader still reads+ # from it.+ secondary_cache_alias="default" if has_dedicated_cache else None,+ )+++flag_definitions_hypercache = _build_flag_definitions_hypercache()def _resolve_team(team: Team | int) -> Team | None:diff --git a/products/feature_flags/backend/rebuild_queue.py b/products/feature_flags/backend/rebuild_queue.pyindex c76bc4027d5e..e59b39da91c7 100644--- a/products/feature_flags/backend/rebuild_queue.py+++ b/products/feature_flags/backend/rebuild_queue.py@@ -19,6 +19,8 @@ DB round (like the verifier) rather than per team.import time+from django.conf import settings+import redis as redis_libimport structlogfrom celery.exceptions import SoftTimeLimitExceeded@@ -87,9 +89,10 @@ def _parse_team_id(raw: bytes | str) -> int | None:def _redis() -> redis_lib.Redis:- # Derive from the HyperCache itself, not a standalone constant, so the queue can- # never read a different Redis than the cache it heals.- return get_client(flag_definitions_hypercache.redis_url)+ # Pinned to the shared Redis, matching the Rust producer. The hypercache's+ # redis_url follows cache_alias, which binds the dedicated cluster, so the+ # producer and consumer must move together or not at all.+ return get_client(settings.REDIS_URL)def drain_rebuild_requests(batch_size: int = DRAIN_BATCH_SIZE) -> dict[str, int]:diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.pyindex 457db49bbcd2..b92b7b132e72 100644--- a/products/feature_flags/backend/test/test_local_evaluation.py+++ b/products/feature_flags/backend/test/test_local_evaluation.py@@ -2,11 +2,13 @@ from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patchfrom django.conf import settings+from django.core.cache import cache, cachesfrom django.db import DatabaseErrorfrom django.test import override_settingsfrom parameterized import parameterized+from posthog.caching.flags_redis_cache import FLAGS_DEDICATED_CACHE_ALIASfrom posthog.models.group_type_mapping import GROUP_TYPES_STALE_CACHE_KEY_PREFIX, GroupTypesUnavailablefrom posthog.models.project import Projectfrom posthog.models.tag import Tag@@ -22,6 +24,7 @@ from products.feature_flags.backend.cache_keys import EU_CROSS_REGION_MIRROR_CACfrom products.feature_flags.backend.flags_cache import get_team_ids_with_recently_updated_flagsfrom products.feature_flags.backend.local_evaluation import (FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG,+ _build_flag_definitions_hypercache,_extract_cohort_ids_from_filters,_get_flags_response_for_local_evaluation,_get_flags_response_for_local_evaluation_batch,@@ -1410,6 +1413,39 @@ class TestFlagDefinitionsCache(BaseTest):# underlying flags were just updated and whose async rebuild is still in flight.assert config.get_team_ids_to_skip_fix_fn == get_team_ids_with_recently_updated_flags+ def test_hypercache_mirrors_writes_to_shared_cache_when_dedicated_alias_registered(self):+ # HyperCache.__init__ reads CACHES[alias]["LOCATION"] for its writer URL;+ # the in-memory backend ignores the stub value.+ with override_settings(+ CACHES={+ "default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"},+ FLAGS_DEDICATED_CACHE_ALIAS: {+ "BACKEND": "django.core.cache.backends.locmem.LocMemCache",+ "LOCATION": "redis://stub:6379/",+ },+ }+ ):+ hypercache = _build_flag_definitions_hypercache()+ assert hypercache.cache_client is caches[FLAGS_DEDICATED_CACHE_ALIAS]+ assert hypercache.secondary_cache_client is caches["default"]++ hypercache.set_cache_value_redis_only(self.team.id, {"flags": [], "v": 1})++ cache_key = hypercache.get_cache_key(self.team.id)+ etag_key = hypercache.get_etag_key(self.team.id)+ dedicated_value = caches[FLAGS_DEDICATED_CACHE_ALIAS].get(cache_key)+ assert dedicated_value is not None+ assert caches["default"].get(cache_key) == dedicated_value+ dedicated_etag = caches[FLAGS_DEDICATED_CACHE_ALIAS].get(etag_key)+ assert dedicated_etag is not None+ assert caches["default"].get(etag_key) == dedicated_etag++ def test_hypercache_uses_default_cache_without_mirror_when_alias_absent(self):+ with override_settings(CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}):+ hypercache = _build_flag_definitions_hypercache()+ assert hypercache.cache_client is cache+ assert hypercache.secondary_cache_client is None+def test_update_flag_definitions_cache_returns_false_on_failure(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.pyindex 88084f1763f7..0105b2791f95 100644--- a/products/feature_flags/backend/test/test_rebuild_queue.py+++ b/products/feature_flags/backend/test/test_rebuild_queue.py@@ -5,6 +5,8 @@ from types import SimpleNamespaceimport pytestfrom unittest.mock import patch+from django.conf import settings+import fakeredisfrom celery.exceptions import SoftTimeLimitExceededfrom prometheus_client import REGISTRY@@ -196,3 +198,17 @@ def test_request_zset_key_matches_rust_contract():# Tripwire for the hand-synced cross-language key: a Python-side rename trips here# and prompts updating FLAG_DEFINITIONS_REBUILD_REQUESTS_ZSET in the Rust service.assert REBUILD_REQUESTS_ZSET == "flag_definitions:rebuild_requests"+++def test_redis_client_pinned_to_the_shared_cluster():+ # The Rust producer enqueues on the shared Redis. Deriving the consumer's client+ # from the hypercache (whose cache_alias binds the dedicated cluster) splits the+ # queue: the drain reads an empty set while misses pile up unseen on the shared one.+ # The hypercache URL is forced to differ because in test settings it equals+ # settings.REDIS_URL, and equal URLs cannot detect a revert of the pin.+ with (+ patch.object(rebuild_queue.flag_definitions_hypercache, "redis_url", "redis://dedicated:6379/"),+ patch.object(rebuild_queue, "get_client") as get_client_mock,+ ):+ rebuild_queue._redis()+ get_client_mock.assert_called_once_with(settings.REDIS_URL)