:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(flags): expose minimal_flag_called_events in the local-eval blob (#71623)
Phil Haack212eed745589
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.jsonindex e149174386e0..d9449d9196ea 100644--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json@@ -1614,6 +1614,14 @@],"label": "Feature flag evaluated at"},+ "$feature_flag_has_experiment": {+ "description": "Whether the feature flag that was called is linked to a live experiment.",+ "examples": [+ "true",+ "false"+ ],+ "label": "Feature flag has experiment"+ },"$feature_flag_id": {"description": "The numeric identifier of the feature flag that was called.","examples": [@@ -6001,6 +6009,14 @@],"label": "Feature flag evaluated at"},+ "$feature_flag_has_experiment": {+ "description": "Whether the feature flag that was called is linked to a live experiment.",+ "examples": [+ "true",+ "false"+ ],+ "label": "Feature flag has experiment"+ },"$feature_flag_id": {"description": "The numeric identifier of the feature flag that was called.","examples": [diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.pyindex c3e259f0b82f..5844d8e612d6 100644--- a/posthog/taxonomy/taxonomy.py+++ b/posthog/taxonomy/taxonomy.py@@ -1750,6 +1750,11 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {"description": "The numeric identifier of the feature flag that was called.","examples": ["1234"],},+ "$feature_flag_has_experiment": {+ "label": "Feature flag has experiment",+ "description": "Whether the feature flag that was called is linked to a live experiment.",+ "examples": ["true", "false"],+ },"$feature_flag_bootstrapped_response": {"label": "Feature flag bootstrapped response","description": "The response value provided to the SDK at initialization via the bootstrap option, before evaluation against PostHog.",diff --git a/products/feature_flags/backend/api/staff_team_config.py b/products/feature_flags/backend/api/staff_team_config.pyindex 2156fc7207b3..2ba089a622e3 100644--- a/products/feature_flags/backend/api/staff_team_config.py+++ b/products/feature_flags/backend/api/staff_team_config.py@@ -115,12 +115,17 @@ class FeatureFlagsStaffTeamConfigViewSet(viewsets.ViewSet):# posthog.tasks.team_metadata sits under posthog.tasks, whose __init__ is a celery# autoimport aggregator that pulls in every task module — keep that off the API- # router's import path by deferring it to call time.+ # router's import path by deferring it to call time. The local tasks module is+ # deferred for the same reason (it imports celery machinery).from posthog.tasks.team_metadata import update_team_metadata_cache_task # noqa: PLC0415- # /flags and /decide read this value out of team_metadata_hypercache, not the DB, so the- # write above has no effect until that cache is rebuilt.+ from products.feature_flags.backend.tasks import update_team_flags_cache # noqa: PLC0415++ # /flags and /decide read this value out of team_metadata_hypercache, and local-eval+ # SDKs read it out of the flag-definitions blob — neither reads the DB, so the write+ # above has no effect until both caches are rebuilt.update_team_metadata_cache_task.delay(team.id)+ update_team_flags_cache.delay(team.id)logger.info("flags_staff_team_config_updated",diff --git a/products/feature_flags/backend/local_evaluation.py b/products/feature_flags/backend/local_evaluation.pyindex d2d3b6ed66f8..8e47cc4a3116 100644--- a/products/feature_flags/backend/local_evaluation.py+++ b/products/feature_flags/backend/local_evaluation.py@@ -60,6 +60,7 @@ from products.feature_flags.backend.flags_cache import ()from products.feature_flags.backend.models.evaluation_context import EvaluationContext, FeatureFlagEvaluationContextfrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfigfrom products.feature_flags.backend.types import FlagFilters, FlagProperty, PropertyFilterTypefrom products.surveys.backend.models import Survey@@ -539,10 +540,28 @@ def clear_flag_definition_caches(team: KeyType, kinds: list[str] | None = None):flag_definitions_hypercache.clear_cache(team, kinds=kinds)+def _local_eval_response(+ *,+ flags: list[dict[str, Any]],+ group_type_mapping: dict[str, str],+ cohorts: dict[str, Any],+ minimal_flag_called_events: bool,+) -> dict[str, Any]:+ return {+ "flags": flags,+ "group_type_mapping": group_type_mapping,+ "cohorts": cohorts,+ "minimal_flag_called_events": minimal_flag_called_events,+ }++def _get_flags_response_for_local_evaluation(team: Team) -> dict[str, Any]:"""Build the local-evaluation response for a single team."""results = _get_flags_response_for_local_evaluation_batch([team])- return results.get(team.id, {"flags": [], "group_type_mapping": {}, "cohorts": {}})+ return results.get(+ team.id,+ _local_eval_response(flags=[], group_type_mapping={}, cohorts={}, minimal_flag_called_events=False),+ )def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[int, dict[str, Any]]:@@ -562,6 +581,16 @@ def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[inteam_by_id = {t.id: t for t in teams}project_ids = list({t.project_id for t in teams})+ # Slim $feature_flag_called gate, exposed top-level so local-eval SDKs (which never+ # call /flags) get the same signal FlagsResponse.minimal_flag_called_events carries.+ # Absent row → False → SDKs send full events, same fail-safe as the /flags path.+ minimal_flag_called_events_by_team: defaultdict[int, bool] = defaultdict(+ bool,+ TeamFeatureFlagsConfig.objects.db_manager(DATABASE_FOR_LOCAL_EVALUATION)+ .filter(team_id__in=team_ids)+ .values_list("team_id", "minimal_flag_called_events"),+ )+# Bulk load survey flag IDs across all teamssurvey_flag_ids: set[int] = set()for row in (@@ -690,22 +719,24 @@ def _get_flags_response_for_local_evaluation_batch(teams: list[Team]) -> dict[inFLAG_PROCESSING_ERROR_COUNTER.inc()continue- response_data: dict[str, Any] = {- "flags": flags_data,- "group_type_mapping": gtm_by_project.get(team.project_id, {}),- "cohorts": cohorts,- }+ response_data = _local_eval_response(+ flags=flags_data,+ group_type_mapping=gtm_by_project.get(team.project_id, {}),+ cohorts=cohorts,+ minimal_flag_called_events=minimal_flag_called_events_by_team[tid],+ )results[tid] = _apply_flag_dependency_transformation(response_data, flag_id_to_key)# Ensure every requested team has a result, even if it had no flagsfor tid in team_ids:if tid not in results:- results[tid] = {- "flags": [],- "group_type_mapping": gtm_by_project.get(team_by_id[tid].project_id, {}),- "cohorts": {},- }+ results[tid] = _local_eval_response(+ flags=[],+ group_type_mapping=gtm_by_project.get(team_by_id[tid].project_id, {}),+ cohorts={},+ minimal_flag_called_events=minimal_flag_called_events_by_team[tid],+ )return results@@ -743,6 +774,16 @@ FLAG_DEFINITIONS_HYPERCACHE_MANAGEMENT_CONFIG = HyperCacheManagementConfig()+# Top-level blob fields (besides "flags", compared separately by key) checked for drift by+# verify_team_flag_definitions. Each entry is (field, mismatch type, default used when a legacy+# blob predates the field — None means the field has always been present).+_TOP_LEVEL_FIELDS_TO_COMPARE: list[tuple[str, str, Any]] = [+ ("cohorts", "COHORTS_MISMATCH", None),+ ("group_type_mapping", "GROUP_TYPE_MAPPING_MISMATCH", None),+ ("minimal_flag_called_events", "MINIMAL_FLAG_CALLED_EVENTS_MISMATCH", False),+]++def verify_team_flag_definitions(team: Team,db_batch_data: dict | None = None,@@ -831,12 +872,12 @@ def verify_team_flag_definitions(diff["field_diffs"] = field_diffsdiffs.append(diff)- # Also compare cohorts and group_type_mapping+ # Also compare top-level blob fields other than flags (cohorts, group_type_mapping, …).+ # A default other than None means a legacy blob missing the key isn't reported as drift.if cached_data is not None and db_data is not None:- if cached_data.get("cohorts") != db_data.get("cohorts"):- diffs.append({"type": "COHORTS_MISMATCH", "flag_key": "cohorts"})- if cached_data.get("group_type_mapping") != db_data.get("group_type_mapping"):- diffs.append({"type": "GROUP_TYPE_MAPPING_MISMATCH", "flag_key": "group_type_mapping"})+ for field, mismatch_type, default in _TOP_LEVEL_FIELDS_TO_COMPARE:+ if cached_data.get(field, default) != db_data.get(field, default):+ diffs.append({"type": mismatch_type, "flag_key": field})if not diffs:return {"status": "match", "issue": "", "details": ""}@@ -845,8 +886,7 @@ def verify_team_flag_definitions(missing_count = sum(1 for d in diffs if d.get("type") == "MISSING_IN_CACHE")stale_count = sum(1 for d in diffs if d.get("type") == "STALE_IN_CACHE")mismatch_count = sum(1 for d in diffs if d.get("type") == "FIELD_MISMATCH")- cohorts_mismatch = any(d.get("type") == "COHORTS_MISMATCH" for d in diffs)- gtm_mismatch = any(d.get("type") == "GROUP_TYPE_MAPPING_MISMATCH" for d in diffs)+ mismatched_types = {d.get("type") for d in diffs}summary_parts = []if missing_count > 0:@@ -857,11 +897,11 @@ def verify_team_flag_definitions(summary_parts.append(f"{mismatch_count} mismatched")flag_summary = f"{', '.join(summary_parts)} flags" if summary_parts else ""- extra_parts = []- if cohorts_mismatch:- extra_parts.append("cohorts mismatch")- if gtm_mismatch:- extra_parts.append("group_type_mapping mismatch")+ extra_parts = [+ f"{field} mismatch"+ for field, mismatch_type, _ in _TOP_LEVEL_FIELDS_TO_COMPARE+ if mismatch_type in mismatched_types+ ]details = "; ".join(filter(None, [flag_summary, ", ".join(extra_parts)]))diff --git a/products/feature_flags/backend/test/test_local_evaluation.py b/products/feature_flags/backend/test/test_local_evaluation.pyindex 565d3a01bbb5..7fe1ebc37d41 100644--- a/products/feature_flags/backend/test/test_local_evaluation.py+++ b/products/feature_flags/backend/test/test_local_evaluation.py@@ -33,6 +33,7 @@ from products.feature_flags.backend.local_evaluation import (verify_team_flag_definitions,)from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.team_feature_flags_config import TeamFeatureFlagsConfigfrom products.surveys.backend.models import Survey@@ -970,6 +971,37 @@ class TestLocalEvaluationBatch(BaseTest):assert "group_type_mapping" in results[team_without_flags.id]assert "cohorts" in results[team_without_flags.id]+ def test_batch_includes_minimal_flag_called_events_gate(self):+ # Local-eval SDKs never call /flags, so the blob is their only source of the slim+ # $feature_flag_called gate. Catches the key being dropped from the payload, a gated+ # team reading False, or an ungated/legacy team (no config row) reading anything but+ # False — including on the no-flags fallback path.+ gated_team = self._create_team_with_project("Gated")+ gated_team_no_flags = self._create_team_with_project("Gated no flags")+ ungated_team = self._create_team_with_project("Ungated")++ TeamFeatureFlagsConfig.objects.update_or_create(team=gated_team, defaults={"minimal_flag_called_events": True})+ TeamFeatureFlagsConfig.objects.update_or_create(+ team=gated_team_no_flags, defaults={"minimal_flag_called_events": True}+ )+ TeamFeatureFlagsConfig.objects.filter(team=ungated_team).delete()++ FeatureFlag.objects.create(+ team=gated_team,+ key="gated-flag",+ filters={"groups": [{"rollout_percentage": 100}]},+ )++ results = _get_flags_response_for_local_evaluation_batch([gated_team, gated_team_no_flags, ungated_team])++ assert results[gated_team.id]["minimal_flag_called_events"] is True+ # Gated team with no flags hits the no-flags fallback path, not the main response path.+ # Without this case, a fallback that hardcodes False instead of threading the gate would+ # pass unnoticed, since the ungated team's expected False is indistinguishable from that.+ assert results[gated_team_no_flags.id]["flags"] == []+ assert results[gated_team_no_flags.id]["minimal_flag_called_events"] is True+ assert results[ungated_team.id]["minimal_flag_called_events"] is False+def test_batch_team_with_no_flags_includes_group_type_mapping(self):team = self._create_team_with_project("GTM Team")@@ -1258,10 +1290,11 @@ class TestLocalEvaluationBatch(BaseTest):filters={"groups": [{"rollout_percentage": 100}]},)- with self.assertNumQueries(2):- # Expected queries: survey flag IDs and flags (with evaluation- # tags via ArrayAgg). Group type mappings are read from- # personhog, not SQL. No cohort query should be issued.+ with self.assertNumQueries(3):+ # Expected queries: the minimal_flag_called_events gate, survey flag+ # IDs, and flags (with evaluation tags via ArrayAgg). Group type+ # mappings are read from personhog, not SQL. No cohort query should+ # be issued.results = _get_flags_response_for_local_evaluation_batch([team])assert results[team.id]["cohorts"] == {}@@ -1437,6 +1470,33 @@ class TestVerifyFlagDefinitions(BaseTest):assert result["status"] == "match"assert result["issue"] == ""+ def test_verify_detects_stale_minimal_flag_called_events(self):+ # A gated team whose blob was cached before the gate flipped must report drift+ # so verify-and-fix rewrites it; otherwise local-eval SDKs keep the stale gate+ # until TTL expiry if the staff endpoint's rebuild task was lost.+ update_flag_definitions_cache(self.team)++ TeamFeatureFlagsConfig.objects.update_or_create(team=self.team, defaults={"minimal_flag_called_events": True})++ result = verify_team_flag_definitions(self.team)++ assert result["status"] == "mismatch"+ assert "minimal_flag_called_events mismatch" in result["details"]++ def test_verify_treats_absent_gate_key_as_false(self):+ # Pre-existing blobs written before the key existed must not report drift for+ # ungated teams — absent and False both mean "full events" to SDKs. Guards+ # against a fleet-wide rewrite storm on deploy.+ update_flag_definitions_cache(self.team)+ cached, _ = flag_definitions_hypercache.get_from_cache_with_source(self.team)+ assert cached is not None+ legacy_blob = {k: v for k, v in cached.items() if k != "minimal_flag_called_events"}+ flag_definitions_hypercache.set_cache_value(self.team, legacy_blob)++ result = verify_team_flag_definitions(self.team)++ assert result["status"] == "match"+def test_verify_returns_mismatch_when_flag_key_renamed(self):flag = FeatureFlag.objects.create(team=self.team,diff --git a/products/feature_flags/backend/test/test_staff_team_config_api.py b/products/feature_flags/backend/test/test_staff_team_config_api.pyindex 625429e963b6..71a4e91bf0f9 100644--- a/products/feature_flags/backend/test/test_staff_team_config_api.py+++ b/products/feature_flags/backend/test/test_staff_team_config_api.py@@ -74,8 +74,11 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)@parameterized.expand([(True,), (False,)])- def test_set_updates_db_value_and_enqueues_cache_refresh_task(self, new_value):- with patch("posthog.tasks.team_metadata.update_team_metadata_cache_task") as mock_task:+ def test_set_updates_db_value_and_enqueues_cache_refresh_tasks(self, new_value):+ with (+ patch("posthog.tasks.team_metadata.update_team_metadata_cache_task") as mock_metadata_task,+ patch("products.feature_flags.backend.tasks.update_team_flags_cache") as mock_flags_task,+ ):response = self.client.post(SET_URL, {"team_id": self.team.id, "minimal_flag_called_events": new_value}, format="json")@@ -85,9 +88,11 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):config = TeamFeatureFlagsConfig.objects.get(team=self.team)self.assertEqual(config.minimal_flag_called_events, new_value)- # /flags and /decide read this value out of team_metadata_hypercache, not the DB, so a- # bare write has no effect until that cache is rebuilt.- mock_task.delay.assert_called_once_with(self.team.id)+ # /flags and /decide read this value out of team_metadata_hypercache, and local-eval+ # SDKs read it out of the flag-definitions blob — a bare DB write has no effect until+ # both caches are rebuilt.+ mock_metadata_task.delay.assert_called_once_with(self.team.id)+ mock_flags_task.delay.assert_called_once_with(self.team.id)def test_set_returns_404_for_unknown_team(self):missing_id = self.team.id + 9999@@ -99,7 +104,10 @@ class TestFeatureFlagsStaffTeamConfigAPI(APIBaseTest):# auto-created row from the team-creation signal.TeamFeatureFlagsConfig.objects.filter(team=self.team).delete()- with patch("posthog.tasks.team_metadata.update_team_metadata_cache_task"):+ with (+ patch("posthog.tasks.team_metadata.update_team_metadata_cache_task"),+ patch("products.feature_flags.backend.tasks.update_team_flags_cache"),+ ):response = self.client.post(SET_URL, {"team_id": self.team.id, "minimal_flag_called_events": True}, format="json")