: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): reconfirm empty group-type reads against the primary (#68703)
posthog[bot]e45619bf2d14
diff --git a/posthog/models/group_type_mapping.py b/posthog/models/group_type_mapping.pyindex c8438dca58b6..c8bb24a4cb49 100644--- a/posthog/models/group_type_mapping.py+++ b/posthog/models/group_type_mapping.py@@ -44,6 +44,17 @@ GROUP_TYPES_FETCH_FAILURES = Counter(labelnames=["operation", "source", "error_type"],)+# A project the eventual (replica) batch read returned empty for despite a populated+# last-known-good. The `outcome` records what the strong (primary) re-read found:+# "primary_had_rows" (replica silently dropped it, corrected), "confirmed_empty"+# (genuinely empty now), or "primary_unavailable_used_stale" (primary read failed,+# served last-known-good rather than an unconfirmed empty).+GROUP_TYPES_REPLICA_EMPTY_DISCREPANCIES = Counter(+ "posthog_group_types_replica_empty_discrepancies",+ "Projects the eventual batch read returned empty for despite a populated last-known-good",+ labelnames=["operation", "outcome"],+)+class GroupTypesUnavailable(HyperCacheDependencyUnavailable):"""Raised by the batch fetch when group types cannot be loaded and no@@ -242,15 +253,19 @@ def get_group_types_for_team(team_id: int, *, caller_tag: str | None = None) ->def _fetch_group_types_for_projects_via_personhog(- client: PersonHogClient, project_ids: list[int]+ client: PersonHogClient, project_ids: list[int], *, consistency: ReadConsistency = "eventual") -> dict[int, list[dict[str, Any]]]:from posthog.personhog_client.converters import proto_group_type_mapping_to_dictfrom posthog.personhog_client.proto import GetGroupTypeMappingsByProjectIdsRequest+ read_options = consistency_to_read_options(consistency)result: dict[int, list[dict[str, Any]]] = {}for i in range(0, len(project_ids), settings.PERSONHOG_BATCH_SIZE):resp = client.get_group_type_mappings_by_project_ids(- GetGroupTypeMappingsByProjectIdsRequest(project_ids=project_ids[i : i + settings.PERSONHOG_BATCH_SIZE])+ GetGroupTypeMappingsByProjectIdsRequest(+ project_ids=project_ids[i : i + settings.PERSONHOG_BATCH_SIZE],+ read_options=read_options,+ ))for batch in resp.results:mappings = [proto_group_type_mapping_to_dict(m) for m in batch.mappings]@@ -338,12 +353,88 @@ def _recover_projects_from_stale_or_fail(project_ids: list[int], exc: DatabaseErreturn recovered+def _reconfirm_emptied_projects_against_primary(+ result: dict[int, list[dict[str, Any]]], project_ids: list[int], *, caller_tag: str | None = None+) -> dict[int, list[dict[str, Any]]]:+ """Guard against a lagging or inconsistent replica silently dropping a project's+ group types.++ The batch fetch reads at eventual consistency (the replica pool), which can return+ an empty mapping for a project that authoritatively has group types. That silent+ empty is what makes the downstream flag-cache write try to erase a populated+ mapping. When a project reads empty but has a populated last-known-good (stale key),+ re-read just those projects from the primary at strong consistency and trust that+ answer — the primary is authoritative for both "was dropped" and "genuinely empty+ now" (e.g. the last group type was deleted).++ Projects that read empty with no last-known-good are treated as genuinely having no+ group types (the common case). They are not re-confirmed, so this adds no primary+ load on the hot path unless a real drop is detected. The write-side guard remains the+ backstop for that cold-cache edge. When the primary confirms a project is genuinely+ empty, its stale key is cleared so a later outage can't resurrect the deleted data+ and so the project stops being flagged as a suspect on every subsequent read.+ """+ suspect_stale: dict[int, list[dict[str, Any]]] = {}+ for pid in project_ids:+ if result.get(pid):+ continue+ stale = get_safe_cache(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{pid}")+ if stale is not None:+ suspect_stale[pid] = stale+ if not suspect_stale:+ return result++ suspect_ids = list(suspect_stale.keys())++ try:+ client = require_personhog_client()+ confirmed = personhog_call(+ "get_group_types_for_projects_reconfirm",+ lambda: _fetch_group_types_for_projects_via_personhog(client, suspect_ids, consistency="strong"),+ caller_tag=f"group_type_mapping/{caller_tag or 'get_group_types_for_projects'}/reconfirm",+ reraise_as=DatabaseError,+ )+ except DatabaseError:+ # Primary confirmation failed. Serve each project's last-known-good rather than+ # the replica's unconfirmed empty, so we never hand back a silent [] over data+ # we know was populated.+ for pid, stale in suspect_stale.items():+ result[pid] = stale+ GROUP_TYPES_REPLICA_EMPTY_DISCREPANCIES.labels(+ operation="get_group_types_for_projects", outcome="primary_unavailable_used_stale"+ ).inc()+ return result++ for pid in suspect_ids:+ primary_rows = confirmed.get(pid) or []+ if primary_rows:+ result[pid] = primary_rows+ GROUP_TYPES_REPLICA_EMPTY_DISCREPANCIES.labels(+ operation="get_group_types_for_projects", outcome="primary_had_rows"+ ).inc()+ logger.warning(+ "group_types_replica_returned_empty_primary_had_rows",+ project_id=pid,+ row_count=len(primary_rows),+ )+ else:+ safe_cache_delete(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{pid}")+ GROUP_TYPES_REPLICA_EMPTY_DISCREPANCIES.labels(+ operation="get_group_types_for_projects", outcome="confirmed_empty"+ ).inc()+ return result++def get_group_types_for_projects(project_ids: list[int], *, caller_tag: str | None = None) -> dict[int, list[dict[str, Any]]]:"""Batch fetch group types for multiple projects via personhog, falling back tothe per-project stale cache on failure.+ The batch read is at eventual consistency; any project that reads empty despite a+ populated last-known-good is re-confirmed against the primary so a lagging replica+ cannot silently return an empty mapping for a project that has group types.+Raises GroupTypesUnavailable if personhog is unavailable and any requestedproject has no cached last-known-good, rather than returning an all-emptymapping. Callers must handle that case.@@ -366,6 +457,7 @@ def get_group_types_for_projects(except DatabaseError as exc:return _recover_projects_from_stale_or_fail(project_ids, exc)+ result = _reconfirm_emptied_projects_against_primary(result, project_ids, caller_tag=caller_tag)_populate_projects_stale_cache(result)return resultdiff --git a/posthog/models/test/test_group_type_mapping.py b/posthog/models/test/test_group_type_mapping.pyindex 61957b2705f7..3605fa7edb69 100644--- a/posthog/models/test/test_group_type_mapping.py+++ b/posthog/models/test/test_group_type_mapping.py@@ -242,6 +242,109 @@ class TestGetGroupTypesForProjects(SimpleTestCase):}+class TestGetGroupTypesForProjectsReplicaReconfirm(SimpleTestCase):+ """The batch fetch reads at eventual consistency; a lagging or inconsistent replica+ can return an empty mapping for a project that authoritatively has group types. That+ silent empty is what drove the flag-cache write to try to erase a populated mapping.+ get_group_types_for_projects must re-confirm such empties against the primary — but+ only when a populated last-known-good exists, so the common no-groups path stays off+ the primary.+ """++ def setUp(self):+ self.populated_pid = 7001+ self.empty_pid = 7002+ self.project_ids = [self.populated_pid, self.empty_pid]+ for pid in self.project_ids:+ _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 self.project_ids:+ _clear_cache(pid)++ def _set_stale(self, pid: int) -> None:+ safe_cache_set(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{pid}", PERSONHOG_SUCCESS_DATA, 3600)++ def _patch_fetch(self, *, replica: dict, primary: dict):+ def fetch(client, project_ids, *, consistency="eventual"):+ source = primary if consistency == "strong" else replica+ return {pid: source.get(pid, []) for pid in project_ids}++ return patch(+ "posthog.models.group_type_mapping._fetch_group_types_for_projects_via_personhog",+ side_effect=fetch,+ )++ def test_replica_empty_with_stale_is_reconfirmed_from_primary(self):+ # The replica silently dropped populated_pid; the primary still has its rows.+ self._set_stale(self.populated_pid)+ rows = [{"group_type": "organization", "group_type_index": 0}]++ with self._patch_fetch(+ replica={self.populated_pid: [], self.empty_pid: []},+ primary={self.populated_pid: rows},+ ) as mock_fetch:+ result = get_group_types_for_projects(self.project_ids)++ assert result[self.populated_pid] == rows+ # empty_pid has no last-known-good, so it is trusted as genuinely empty.+ assert result[self.empty_pid] == []++ strong_calls = [c for c in mock_fetch.call_args_list if c.kwargs.get("consistency") == "strong"]+ assert len(strong_calls) == 1+ assert strong_calls[0].args[1] == [self.populated_pid]++ def test_replica_empty_without_stale_is_not_reconfirmed(self):+ # No last-known-good for either project → the primary is never probed and the+ # empties are trusted (the common no-group-types path must stay cheap).+ with self._patch_fetch(+ replica={self.populated_pid: [], self.empty_pid: []},+ primary={self.populated_pid: [{"group_type": "organization", "group_type_index": 0}]},+ ) as mock_fetch:+ result = get_group_types_for_projects(self.project_ids)++ assert result == {self.populated_pid: [], self.empty_pid: []}+ assert [c for c in mock_fetch.call_args_list if c.kwargs.get("consistency") == "strong"] == []++ def test_replica_empty_with_stale_but_primary_empty_stays_empty(self):+ # The last group type was genuinely deleted: the primary confirms empty, so we+ # trust it rather than resurrecting the (now outdated) last-known-good.+ self._set_stale(self.populated_pid)++ with self._patch_fetch(+ replica={self.populated_pid: [], self.empty_pid: []},+ primary={self.populated_pid: []},+ ):+ result = get_group_types_for_projects(self.project_ids)++ assert result[self.populated_pid] == []+ # The now-outdated last-known-good is cleared so it can't resurrect the deleted+ # group types on a later personhog outage, and so this project stops being+ # flagged as a suspect on every subsequent read.+ assert get_safe_cache(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{self.populated_pid}") is None++ def test_primary_reconfirm_failure_serves_stale_not_empty(self):+ # If the primary confirmation itself fails, serve the last-known-good rather than+ # handing back the replica's unconfirmed empty.+ self._set_stale(self.populated_pid)++ def fetch(client, project_ids, *, consistency="eventual"):+ if consistency == "strong":+ raise RuntimeError("primary unavailable")+ return {pid: [] for pid in project_ids}++ with patch(+ "posthog.models.group_type_mapping._fetch_group_types_for_projects_via_personhog",+ side_effect=fetch,+ ):+ result = get_group_types_for_projects(self.project_ids)++ assert result[self.populated_pid] == PERSONHOG_SUCCESS_DATA++class TestGetGroupTypesForProjectCacheBehavior(SimpleTestCase):def setUp(self):self.project_id = 888