: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): count projects tab evaluations from flag_evaluations (#110148)
Phil Haack0a728c9dfdf9
diff --git a/posthog/test/base.py b/posthog/test/base.pyindex 097bf6a4e231..d745f8f54558 100644--- a/posthog/test/base.py+++ b/posthog/test/base.py@@ -1794,6 +1794,34 @@ def _create_event(**kwargs):return kwargs["event_uuid"]+def _create_flag_evaluations(team_id: int, flag_key: str, count: int = 1, timestamp: dt.datetime | None = None) -> None:+ """Insert `count` $feature_flag_called rows for flag_key into flag_evaluations. Unlike _create_event, it writes+ the rows immediately."""+ timestamp = timestamp or dt.datetime.now(dt.UTC)+ properties = json.dumps({"$feature_flag": flag_key, "$feature_flag_response": True})+ # writable_flag_evaluations does not declare flag_key. The shard computes it from properties.$feature_flag.+ sync_execute(+ """+ INSERT INTO writable_flag_evaluations+ (uuid, event, properties, timestamp, team_id, distinct_id, created_at, person_id)+ VALUES+ """,+ [+ (+ str(uuid.uuid4()),+ "$feature_flag_called",+ properties,+ timestamp,+ team_id,+ "evaluator",+ timestamp,+ str(uuid.uuid4()),+ )+ for _ in range(count)+ ],+ )++def _warn_if_session_id_malformed(session_id: str):try:session_id_parsed = uuid.UUID(session_id)diff --git a/posthog/test/test_feature_flag_analytics.py b/posthog/test/test_feature_flag_analytics.pyindex f64de495a53d..e8a72939dac1 100644--- a/posthog/test/test_feature_flag_analytics.py+++ b/posthog/test/test_feature_flag_analytics.py@@ -10,6 +10,7 @@ from posthog.test.base import (ClickhouseTestMixin,QueryMatchingTest,_create_event,+ _create_flag_evaluations,flush_persons_and_events,snapshot_postgres_queries_context,)@@ -17,6 +18,8 @@ from unittest.mock import MagicMock, patchfrom django.core.cache import cache+from parameterized import parameterized+from posthog import redisfrom posthog.constants import FlagRequestTypefrom posthog.errors import CHQueryErrorUnknownTable@@ -24,6 +27,7 @@ from posthog.models.team.team import Teamfrom posthog.tasks.tasks import find_flags_with_enriched_analytics as find_flags_with_enriched_analytics_taskfrom products.feature_flags.backend.api.feature_flag import _create_usage_dashboard+from products.feature_flags.backend.facade.enums import FlagEvaluationsModefrom products.feature_flags.backend.flag_analytics import (SDK_LIBRARIES,_enriched_flag_key_expr_sql,@@ -38,6 +42,7 @@ from products.feature_flags.backend.flag_analytics import (increment_request_count,)from products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfigclass TestFeatureFlagAnalytics(BaseTest, QueryMatchingTest):@@ -1099,10 +1104,13 @@ class TestFindFlagsWithEnrichedAnalyticsTask(BaseTest):class TestCrossProjectEvaluations(ClickhouseTestMixin, APIBaseTest):def test_returns_zero_when_no_events(self):- counts = get_evaluations_7d_by_team("some_key", [self.team.id])+ counts = get_evaluations_7d_by_team("some_key", [self.team.id], from_flag_evaluations=False)assert counts == {self.team.id: 0}- def test_counts_events_by_team(self):+ @parameterized.expand([("events", False, 2, 1), ("flag_evaluations", True, 1, 3)])+ def test_counts_flag_calls_by_team_from_the_selected_table(+ self, _name, from_flag_evaluations, team_count, other_team_count+ ):other_team = self.organization.teams.create(name="Other")_create_event(team=self.team,@@ -1130,19 +1138,28 @@ class TestCrossProjectEvaluations(ClickhouseTestMixin, APIBaseTest):)flush_persons_and_events()- counts = get_evaluations_7d_by_team("my_flag", [self.team.id, other_team.id])+ _create_flag_evaluations(self.team.id, "my_flag")+ _create_flag_evaluations(other_team.id, "my_flag", count=3)+ _create_flag_evaluations(self.team.id, "unrelated")+ _create_flag_evaluations(+ self.team.id, "my_flag", timestamp=datetime.datetime.now(datetime.UTC) - datetime.timedelta(days=8)+ )++ counts = get_evaluations_7d_by_team(+ "my_flag", [self.team.id, other_team.id], from_flag_evaluations=from_flag_evaluations+ )- assert counts == {self.team.id: 2, other_team.id: 1}+ assert counts == {self.team.id: team_count, other_team.id: other_team_count}def test_returns_empty_dict_when_no_team_ids(self):- assert get_evaluations_7d_by_team("any_flag", []) == {}+ assert get_evaluations_7d_by_team("any_flag", [], from_flag_evaluations=False) == {}def test_returns_none_when_clickhouse_fails(self):with patch("products.feature_flags.backend.flag_analytics.sync_execute",side_effect=RuntimeError("boom"),):- assert get_evaluations_7d_by_team("my_flag", [self.team.id, 99]) is None+ assert get_evaluations_7d_by_team("my_flag", [self.team.id, 99], from_flag_evaluations=False) is Noneclass TestCachedCrossProjectEvaluations(ClickhouseTestMixin, APIBaseTest):@@ -1155,8 +1172,8 @@ class TestCachedCrossProjectEvaluations(ClickhouseTestMixin, APIBaseTest):"products.feature_flags.backend.flag_analytics.get_evaluations_7d_by_team",return_value={self.team.id: 5},) as spy:- first = get_cached_evaluations_7d_by_team("my_flag", [self.team.id])- second = get_cached_evaluations_7d_by_team("my_flag", [self.team.id])+ first = get_cached_evaluations_7d_by_team("my_flag", [self.team.id], self.organization.id)+ second = get_cached_evaluations_7d_by_team("my_flag", [self.team.id], self.organization.id)assert first == {self.team.id: 5}assert second == {self.team.id: 5}@@ -1167,15 +1184,33 @@ class TestCachedCrossProjectEvaluations(ClickhouseTestMixin, APIBaseTest):"products.feature_flags.backend.flag_analytics.get_evaluations_7d_by_team",side_effect=[None, {self.team.id: 7}],) as spy:- first = get_cached_evaluations_7d_by_team("my_flag", [self.team.id])- second = get_cached_evaluations_7d_by_team("my_flag", [self.team.id])+ first = get_cached_evaluations_7d_by_team("my_flag", [self.team.id], self.organization.id)+ second = get_cached_evaluations_7d_by_team("my_flag", [self.team.id], self.organization.id)assert first is Noneassert second == {self.team.id: 7}assert spy.call_count == 2def test_cached_returns_empty_dict_when_no_team_ids(self):- assert get_cached_evaluations_7d_by_team("any_flag", []) == {}+ assert get_cached_evaluations_7d_by_team("any_flag", [], self.organization.id) == {}++ def test_mode_change_does_not_serve_the_result_cached_under_the_previous_mode(self):+ _create_event(+ team=self.team,+ distinct_id="u1",+ event="$feature_flag_called",+ properties={"$feature_flag": "my_flag", "$feature_flag_response": True},+ )+ flush_persons_and_events()+ _create_flag_evaluations(self.team.id, "my_flag", count=2)+ assert get_cached_evaluations_7d_by_team("my_flag", [self.team.id], self.organization.id) == {self.team.id: 1}++ OrganizationFeatureFlagsConfig.objects.filter(organization=self.organization).update(+ flag_evaluations_mode=FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY+ )+ counts = get_cached_evaluations_7d_by_team("my_flag", [self.team.id], self.organization.id)++ assert counts == {self.team.id: 2}class TestFlagKeyFilterSQL(BaseTest):diff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.pyindex b40a97c6ed8f..29ef50a044c9 100644--- a/products/feature_flags/backend/api/organization_feature_flag.py+++ b/products/feature_flags/backend/api/organization_feature_flag.py@@ -287,7 +287,7 @@ class OrganizationFeatureFlagView(self._redact_encrypted_payloads(request, flag)counts_by_team = get_cached_evaluations_7d_by_team(- cast(str, feature_flag_key), [flag.team_id for flag in flags]+ cast(str, feature_flag_key), [flag.team_id for flag in flags], self.organization.id)flags_data = [diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambrindex 04097447e97e..a2239e678b14 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr@@ -1626,6 +1626,15 @@'''# ---# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.15+ '''+ SELECT "feature_flags_organizationfeatureflagsconfig"."flag_evaluations_mode" AS "flag_evaluations_mode"+ FROM "feature_flags_organizationfeatureflagsconfig"+ WHERE "feature_flags_organizationfeatureflagsconfig"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ ORDER BY "feature_flags_organizationfeatureflagsconfig"."organization_id" ASC+ LIMIT 1+ '''+# ---+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.16'''SELECT "posthog_user"."id","posthog_user"."password",@@ -1672,7 +1681,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.16+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.17'''SELECT "posthog_user"."id","posthog_user"."password",diff --git a/products/feature_flags/backend/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.pyindex 679895d1d9aa..9aa94cefb1d7 100644--- a/products/feature_flags/backend/api/test/test_organization_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py@@ -6,6 +6,7 @@ from posthog.test.base import (ClickhouseTestMixin,QueryMatchingTest,_create_event,+ _create_flag_evaluations,flush_persons_and_events,snapshot_postgres_queries,snapshot_postgres_queries_context,@@ -40,7 +41,9 @@ from products.feature_flags.backend.encrypted_flag_payloads import (encrypt_flag_payloads,get_decrypted_flag_payload,)+from products.feature_flags.backend.facade.enums import FlagEvaluationsModefrom products.feature_flags.backend.models.feature_flag import FeatureFlag+from products.feature_flags.backend.models.organization_feature_flags_config import OrganizationFeatureFlagsConfigfrom products.feature_flags.backend.models.scheduled_change import ScheduledChangefrom products.surveys.backend.models import Survey@@ -3950,7 +3953,15 @@ class TestOrganizationFeatureFlagEvaluations(ClickhouseTestMixin, APIBaseTest):for entry in body:assert "evaluations_7d" in entry- def test_evaluation_counts_match_events(self):+ @parameterized.expand(+ [+ ("events", FlagEvaluationsMode.EVENTS, 2, 1),+ ("read_flag_evaluations", FlagEvaluationsMode.READ_FLAG_EVALUATIONS, 2, 1),+ ("flag_evaluations_only", FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY, 1, 3),+ ]+ )+ def test_evaluation_counts_come_from_the_table_the_mode_selects(self, _name, mode, team_count, other_team_count):+ OrganizationFeatureFlagsConfig.objects.filter(organization=self.organization).update(flag_evaluations_mode=mode)_create_event(team=self.team,distinct_id="u1",@@ -3970,12 +3981,13 @@ class TestOrganizationFeatureFlagEvaluations(ClickhouseTestMixin, APIBaseTest):properties={"$feature_flag": "shared_flag", "$feature_flag_response": False},)flush_persons_and_events()+ _create_flag_evaluations(self.team.id, "shared_flag")+ _create_flag_evaluations(self.other_team.id, "shared_flag", count=3)body = self.client.get(self._url("shared_flag")).json()by_team = {entry["team_id"]: entry["evaluations_7d"] for entry in body}- assert by_team[self.team.id] == 2- assert by_team[self.other_team.id] == 1+ assert by_team == {self.team.id: team_count, self.other_team.id: other_team_count}def test_clickhouse_failure_returns_null_evaluations(self):with patch(diff --git a/products/feature_flags/backend/facade/enums.py b/products/feature_flags/backend/facade/enums.pyindex 82d19214ae58..6ed0ef01d49a 100644--- a/products/feature_flags/backend/facade/enums.py+++ b/products/feature_flags/backend/facade/enums.py@@ -16,7 +16,8 @@ class FlagEvaluationsMode(LabeledIntEnum):# The Usage tab reads flag_evaluations, and the HogQL table is visible.READ_FLAG_EVALUATIONS = 1, "Read flag evaluations"# As READ_FLAG_EVALUATIONS, and ingestion stops writing $feature_flag_called to events. Ingestion- # ignores this mode until the change that implements it deploys. Until then the mode acts as- # READ_FLAG_EVALUATIONS. An organization already on this mode stops the events writes when that- # change deploys.+ # ignores this mode until the change that implements it deploys. Until then the Usage tab and the+ # HogQL table act as they do on READ_FLAG_EVALUATIONS. Some readers, such as the organization flag+ # Projects tab, read flag_evaluations only in this mode. An organization already on this mode+ # stops the events writes when that change deploys.FLAG_EVALUATIONS_ONLY = 2, "Flag evaluations only"diff --git a/products/feature_flags/backend/flag_analytics.py b/products/feature_flags/backend/flag_analytics.pyindex 7045c50b1a45..4d0b01efba64 100644--- a/products/feature_flags/backend/flag_analytics.py+++ b/products/feature_flags/backend/flag_analytics.py@@ -1,6 +1,7 @@import timefrom datetime import datetimefrom typing import TYPE_CHECKING+from uuid import UUIDfrom django.conf import settingsfrom django.core.cache import cache@@ -13,8 +14,11 @@ from posthog.constants import FlagRequestTypefrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.dashboard_templates import add_enriched_insights_to_feature_flag_dashboardfrom posthog.models import Team+from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_TABLEfrom posthog.redis import get_client, redis+from products.feature_flags.backend.facade.enums import FlagEvaluationsMode+from products.feature_flags.backend.facade.flags import get_organization_flag_evaluations_modefrom products.feature_flags.backend.models.feature_flag import FeatureFlagif TYPE_CHECKING:@@ -301,21 +305,29 @@ def _flag_key_filter_sql() -> str:return "JSONExtractString(properties, '$feature_flag') = %(flag_key)s"-def _build_cross_project_evals_query() -> str:+def _build_cross_project_evals_query(from_flag_evaluations: bool) -> str:+ if from_flag_evaluations:+ # flag_evaluations stores only $feature_flag_called rows, so it needs no event filter.+ table, prewhere, flag_key_filter = FLAG_EVALUATIONS_TABLE, "", "flag_key = %(flag_key)s"+ else:+ table, prewhere, flag_key_filter = "events", "PREWHERE event = '$feature_flag_called'", _flag_key_filter_sql()return f"""SELECT team_id, count() AS evaluations-FROM events-PREWHERE event = '$feature_flag_called'-WHERE {_flag_key_filter_sql()}+FROM {table}+{prewhere}+WHERE {flag_key_filter}AND team_id IN %(team_ids)sAND timestamp >= now() - INTERVAL 7 DAYGROUP BY team_id"""-def get_evaluations_7d_by_team(flag_key: str, team_ids: list[int]) -> dict[int, int] | None:+def get_evaluations_7d_by_team(+ flag_key: str, team_ids: list[int], *, from_flag_evaluations: bool+) -> dict[int, int] | None:"""Return per-team 7-day counts of `$feature_flag_called` events for flag_key.+ Reads flag_evaluations when `from_flag_evaluations` is set, and events otherwise.Returns a dict mapping team_id -> count (all requested team ids are present;teams with no events map to 0). Returns `None` when ClickHouse fails so thecaller can render an unavailable state instead of a misleading zero.@@ -325,7 +337,10 @@ def get_evaluations_7d_by_team(flag_key: str, team_ids: list[int]) -> dict[int,tag_queries(product=Product.FEATURE_FLAGS, feature=Feature.QUERY, name="get_evaluations_7d_by_team")try:- rows = sync_execute(_build_cross_project_evals_query(), {"flag_key": flag_key, "team_ids": tuple(team_ids)})+ rows = sync_execute(+ _build_cross_project_evals_query(from_flag_evaluations),+ {"flag_key": flag_key, "team_ids": tuple(team_ids)},+ )except Exception as error:capture_exception(error)return None@@ -336,21 +351,32 @@ def get_evaluations_7d_by_team(flag_key: str, team_ids: list[int]) -> dict[int,return counts-def get_cached_evaluations_7d_by_team(flag_key: str, team_ids: list[int]) -> dict[int, int] | None:+def get_cached_evaluations_7d_by_team(+ flag_key: str, team_ids: list[int], organization_id: UUID+) -> dict[int, int] | None:"""Cached variant of get_evaluations_7d_by_team with a 5-minute TTL.+ Every team in `team_ids` must belong to the organization `organization_id`.+ Only an organization on FLAG_EVALUATIONS_ONLY reads flag_evaluations. Unlike+ the Usage tab, READ_FLAG_EVALUATIONS stays on events, because ingestion keeps+ writing every flag call to events in that mode.Failure results (None) are not cached, so recovery is immediate onceClickHouse is reachable again."""if not team_ids:return {}- cache_key = f"flag_analytics:evals_7d:{flag_key}:" + ",".join(str(t) for t in sorted(team_ids))+ from_flag_evaluations = (+ get_organization_flag_evaluations_mode(organization_id) == FlagEvaluationsMode.FLAG_EVALUATIONS_ONLY+ )+ # The key names the source table, so a mode change cannot serve a count read from the other table.+ source = FLAG_EVALUATIONS_TABLE if from_flag_evaluations else "events"+ cache_key = f"flag_analytics:evals_7d:{source}:{flag_key}:" + ",".join(str(t) for t in sorted(team_ids))cached = cache.get(cache_key)if cached is not None:return cached- result = get_evaluations_7d_by_team(flag_key, team_ids)+ result = get_evaluations_7d_by_team(flag_key, team_ids, from_flag_evaluations=from_flag_evaluations)if result is not None:cache.set(cache_key, result, timeout=CROSS_PROJECT_EVALS_CACHE_TTL)return result