: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(app-context): evaluate only the app's flags in the flag bootstrap (#125166)
Paul D'Ambrab2e3b704030d
diff --git a/posthog/test/test_get_context_for_template.py b/posthog/test/test_get_context_for_template.pyindex c7b9ec5854c4..b3397e45a69e 100644--- a/posthog/test/test_get_context_for_template.py+++ b/posthog/test/test_get_context_for_template.py@@ -11,6 +11,7 @@ from django.contrib.sessions.middleware import SessionMiddlewarefrom django.http import HttpRequest, HttpResponsefrom django.template.loader import render_to_stringfrom django.test import RequestFactory, SimpleTestCase+from django.utils import timezonefrom parameterized import parameterized@@ -21,8 +22,9 @@ from posthog.stable_chunks import StableChunksfrom posthog.templatetags.posthog_filters import TolerantJSONEncoderfrom posthog.utils import (DEFERRED_APP_CONTEXT_FLAG,+ app_flag_keys,deferred_app_context_variant,- flags_for_app_evaluation_context,+ feature_flag_bootstrap,get_context_for_template,get_persisted_feature_flags_for_app_context,)@@ -100,7 +102,7 @@ STABLE_CHUNKS = StableChunks()-class TestFlagsForAppEvaluationContext(SimpleTestCase):+class TestAppFlagKeys(SimpleTestCase):@parameterized.expand([("no_contexts_is_kept", {"evaluation_contexts": None}, True),@@ -114,19 +116,41 @@ class TestFlagsForAppEvaluationContext(SimpleTestCase):])def test_keeps_flags_the_app_evaluates(self, _name, definition, kept):- definitions = [{"key": "the-flag", **definition}]+ definitions = [{"key": "the-flag", **definition}, {"key": "untagged"}]- actual = flags_for_app_evaluation_context({"the-flag": True, "untagged": True}, definitions)+ assert app_flag_keys(definitions) == (["the-flag", "untagged"] if kept else ["untagged"])- assert actual == ({"the-flag": True, "untagged": True} if kept else {"untagged": True})- def test_keeps_every_flag_before_definitions_load(self):- assert flags_for_app_evaluation_context({"the-flag": True}, None) == {"the-flag": True}+class TestFeatureFlagBootstrap(SimpleTestCase):+ def user(self) -> User:+ return User(distinct_id="user-1", email="[email protected]", date_joined=timezone.now())- def test_keeps_no_flags_when_analytics_is_disabled(self):- definitions = [{"key": "the-flag", "evaluation_contexts": ["posthog-website"]}]+ def test_asks_the_sdk_for_the_app_flags_only(self):+ definitions = [{"key": "app"}, {"key": "server", "evaluation_runtime": "server"}]+ with (+ mock.patch("posthog.utils.posthoganalytics.feature_flag_definitions", return_value=definitions),+ mock.patch("posthog.utils.posthoganalytics.get_all_flags", return_value={"app": True}) as get_all_flags,+ ):+ actual = feature_flag_bootstrap(self.user(), {})++ assert actual == {"app": True}+ assert get_all_flags.call_args.kwargs["flag_keys_to_evaluate"] == ["app"]++ @parameterized.expand(+ [+ ("app_has_no_flags", [{"key": "server", "evaluation_runtime": "server"}], {}),+ ("definitions_not_loaded", None, None),+ ]+ )+ def test_skips_the_sdk_when_it_would_evaluate_every_flag(self, _name, definitions, expected):+ with (+ mock.patch("posthog.utils.posthoganalytics.feature_flag_definitions", return_value=definitions),+ mock.patch("posthog.utils.posthoganalytics.get_all_flags") as get_all_flags,+ ):+ actual = feature_flag_bootstrap(self.user(), {})- assert flags_for_app_evaluation_context(None, definitions) is None+ assert actual == expected+ get_all_flags.assert_not_called()class TestShouldDeferAppContext(SimpleTestCase):@@ -257,8 +281,9 @@ class TestGetContextForTemplate(APIBaseTest):@parameterized.expand([("shares_email", False, "[email protected]"), ("anonymized", True, None)])@mock.patch("posthog.utils.posthoganalytics.get_all_flags", return_value={})+ @mock.patch("posthog.utils.posthoganalytics.feature_flag_definitions", return_value=[{"key": "some-flag"}])def test_flag_bootstrap_evaluates_with_the_identity_the_browser_sends(- self, _name, anonymize_data, expected_email, mock_get_all_flags+ self, _name, anonymize_data, expected_email, _mock_definitions, mock_get_all_flags):self.user.email = "[email protected]"self.user.anonymize_data = anonymize_data@@ -396,7 +421,7 @@ class TestGetContextForTemplate(APIBaseTest):assert "stable_chunks_importmap" not in context@mock.patch("posthog.utils.posthoganalytics.get_all_flags", return_value={"some-flag": True})- @mock.patch("posthog.utils.posthoganalytics.feature_flag_definitions", return_value=None)+ @mock.patch("posthog.utils.posthoganalytics.feature_flag_definitions", return_value=[{"key": "some-flag"}])def test_deferred_page_gets_the_user_data_from_app_context(self, _mock_definitions, _mock_get_all_flags):def user_request(path: str) -> HttpRequest:request = RequestFactory().get(path)diff --git a/posthog/utils.py b/posthog/utils.pyindex dd533df45d93..d6e48b01198e 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -490,19 +490,16 @@ def _read_preload_manifest(manifest_path: str, include_authenticated_shell: boolAPP_EVALUATION_CONTEXT = "posthog-web-app"-def flags_for_app_evaluation_context(- flags: dict[str, Any] | None, definitions: list[dict[str, Any]] | None-) -> dict[str, Any] | None:+def app_flag_keys(definitions: list[dict[str, Any]] | None) -> list[str] | None:"""- Drops flags that /flags leaves out for the app, which sends `evaluation_contexts: ['posthog-web-app']`+ The flags /flags returns for the app, which sends `evaluation_contexts: ['posthog-web-app']`from `loadPostHogJS.tsx`. The Python SDK evaluates locally without applying evaluation contexts, and italso returns disabled flags and server-only flags, which /flags never sends to a browser.+ None means the definitions have not loaded yet."""- # The SDK returns no flags at all when analytics is disabled, for example in tests or with OPT_OUT_CAPTURE.- if flags is None:+ if definitions is None:return None- excluded = {definition["key"] for definition in definitions or [] if not _app_evaluates_flag(definition)}- return {key: value for key, value in flags.items() if key not in excluded}+ return [definition["key"] for definition in definitions if _app_evaluates_flag(definition)]def _app_evaluates_flag(definition: dict[str, Any]) -> bool:@@ -875,15 +872,22 @@ def feature_flag_bootstrap(user: "User", current_user: dict[str, Any]) -> Option)if identity is None:return None+ flag_keys = app_flag_keys(posthoganalytics.feature_flag_definitions())+ # Without definitions the SDK loads them and evaluates every flag, server-only flags included.+ if flag_keys is None:+ return None+ # The SDK reads an empty list as "evaluate every flag".+ if not flag_keys:+ return {}with tracer.start_as_current_span("template.feature_flag_bootstrap"):- feature_flags = posthoganalytics.get_all_flags(+ return posthoganalytics.get_all_flags(identity.distinct_id,only_evaluate_locally=True,person_properties=identity.person_properties,groups=identity.groups,group_properties=identity.group_properties,+ flag_keys_to_evaluate=flag_keys,)- return flags_for_app_evaluation_context(feature_flags, posthoganalytics.feature_flag_definitions())def add_user_app_context(request: HttpRequest, posthog_app_context: dict[str, Any]) -> None: