: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): harden local-eval cache against silent group-mapping corruption (#61179)
Matheus Batista1a94c98dc8ef
diff --git a/posthog/models/group_type_mapping.py b/posthog/models/group_type_mapping.pyindex 243edc9b72e9..b443f9171dbc 100644--- a/posthog/models/group_type_mapping.py+++ b/posthog/models/group_type_mapping.py@@ -13,19 +13,74 @@ from django.db import DatabaseError, modelsfrom django.utils import timezoneimport structlog+from prometheus_client import Counterfrom posthog.models.utils import RootTeamMixin+from posthog.person_db_router import PERSONS_DB_FOR_WRITEfrom posthog.personhog_client.metrics import PERSONHOG_ROUTING_ERRORS_TOTAL, PERSONHOG_ROUTING_TOTAL, get_client_namefrom posthog.rbac.decorators import field_access_control-from posthog.utils import get_safe_cache, safe_cache_delete, safe_cache_set+from posthog.storage.hypercache import HyperCacheDependencyUnavailable+from posthog.utils import capture_exception_throttled, get_safe_cache, safe_cache_delete, safe_cache_setlogger = structlog.get_logger(__name__)GROUP_TYPES_CACHE_TTL = 60 * 5 # 5 minutesGROUP_TYPES_STALE_CACHE_TTL = 60 * 60 * 24 # 24 hours — last-known-good fallback during outagesGROUP_TYPES_NEGATIVE_CACHE_TTL = 30 # seconds — short so we detect DB recovery quickly+GROUP_TYPES_CONFIRMED_EMPTY_CACHE_TTL = 60 * 5 # 5 minutes — bounds the corruption window if invalidation is missedGROUP_TYPES_CACHE_KEY_PREFIX = "group_types_for_project_"GROUP_TYPES_STALE_CACHE_KEY_PREFIX = "group_types_for_project_stale_"+GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX = "group_types_for_project_confirmed_empty_"++# Throttle window for capturing group-type fetch failures, shared across processes+# via the cache so many workers failing at once report at most once per window.+GROUP_TYPES_FAILURE_CAPTURE_THROTTLE_TTL = 60 # seconds++# Terminal failure of a group-type fetch, after all fallbacks. Separate from the+# personhog routing counters: these sites query the persons DB directly via the ORM+# and never call personhog, so the failure must not land on the personhog metrics.+GROUP_TYPES_FETCH_FAILURES = Counter(+ "posthog_group_types_fetch_failures",+ "Terminal failures fetching group-type mappings, by operation/source/error_type",+ labelnames=["operation", "source", "error_type"],+)+++class GroupTypesUnavailable(HyperCacheDependencyUnavailable):+ """Raised by the batch fetch when group types cannot be loaded and no+ last-known-good is cached for one or more projects.++ Callers fail closed instead of persisting an empty mapping: an empty mapping+ makes every group-aggregated flag for the team evaluate to false. Subclasses the+ storage-layer base so HyperCache can catch it without importing this type.+ """++ def __init__(self, project_ids: list[int]) -> None:+ super().__init__(f"Group types unavailable for projects: {project_ids}")+ self.project_ids = project_ids+++def _record_group_types_fetch_failure(*, operation: str, log_event: str, exc: BaseException, **log_fields: Any) -> None:+ """Record a terminal group-type fetch failure: increment the failure counter, log+ the traceback, and capture the exception (throttled across processes).++ The counter is always incremented; only the capture is throttled. Each log line+ records whether the capture ran or was throttled.+ """+ GROUP_TYPES_FETCH_FAILURES.labels(operation=operation, source="django_orm", error_type="db_error").inc()++ throttle_key = f"group_types_failure_capture_throttle:{operation}"+ captured = capture_exception_throttled(throttle_key, exc, GROUP_TYPES_FAILURE_CAPTURE_THROTTLE_TTL)++ logger.exception(+ log_event,+ operation=operation,+ error_type="db_error",+ exception_captured=captured,+ capture_throttled=not captured,+ **log_fields,+ )+# Defined here for reuse between OS and EEGROUP_TYPE_MAPPING_SERIALIZER_FIELDS = [@@ -106,6 +161,9 @@ class GroupTypeMapping(RootTeamMixin, models.Model):def invalidate_group_types_cache(project_id: int) -> None:safe_cache_delete(f"{GROUP_TYPES_CACHE_KEY_PREFIX}{project_id}")safe_cache_delete(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{project_id}")+ # Clear the confirmed-empty marker so a team adding its first group type stops+ # short-circuiting project_has_group_types_authoritatively to False immediately.+ safe_cache_delete(f"{GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX}{project_id}")def _fetch_group_types_via_personhog(client: PersonHogClient, project_id: int) -> list[dict[str, Any]]:@@ -137,7 +195,7 @@ def get_group_types_for_project(project_id: int) -> list[dict[str, Any]]:operation="get_group_types_for_project", source="personhog", client_name=get_client_name()).inc()safe_cache_set(cache_key, result, GROUP_TYPES_CACHE_TTL)- safe_cache_set(stale_cache_key, result, GROUP_TYPES_STALE_CACHE_TTL)+ _write_project_stale_if_non_empty(project_id, result)return resultexcept Exception:PERSONHOG_ROUTING_ERRORS_TOTAL.labels(@@ -158,10 +216,15 @@ def get_group_types_for_project(project_id: int) -> list[dict[str, Any]]:operation="get_group_types_for_project", source="django_orm", client_name=get_client_name()).inc()safe_cache_set(cache_key, result, GROUP_TYPES_CACHE_TTL)- safe_cache_set(stale_cache_key, result, GROUP_TYPES_STALE_CACHE_TTL)+ _write_project_stale_if_non_empty(project_id, result)return result- except DatabaseError:- logger.warning("persons_db_group_types_failure", project_id=project_id, exc_info=True)+ except DatabaseError as exc:+ _record_group_types_fetch_failure(+ operation="get_group_types_for_project",+ log_event="persons_db_group_types_failure",+ exc=exc,+ project_id=project_id,+ )stale = get_safe_cache(stale_cache_key)if stale is not None:safe_cache_set(cache_key, stale, GROUP_TYPES_NEGATIVE_CACHE_TTL)@@ -210,8 +273,13 @@ def get_group_types_for_team(team_id: int) -> list[dict[str, Any]]:.order_by("group_type_index").values(*GROUP_TYPE_MAPPING_SERIALIZER_FIELDS))- except DatabaseError:- logger.warning("persons_db_group_types_for_team_failure", team_id=team_id, exc_info=True)+ except DatabaseError as exc:+ _record_group_types_fetch_failure(+ operation="get_group_types_for_team",+ log_event="persons_db_group_types_for_team_failure",+ exc=exc,+ team_id=team_id,+ )return []@@ -262,8 +330,63 @@ def _memoise_group_types_on(target: Team | Project, project_id: int) -> list[dicreturn getattr(target, _REQUEST_CACHED_GROUP_TYPES_ATTR)+def _write_project_stale_if_non_empty(project_id: int, mappings: list[dict[str, Any]]) -> None:+ """Persist a project's group types to its stale (last-known-good) key, only when+ non-empty. Overwriting a populated entry with [] would erase the fallback the+ outage recovery and the write-side empty-mapping guard depend on.+ """+ if mappings:+ safe_cache_set(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{project_id}", mappings, GROUP_TYPES_STALE_CACHE_TTL)+++def _populate_projects_stale_cache(result: dict[int, list[dict[str, Any]]]) -> None:+ """Write each project's non-empty group types to its per-project stale key, the+ last-known-good shared by the batch and single-project paths.++ Empty results are skipped: overwriting a populated entry with an empty list would+ erase the fallback that outage recovery and the write-side guard read.+ """+ for project_id, mappings in result.items():+ _write_project_stale_if_non_empty(project_id, mappings)+++def _recover_projects_from_stale_or_fail(project_ids: list[int], exc: DatabaseError) -> dict[int, list[dict[str, Any]]]:+ """Recover a batch fetch from the per-project stale cache after a DB failure.++ Records the failure, then serves each project's last-known-good. Raises+ GroupTypesUnavailable if any project has no stale entry, so the caller never+ persists an all-empty mapping over populated data.+ """+ _record_group_types_fetch_failure(+ operation="get_group_types_for_projects",+ log_event="persons_db_group_types_for_projects_failure",+ exc=exc,+ project_ids=project_ids,+ )++ recovered: dict[int, list[dict[str, Any]]] = {}+ unrecovered: list[int] = []+ for project_id in project_ids:+ stale = get_safe_cache(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{project_id}")+ if stale is not None:+ recovered[project_id] = stale+ else:+ unrecovered.append(project_id)++ if unrecovered:+ raise GroupTypesUnavailable(unrecovered)++ return recovered++def get_group_types_for_projects(project_ids: list[int]) -> dict[int, list[dict[str, Any]]]:- """Batch fetch group types for multiple projects via personhog, falling back to ORM on error."""+ """Batch fetch group types for multiple projects via personhog, falling back to+ ORM, then to the per-project stale cache on a DB failure.++ Raises GroupTypesUnavailable if the persons DB is unavailable and any requested+ project has no cached last-known-good, rather than returning an all-empty+ mapping. Callers must handle that case.+ """from posthog.personhog_client.client import get_personhog_clientclient = get_personhog_client()@@ -275,6 +398,7 @@ def get_group_types_for_projects(project_ids: list[int]) -> dict[int, list[dict[PERSONHOG_ROUTING_TOTAL.labels(operation="get_group_types_for_projects", source="personhog", client_name=get_client_name()).inc()+ _populate_projects_stale_cache(result)return resultexcept Exception:PERSONHOG_ROUTING_ERRORS_TOTAL.labels(@@ -297,11 +421,52 @@ def get_group_types_for_projects(project_ids: list[int]) -> dict[int, list[dict[):pid = row.pop("project_id")result.setdefault(pid, []).append(row)- except DatabaseError:- logger.warning("persons_db_group_types_for_projects_failure", project_ids=project_ids, exc_info=True)+ except DatabaseError as exc:+ return _recover_projects_from_stale_or_fail(project_ids, exc)++ _populate_projects_stale_cache(result)return result+def project_has_group_types_authoritatively(project_id: int) -> bool:+ """True if the project has group types per the persons-DB primary, or if that+ cannot be confirmed (fail closed).++ The local-eval empty-mapping guard uses this when its cheap last-known-good signal+ (the per-project stale key) is absent, so a write that would empty a populated+ mapping is only allowed when the project is *confirmed* to have no group types.++ Reads the primary (PERSONS_DB_FOR_WRITE) on purpose: the normal fetch already+ returned the suspect empty (possibly from personhog or a lagging replica), so this+ independent check must hit the source of truth rather than route through personhog+ again. On a DB error it returns True — the caller must not treat an unconfirmable+ state as safe to empty.++ A short-lived "confirmed empty" marker caches the authoritative False so a team+ that has never had group types — the common case, where this fires on every+ no-group rebuild — doesn't probe the writer DB each time. invalidate_group_types_cache+ clears the marker when a group type is created, and the short TTL bounds the window+ if that invalidation is ever missed.+ """+ confirmed_empty_key = f"{GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX}{project_id}"+ if get_safe_cache(confirmed_empty_key):+ return False+ try:+ has_group_types = (+ GroupTypeMapping.objects.using(PERSONS_DB_FOR_WRITE) # nosemgrep: no-direct-persons-db-orm+ .filter(project_id=project_id)+ .exists()+ )+ except DatabaseError:+ logger.warning("group_types_primary_confirmation_failed", project_id=project_id, exc_info=True)+ return True+ if not has_group_types:+ # Only cache the negative. A True must keep hitting the DB so a later deletion+ # is seen promptly, and the DB-error branch above must never be cached.+ safe_cache_set(confirmed_empty_key, True, GROUP_TYPES_CONFIRMED_EMPTY_CACHE_TTL)+ return has_group_types++def update_group_type_mapping_fields(instance: GroupTypeMapping,*,@@ -440,8 +605,6 @@ def clear_dashboard_from_group_type_mapping(team_id: int, dashboard_id: int, proexc_info=True,)- from posthog.person_db_router import PERSONS_DB_FOR_WRITE-PERSONHOG_ROUTING_TOTAL.labels(operation="clear_dashboard_from_group_type_mapping", source="django_orm", client_name=get_client_name()).inc()diff --git a/posthog/models/test/test_group_type_mapping.py b/posthog/models/test/test_group_type_mapping.pyindex 64f2b5946c4c..5383c7e85019 100644--- a/posthog/models/test/test_group_type_mapping.py+++ b/posthog/models/test/test_group_type_mapping.py@@ -6,15 +6,21 @@ from parameterized import parameterizedfrom posthog.models.group_type_mapping import (GROUP_TYPES_CACHE_KEY_PREFIX,+ GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX,GROUP_TYPES_STALE_CACHE_KEY_PREFIX,+ GroupTypesUnavailable,+ _record_group_types_fetch_failure,clear_dashboard_from_group_type_mapping,delete_group_type_mapping,get_group_types_for_project,get_group_types_for_projects,get_group_types_for_team,+ invalidate_group_types_cache,+ project_has_group_types_authoritatively,update_group_type_mapping_fields,)-from posthog.utils import safe_cache_delete+from posthog.person_db_router import PERSONS_DB_FOR_WRITE+from posthog.utils import get_safe_cache, safe_cache_delete, safe_cache_setdef _clear_cache(project_id: int) -> None:@@ -502,6 +508,33 @@ class TestGetGroupTypesForProjectCacheBehavior(SimpleTestCase):stale = get_safe_cache(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{self.project_id}")assert stale == PERSONHOG_SUCCESS_DATA+ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ @patch("posthog.models.group_type_mapping._fetch_group_types_via_personhog")+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")+ def test_empty_success_does_not_clobber_populated_stale(+ self,+ mock_errors_counter,+ mock_routing_counter,+ mock_fetch_personhog,+ mock_objects,+ ):+ from posthog.utils import get_safe_cache++ # A populated last-known-good already exists (e.g. written by the batch path).+ stale_key = f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{self.project_id}"+ safe_cache_set(stale_key, PERSONHOG_SUCCESS_DATA, 3600)++ # Upstream succeeds but returns empty — the "empty-but-not-erroring" failure+ # mode the corruption guard depends on the stale fallback to catch.+ mock_fetch_personhog.return_value = []++ result = get_group_types_for_project(self.project_id)++ # The empty success is served, but must not erase the populated fallback.+ assert result == []+ assert get_safe_cache(stale_key) == PERSONHOG_SUCCESS_DATA+class TestGetGroupTypesForTeamEdgeCases(SimpleTestCase):def setUp(self):@@ -560,17 +593,21 @@ class TestGetGroupTypesForTeamEdgeCases(SimpleTestCase):class TestGetGroupTypesForProjectsEdgeCases(SimpleTestCase):def setUp(self):+ for pid in (10, 20):+ _clear_cache(pid)self._client_patcher = patch(_CLIENT_PATCH, return_value=MagicMock())self._client_patcher.start()def tearDown(self):self._client_patcher.stop()+ for pid in (10, 20):+ _clear_cache(pid)@patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")@patch("posthog.models.group_type_mapping._fetch_group_types_for_projects_via_personhog")@patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_TOTAL")@patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")- def test_orm_database_error_returns_empty_dicts(+ def test_orm_database_error_without_stale_fails_closed(self,mock_errors_counter,mock_routing_counter,@@ -590,9 +627,12 @@ class TestGetGroupTypesForProjectsEdgeCases(SimpleTestCase):mock_qs.order_by.return_value.values.return_value = mock_values_qsmock_objects.filter.return_value = mock_qs- result = get_group_types_for_projects([10, 20])+ # With no last-known-good, the batch fetch fails closed rather than+ # returning an all-empty mapping that would silently disable group flags.+ with self.assertRaises(GroupTypesUnavailable) as ctx:+ get_group_types_for_projects([10, 20])- assert result == {10: [], 20: []}+ assert set(ctx.exception.project_ids) == {10, 20}# ── Write helper tests ─────────────────────────────────────────────@@ -851,3 +891,299 @@ class TestClearDashboardFromGroupTypeMapping(SimpleTestCase):mock_objects.using.assert_called_once()mock_errors_counter.labels.assert_called_once()+++# ── Terminal-failure hardening tests ──────────────────────────────────+++def _make_db_error_objects() -> MagicMock:+ # GroupTypeMapping.objects mock whose .filter(...).order_by(...).values()+ # raises DatabaseError when iterated.+ from django.db import DatabaseError++ def _raise_db_error():+ raise DatabaseError("db is down")++ mock_values_qs = MagicMock()+ mock_values_qs.__iter__ = MagicMock(side_effect=_raise_db_error)+ mock_qs = MagicMock()+ mock_qs.order_by.return_value.values.return_value = mock_values_qs+ mock_objects = MagicMock()+ mock_objects.filter.return_value = mock_qs+ return mock_objects+++class TestTerminalFetchFailureMetric(SimpleTestCase):+ def setUp(self):+ self.project_id = 7777+ _clear_cache(self.project_id)+ # client None skips the personhog leg, isolating the ORM failure+ self._client_patcher = patch(_CLIENT_PATCH, return_value=None)+ self._client_patcher.start()++ def tearDown(self):+ self._client_patcher.stop()+ _clear_cache(self.project_id)++ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ @patch("posthog.models.group_type_mapping.GROUP_TYPES_FETCH_FAILURES")+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")+ def test_single_project_db_error_increments_fetch_failures_not_personhog(+ self, mock_personhog_errors, mock_fetch_failures, mock_objects+ ):+ mock_objects.filter.side_effect = _make_db_error_objects().filter++ result = get_group_types_for_project(self.project_id)++ assert result == []+ mock_fetch_failures.labels.assert_called_once_with(+ operation="get_group_types_for_project", source="django_orm", error_type="db_error"+ )+ mock_personhog_errors.labels.assert_not_called()++ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ @patch("posthog.models.group_type_mapping.GROUP_TYPES_FETCH_FAILURES")+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")+ def test_team_db_error_increments_fetch_failures_not_personhog(+ self, mock_personhog_errors, mock_fetch_failures, mock_objects+ ):+ mock_objects.filter.side_effect = _make_db_error_objects().filter++ result = get_group_types_for_team(4242)++ assert result == []+ mock_fetch_failures.labels.assert_called_once_with(+ operation="get_group_types_for_team", source="django_orm", error_type="db_error"+ )+ mock_personhog_errors.labels.assert_not_called()++ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ @patch("posthog.models.group_type_mapping.GROUP_TYPES_FETCH_FAILURES")+ @patch("posthog.models.group_type_mapping.PERSONHOG_ROUTING_ERRORS_TOTAL")+ def test_projects_db_error_increments_fetch_failures_not_personhog(+ self, mock_personhog_errors, mock_fetch_failures, mock_objects+ ):+ mock_objects.filter.side_effect = _make_db_error_objects().filter++ # No stale, so it fails closed, but the counter still fires first+ with self.assertRaises(GroupTypesUnavailable):+ get_group_types_for_projects([self.project_id])++ mock_fetch_failures.labels.assert_called_once_with(+ operation="get_group_types_for_projects", source="django_orm", error_type="db_error"+ )+ mock_personhog_errors.labels.assert_not_called()+++class TestGetGroupTypesForProjectsFailClosed(SimpleTestCase):+ def setUp(self):+ self.project_ids = [101, 102]+ for pid in self.project_ids:+ _clear_cache(pid)+ self._client_patcher = patch(_CLIENT_PATCH, return_value=None)+ self._client_patcher.start()++ def tearDown(self):+ self._client_patcher.stop()+ for pid in self.project_ids:+ _clear_cache(pid)++ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ def test_db_error_recovers_each_project_from_stale(self, mock_objects):+ mock_objects.filter.side_effect = _make_db_error_objects().filter++ stale_101 = [{"group_type": "org", "group_type_index": 0}]+ stale_102 = [{"group_type": "company", "group_type_index": 0}]+ safe_cache_set(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}101", stale_101, 3600)+ safe_cache_set(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}102", stale_102, 3600)++ result = get_group_types_for_projects(self.project_ids)++ assert result == {101: stale_101, 102: stale_102}++ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ def test_db_error_raises_group_types_unavailable_when_no_stale(self, mock_objects):+ mock_objects.filter.side_effect = _make_db_error_objects().filter++ with self.assertRaises(GroupTypesUnavailable) as ctx:+ get_group_types_for_projects(self.project_ids)++ assert set(ctx.exception.project_ids) == {101, 102}++ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ def test_db_error_raises_when_any_project_lacks_stale(self, mock_objects):+ mock_objects.filter.side_effect = _make_db_error_objects().filter++ # Only 101 has a last-known-good; 102 is unrecoverable, so it fails closed+ safe_cache_set(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}101", [{"group_type": "org", "group_type_index": 0}], 3600)++ with self.assertRaises(GroupTypesUnavailable) as ctx:+ get_group_types_for_projects(self.project_ids)++ assert ctx.exception.project_ids == [102]++ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ def test_empty_stale_counts_as_recovered(self, mock_objects):+ # A cached empty list is a known value, so it recovers rather than failing closed+ mock_objects.filter.side_effect = _make_db_error_objects().filter++ safe_cache_set(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}101", [], 3600)+ safe_cache_set(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}102", [], 3600)++ result = get_group_types_for_projects(self.project_ids)++ assert result == {101: [], 102: []}+++class TestProjectsStaleCachePopulation(SimpleTestCase):+ def setUp(self):+ self.project_ids = [201, 202]+ for pid in self.project_ids:+ _clear_cache(pid)+ self._client_patcher = patch(_CLIENT_PATCH, return_value=None)+ self._client_patcher.start()++ def tearDown(self):+ self._client_patcher.stop()+ for pid in self.project_ids:+ _clear_cache(pid)++ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ def test_orm_success_writes_non_empty_to_stale_only(self, mock_objects):+ from posthog.utils import get_safe_cache++ orm_rows = [+ {"project_id": 201, "group_type": "organization", "group_type_index": 0},+ ]+ mock_qs = MagicMock()+ mock_qs.order_by.return_value.values.return_value = [dict(r) for r in orm_rows]+ mock_objects.filter.return_value = mock_qs++ result = get_group_types_for_projects(self.project_ids)++ # 201 had a mapping → persisted to stale; 202 was empty → stale left absent+ assert result[201] == [{"group_type": "organization", "group_type_index": 0}]+ assert result[202] == []+ assert get_safe_cache(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}201") == [+ {"group_type": "organization", "group_type_index": 0}+ ]+ assert get_safe_cache(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}202") is None++ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ def test_empty_success_does_not_overwrite_existing_stale(self, mock_objects):+ from posthog.utils import get_safe_cache++ prior = [{"group_type": "organization", "group_type_index": 0}]+ safe_cache_set(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}201", prior, 3600)++ mock_qs = MagicMock()+ mock_qs.order_by.return_value.values.return_value = [] # empty success+ mock_objects.filter.return_value = mock_qs++ get_group_types_for_projects([201])++ # Empty result must not clobber the populated last-known-good+ assert get_safe_cache(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}201") == prior+++class TestRecordGroupTypesFetchFailureThrottle(SimpleTestCase):+ def setUp(self):+ self.operation = "get_group_types_for_projects"+ safe_cache_delete(f"group_types_failure_capture_throttle:{self.operation}")++ def tearDown(self):+ safe_cache_delete(f"group_types_failure_capture_throttle:{self.operation}")++ @patch("posthog.models.group_type_mapping.GROUP_TYPES_FETCH_FAILURES")+ @patch("posthog.models.group_type_mapping.logger")+ @patch("posthog.utils.capture_exception")+ def test_captures_once_then_logs_throttled(self, mock_capture, mock_logger, mock_counter):+ from django.db import DatabaseError++ exc = DatabaseError("db down")++ _record_group_types_fetch_failure(+ operation=self.operation, log_event="persons_db_group_types_for_projects_failure", exc=exc, project_ids=[1]+ )+ _record_group_types_fetch_failure(+ operation=self.operation, log_event="persons_db_group_types_for_projects_failure", exc=exc, project_ids=[1]+ )++ # Captured once across the throttle window, but the counter moves both times+ mock_capture.assert_called_once_with(exc)+ assert mock_counter.labels.call_count == 2++ first_kwargs = mock_logger.exception.call_args_list[0].kwargs+ second_kwargs = mock_logger.exception.call_args_list[1].kwargs+ assert first_kwargs["exception_captured"] is True+ assert first_kwargs["capture_throttled"] is False+ assert second_kwargs["exception_captured"] is False+ assert second_kwargs["capture_throttled"] is True+++class TestProjectHasGroupTypesAuthoritatively(SimpleTestCase):+ _PROJECT_IDS = (123, 777, 888)++ def setUp(self):+ self._clear_markers()++ def tearDown(self):+ self._clear_markers()++ def _clear_markers(self):+ for project_id in self._PROJECT_IDS:+ safe_cache_delete(f"{GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX}{project_id}")++ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ def test_returns_true_when_rows_exist(self, mock_objects):+ mock_objects.using.return_value.filter.return_value.exists.return_value = True++ assert project_has_group_types_authoritatively(123) is True+ # Reads the primary, not a replica, so a lagging read cannot fake a deletion.+ mock_objects.using.assert_called_once_with(PERSONS_DB_FOR_WRITE)+ mock_objects.using.return_value.filter.assert_called_once_with(project_id=123)++ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ def test_returns_false_when_no_rows(self, mock_objects):+ mock_objects.using.return_value.filter.return_value.exists.return_value = False++ assert project_has_group_types_authoritatively(123) is False++ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ def test_fails_closed_on_db_error(self, mock_objects):+ from django.db import DatabaseError++ mock_objects.using.return_value.filter.return_value.exists.side_effect = DatabaseError("db down")++ # Cannot confirm absence → assume present so the caller keeps the existing entry.+ assert project_has_group_types_authoritatively(123) is True++ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ def test_confirmed_empty_marker_short_circuits_second_call(self, mock_objects):+ exists_mock = mock_objects.using.return_value.filter.return_value.exists+ exists_mock.return_value = False++ # First call confirms empty against the DB and caches the marker.+ assert project_has_group_types_authoritatively(777) is False+ # Second call reads the marker instead of probing the writer DB again.+ assert project_has_group_types_authoritatively(777) is False+ exists_mock.assert_called_once()++ @patch("posthog.models.group_type_mapping.GroupTypeMapping.objects")+ def test_present_result_is_not_cached(self, mock_objects):+ exists_mock = mock_objects.using.return_value.filter.return_value.exists+ exists_mock.return_value = True++ # A True is never cached, so a later deletion is seen on the next call.+ assert project_has_group_types_authoritatively(777) is True+ assert project_has_group_types_authoritatively(777) is True+ assert exists_mock.call_count == 2++ def test_invalidate_group_types_cache_clears_confirmed_empty_marker(self):+ marker_key = f"{GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX}888"+ safe_cache_set(marker_key, True, 300)++ invalidate_group_types_cache(888)++ # A team adding its first group type must stop short-circuiting to False at once.+ assert get_safe_cache(marker_key) is Nonediff --git a/posthog/settings/feature_flags.py b/posthog/settings/feature_flags.pyindex 7d1fcdac83e5..b148a19772c3 100644--- a/posthog/settings/feature_flags.py+++ b/posthog/settings/feature_flags.py@@ -99,3 +99,6 @@ MAX_FEATURE_FLAG_FILTER_SIZE_BYTES: int = get_from_env(512 * 1024,type_cast=int, # 512KB)++# Team ID for the local-evaluation canary. Unset disables the canary task.+FEATURE_FLAGS_CANARY_TEAM_ID: int | None = get_from_env("FEATURE_FLAGS_CANARY_TEAM_ID", optional=True, type_cast=int)diff --git a/posthog/storage/hypercache.py b/posthog/storage/hypercache.pyindex 1910396a9218..e3644c7318d4 100644--- a/posthog/storage/hypercache.py+++ b/posthog/storage/hypercache.py@@ -23,6 +23,16 @@ DEFAULT_CACHE_MISS_TTL = 60 * 60 * 24 # 1 day - it will be invalidated by the dDEFAULT_CACHE_TTL = 60 * 60 * 24 * 30 # 30 days+class HyperCacheDependencyUnavailable(Exception):+ """Raised by a ``load_fn`` when an upstream dependency is unavailable.++ HyperCache treats it as a transient signal, not a value: write paths skip the+ write so the existing entry is kept, and the read path returns a miss without+ caching a sentinel so the next read retries. Callers subclass it so the storage+ layer can catch this base without importing their exception types.+ """++def get_cache_writer_url(cache_alias: str) -> str:"""Get writer Redis URL from cache alias.@@ -51,6 +61,12 @@ CACHE_SYNC_COUNTER = Counter(labelnames=["result", "namespace", "value"],)+HYPERCACHE_REBUILD_SKIPPED_COUNTER = Counter(+ "posthog_hypercache_rebuild_skipped",+ "Rebuilds skipped because a dependency was unavailable, keeping the existing entry",+ labelnames=["namespace", "reason"],+)+CACHE_SYNC_DURATION_HISTOGRAM = Histogram("posthog_hypercache_sync_duration_seconds","Time taken to sync hypercache in seconds",@@ -229,7 +245,17 @@ class HyperCache:pass# NOTE: This only applies to the django version - the dedicated service will rely entirely on the cache- data = self.load_fn(key)+ try:+ data = self.load_fn(key)+ except HyperCacheDependencyUnavailable:+ # Return a miss without caching a sentinel, so the next read retries. The+ # distinct "dependency_unavailable" source lets etag-aware callers fail+ # loud (retryable 503) instead of treating it like a plain cache miss; the+ # other callers (get_from_cache, verifiers) still see None and degrade.+ HYPERCACHE_CACHE_COUNTER.labels(+ result="dependency_unavailable", namespace=self.namespace, value=self.value+ ).inc()+ return None, "dependency_unavailable"if isinstance(data, HyperCacheStoreMissing):self._set_cache_value_redis(key, None)@@ -321,10 +347,14 @@ class HyperCache:- Otherwise: (data, current_etag, True) - 200 case with full dataNote: If Redis fails during ETag check, gracefully degrades to returning- the full data (treating as modified) rather than raising an exception.+ the full data (treating as modified) rather than raising an exception. A+ dependency-unavailable signal on a cold miss is the exception: it is re-raised+ as HyperCacheDependencyUnavailable so the caller can fail loud and retryable."""if not self.enable_etag:- data, _ = self.get_from_cache_with_source(key)+ data, source = self.get_from_cache_with_source(key)+ if source == "dependency_unavailable":+ raise HyperCacheDependencyUnavailable(f"Dependency unavailable loading {self.namespace}/{self.value}")return data, None, Truetry:@@ -335,6 +365,9 @@ class HyperCache:data, source = self.get_from_cache_with_source(key)+ if source == "dependency_unavailable":+ raise HyperCacheDependencyUnavailable(f"Dependency unavailable loading {self.namespace}/{self.value}")+# If we loaded from S3 or DB, the ETag was set during _set_cache_value_redis# Re-fetch it to ensure we return the correct valueif source in ("s3", "db"):@@ -342,6 +375,10 @@ class HyperCache:return data, current_etag, Trueexcept Exception as e:+ # A dependency-unavailable signal must reach the caller as a typed,+ # retryable error — not be swallowed like a Redis failure below.+ if isinstance(e, HyperCacheDependencyUnavailable):+ raise# Gracefully degrade: return full data when Redis failslogger.warning(f"Redis failure during ETag check for {self.namespace}, falling back to full response", error=str(e)@@ -353,7 +390,12 @@ class HyperCache:# If everything fails, return None with modified=Truereturn None, None, True- def update_cache(self, key: KeyType, ttl: Optional[int] = None) -> bool:+ def update_cache(+ self,+ key: KeyType,+ ttl: Optional[int] = None,+ should_skip_write: Optional[Callable[[KeyType, dict], bool]] = None,+ ) -> bool:logger.info(f"Syncing {self.namespace} cache for team {key}")start_time = time.time()@@ -361,9 +403,24 @@ class HyperCache:size: int | None = Nonetry:data = self.load_fn(key)+ if should_skip_write is not None and isinstance(data, dict) and should_skip_write(key, data):+ # A caller-supplied predicate vetoed persisting this freshly loaded+ # value (e.g. it would overwrite good data with a degraded one). Keep+ # the existing entry; the predicate owns its own metric/logging.+ return Falsesize = self.set_cache_value(key, data, ttl=ttl)success = Truereturn True+ except HyperCacheDependencyUnavailable:+ # Skip the write to keep the existing entry, and count the skip so the skip+ # counter reflects the refresh/warm path too, not just the signal path. The+ # source of the failure already reported it, so don't report it again here.+ HYPERCACHE_REBUILD_SKIPPED_COUNTER.labels(namespace=self.namespace, reason="dependency_unavailable").inc()+ logger.warning(+ f"Skipping {self.namespace} cache sync for team {key}: dependency unavailable",+ namespace=self.namespace,+ )+ return Falseexcept Exception as e:capture_exception(e)logger.exception(f"Failed to sync {self.namespace} cache for team {key}", exception=str(e))diff --git a/posthog/storage/test/test_hypercache.py b/posthog/storage/test/test_hypercache.pyindex 2c41b79fd12e..710c541982ad 100644--- a/posthog/storage/test/test_hypercache.py+++ b/posthog/storage/test/test_hypercache.py@@ -10,7 +10,13 @@ from django.test import override_settingsfrom parameterized import parameterizedfrom posthog.storage import object_storage-from posthog.storage.hypercache import DEFAULT_CACHE_MISS_TTL, DEFAULT_CACHE_TTL, HyperCache, HyperCacheStoreMissing+from posthog.storage.hypercache import (+ DEFAULT_CACHE_MISS_TTL,+ DEFAULT_CACHE_TTL,+ HyperCache,+ HyperCacheDependencyUnavailable,+ HyperCacheStoreMissing,+)class HyperCacheTestBase:@@ -152,6 +158,76 @@ class TestHyperCacheUpdateCache(HyperCacheTestBase):assert result is False+class TestHyperCacheDependencyUnavailable(HyperCacheTestBase):+ """A load_fn raising HyperCacheDependencyUnavailable skips the write and returns a+ miss without caching a sentinel."""++ @staticmethod+ def _load_fn_unavailable(team):+ raise HyperCacheDependencyUnavailable("persons db down")++ def test_update_cache_returns_false_and_writes_nothing(self):+ hc = HyperCache(namespace="dep_test", value="value", load_fn=self._load_fn_unavailable)+ hc.clear_cache(self.team_id, kinds=["redis", "s3"])++ with (+ patch("posthog.storage.hypercache.capture_exception") as mock_capture,+ patch("posthog.storage.hypercache.HYPERCACHE_REBUILD_SKIPPED_COUNTER") as mock_skipped,+ ):+ result = hc.update_cache(self.team_id)++ assert result is False+ # Nothing written, not even a miss sentinel, so a prior entry survives+ assert cache.get(hc.get_cache_key(self.team_id)) is None+ # The source of the failure already reported it, so update_cache does not+ mock_capture.assert_not_called()+ # The skip is counted so the refresh/warm path feeds the skip metric, not just+ # the signal path+ mock_skipped.labels.assert_called_once_with(namespace="dep_test", reason="dependency_unavailable")+ mock_skipped.labels.return_value.inc.assert_called_once()++ def test_get_from_cache_returns_transient_miss_without_sentinel(self):+ hc = HyperCache(namespace="dep_test", value="value", load_fn=self._load_fn_unavailable)+ hc.clear_cache(self.team_id, kinds=["redis", "s3"])++ result, source = hc.get_from_cache_with_source(self.team_id)++ assert result is None+ # Distinct from a plain "db" miss so etag-aware callers can fail loud+ assert source == "dependency_unavailable"+ # No miss sentinel cached, so the next read retries instead of serving a cached miss+ assert cache.get(hc.get_cache_key(self.team_id)) is None++ def test_get_if_none_match_raises_when_etag_enabled_and_cold(self):+ # On a cold cache during an outage, the etag-aware read must surface the typed+ # signal to the caller (→ retryable 503), not degrade to a silent miss.+ hc = HyperCache(namespace="dep_test", value="value", load_fn=self._load_fn_unavailable, enable_etag=True)+ hc.clear_cache(self.team_id, kinds=["redis", "s3"])++ with pytest.raises(HyperCacheDependencyUnavailable):+ hc.get_if_none_match(self.team_id, client_etag=None)++ def test_get_if_none_match_raises_when_etag_disabled_and_cold(self):+ hc = HyperCache(namespace="dep_test", value="value", load_fn=self._load_fn_unavailable)+ hc.clear_cache(self.team_id, kinds=["redis", "s3"])++ with pytest.raises(HyperCacheDependencyUnavailable):+ hc.get_if_none_match(self.team_id, client_etag=None)++ def test_get_if_none_match_still_degrades_on_redis_failure(self):+ # A genuine Redis failure during the etag check must still degrade to full+ # data — only the dependency-unavailable signal is re-raised.+ hc = HyperCache(namespace="dep_test", value="value", load_fn=lambda team: {"ok": True}, enable_etag=True)+ hc.clear_cache(self.team_id, kinds=["redis", "s3"])++ with patch.object(hc, "get_etag", side_effect=Exception("redis down")):+ data, etag, modified = hc.get_if_none_match(self.team_id, client_etag=None)++ assert data == {"ok": True}+ assert etag is None+ assert modified is True++class TestHyperCacheIntegration(HyperCacheTestBase):def test_full_cache_flow(self):"""Test the full cache flow: Redis miss -> S3 miss -> DB load -> cache set"""diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 67d6a0fcc6f7..2e233e75ac94 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -76,6 +76,7 @@ from products.feature_flags.backend.tasks import (cleanup_stale_flag_definitions_expiry_tracking_task,cleanup_stale_flags_expiry_tracking_task,compute_feature_flag_metrics,+ feature_flags_local_eval_canary_task,refresh_expiring_flag_definitions_cache_entries,refresh_expiring_flags_cache_entries,)@@ -288,6 +289,15 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:expires_seconds=60 * 60,)+ # Feature flags local-eval canary - every 5 minutes+ add_periodic_task_with_expiry(+ sender,+ crontab(minute="*/5"),+ feature_flags_local_eval_canary_task.s(),+ name="feature flags local-eval canary",+ expires_seconds=5 * 60,+ )+# Auth token cache verification - every 6 hours at minute 40# Verifies per-token auth cache entries against the database,# deleting stale entries that signal-based invalidation may have missed.diff --git a/posthog/utils.py b/posthog/utils.pyindex b2e391eea93d..b92c6f1970a8 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -1348,6 +1348,21 @@ def safe_cache_set(cache_key: str, value: Any, timeout: int | None = None) -> Nologger.warning("safe_cache_set_failure", cache_key=cache_key, exc_info=True)+def safe_cache_add(cache_key: str, value: Any, timeout: int | None = None) -> bool:+ """Best-effort atomic set-if-absent. Returns True if this caller set the key+ (i.e. won the race), False if it was already present — useful for cross-process+ throttles where a wave of workers must act at most once per window.++ On a cache failure, returns True so the caller still proceeds (e.g. captures the+ error) rather than silently dropping the signal, matching the fail-visible+ behaviour of the other safe_cache_* helpers."""+ try:+ return bool(cache.add(cache_key, value, timeout))+ except Exception:+ logger.warning("safe_cache_add_failure", cache_key=cache_key, exc_info=True)+ return True++def safe_cache_delete(cache_key: str) -> None:"""Best-effort cache delete. Logs a warning on failure so Redis blipsare visible during incidents without breaking the calling request."""@@ -1357,6 +1372,19 @@ def safe_cache_delete(cache_key: str) -> None:logger.warning("safe_cache_delete_failure", cache_key=cache_key, exc_info=True)+def capture_exception_throttled(throttle_key: str, exc: BaseException, ttl: int) -> bool:+ """Capture an exception at most once per ``ttl`` window across processes (gated on+ an atomic set-if-absent in the cache). Returns True if this caller captured, False+ if it was throttled, so the caller can record which happened.++ The atomic add means a wave of workers failing at once captures only once, instead+ of each racing past a non-atomic get-then-set."""+ captured = safe_cache_add(throttle_key, True, ttl)+ if captured:+ capture_exception(exc)+ return captured++def is_anonymous_id(distinct_id: str) -> bool:# Our anonymous ids are _not_ uuids, but a random collection of stringsreturn bool(re.match(ANONYMOUS_REGEX, distinct_id))diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex 2d29e0d97bb8..eb4c60c272ed 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -77,6 +77,7 @@ from posthog.rate_limit import BurstRateThrottle, ClickHouseBurstRateThrottle, Cfrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.rbac.user_access_control import UserAccessControlSerializerMixinfrom posthog.settings.feature_flags import LOCAL_EVAL_RATE_LIMITS, REMOTE_CONFIG_RATE_LIMITS+from posthog.storage.hypercache import HyperCacheDependencyUnavailablefrom posthog.utils import is_valid_regexfrom posthog.views import format_bytes@@ -302,6 +303,11 @@ LOCAL_EVALUATION_PERSONAL_API_KEY_SOURCE_COUNTER = Counter(labelnames=["source"], # "header", "body", "query_string")+LOCAL_EVALUATION_DEPENDENCY_UNAVAILABLE_COUNTER = Counter(+ "posthog_local_evaluation_dependency_unavailable_total",+ "Local evaluation requests returning 503 because a flag dependency was unavailable on a cold cache",+)+_AUTH_METHOD_BY_CLASS: dict[type, str] = {ProjectSecretAPIKeyAuthentication: "secret_api_key",PersonalAPIKeyAuthentication: "personal_api_key",@@ -3446,6 +3452,7 @@ class FeatureFlagViewSet(200: OpenApiResponse(response=LocalEvaluationResponseSerializer()),402: OpenApiResponse(description="Payment required"),500: OpenApiResponse(description="Internal server error"),+ 503: OpenApiResponse(description="Feature flag dependencies temporarily unavailable"),},)@action(@@ -3549,6 +3556,27 @@ class FeatureFlagViewSet(response["Cache-Control"] = "private, must-revalidate"return response+ except HyperCacheDependencyUnavailable:+ # Cold cache during an upstream (persons DB) outage. Fail loud with a+ # retryable 503 rather than a generic 500: SDKs treat 5xx as "retry / keep+ # last-known config". The dependency layer already captured this (throttled),+ # so re-capturing per request would flood Sentry during an outage.+ LOCAL_EVALUATION_DEPENDENCY_UNAVAILABLE_COUNTER.inc()+ duration = time.time() - start_time+ logger.warning(+ "Feature flag dependencies unavailable during local evaluation",+ extra={"duration": duration, "team_id": self.team.pk},+ )+ response = Response(+ {+ "type": "service_unavailable",+ "code": "flags_dependency_unavailable",+ "detail": "Feature flag dependencies are temporarily unavailable; retry shortly",+ },+ status=status.HTTP_503_SERVICE_UNAVAILABLE,+ )+ response["Retry-After"] = "30"+ return responseexcept Exception as e:duration = time.time() - start_timelogger.error(diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex 1a369a897766..70c49b1c8e39 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -7546,6 +7546,100 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):self.assertEqual(len(cached_json["flags"]), 1)self.assertEqual(cached_json["flags"][0]["key"], "test-flag")+ @patch("products.feature_flags.backend.api.feature_flag.capture_exception")+ def test_local_evaluation_returns_503_when_dependency_unavailable(self, mock_capture):+ """A cold cache during a persons-DB outage fails loud with a retryable 503, not a+ generic 500, and does not re-capture (the dependency layer already did, throttled).++ Drives the real cache→hypercache→endpoint chain (only the group-type fetch is+ patched), so a regressed source token would also surface here."""+ from posthog.models.group_type_mapping import GroupTypesUnavailable++ from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches++ personal_api_key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)+ )++ # Cold cache (Redis + S3) so the read falls through to load_fn, whose group-type+ # fetch is the unavailable dependency. GroupTypesUnavailable subclasses+ # HyperCacheDependencyUnavailable, so this also confirms the endpoint catches the base.+ clear_flag_definition_caches(self.team)+ self.client.logout()+ with patch(+ "products.feature_flags.backend.local_evaluation.get_group_types_for_projects",+ side_effect=GroupTypesUnavailable([self.team.project_id]),+ ):+ response = self.client.get(+ "/api/feature_flag/local_evaluation",+ headers={"authorization": f"Bearer {personal_api_key}"},+ )++ self.assertEqual(response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)+ self.assertEqual(+ response.json(),+ {+ "type": "service_unavailable",+ "code": "flags_dependency_unavailable",+ "detail": "Feature flag dependencies are temporarily unavailable; retry shortly",+ },+ )+ self.assertEqual(response.headers.get("Retry-After"), "30")+ mock_capture.assert_not_called()++ def test_local_evaluation_serves_cached_flags_when_dependency_unavailable(self):+ """A warm cache keeps serving the last-known-good payload during a persons-DB+ outage and never reaches load_fn — the PR's headline behavior. A regression that+ let a warm read fall through to the loader would 503 users who have good data+ cached.++ Drives the real cache→hypercache→endpoint chain; the loader is replaced only+ after the cache is warmed, so a warm hit must not invoke it."""+ from posthog.models.group_type_mapping import GroupTypesUnavailable++ from products.feature_flags.backend import local_evaluation+ from products.feature_flags.backend.local_evaluation import clear_flag_definition_caches++ FeatureFlag.objects.filter(team=self.team).delete()+ FeatureFlag.objects.create(+ team=self.team,+ created_by=self.user,+ key="test-flag",+ filters={"groups": [{"properties": [], "rollout_percentage": 100}]},+ )++ personal_api_key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="Test", user=self.user, scopes=["*"], secure_value=hash_key_value(personal_api_key)+ )++ # Warm the cache (Redis + S3) with one successful read.+ clear_flag_definition_caches(self.team)+ self.client.logout()+ warm = self.client.get(+ "/api/feature_flag/local_evaluation",+ headers={"authorization": f"Bearer {personal_api_key}"},+ )+ self.assertEqual(warm.status_code, status.HTTP_200_OK)++ # The dependency now fails on any rebuild. Patching the loader directly proves a+ # warm hit never reaches it: if it did, this would raise → 503.+ with patch.object(+ local_evaluation,+ "_get_flags_response_for_local_evaluation",+ side_effect=GroupTypesUnavailable([self.team.project_id]),+ ) as mock_load:+ response = self.client.get(+ "/api/feature_flag/local_evaluation",+ headers={"authorization": f"Bearer {personal_api_key}"},+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertEqual([flag["key"] for flag in data["flags"]], ["test-flag"])+ mock_load.assert_not_called()+def test_local_evaluation_caching_with_cohorts(self):"""Test caching with send_cohorts parameter."""cohort = Cohort.objects.create(diff --git a/products/feature_flags/backend/canary.py b/products/feature_flags/backend/canary.pynew file mode 100644index 000000000000..272e1bc6f97e--- /dev/null+++ b/products/feature_flags/backend/canary.py@@ -0,0 +1,94 @@+"""Canary for feature-flags local evaluation.++Builds a configured team's local-eval payload on a schedule and checks that its+``group_type_mapping`` is non-empty and that its group-aggregated flags resolve to a+group type. Gated on ``FEATURE_FLAGS_CANARY_TEAM_ID``; unset means it does nothing.+"""++from typing import Any++from django.conf import settings++import structlog+from prometheus_client import CollectorRegistry, Counter, Gauge++from posthog.models.team import Team++from products.feature_flags.backend.local_evaluation import _get_flags_response_for_local_evaluation++logger = structlog.get_logger(__name__)+++def _unresolved_group_aggregated_flags(payload: dict[str, Any], group_type_mapping: dict[str, str]) -> list[str]:+ """Keys of group-aggregated flags whose aggregation index is absent from the+ mapping, so the flag cannot resolve to a group type."""+ unresolved: list[str] = []+ for flag in payload.get("flags") or []:+ index = (flag.get("filters") or {}).get("aggregation_group_type_index")+ if index is not None and str(index) not in group_type_mapping:+ unresolved.append(flag.get("key", ""))+ return unresolved+++def run_local_eval_canary(registry: CollectorRegistry | None) -> None:+ """Build the canary team's local-eval payload and record its health on the given+ registry. Does nothing when ``FEATURE_FLAGS_CANARY_TEAM_ID`` is unset.++ Metrics:+ - ``posthog_feature_flags_local_eval_canary_group_mapping_present``: 1 when the+ mapping is non-empty, else 0.+ - ``posthog_feature_flags_local_eval_canary_failure_total``: incremented on an+ empty mapping, an unresolved group flag, or an exception.+ """+ team_id = settings.FEATURE_FLAGS_CANARY_TEAM_ID+ if team_id is None:+ logger.debug("Feature flags local-eval canary not configured, skipping")+ return++ present_gauge = Gauge(+ "posthog_feature_flags_local_eval_canary_group_mapping_present",+ "Whether the canary team's local-eval group_type_mapping is non-empty (1) or empty/errored (0)",+ registry=registry,+ )+ failure_counter = Counter(+ "posthog_feature_flags_local_eval_canary_failure",+ "Failures of the feature-flags local-eval canary",+ registry=registry,+ )++ try:+ team = Team.objects.get(id=team_id)+ except Team.DoesNotExist:+ present_gauge.set(0)+ failure_counter.inc()+ logger.exception("Feature flags local-eval canary team not found", team_id=team_id)+ return++ try:+ payload = _get_flags_response_for_local_evaluation(team, include_cohorts=True)+ except Exception as e:+ present_gauge.set(0)+ failure_counter.inc()+ logger.exception("Feature flags local-eval canary failed to build payload", team_id=team_id, error=str(e))+ return++ group_type_mapping = payload.get("group_type_mapping") or {}+ mapping_present = bool(group_type_mapping)+ present_gauge.set(1 if mapping_present else 0)++ unresolved = _unresolved_group_aggregated_flags(payload, group_type_mapping)+ if not mapping_present or unresolved:+ failure_counter.inc()+ logger.error(+ "Feature flags local-eval canary unhealthy",+ team_id=team_id,+ group_type_mapping_present=mapping_present,+ unresolved_group_flags=unresolved,+ )+ return++ logger.info(+ "Feature flags local-eval canary healthy",+ team_id=team_id,+ group_type_count=len(group_type_mapping),+ )diff --git a/products/feature_flags/backend/flags_cache.py b/products/feature_flags/backend/flags_cache.pyindex 5151fcac7fb3..031c63d003f1 100644--- a/products/feature_flags/backend/flags_cache.py+++ b/products/feature_flags/backend/flags_cache.py@@ -547,8 +547,11 @@ def verify_team_flags(db_data = _get_feature_flags_for_service(team)db_flags = db_data.get("flags", []) if isinstance(db_data, dict) else []- # Cache miss (source="db" or "miss" means data was not found in cache)- if source in ("db", "miss"):+ # Cache miss. This verifier reads Redis only (via batch_get_from_cache), so in+ # practice source is "redis" or "miss"; "db"/"dependency_unavailable" are matched+ # defensively to stay in lock-step with verify_team_flag_definitions, which can see+ # them through its single-team cold-load fallback. All mean "nothing cached", not drift.+ if source in ("db", "miss", "dependency_unavailable"):return {"status": "miss","issue": "CACHE_MISS",diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.pyindex e8a2f92888d7..e7c76ac56581 100644--- a/products/feature_flags/backend/local_evaluation.py+++ b/products/feature_flags/backend/local_evaluation.py@@ -38,10 +38,17 @@ from prometheus_client import Counterfrom posthog.models.cohort.cohort import Cohort, CohortOrEmpty, is_cohort_recalculation_only_savefrom posthog.models.cohort.util import get_nested_cohort_ids+from posthog.models.group_type_mapping import (+ GROUP_TYPES_STALE_CACHE_KEY_PREFIX,+ GroupTypesUnavailable,+ get_group_types_for_projects,+ project_has_group_types_authoritatively,+)from posthog.models.team import Teamfrom posthog.person_db_router import PERSONS_DB_FOR_READ-from posthog.storage.hypercache import HyperCache, emit_cache_sync_metrics+from posthog.storage.hypercache import HYPERCACHE_REBUILD_SKIPPED_COUNTER, HyperCache, KeyType, emit_cache_sync_metricsfrom posthog.storage.hypercache_manager import HyperCacheManagementConfig+from posthog.utils import capture_exception_throttled, get_safe_cachefrom products.feature_flags.backend.flags_cache import (_compare_flag_fields,@@ -66,6 +73,16 @@ FLAG_PROCESSING_ERROR_COUNTER = Counter("Number of flags dropped from cache due to processing errors",)+# Rebuilds vetoed because the freshly built group_type_mapping was empty over+# populated data. group_type_mapping is a feature-flags concept, so the counter lives+# here rather than in the generic storage layer. The namespace label is kept for+# wire compatibility even though this guard only ever runs for "feature_flags".+HYPERCACHE_GROUP_MAPPING_EMPTIED_COUNTER = Counter(+ "posthog_hypercache_group_mapping_emptied",+ "Rebuilds skipped because the freshly built group_type_mapping was empty over populated data",+ labelnames=["namespace"],+)+def _get_properties_from_filters(filters: Union[dict, FlagFilters], property_type: str | None = None@@ -450,6 +467,55 @@ def update_flag_definitions_cache(team: Team | int, ttl: int | None = None) -> breturn success+# Throttle window for capturing skipped rebuilds, shared across processes via the+# cache so many workers skipping at once report at most once per window.+_FLAG_CACHE_SKIP_CAPTURE_THROTTLE_TTL = 60 # seconds+++def _capture_flag_cache_skip_throttled(throttle_key: str, exc: BaseException, message: str, **log_fields: Any) -> None:+ """Log a skipped flag-cache rebuild and capture the exception, throttling the+ capture across processes. Each log line records whether the capture ran or was+ throttled."""+ captured = capture_exception_throttled(throttle_key, exc, _FLAG_CACHE_SKIP_CAPTURE_THROTTLE_TTL)+ logger.error(message, exception_captured=captured, capture_throttled=not captured, **log_fields)+++def _group_mapping_would_be_emptied(team: Team, payload: dict[str, Any]) -> bool:+ """True when writing this payload would replace a populated group_type_mapping+ with an empty one.++ An empty freshly built mapping is correct for a team with no group types but is+ the symptom of a silent upstream failure for a team that has them. The per-project+ stale key is the cheap last-known-good signal; when it is absent (never populated,+ expired, or deleted by a concurrent invalidate_group_types_cache) we confirm+ against the persons-DB primary, so the check cannot be defeated by stale-key+ timing.+ """+ if payload.get("group_type_mapping"):+ return False+ if get_safe_cache(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{team.project_id}"):+ return True+ return project_has_group_types_authoritatively(team.project_id)+++def _skip_write_if_group_mapping_emptied(key: KeyType, payload: dict[str, Any]) -> bool:+ """Veto a flag-definitions write that would empty a populated group_type_mapping,+ emitting the skip metric + throttled capture. Shared by every write path — the+ signal-driven rebuild and the refresh/warm update_cache path — so the guard can't+ be bypassed depending on which trigger fired."""+ team = HyperCache.team_from_key(key)+ if not _group_mapping_would_be_emptied(team, payload):+ return False+ HYPERCACHE_GROUP_MAPPING_EMPTIED_COUNTER.labels(namespace="feature_flags").inc()+ _capture_flag_cache_skip_throttled(+ "flag_cache_group_mapping_emptied_capture_throttle",+ Exception(f"group_type_mapping would be emptied for team {team.id}"),+ "Skipped feature_flags cache rebuild: refusing to empty a populated group_type_mapping",+ team_id=team.id,+ )+ return True++def update_flag_caches(team: Team):"""Update both flag cache variants."""logger.info("Syncing feature_flags cache for team", team_id=team.id)@@ -460,12 +526,30 @@ def update_flag_caches(team: Team):size_without_cohorts: int | None = Nonetry:with_cohorts = _get_flags_response_for_local_evaluation(team, include_cohorts=True)- size_with_cohorts = flag_definitions_hypercache.set_cache_value(team, with_cohorts)+ # Both variants share the same mapping, so one check gates both writes.+ if _skip_write_if_group_mapping_emptied(team, with_cohorts):+ return++ # Build both payloads before persisting either, so a failure on the second+ # fetch (e.g. the persons DB drops in this window) skips both writes and the+ # two variants can't drift out of sync.without_cohorts = _get_flags_response_for_local_evaluation(team, include_cohorts=False)++ size_with_cohorts = flag_definitions_hypercache.set_cache_value(team, with_cohorts)size_without_cohorts = flag_definitions_without_cohorts_hypercache.set_cache_value(team, without_cohorts)success = True+ except GroupTypesUnavailable as e:+ # Group types could not be loaded; skip the write to keep the existing entry.+ HYPERCACHE_REBUILD_SKIPPED_COUNTER.labels(namespace="feature_flags", reason="group_types_unavailable").inc()+ _capture_flag_cache_skip_throttled(+ "flag_cache_group_types_unavailable_capture_throttle",+ e,+ "Skipped feature_flags cache rebuild: group types unavailable",+ team_id=team.id,+ )+ returnexcept Exception as e:capture_exception(e)logger.exception("Failed to sync feature_flags cache for team", team_id=team.id, exception=str(e))@@ -583,8 +667,6 @@ def _get_flags_response_for_local_evaluation_batch(# Bulk load group type mappings for all projectsgtm_by_project: dict[int, dict[str, str]] = defaultdict(dict)- from posthog.models.group_type_mapping import get_group_types_for_projects-for pid, mappings in get_group_types_for_projects(list(project_ids)).items():for m in mappings:gtm_by_project[pid][str(m["group_type_index"])] = m["group_type"]@@ -683,14 +765,18 @@ def _update_flag_definitions_with_cohorts(team: Team | int, ttl: int | None = Noresolved_team = _resolve_team(team)if resolved_team is None:return False- return flag_definitions_hypercache.update_cache(resolved_team, ttl=ttl)+ return flag_definitions_hypercache.update_cache(+ resolved_team, ttl=ttl, should_skip_write=_skip_write_if_group_mapping_emptied+ )def _update_flag_definitions_without_cohorts(team: Team | int, ttl: int | None = None) -> bool:resolved_team = _resolve_team(team)if resolved_team is None:return False- return flag_definitions_without_cohorts_hypercache.update_cache(resolved_team, ttl=ttl)+ return flag_definitions_without_cohorts_hypercache.update_cache(+ resolved_team, ttl=ttl, should_skip_write=_skip_write_if_group_mapping_emptied+ )# HyperCache management configs for warming/verification.@@ -754,8 +840,9 @@ def verify_team_flag_definitions(db_flags = db_data.get("flags", []) if isinstance(db_data, dict) else []- # Cache miss (source="db" or "miss" means data was not found in cache)- if source in ("db", "miss"):+ # Cache miss — no usable cache entry (db/miss, or dependency_unavailable when a+ # cold load could not reach its upstream). All mean "nothing cached", not drift.+ if source in ("db", "miss", "dependency_unavailable"):return {"status": "miss","issue": "CACHE_MISS",diff --git a/products/feature_flags/backend/tasks.py b/products/feature_flags/backend/tasks.pyindex b363b4663c83..0a16c293ef7f 100644--- a/products/feature_flags/backend/tasks.py+++ b/products/feature_flags/backend/tasks.py@@ -1,6 +1,7 @@import timefrom django.conf import settings+from django.core.cache import cache as django_cachefrom django.db.models import Count, F, Func, IntegerField, Max, Sum, TextFieldfrom django.db.models.functions import Cast@@ -13,6 +14,7 @@ from posthog.scoping_audit import skip_team_scope_auditfrom posthog.storage.hypercache_manager import HYPERCACHE_SIGNAL_UPDATE_COUNTERfrom posthog.tasks.utils import CeleryQueue, PushGatewayTask+from products.feature_flags.backend.canary import run_local_eval_canaryfrom products.feature_flags.backend.flags_cache import (cleanup_stale_expiry_tracking,get_cache_stats,@@ -28,6 +30,10 @@ from products.feature_flags.backend.models.feature_flag import FeatureFlaglogger = structlog.get_logger(__name__)+# Matches the task's hard time_limit so a crashed run's lock expires before the next+# 5-minute schedule.+LOCAL_EVAL_CANARY_LOCK_TIMEOUT_SECONDS = 90+@shared_task(ignore_result=True, queue=CeleryQueue.FEATURE_FLAGS.value)@skip_team_scope_audit@@ -401,3 +407,36 @@ def cleanup_stale_flag_definitions_expiry_tracking_task(self: PushGatewayTask) -entries_cleaned_gauge.set(total_removed)logger.info("Completed flag definitions expiry tracking cleanup", total_removed_count=total_removed)+++@shared_task(+ bind=True,+ base=PushGatewayTask,+ ignore_result=True,+ queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value,+ soft_time_limit=60,+ time_limit=LOCAL_EVAL_CANARY_LOCK_TIMEOUT_SECONDS,+)+def feature_flags_local_eval_canary_task(self: PushGatewayTask) -> None:+ """Periodic canary for feature-flags local evaluation.++ Builds the configured team's local-eval payload and checks its group_type_mapping+ is non-empty. Does nothing unless FEATURE_FLAGS_CANARY_TEAM_ID is set. A+ distributed lock skips overlapping runs.++ Metrics:+ - posthog_feature_flags_local_eval_canary_group_mapping_present (gauge, 1/0)+ - posthog_feature_flags_local_eval_canary_failure_total (counter)+ """+ if settings.FEATURE_FLAGS_CANARY_TEAM_ID is None:+ return++ lock_key = "posthog:feature_flags_local_eval_canary:lock"+ if not django_cache.add(lock_key, "locked", timeout=LOCAL_EVAL_CANARY_LOCK_TIMEOUT_SECONDS):+ logger.info("Skipping feature flags local-eval canary - already running")+ return++ try:+ run_local_eval_canary(self.metrics_registry)+ finally:+ django_cache.delete(lock_key)diff --git a/products/feature_flags/backend/test/test_canary.py b/products/feature_flags/backend/test/test_canary.pynew file mode 100644index 000000000000..2ab6f692238f--- /dev/null+++ b/products/feature_flags/backend/test/test_canary.py@@ -0,0 +1,121 @@+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.test import override_settings++from prometheus_client import CollectorRegistry++from posthog.tasks.test.utils import PushGatewayTaskTestMixin+from posthog.test.test_utils import create_group_type_mapping_without_created_at++from products.feature_flags.backend.canary import run_local_eval_canary+from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.tasks import feature_flags_local_eval_canary_task++_PRESENT_GAUGE = "posthog_feature_flags_local_eval_canary_group_mapping_present"+_FAILURE_COUNTER = "posthog_feature_flags_local_eval_canary_failure_total"+++class TestLocalEvalCanary(BaseTest):+ def setUp(self):+ super().setUp()+ self.registry = CollectorRegistry()++ def _present(self) -> float | None:+ return self.registry.get_sample_value(_PRESENT_GAUGE)++ def _failures(self) -> float | None:+ return self.registry.get_sample_value(_FAILURE_COUNTER)++ def test_no_op_when_team_id_unset(self):+ with override_settings(FEATURE_FLAGS_CANARY_TEAM_ID=None):+ run_local_eval_canary(self.registry)++ # No metrics registered when the canary is not configured+ assert self._present() is None+ assert self._failures() is None++ def test_healthy_team_marks_mapping_present(self):+ create_group_type_mapping_without_created_at(+ team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0+ )++ with override_settings(FEATURE_FLAGS_CANARY_TEAM_ID=self.team.id):+ run_local_eval_canary(self.registry)++ assert self._present() == 1+ assert self._failures() == 0++ def test_empty_mapping_marks_absent_and_fails(self):+ # Team with no group types, so the mapping is empty+ with override_settings(FEATURE_FLAGS_CANARY_TEAM_ID=self.team.id):+ run_local_eval_canary(self.registry)++ assert self._present() == 0+ assert self._failures() == 1++ def test_unresolved_group_flag_fails_even_with_mapping_present(self):+ create_group_type_mapping_without_created_at(+ team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0+ )+ # Flag aggregates on an index absent from the mapping, so it cannot resolve+ FeatureFlag.objects.create(+ team=self.team,+ key="orphan-group-flag",+ filters={"aggregation_group_type_index": 1, "groups": [{"rollout_percentage": 100}]},+ )++ with override_settings(FEATURE_FLAGS_CANARY_TEAM_ID=self.team.id):+ run_local_eval_canary(self.registry)++ assert self._present() == 1 # the mapping itself is non-empty+ assert self._failures() == 1 # but a group flag can't resolve++ def test_missing_team_marks_absent_and_fails(self):+ with override_settings(FEATURE_FLAGS_CANARY_TEAM_ID=2_000_000_000):+ run_local_eval_canary(self.registry)++ assert self._present() == 0+ assert self._failures() == 1++ def test_build_failure_marks_absent_and_fails(self):+ # A build exception is the exact failure the canary exists to catch: it must+ # mark the mapping absent and count a failure, not report healthy.+ with (+ override_settings(FEATURE_FLAGS_CANARY_TEAM_ID=self.team.id),+ patch(+ "products.feature_flags.backend.canary._get_flags_response_for_local_evaluation",+ side_effect=Exception("boom"),+ ),+ ):+ run_local_eval_canary(self.registry)++ assert self._present() == 0+ assert self._failures() == 1+++@override_settings(FEATURE_FLAGS_CANARY_TEAM_ID=None)+class TestLocalEvalCanaryTask(PushGatewayTaskTestMixin, BaseTest):+ @patch("products.feature_flags.backend.tasks.run_local_eval_canary")+ def test_task_no_ops_when_unset(self, mock_run):+ feature_flags_local_eval_canary_task()+ mock_run.assert_not_called()++ @patch("products.feature_flags.backend.tasks.run_local_eval_canary")+ def test_task_runs_canary_when_configured(self, mock_run):+ with override_settings(FEATURE_FLAGS_CANARY_TEAM_ID=self.team.id):+ feature_flags_local_eval_canary_task()+ mock_run.assert_called_once()++ @patch("products.feature_flags.backend.tasks.run_local_eval_canary")+ def test_task_skips_when_lock_held(self, mock_run):+ from django.core.cache import cache as django_cache++ lock_key = "posthog:feature_flags_local_eval_canary:lock"+ django_cache.add(lock_key, "locked", timeout=60)+ try:+ with override_settings(FEATURE_FLAGS_CANARY_TEAM_ID=self.team.id):+ feature_flags_local_eval_canary_task()+ mock_run.assert_not_called()+ finally:+ django_cache.delete(lock_key)diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.pyindex 637531d34dd3..a52abed878be 100644--- a/products/feature_flags/backend/test/test_local_evaluation.py+++ b/products/feature_flags/backend/test/test_local_evaluation.py@@ -1,17 +1,23 @@from posthog.test.base import BaseTest-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom django.conf import settings+from django.db import DatabaseErrorfrom django.test import override_settingsfrom parameterized import parameterizedfrom posthog.models.cohort.cohort import Cohort-from posthog.models.group_type_mapping import GroupTypeMapping+from posthog.models.group_type_mapping import (+ GROUP_TYPES_STALE_CACHE_KEY_PREFIX,+ GroupTypeMapping,+ GroupTypesUnavailable,+)from posthog.models.project import Projectfrom posthog.models.tag import Tagfrom posthog.models.team.team import Teamfrom posthog.test.test_utils import create_group_type_mapping_without_created_at+from posthog.utils import safe_cache_deletefrom products.feature_flags.backend.flags_cache import get_team_ids_with_recently_updated_flagsfrom products.feature_flags.backend.local_evaluation import (@@ -213,6 +219,184 @@ class TestLocalEvaluationCache(BaseTest):self._assert_payload_valid_with_cohorts(response)+class TestUpdateFlagCachesGroupMappingGuards(BaseTest):+ def setUp(self):+ super().setUp()+ project, team = Project.objects.create_with_team(+ initiating_user=self.user,+ organization=self.organization,+ name="Guard project",+ )+ self.team = team+ create_group_type_mapping_without_created_at(+ team=self.team, project_id=self.team.project_id, group_type="organization", group_type_index=0+ )+ FeatureFlag.objects.create(+ team=self.team,+ key="group-flag",+ filters={"aggregation_group_type_index": 0, "groups": [{"rollout_percentage": 100}]},+ )+ clear_flag_definition_caches(self.team)+ self._clear_stale()++ def tearDown(self):+ self._clear_stale()+ super().tearDown()++ def _clear_stale(self):+ safe_cache_delete(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{self.team.project_id}")++ def _cached_group_type_mapping(self) -> dict:+ response, _ = flag_definitions_hypercache.get_from_cache_with_source(self.team)+ return (response or {}).get("group_type_mapping", {})++ @patch("products.feature_flags.backend.local_evaluation.HYPERCACHE_REBUILD_SKIPPED_COUNTER")+ def test_skips_write_on_group_types_unavailable(self, mock_skipped_counter):+ # Warm with the real fetch so a prior good entry exists+ update_flag_caches(self.team)+ assert self._cached_group_type_mapping() == {"0": "organization"}++ # Persons DB now unavailable with no recoverable last-known-good+ with patch(+ "products.feature_flags.backend.local_evaluation.get_group_types_for_projects",+ side_effect=GroupTypesUnavailable([self.team.project_id]),+ ):+ with patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set:+ update_flag_caches(self.team)+ mock_set.assert_not_called()++ mock_skipped_counter.labels.assert_called_once_with(namespace="feature_flags", reason="group_types_unavailable")+ # Prior good entry survives untouched+ assert self._cached_group_type_mapping() == {"0": "organization"}++ @patch("products.feature_flags.backend.local_evaluation.HYPERCACHE_GROUP_MAPPING_EMPTIED_COUNTER")+ def test_skips_write_when_mapping_would_be_emptied(self, mock_emptied_counter):+ # Warm with the real fetch so the non-empty last-known-good stale exists+ update_flag_caches(self.team)+ assert self._cached_group_type_mapping() == {"0": "organization"}++ # Fetch now returns empty without erroring, while last-known-good is non-empty+ with patch(+ "products.feature_flags.backend.local_evaluation.get_group_types_for_projects",+ return_value={self.team.project_id: []},+ ):+ with patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set:+ update_flag_caches(self.team)+ mock_set.assert_not_called()++ mock_emptied_counter.labels.assert_called_once_with(namespace="feature_flags")+ assert self._cached_group_type_mapping() == {"0": "organization"}++ @patch("products.feature_flags.backend.local_evaluation.HYPERCACHE_GROUP_MAPPING_EMPTIED_COUNTER")+ def test_refresh_path_skips_write_when_mapping_would_be_emptied(self, mock_emptied_counter):+ # The periodic refresh/warm path goes through update_cache, not update_flag_caches.+ # It must apply the same guard so a silent empty can't overwrite good data here either.+ update_flag_caches(self.team)+ assert self._cached_group_type_mapping() == {"0": "organization"}++ with patch(+ "products.feature_flags.backend.local_evaluation.get_group_types_for_projects",+ return_value={self.team.project_id: []},+ ):+ with patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set:+ assert _update_flag_definitions_with_cohorts(self.team) is False+ mock_set.assert_not_called()++ mock_emptied_counter.labels.assert_called_once_with(namespace="feature_flags")+ assert self._cached_group_type_mapping() == {"0": "organization"}++ @patch("products.feature_flags.backend.local_evaluation.HYPERCACHE_GROUP_MAPPING_EMPTIED_COUNTER")+ def test_single_project_empty_success_does_not_defeat_guard(self, mock_emptied_counter):+ # Layer interaction: the high-frequency single-project fetch shares the stale+ # key with the rebuild guard. A single-project empty-success must not clobber+ # that key, or a later rebuild would wave the empty mapping through.+ from posthog.models.group_type_mapping import GROUP_TYPES_CACHE_KEY_PREFIX, get_group_types_for_project++ # Warm with the real fetch so the non-empty last-known-good stale exists.+ update_flag_caches(self.team)+ assert self._cached_group_type_mapping() == {"0": "organization"}++ # A single-project fetch returns empty without erroring (the empty-but-not-+ # erroring upstream). It must not overwrite the populated stale fallback.+ safe_cache_delete(f"{GROUP_TYPES_CACHE_KEY_PREFIX}{self.team.project_id}")+ with (+ patch("posthog.personhog_client.client.get_personhog_client", return_value=MagicMock()),+ patch("posthog.models.group_type_mapping._fetch_group_types_via_personhog", return_value=[]),+ ):+ assert get_group_types_for_project(self.team.project_id) == []++ # Stale survived, so a subsequent empty-success rebuild still trips the guard.+ with patch(+ "products.feature_flags.backend.local_evaluation.get_group_types_for_projects",+ return_value={self.team.project_id: []},+ ):+ with patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set:+ update_flag_caches(self.team)+ mock_set.assert_not_called()++ mock_emptied_counter.labels.assert_called_once_with(namespace="feature_flags")+ assert self._cached_group_type_mapping() == {"0": "organization"}++ @patch("products.feature_flags.backend.local_evaluation.HYPERCACHE_GROUP_MAPPING_EMPTIED_COUNTER")+ def test_writes_when_genuinely_empty(self, mock_emptied_counter):+ # A team that truly has no group types must still rebuild normally+ GroupTypeMapping.objects.filter(team_id=self.team.id).delete()+ self._clear_stale()+ clear_flag_definition_caches(self.team)++ update_flag_caches(self.team)++ # Wrote an empty mapping (correct for this team) without tripping the guard+ assert self._cached_group_type_mapping() == {}+ mock_emptied_counter.labels.assert_not_called()++ @patch("products.feature_flags.backend.local_evaluation.HYPERCACHE_GROUP_MAPPING_EMPTIED_COUNTER")+ def test_skips_write_when_stale_absent_but_primary_has_group_types(self, mock_emptied_counter):+ # TOCTOU / replica-lag: the stale key was deleted by a concurrent+ # invalidate_group_types_cache (or expired) while the group type still exists.+ # The guard must confirm against the primary, not wave the empty through.+ update_flag_caches(self.team)+ assert self._cached_group_type_mapping() == {"0": "organization"}++ # Simulate the concurrent invalidation deleting the last-known-good stale key.+ self._clear_stale()++ # Fetch returns empty without erroring, but the row still exists in the DB.+ with patch(+ "products.feature_flags.backend.local_evaluation.get_group_types_for_projects",+ return_value={self.team.project_id: []},+ ):+ with patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set:+ update_flag_caches(self.team)+ mock_set.assert_not_called()++ mock_emptied_counter.labels.assert_called_once_with(namespace="feature_flags")+ assert self._cached_group_type_mapping() == {"0": "organization"}++ @patch("products.feature_flags.backend.local_evaluation.HYPERCACHE_GROUP_MAPPING_EMPTIED_COUNTER")+ def test_fails_closed_when_confirmation_read_errors(self, mock_emptied_counter):+ # Stale absent and the authoritative confirmation read fails: the guard must+ # fail closed (block the empty write) rather than risk clobbering good data.+ update_flag_caches(self.team)+ assert self._cached_group_type_mapping() == {"0": "organization"}+ self._clear_stale()++ with (+ patch(+ "products.feature_flags.backend.local_evaluation.get_group_types_for_projects",+ return_value={self.team.project_id: []},+ ),+ patch("posthog.models.group_type_mapping.GroupTypeMapping.objects") as mock_objects,+ ):+ mock_objects.using.return_value.filter.return_value.exists.side_effect = DatabaseError("persons db down")+ with patch.object(flag_definitions_hypercache, "set_cache_value") as mock_set:+ update_flag_caches(self.team)+ mock_set.assert_not_called()++ mock_emptied_counter.labels.assert_called_once_with(namespace="feature_flags")+ assert self._cached_group_type_mapping() == {"0": "organization"}++class TestLocalEvaluationSignals(BaseTest):@patch("products.feature_flags.backend.tasks.update_team_flags_cache")@patch("django.db.transaction.on_commit", lambda fn: fn())