Skip to content

: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.

fix(flags): reconfirm cold-cache group types and degroup skip exception (#72481)

posthog[bot]cb360915021b
diff --git a/posthog/models/group_type_mapping.py b/posthog/models/group_type_mapping.py
index dd89cfba76c2..355be6cae68b 100644
--- a/posthog/models/group_type_mapping.py
+++ b/posthog/models/group_type_mapping.py
@@ -371,29 +371,40 @@ def _reconfirm_emptied_projects_against_primary(
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.
+ mapping. Every project that reads empty is re-confirmed against the primary at strong
+ consistency — unless it has no last-known-good and carries a "confirmed empty" marker
+ from a recent primary read — and we trust that answer: the primary is authoritative
+ for both "was dropped" and "genuinely empty now" (e.g. the last group type was
+ deleted).
+
+ Reconfirming every empty (not only those with a populated last-known-good) closes the
+ cold-cache edge — empty replica read, no stale key, project actually populated — that
+ otherwise slipped past to the write-side guard and fired its exception. The
+ confirmed-empty marker bounds the cost: a project with genuinely no group types (the
+ common case) is probed at most once per marker TTL rather than on every rebuild, and
+ the same marker short-circuits the write-side project_has_group_types_authoritatively
+ check, so this moves that primary read earlier rather than adding new load.
+
+ 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 the confirmed-empty marker is set
+ so subsequent reads skip the primary probe.
"""
- suspect_stale: dict[int, list[dict[str, Any]]] = {}
+ # pid -> last-known-good (None when no stale key exists — the cold-cache edge).
+ suspects: dict[int, list[dict[str, Any]] | None] = {}
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:
+ # A populated last-known-good always wins over the marker: the two can only
+ # disagree via a race or a dropped safe_cache_delete, and the write-side guard
+ # resolves that disagreement the same way (stale key checked before the marker).
+ if stale is None and get_safe_cache(f"{GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX}{pid}"):
+ continue
+ suspects[pid] = stale
+ if not suspects:
return result
- suspect_ids = list(suspect_stale.keys())
+ suspect_ids = list(suspects.keys())
try:
client = require_personhog_client()
@@ -405,9 +416,12 @@ def _reconfirm_emptied_projects_against_primary(
)
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():
+ # the replica's unconfirmed empty, so we never hand back a silent [] over data we
+ # know was populated. Projects with no last-known-good keep the replica's empty —
+ # there is nothing to restore and it can't be confirmed either way.
+ for pid, stale in suspects.items():
+ if stale is None:
+ continue
result[pid] = stale
GROUP_TYPES_REPLICA_EMPTY_DISCREPANCIES.labels(
operation="get_group_types_for_projects", outcome="primary_unavailable_used_stale"
@@ -428,6 +442,9 @@ def _reconfirm_emptied_projects_against_primary(
)
else:
safe_cache_delete(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{pid}")
+ safe_cache_set(
+ f"{GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX}{pid}", True, GROUP_TYPES_CONFIRMED_EMPTY_CACHE_TTL
+ )
GROUP_TYPES_REPLICA_EMPTY_DISCREPANCIES.labels(
operation="get_group_types_for_projects", outcome="confirmed_empty"
).inc()
@@ -440,9 +457,10 @@ def get_group_types_for_projects(
"""Batch fetch group types for multiple projects via personhog, falling back to
the 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.
+ The batch read is at eventual consistency; any project that reads empty is
+ re-confirmed against the primary (unless a recent primary read already marked it
+ confirmed-empty) 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 requested
project has no cached last-known-good, rather than returning an all-empty
diff --git a/posthog/models/test/test_group_type_mapping.py b/posthog/models/test/test_group_type_mapping.py
index 39ded6e834b7..70cae658f84d 100644
--- a/posthog/models/test/test_group_type_mapping.py
+++ b/posthog/models/test/test_group_type_mapping.py
@@ -30,6 +30,7 @@ from posthog.utils import get_safe_cache, safe_cache_delete, safe_cache_set
def _clear_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}")
+ safe_cache_delete(f"{GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX}{project_id}")
PERSONHOG_SUCCESS_DATA = [
@@ -262,9 +263,9 @@ 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.
+ get_group_types_for_projects must re-confirm every empty against the primary —
+ including the cold-cache edge where no last-known-good exists — while a confirmed-empty
+ marker keeps the common no-groups path off the primary after the first probe.
"""
def setUp(self):
@@ -294,9 +295,11 @@ class TestGetGroupTypesForProjectsReplicaReconfirm(SimpleTestCase):
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)
+ def test_replica_empty_without_stale_is_reconfirmed_from_primary(self):
+ # The cold-cache edge: the replica dropped populated_pid, there is no stale key,
+ # and the project is authoritatively populated. The reconfirm must still probe the
+ # primary and correct the empty, closing the edge that otherwise reached (and fired)
+ # the write-side guard.
rows = [{"group_type": "organization", "group_type_index": 0}]
with self._patch_fetch(
@@ -306,24 +309,63 @@ class TestGetGroupTypesForProjectsReplicaReconfirm(SimpleTestCase):
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]
+ assert sorted(strong_calls[0].args[1]) == sorted(self.project_ids)
- 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).
+ def test_confirmed_empty_marker_keeps_cold_empties_off_primary(self):
+ # A genuinely empty project is probed once, marked confirmed-empty, then skipped on
+ # the next read — so reconfirming cold empties doesn't hammer the primary on every
+ # rebuild for the common no-group-types case.
with self._patch_fetch(
replica={self.populated_pid: [], self.empty_pid: []},
- primary={self.populated_pid: [{"group_type": "organization", "group_type_index": 0}]},
+ primary={},
) as mock_fetch:
+ get_group_types_for_projects(self.project_ids)
+ # Second call: both projects now carry the confirmed-empty marker, so the
+ # replica's empty is trusted without another primary probe.
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"] == []
+ strong_calls = [c for c in mock_fetch.call_args_list if c.kwargs.get("consistency") == "strong"]
+ assert len(strong_calls) == 1
+
+ def test_replica_empty_with_stale_is_reconfirmed_from_primary(self):
+ # The real replica-drop case: a populated last-known-good exists and the primary
+ # still has the rows. Covered separately from the cold-cache edge because this is
+ # the path that fires during an actual replica lag incident.
+ 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},
+ ):
+ result = get_group_types_for_projects(self.project_ids)
+
+ assert result[self.populated_pid] == rows
+
+ def test_stale_key_outranks_confirmed_empty_marker(self):
+ # The marker and a populated last-known-good can only disagree via a race or a
+ # dropped safe_cache_delete. When they do, the stale key wins and the project is
+ # still reconfirmed — otherwise the marker would suppress the correction for its
+ # whole TTL, and the write-side guard (which checks the stale key first) would
+ # fire the exception this reconfirm exists to prevent.
+ self._set_stale(self.populated_pid)
+ safe_cache_set(f"{GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX}{self.populated_pid}", True, 3600)
+ 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
+ strong_calls = [c for c in mock_fetch.call_args_list if c.kwargs.get("consistency") == "strong"]
+ assert len(strong_calls) == 1
+ assert self.populated_pid in strong_calls[0].args[1]
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
@@ -338,13 +380,15 @@ class TestGetGroupTypesForProjectsReplicaReconfirm(SimpleTestCase):
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.
+ # group types on a later personhog outage, and the confirmed-empty marker is set so
+ # this project stops probing the primary on every subsequent read.
assert get_safe_cache(f"{GROUP_TYPES_STALE_CACHE_KEY_PREFIX}{self.populated_pid}") is None
+ assert get_safe_cache(f"{GROUP_TYPES_CONFIRMED_EMPTY_CACHE_KEY_PREFIX}{self.populated_pid}") is True
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.
+ # If the primary confirmation itself fails, serve the last-known-good for the project
+ # that has one rather than handing back the replica's unconfirmed empty. A project
+ # with no last-known-good has nothing to restore, so it keeps the replica's empty.
self._set_stale(self.populated_pid)
def fetch(client, project_ids, *, consistency="eventual"):
@@ -359,6 +403,7 @@ class TestGetGroupTypesForProjectsReplicaReconfirm(SimpleTestCase):
result = get_group_types_for_projects(self.project_ids)
assert result[self.populated_pid] == PERSONHOG_SUCCESS_DATA
+ assert result[self.empty_pid] == []
class TestGetGroupTypesForProjectCacheBehavior(SimpleTestCase):
diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.py
index 8e47cc4a3116..9c72ea1c84d9 100644
--- a/products/feature_flags/backend/local_evaluation.py
+++ b/products/feature_flags/backend/local_evaluation.py
@@ -482,7 +482,10 @@ def _skip_write_if_group_mapping_emptied(key: KeyType, payload: dict[str, Any])
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}"),
+ # Keep team.id out of the message so error tracking groups every team's skip into
+ # one issue instead of spawning a separate issue per team. The team is on the log
+ # line below for debugging.
+ Exception("group_type_mapping would be emptied for a team with populated group types"),
"Skipped feature_flags cache rebuild: refusing to empty a populated group_type_mapping",
team_id=team.id,
)