: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
fix(flags): key the EU flags mirror with a sentinel cache key (#72042)
Phil Haack3eda4bf848a0
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 0860b643af38..6303c6853770 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -88,7 +88,7 @@ from products.feature_flags.backend.tasks import (feature_flags_local_eval_canary_task,refresh_expiring_flag_definitions_cache_entries,refresh_expiring_flags_cache_entries,- sync_cross_region_dogfood_flags_task,+ sync_cross_region_flags_task,)from products.logs.backend.facade.tasks import logs_alert_events_cleanup_taskfrom products.pulse.backend.tasks import mark_stale_pulse_briefs_failed@@ -375,7 +375,7 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:expires_seconds=5 * 60,)- # Cross-region dogfood flags sync (EU only) - every 30s, matching the SDK's+ # Cross-region flags sync (EU only) - every 30s, matching the SDK's# own default poll_interval so EU's local-eval freshness matches what a# customer backend gets. Raw interval is safe here (sub-minute; see the# warning on add_periodic_task_with_expiry above). Registered only in EU so@@ -385,8 +385,8 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:if get_instance_region() == "EU":sender.add_periodic_task(30,- sync_cross_region_dogfood_flags_task.s(),- name="cross-region dogfood flags sync",+ sync_cross_region_flags_task.s(),+ name="cross-region flags sync",expires=30,)diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.pyindex b1dd0b68b2de..f6201925a396 100644--- a/posthog/test/test_utils.py+++ b/posthog/test/test_utils.py@@ -60,6 +60,9 @@ from posthog.utils import (variables_override_requested_by_client,)+from products.feature_flags.backend.cache_keys import EU_CROSS_REGION_MIRROR_CACHE_KEY+from products.feature_flags.backend.local_evaluation import flag_definitions_hypercache+class TestAbsoluteUrls(TestCase):def test_format_absolute_url(self) -> None:@@ -1331,6 +1334,7 @@ class TestBuildFlagProvider(TestCase):# create is the first one. Cascade deletes roll back with the test transaction.User.objects.all().delete()Organization.objects.all().delete()+ flag_definitions_hypercache.clear_cache(EU_CROSS_REGION_MIRROR_CACHE_KEY, kinds=["redis", "s3"])@patch.dict(os.environ, {"POSTHOG_SELF_TEAM_ID": "5"}, clear=False)@override_settings(SELF_CAPTURE=True, E2E_TESTING=False)@@ -1346,12 +1350,22 @@ class TestBuildFlagProvider(TestCase):assert _build_flag_provider()._resolve_team_id() == first_team.id+ @parameterized.expand(+ [+ (None, 2),+ ("US", 2),+ ("EU", EU_CROSS_REGION_MIRROR_CACHE_KEY),+ ]+ )@patch.dict(os.environ, {}, clear=False)- @override_settings(SELF_CAPTURE=False, E2E_TESTING=False)- def test_falls_back_to_team_2_off_self_capture(self):+ def test_cloud_routes_by_region(self, cloud_deployment: str | None, expected_key: int | str) -> None:+ # EU has no Postgres rows for PostHog's own team, so it must read the+ # sentinel-keyed mirror that cross_region_flag_sync writes, not literal team+ # id 2 -- which on EU belongs to a real, unrelated team. Every other region+ # falls back to the canonical PostHog-internal team 2.os.environ.pop("POSTHOG_SELF_TEAM_ID", None)-- assert _build_flag_provider()._resolve_team_id() == 2+ with override_settings(SELF_CAPTURE=False, E2E_TESTING=False, CLOUD_DEPLOYMENT=cloud_deployment):+ assert _build_flag_provider()._resolve_team_id() == expected_key@patch.dict(os.environ, {}, clear=False)@override_settings(SELF_CAPTURE=True, E2E_TESTING=True)@@ -1360,6 +1374,22 @@ class TestBuildFlagProvider(TestCase):assert _build_flag_provider()._resolve_team_id() == 2+ @patch.dict(os.environ, {}, clear=False)+ @override_settings(SELF_CAPTURE=False, E2E_TESTING=False, CLOUD_DEPLOYMENT="EU")+ def test_eu_region_provider_reads_back_payload_written_under_sentinel_key(self):+ os.environ.pop("POSTHOG_SELF_TEAM_ID", None)+ payload = {"flags": [{"key": "mirrored-flag"}], "group_type_mapping": {}, "cohorts": {}}+ flag_definitions_hypercache.set_cache_value(EU_CROSS_REGION_MIRROR_CACHE_KEY, payload)++ definitions = _build_flag_provider().get_flag_definitions()+ assert definitions is not None+ assert dict(definitions) == payload++ @patch.dict(os.environ, {"POSTHOG_SELF_TEAM_ID": "5"}, clear=False)+ @override_settings(SELF_CAPTURE=False, E2E_TESTING=False, CLOUD_DEPLOYMENT="EU")+ def test_explicit_env_team_id_wins_over_eu_region(self):+ assert _build_flag_provider()._resolve_team_id() == 5+VALID_PRELOAD_MANIFEST = {"css": "static/index-ABC123.css",diff --git a/posthog/utils.py b/posthog/utils.pyindex 05fc0257fe8b..9cef011c7f33 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -816,6 +816,9 @@ def _build_flag_provider() -> "HyperCacheFlagProvider":initialize_self_capture_api_token() (ASGI). Callers assign the result toposthoganalytics.flag_definition_cache_provider and handle loading themselves."""+ from products.feature_flags.backend.cache_keys import (+ EU_CROSS_REGION_MIRROR_CACHE_KEY, # noqa: PLC0415 — this core module doesn't otherwise depend on product code+ )from products.feature_flags.backend.sdk_cache_provider import ( # noqa: PLC0415 — keeps the heavy dep off the import pathHyperCacheFlagProvider,)@@ -832,7 +835,11 @@ def _build_flag_provider() -> "HyperCacheFlagProvider":# Intentionally the FIRST team, not self-capture's current_team — see# resolve_dogfood_flags_team().return HyperCacheFlagProvider.for_dynamic_resolution(get_dogfood_flags_team_id)- # Cloud (SELF_CAPTURE off) or E2E: the canonical PostHog-internal team is 2.+ if get_instance_region() == "EU":+ # EU has no rows for PostHog's own team — reads go to the sentinel-keyed+ # mirror that cross_region_flag_sync writes (see the key's definition).+ return HyperCacheFlagProvider.for_static_team(EU_CROSS_REGION_MIRROR_CACHE_KEY)+ # Cloud (SELF_CAPTURE off) or E2E, non-EU: the canonical PostHog-internal team is 2.return HyperCacheFlagProvider.for_static_team(2)diff --git a/products/feature_flags/backend/cache_keys.py b/products/feature_flags/backend/cache_keys.pynew file mode 100644index 000000000000..d9efcc89d161--- /dev/null+++ b/products/feature_flags/backend/cache_keys.py@@ -0,0 +1,8 @@+# Cache key for cross_region_flag_sync's EU mirror of PostHog's own (US team 2) flag+# definitions. Deliberately non-numeric — a real Team.id is always an int, so this can+# never collide with a real team's key in flag_definitions_hypercache's per-team keyspace.+# Lives in its own leaf module (no imports of its own) so both sdk_cache_provider.py and+# local_evaluation.py can depend on it without either depending on the other — importing+# it never triggers the circular import chain that local_evaluation.py's own import does+# (see sdk_cache_provider._get_hypercache).+EU_CROSS_REGION_MIRROR_CACHE_KEY = "cross-region-flags-mirror"diff --git a/products/feature_flags/backend/cross_region_flag_sync.py b/products/feature_flags/backend/cross_region_flag_sync.pyindex 7586f2bed8d0..59f7c4e6d8f3 100644--- a/products/feature_flags/backend/cross_region_flag_sync.py+++ b/products/feature_flags/backend/cross_region_flag_sync.py@@ -1,19 +1,21 @@"""-Cross-region sync of the dogfood team's (team 2) flag definitions into EU's+Cross-region sync of PostHog's own (team 2) flag definitions into EU'sHyperCache.Every other team's `flag_definitions_hypercache` entry is rebuilt locally byDjango signals reading straight from Postgres (see local_evaluation.py). Team 2--- PostHog's internal "self" team, used for our own dogfooded local evaluation+-- PostHog's internal "self" team, used for our own local evaluation-- lives only in the US Postgres, so EU has no rows to build it from. Ratherthan have every EU pod poll the US API directly (which HyperCache exists toavoid), a single periodic task fetches team 2's flag definitions from the USregion's authenticated `/flags/definitions` endpoint and writes the result-straight into EU's HyperCache, so every EU pod still reads from the shared-cache with zero per-pod polling.+into EU's HyperCache under EU_CROSS_REGION_MIRROR_CACHE_KEY — a string+sentinel, because EU allocates team ids independently of US and a numeric key+would collide with a real EU team's entry. Every EU pod still reads from the+shared cache with zero per-pod polling.No-op on US, where team 2's HyperCache entry is already populated by the-normal signal-driven path.+normal signal-driven path under its real team id."""from django.conf import settings@@ -24,14 +26,11 @@ from posthoganalytics.request import US_INGESTION_ENDPOINTfrom posthog.utils import capture_exception_throttled, get_instance_region+from products.feature_flags.backend.cache_keys import EU_CROSS_REGION_MIRROR_CACHE_KEYfrom products.feature_flags.backend.local_evaluation import flag_definitions_hypercachelogger = structlog.get_logger(__name__)-# PostHog's own internal "self" team, canonically team 2 (see _build_flag_provider-# in posthog/utils.py). Only its US Postgres rows are authoritative.-DOGFOOD_SELF_TEAM_ID = 2-_FLAGS_DEFINITIONS_PATH = "/flags/definitions"_REQUEST_TIMEOUT_SECONDS = (3, 10) # (connect, read)@@ -39,12 +38,12 @@ _REQUEST_TIMEOUT_SECONDS = (3, 10) # (connect, read)# unexpected request error) to PostHog error tracking, shared across the 30s schedule# so a sustained outage reports once per window instead of once per tick. Expected# transient network blips (connection/timeout/proxy errors) are logged, not captured.-_SYNC_FAILURE_CAPTURE_THROTTLE_KEY = "cross_region_dogfood_flags_sync_capture_throttle"+_SYNC_FAILURE_CAPTURE_THROTTLE_KEY = "cross_region_flags_sync_capture_throttle"_SYNC_FAILURE_CAPTURE_THROTTLE_TTL = 300 # seconds-def sync_cross_region_dogfood_flags() -> None:- """Refresh team 2's flag-definitions HyperCache entry in EU from the US region.+def sync_cross_region_flags() -> None:+ """Refresh EU's mirror of US team 2's flag definitions from the US region.No-op outside EU or when the PSAK isn't configured. Uses the endpoint's ETagsupport: sends `If-None-Match` with the locally cached ETag, so an unchanged@@ -57,11 +56,11 @@ def sync_cross_region_dogfood_flags() -> None:token = settings.POSTHOG_FLAGS_PROJECT_SECRET_TOKENif not token:- logger.debug("cross_region_dogfood_flags_sync_no_token")+ logger.debug("cross_region_flags_sync_no_token")returnheaders = {"Authorization": f"Bearer {token}"}- local_etag = flag_definitions_hypercache.get_etag(DOGFOOD_SELF_TEAM_ID)+ local_etag = flag_definitions_hypercache.get_etag(EU_CROSS_REGION_MIRROR_CACHE_KEY)if local_etag:headers["If-None-Match"] = f'"{local_etag}"'@@ -79,7 +78,7 @@ def sync_cross_region_dogfood_flags() -> None:returnexcept requests.RequestException as e:capture_exception_throttled(_SYNC_FAILURE_CAPTURE_THROTTLE_KEY, e, _SYNC_FAILURE_CAPTURE_THROTTLE_TTL)- logger.warning("cross_region_dogfood_flags_sync_request_failed", error=str(e))+ logger.warning("cross_region_flags_sync_request_failed", error=str(e))returnif response.status_code == 304:@@ -87,7 +86,7 @@ def sync_cross_region_dogfood_flags() -> None:if response.status_code != 200:logger.warning(- "cross_region_dogfood_flags_sync_bad_status",+ "cross_region_flags_sync_bad_status",status_code=response.status_code,)return@@ -96,21 +95,21 @@ def sync_cross_region_dogfood_flags() -> None:payload = response.json()except ValueError as e:capture_exception_throttled(_SYNC_FAILURE_CAPTURE_THROTTLE_KEY, e, _SYNC_FAILURE_CAPTURE_THROTTLE_TTL)- logger.warning("cross_region_dogfood_flags_sync_bad_json")+ logger.warning("cross_region_flags_sync_bad_json")returnif not isinstance(payload, dict):# A malformed-but-valid-JSON body (e.g. null, a list) would otherwise be cached# verbatim and served to every EU pod until the next successful sync.- logger.warning("cross_region_dogfood_flags_sync_unexpected_shape", payload_type=type(payload).__name__)+ logger.warning("cross_region_flags_sync_unexpected_shape", payload_type=type(payload).__name__)return# update_cache (not bare set_cache_value) for parity with the signal-driven write# path: it emits the cache-sync metrics dashboards watch, and its info log only# fires when flags actually changed, since unchanged upstreams 304 above. The# write is unconditional (no skip_if_unchanged): a 200 already means the content- # changed, and a bare int key isn't tracked in the expiry sorted set (unlike a- # Team key), so this write is what re-stamps the Redis TTL. On a long run of 304s- # the entry can still expire; that self-heals within one tick, because the etag- # expires with it, so the next poll sends no If-None-Match and gets a full 200.- flag_definitions_hypercache.update_cache(DOGFOOD_SELF_TEAM_ID, data=payload)+ # changed, and a non-Team key isn't tracked in the expiry sorted set, so this+ # write is what re-stamps the Redis TTL. On a long run of 304s the entry can+ # still expire; that self-heals within one tick, because the etag expires with+ # it, so the next poll sends no If-None-Match and gets a full 200.+ flag_definitions_hypercache.update_cache(EU_CROSS_REGION_MIRROR_CACHE_KEY, data=payload)diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.pyindex ab3a86bc66cf..d2d3b6ed66f8 100644--- a/products/feature_flags/backend/local_evaluation.py+++ b/products/feature_flags/backend/local_evaluation.py@@ -39,13 +39,20 @@ from posthog.models.group_type_mapping import (project_has_group_types_authoritatively,)from posthog.models.team import Team-from posthog.storage.hypercache import HYPERCACHE_REBUILD_SKIPPED_COUNTER, HyperCache, KeyType, emit_cache_sync_metrics+from posthog.storage.hypercache import (+ HYPERCACHE_REBUILD_SKIPPED_COUNTER,+ HyperCache,+ HyperCacheDependencyUnavailable,+ KeyType,+ emit_cache_sync_metrics,+)from posthog.storage.hypercache_manager import HyperCacheManagementConfigfrom posthog.utils import capture_exception_throttled, get_safe_cachefrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty, is_cohort_recalculation_only_savefrom products.cohorts.backend.models.util import get_nested_cohort_idsfrom products.experiments.backend.models.experiment import Experiment, live_experiment_exists+from products.feature_flags.backend.cache_keys import EU_CROSS_REGION_MIRROR_CACHE_KEYfrom products.feature_flags.backend.flags_cache import (_compare_flag_fields,get_team_ids_with_recently_updated_flags,@@ -377,10 +384,22 @@ DATABASE_FOR_LOCAL_EVALUATION = (else "replica")++def _load_flag_definitions_with_cohorts(key: KeyType) -> dict[str, Any]:+ if key == EU_CROSS_REGION_MIRROR_CACHE_KEY:+ # No DB row backs this key — it's a pure cache mirror written only by+ # cross_region_flag_sync's periodic task. A cold cache should wait for the+ # next sync tick, not attempt (and fail) a Team lookup. Raising (rather than+ # returning HyperCacheStoreMissing) avoids caching a day-long miss sentinel+ # and deleting the ETag, which could shadow a concurrent sync write.+ raise HyperCacheDependencyUnavailable(f"{EU_CROSS_REGION_MIRROR_CACHE_KEY} not yet synced")+ 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=lambda key: _get_flags_response_for_local_evaluation(HyperCache.team_from_key(key)),+ 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),@@ -510,9 +529,9 @@ def update_flag_caches(team: Team):emit_cache_sync_metrics(result, "feature_flags", "flags_with_cohorts.json", size=size)-def clear_flag_definition_caches(team: Team | int, kinds: list[str] | None = None):+def clear_flag_definition_caches(team: KeyType, kinds: list[str] | None = None):"""- Clear the flag definitions cache for a team.+ Clear the flag definitions cache for a team (or the EU cross-region mirror sentinel).Clears from shared cache and removes from expiry tracking.Expiry tracking cleanup is handled by HyperCache.clear_cache() internally.diff --git a/products/feature_flags/backend/sdk_cache_provider.py b/products/feature_flags/backend/sdk_cache_provider.pyindex b6f4e3c7047c..e7b9a38e19e1 100644--- a/products/feature_flags/backend/sdk_cache_provider.py+++ b/products/feature_flags/backend/sdk_cache_provider.py@@ -24,24 +24,28 @@ class HyperCacheFlagProvider:by reading directly from the same Redis cache."""- def __init__(self, team_id_resolver: Callable[[], Optional[int]]):+ def __init__(self, team_id_resolver: Callable[[], Optional[int | str]]):self._team_id_resolver = team_id_resolver- self._team_id: Optional[int] = None # memoized first non-None resolution+ self._team_id: Optional[int | str] = None # memoized first non-None resolutionself._hypercache: Optional[HyperCache] = Noneself._logged_resolved_team = Falseself._logged_zero_flags = False@classmethod- def for_static_team(cls, team_id: int) -> HyperCacheFlagProvider:- """Cloud / E2E / explicit operator override: a fixed, known team id."""+ def for_static_team(cls, team_id: int | str) -> HyperCacheFlagProvider:+ """Cloud / E2E / explicit operator override: a fixed, known cache key.++ Usually a real team id; on EU it's EU_CROSS_REGION_MIRROR_CACHE_KEY, the+ string sentinel the cross-region sync writes US team 2's definitions under.+ """return cls(team_id_resolver=lambda: team_id)@classmethod- def for_dynamic_resolution(cls, team_id_resolver: Callable[[], Optional[int]]) -> HyperCacheFlagProvider:+ def for_dynamic_resolution(cls, team_id_resolver: Callable[[], Optional[int | str]]) -> HyperCacheFlagProvider:"""Local/self-hosted: resolve the team id lazily, retrying while it returns None."""return cls(team_id_resolver=team_id_resolver)- def _resolve_team_id(self) -> Optional[int]:+ def _resolve_team_id(self) -> Optional[int | str]:# Resolve once and memoize; a None result is NOT cached, so we retry next poll# (resolution may run before the first team exists / before migrations).if self._team_id is None:diff --git a/products/feature_flags/backend/tasks.py b/products/feature_flags/backend/tasks.pyindex 6d7bcbba75fb..3d95fdbb4270 100644--- a/products/feature_flags/backend/tasks.py+++ b/products/feature_flags/backend/tasks.py@@ -15,7 +15,7 @@ from posthog.storage.hypercache_manager import HYPERCACHE_SIGNAL_UPDATE_COUNTERfrom posthog.tasks.utils import CeleryQueue, PushGatewayTaskfrom products.feature_flags.backend.canary import run_local_eval_canary-from products.feature_flags.backend.cross_region_flag_sync import sync_cross_region_dogfood_flags+from products.feature_flags.backend.cross_region_flag_sync import sync_cross_region_flagsfrom products.feature_flags.backend.flags_cache import (cleanup_stale_expiry_tracking,clear_flags_cache,@@ -66,14 +66,14 @@ def drain_flag_definitions_rebuild_requests() -> None:@shared_task(ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value)-def sync_cross_region_dogfood_flags_task() -> None:- """Celery entrypoint for sync_cross_region_dogfood_flags.+def sync_cross_region_flags_task() -> None:+ """Celery entrypoint for sync_cross_region_flags.On its own queue (not CeleryQueue.FEATURE_FLAGS) because it makes a blockingcross-region HTTP call: a stalled upstream shouldn't be able to delay thefast, sub-second signal-driven cache rebuilds sharing that queue."""- sync_cross_region_dogfood_flags()+ sync_cross_region_flags()@shared_task(ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS.value)diff --git a/products/feature_flags/backend/test/test_cross_region_flag_sync.py b/products/feature_flags/backend/test/test_cross_region_flag_sync.pyindex f48de482e0e7..62b974cc20d0 100644--- a/products/feature_flags/backend/test/test_cross_region_flag_sync.py+++ b/products/feature_flags/backend/test/test_cross_region_flag_sync.py@@ -6,7 +6,8 @@ from django.test import override_settingsimport requestsfrom parameterized import parameterized-from products.feature_flags.backend.cross_region_flag_sync import DOGFOOD_SELF_TEAM_ID, sync_cross_region_dogfood_flags+from products.feature_flags.backend.cache_keys import EU_CROSS_REGION_MIRROR_CACHE_KEY+from products.feature_flags.backend.cross_region_flag_sync import sync_cross_region_flagsfrom products.feature_flags.backend.local_evaluation import clear_flag_definition_caches, flag_definitions_hypercache_MODULE = "products.feature_flags.backend.cross_region_flag_sync"@@ -23,17 +24,17 @@ def _mock_response(status_code: int, json_data: dict | list | None = None, json_@override_settings(CLOUD_DEPLOYMENT="EU", POSTHOG_FLAGS_PROJECT_SECRET_TOKEN="phs_test_token")-class TestSyncCrossRegionDogfoodFlags(BaseTest):+class TestSyncCrossRegionFlags(BaseTest):def setUp(self):super().setUp()- clear_flag_definition_caches(DOGFOOD_SELF_TEAM_ID, kinds=["redis", "s3"])+ clear_flag_definition_caches(EU_CROSS_REGION_MIRROR_CACHE_KEY, kinds=["redis", "s3"])@override_settings(CLOUD_DEPLOYMENT="US")def test_no_op_outside_eu(self):# Every EU pod would otherwise re-poll the US API directly -- exactly the# per-pod polling this task exists to replace -- if this guard were dropped.with patch(f"{_MODULE}.requests.get") as mock_get:- sync_cross_region_dogfood_flags()+ sync_cross_region_flags()mock_get.assert_not_called()@@ -42,21 +43,24 @@ class TestSyncCrossRegionDogfoodFlags(BaseTest):# Before the charts secret is provisioned, this would otherwise send a# request with an empty bearer token every 30s.with patch(f"{_MODULE}.requests.get") as mock_get:- sync_cross_region_dogfood_flags()+ sync_cross_region_flags()mock_get.assert_not_called()def test_sends_stored_etag_and_skips_write_on_304(self):+ # Regression guard for the sentinel-key fix: the etag that gates the+ # conditional GET must be read/written under EU_CROSS_REGION_MIRROR_CACHE_KEY,+ # not team id 2 -- a real, unrelated EU team's id.payload = {"flags": [{"key": "existing"}], "group_type_mapping": {}, "cohorts": {}}- flag_definitions_hypercache.set_cache_value(DOGFOOD_SELF_TEAM_ID, payload)- local_etag = flag_definitions_hypercache.get_etag(DOGFOOD_SELF_TEAM_ID)+ flag_definitions_hypercache.set_cache_value(EU_CROSS_REGION_MIRROR_CACHE_KEY, payload)+ local_etag = flag_definitions_hypercache.get_etag(EU_CROSS_REGION_MIRROR_CACHE_KEY)assert local_etagwith (patch(f"{_MODULE}.requests.get", return_value=_mock_response(304)) as mock_get,patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set,):- sync_cross_region_dogfood_flags()+ sync_cross_region_flags()url, kwargs = mock_get.call_argsassert url[0] == "https://us.i.posthog.com/flags/definitions"@@ -65,16 +69,23 @@ class TestSyncCrossRegionDogfoodFlags(BaseTest):# 304 means unchanged -- a write here would defeat the point of sending the etag.mock_set.assert_not_called()- def test_writes_fetched_payload_on_200(self):- payload = {"flags": [{"key": "new-flag"}], "group_type_mapping": {}, "cohorts": {}}+ def test_writes_fetched_payload_under_sentinel_key_without_clobbering_real_team(self):+ # The collision this change fixes: before the sentinel key, the sync wrote+ # under the plain team-id key 2, which is EU's own real, unrelated team.+ # A real team's cache entry must be untouched by this sync -- exercised at+ # the cache-key level (no DB row) so the test can't collide on team id 2.+ real_team_payload = {"flags": [{"key": "real-eu-flag"}], "group_type_mapping": {}, "cohorts": {}}+ flag_definitions_hypercache.set_cache_value(2, real_team_payload)- with patch(f"{_MODULE}.requests.get", return_value=_mock_response(200, payload)):- sync_cross_region_dogfood_flags()+ sync_payload = {"flags": [{"key": "mirrored-us-flag"}], "group_type_mapping": {}, "cohorts": {}}+ with patch(f"{_MODULE}.requests.get", return_value=_mock_response(200, sync_payload)):+ sync_cross_region_flags()- assert flag_definitions_hypercache.get_from_cache(DOGFOOD_SELF_TEAM_ID) == payload+ assert flag_definitions_hypercache.get_from_cache(EU_CROSS_REGION_MIRROR_CACHE_KEY) == sync_payload# A write that doesn't arm the ETag would make every later tick skip the# conditional GET, silently degrading to a full transfer on every poll.- assert flag_definitions_hypercache.get_etag(DOGFOOD_SELF_TEAM_ID)+ assert flag_definitions_hypercache.get_etag(EU_CROSS_REGION_MIRROR_CACHE_KEY)+ assert flag_definitions_hypercache.get_from_cache(2) == real_team_payload@parameterized.expand([@@ -92,7 +103,7 @@ class TestSyncCrossRegionDogfoodFlags(BaseTest):patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set,patch(f"{_MODULE}.capture_exception_throttled") as mock_capture,):- sync_cross_region_dogfood_flags()+ sync_cross_region_flags()mock_set.assert_not_called()mock_capture.assert_not_called()@@ -105,7 +116,7 @@ class TestSyncCrossRegionDogfoodFlags(BaseTest):patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set,patch(f"{_MODULE}.capture_exception_throttled") as mock_capture,):- sync_cross_region_dogfood_flags()+ sync_cross_region_flags()mock_set.assert_not_called()mock_capture.assert_called_once()@@ -124,6 +135,6 @@ class TestSyncCrossRegionDogfoodFlags(BaseTest):patch(f"{_MODULE}.requests.get", return_value=_mock_response(status_code, json_data, json_error)),patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set,):- sync_cross_region_dogfood_flags()+ sync_cross_region_flags()mock_set.assert_not_called()diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.pyindex 467730a88dde..565d3a01bbb5 100644--- a/products/feature_flags/backend/test/test_local_evaluation.py+++ b/products/feature_flags/backend/test/test_local_evaluation.py@@ -18,6 +18,7 @@ from posthog.utils import safe_cache_deletefrom products.cohorts.backend.models.cohort import Cohortfrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.cache_keys import EU_CROSS_REGION_MIRROR_CACHE_KEYfrom 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,@@ -1335,6 +1336,17 @@ class TestFlagDefinitionsCache(BaseTest):result = update_flag_definitions_cache(999999)assert result is False+ def test_cold_read_of_cross_region_sentinel_returns_none_without_querying_team(self):+ # The EU mirror sentinel has no backing Team row, so a cold read must+ # short-circuit in the load_fn instead of raising Team.DoesNotExist.+ clear_flag_definition_caches(EU_CROSS_REGION_MIRROR_CACHE_KEY, kinds=["redis", "s3"])++ with patch.object(Team.objects, "get") as mock_team_get:+ result = flag_definitions_hypercache.get_from_cache(EU_CROSS_REGION_MIRROR_CACHE_KEY)++ assert result is None+ mock_team_get.assert_not_called()+def test_clear_flag_definition_caches(self):FeatureFlag.objects.create(team=self.team,