: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): bootstrap flags with the identity the browser sends (#119619)
Paul D'Ambraa6831d2146e0
diff --git a/frontend/src/lib/utils/posthogIdentity.ts b/frontend/src/lib/utils/posthogIdentity.tsindex 466b1a13f1a1..1f9cfba4c647 100644--- a/frontend/src/lib/utils/posthogIdentity.ts+++ b/frontend/src/lib/utils/posthogIdentity.ts@@ -15,7 +15,10 @@ interface UserIdentity {groups: PostHogGroup[]}-/** Feature flags target these person and group properties, so this list also decides what a user's flags can use. */+/**+ * Feature flags target these person and group properties, so this list also decides what a user's flags can use.+ * `_flag_identity` in `posthog/utils.py` builds the same inputs for the server flag bootstrap. Change both together.+ */function userIdentity(user: UserType): UserIdentity {const groups: PostHogGroup[] = []if (user.team) {diff --git a/posthog/test/test_get_context_for_template.py b/posthog/test/test_get_context_for_template.pyindex c29d00aed8c6..6053aa04d053 100644--- a/posthog/test/test_get_context_for_template.py+++ b/posthog/test/test_get_context_for_template.py@@ -5,6 +5,7 @@ from posthog.test.base import APIBaseTestfrom unittest import mockfrom unittest.mock import MagicMock+from django.conf import settingsfrom django.contrib.auth.models import AnonymousUserfrom django.contrib.sessions.middleware import SessionMiddlewarefrom django.http import HttpResponse@@ -187,17 +188,54 @@ class TestGetContextForTemplate(APIBaseTest):app_context = actual["posthog_app_context"]assert app_context["homepage"] == (stored_homepage or None)+ @parameterized.expand([("shares_email", False, "[email protected]"), ("anonymized", True, None)])@mock.patch("posthog.utils.posthoganalytics.get_all_flags", return_value={})- def test_flag_bootstrap_evaluates_with_the_project_group(self, mock_get_all_flags):+ def test_flag_bootstrap_evaluates_with_the_identity_the_browser_sends(+ self, _name, anonymize_data, expected_email, mock_get_all_flags+ ):+ self.user.email = "[email protected]"+ self.user.anonymize_data = anonymize_data+ self.user.save()+ self.organization.customer_id = "cus_123"+ self.organization.save()request = RequestFactory().get("/")SessionMiddleware(lambda _request: HttpResponse()).process_request(request)request.user = self.user- get_context_for_template("layout", request)+ with self.settings(SITE_URL="https://app.example.com"):+ get_context_for_template("layout", request)kwargs = mock_get_all_flags.call_args.kwargs- assert kwargs["groups"]["project"] == str(self.team.uuid)- assert kwargs["group_properties"]["project"]["id"] == self.team.id+ assert kwargs["person_properties"] == {+ "email": expected_email,+ "joined_at": self.user.date_joined.isoformat(),+ }+ assert kwargs["groups"] == {+ "project": str(self.team.uuid),+ "organization": str(self.organization.id),+ "customer": "cus_123",+ "instance": "https://app.example.com",+ }+ assert kwargs["group_properties"]["project"] == {+ "id": self.team.id,+ "uuid": str(self.team.uuid),+ "name": self.team.name,+ "ingested_event": self.team.ingested_event,+ "is_demo": self.team.is_demo,+ "timezone": self.team.timezone,+ "instance_tag": settings.INSTANCE_TAG,+ }+ assert kwargs["group_properties"]["organization"] == {+ "id": str(self.organization.id),+ "name": self.organization.name,+ "slug": self.organization.slug,+ "created_at": mock.ANY,+ "available_product_features": self.organization.available_product_features or [],+ "member_count": 1,+ "project_count": 1,+ "instance_tag": settings.INSTANCE_TAG,+ }+ assert kwargs["group_properties"]["instance"] == {"site_url": "https://app.example.com"}def test_bootstraps_project_tags_into_app_context(self):# projectLogic reads currentProject from the app context and only calls the API when it isdiff --git a/posthog/utils.py b/posthog/utils.pyindex 48461840f95f..e5ef2c4b40d6 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -53,6 +53,7 @@ from rest_framework.utils.encoders import JSONEncoderfrom posthog.cloud_utils import get_cached_instance_license, is_cloudfrom posthog.constants import POSTHOG_JS_CLOUD_HOST, POSTHOG_JS_CLOUD_TOKEN, AvailableFeature+from posthog.dataclasses import frozenfrom posthog.exceptions import RequestParsingError, UnspecifiedCompressionFallbackParsingErrorfrom posthog.exceptions_capture import capture_exceptionfrom posthog.git import get_git_branch, get_git_commit_short@@ -485,6 +486,60 @@ def _read_preload_manifest(manifest_path: str, include_authenticated_shell: boolreturn ("", (), "")+@frozen+class _FlagIdentity:+ person_properties: dict[str, Any]+ groups: dict[str, str]+ group_properties: dict[str, dict[str, Any]]+++def _flag_identity(current_user: dict[str, Any], joined_at: str) -> _FlagIdentity:+ """+ Mirrors `userIdentity()` in `frontend/src/lib/utils/posthogIdentity.ts`, which sends these inputs to /flags.+ Local evaluation drops any flag it cannot decide from them, and decides a flag differently when they differ.+ """+ groups: dict[str, str] = {}+ group_properties: dict[str, dict[str, Any]] = {}+ organization = current_user.get("organization")+ team = current_user.get("team")+ metadata = (organization.get("metadata") or {}) if organization else {}+ if team:+ groups["project"] = team["uuid"]+ group_properties["project"] = {+ "id": team["id"],+ "uuid": team["uuid"],+ "name": team["name"],+ "ingested_event": team["ingested_event"],+ "is_demo": team["is_demo"],+ "timezone": team["timezone"],+ "instance_tag": metadata.get("instance_tag"),+ }+ if organization:+ groups["organization"] = organization["id"]+ group_properties["organization"] = {+ "id": organization["id"],+ "name": organization["name"],+ "slug": organization["slug"],+ "created_at": organization["created_at"],+ "available_product_features": organization["available_product_features"],+ "member_count": organization["member_count"],+ "project_count": len(organization["teams"]),+ **metadata,+ }+ if organization.get("customer_id"):+ groups["customer"] = organization["customer_id"]+ groups["instance"] = settings.SITE_URL+ group_properties["instance"] = {"site_url": settings.SITE_URL}+ return _FlagIdentity(+ person_properties={+ "email": None if current_user["anonymize_data"] else current_user["email"],+ "joined_at": joined_at,+ },+ groups=groups,+ group_properties=group_properties,+ )++@tracer.start_as_current_span("template.context")def get_context_for_template(template_name: str,@@ -714,34 +769,16 @@ def _build_template_context(context["posthog_app_context"] = posthog_app_contextif posthog_distinct_id:- groups = {}- group_properties: dict[str, dict[str, str | int]] = {}- person_properties = {}- if request.user and request.user.is_authenticated:- user = cast("User", request.user)- person_properties["email"] = user.email- person_properties["joined_at"] = user.date_joined.isoformat()- if user.organization:- groups["organization"] = str(user.organization.id)- group_properties["organization"] = {- "name": user.organization.name,- "created_at": user.organization.created_at.isoformat(),- }- if user.team:- groups["project"] = str(user.team.uuid)- group_properties["project"] = {- "id": user.team.id,- "uuid": str(user.team.uuid),- "name": user.team.name,- }+ user = cast("User", request.user)+ identity = _flag_identity(posthog_app_context["current_user"], user.date_joined.isoformat())with tracer.start_as_current_span("template.feature_flag_bootstrap"):feature_flags = posthoganalytics.get_all_flags(posthog_distinct_id,only_evaluate_locally=True,- person_properties=person_properties,- groups=groups,- group_properties=group_properties,+ person_properties=identity.person_properties,+ groups=identity.groups,+ group_properties=identity.group_properties,)# don't forcefully set distinctID, as this breaks the link for anonymous users coming from `posthog.com`.posthog_bootstrap["featureFlags"] = feature_flags