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): load flag definitions in ASGI self-capture init (#62788)

Arthur Moreira de Deusa1d06c3847fc
diff --git a/posthog/apps.py b/posthog/apps.py
index ce1c37643ab1..90ba9bc666c8 100644
--- a/posthog/apps.py
+++ b/posthog/apps.py
@@ -10,8 +10,8 @@ from posthoganalytics.client import Client
from posthog.git import get_git_branch, get_git_commit_short
from posthog.utils import (
+ _build_flag_provider,
get_available_timezones_with_offsets,
- get_dogfood_flags_team_id,
get_instance_region,
get_machine_id,
initialize_self_capture_api_token,
@@ -100,25 +100,7 @@ class PostHogConfig(AppConfig):
# the cache is cold. In E2E testing personal_api_key is None, so a cold cache
# will result in no flag definitions being loaded — which is acceptable there.
if not posthoganalytics.disabled:
- from products.feature_flags.backend.sdk_cache_provider import HyperCacheFlagProvider
-
- explicit_team_id = os.environ.get("POSTHOG_SELF_TEAM_ID")
- if explicit_team_id:
- # Operator override: pin the flag-definitions team explicitly.
- # Truthiness, not `is not None`: an empty env var means "unset" and must
- # fall through to the defaults below, not crash on int("").
- provider = HyperCacheFlagProvider.for_static_team(int(explicit_team_id))
- elif settings.SELF_CAPTURE and not settings.E2E_TESTING:
- # Local/self-hosted: read flag definitions from the dogfood team
- # (project.teams.first()), resolved lazily once teams/migrations exist.
- # Intentionally the FIRST team, not self-capture's current_team — see
- # resolve_dogfood_flags_team() in posthog/utils.py.
- provider = HyperCacheFlagProvider.for_dynamic_resolution(get_dogfood_flags_team_id)
- else:
- # Cloud (SELF_CAPTURE off) or E2E: the canonical PostHog-internal team is 2.
- provider = HyperCacheFlagProvider.for_static_team(2)
-
- posthoganalytics.flag_definition_cache_provider = provider # ty: ignore[invalid-assignment]
+ posthoganalytics.flag_definition_cache_provider = _build_flag_provider() # ty: ignore[invalid-assignment]
# load feature flag definitions if not already loaded
if not posthoganalytics.disabled and posthoganalytics.feature_flag_definitions() is None:
diff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.py
index 1e40b5557007..bfb6b24f159c 100644
--- a/posthog/test/test_utils.py
+++ b/posthog/test/test_utils.py
@@ -1,3 +1,4 @@
+import os
import json
import base64
from datetime import datetime, timedelta
@@ -12,7 +13,7 @@ from unittest.mock import call, patch
from django.core.cache import cache
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpRequest
-from django.test import TestCase
+from django.test import TestCase, override_settings
from django.test.client import RequestFactory
from parameterized import parameterized
@@ -23,6 +24,7 @@ from posthog.models import EventDefinition, GroupTypeMapping, Organization, Team
from posthog.settings.utils import get_from_env
from posthog.utils import (
PotentialSecurityProblemException,
+ _build_flag_provider,
absolute_uri,
base64_decode,
filters_override_requested_by_client,
@@ -1161,3 +1163,40 @@ class TestResolveDogfoodFlagsTeam(TestCase):
def test_returns_none_when_there_are_no_teams(self):
assert resolve_dogfood_flags_team() is None
assert get_dogfood_flags_team_id() is None
+
+
+class TestBuildFlagProvider(TestCase):
+ def setUp(self):
+ super().setUp()
+ # The dogfood branch reads the whole teams table; clear ambient rows so the team we
+ # create is the first one. Cascade deletes roll back with the test transaction.
+ User.objects.all().delete()
+ Organization.objects.all().delete()
+
+ @patch.dict(os.environ, {"POSTHOG_SELF_TEAM_ID": "5"}, clear=False)
+ @override_settings(SELF_CAPTURE=True, E2E_TESTING=False)
+ def test_explicit_env_team_id_wins_over_self_capture(self):
+ assert _build_flag_provider()._resolve_team_id() == 5
+
+ @patch.dict(os.environ, {}, clear=False)
+ @override_settings(SELF_CAPTURE=True, E2E_TESTING=False)
+ def test_self_capture_routes_to_dogfood_first_team(self):
+ os.environ.pop("POSTHOG_SELF_TEAM_ID", None)
+ organization = Organization.objects.create(name="Org")
+ first_team = Team.objects.create(organization=organization, name="First")
+
+ assert _build_flag_provider()._resolve_team_id() == first_team.id
+
+ @patch.dict(os.environ, {}, clear=False)
+ @override_settings(SELF_CAPTURE=False, E2E_TESTING=False)
+ def test_falls_back_to_team_2_off_self_capture(self):
+ os.environ.pop("POSTHOG_SELF_TEAM_ID", None)
+
+ assert _build_flag_provider()._resolve_team_id() == 2
+
+ @patch.dict(os.environ, {}, clear=False)
+ @override_settings(SELF_CAPTURE=True, E2E_TESTING=True)
+ def test_e2e_overrides_self_capture_to_team_2(self):
+ os.environ.pop("POSTHOG_SELF_TEAM_ID", None)
+
+ assert _build_flag_provider()._resolve_team_id() == 2
diff --git a/posthog/utils.py b/posthog/utils.py
index f2873add9fa2..ed555df4a174 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -79,6 +79,7 @@ if TYPE_CHECKING:
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
+ from products.feature_flags.backend.sdk_cache_provider import HyperCacheFlagProvider
from products.product_analytics.backend.models.insight_variable import InsightVariable
DATERANGE_MAP = {
@@ -735,8 +736,41 @@ def get_dogfood_flags_team_id() -> Optional[int]:
return team.id if team is not None else None
+def _build_flag_provider() -> "HyperCacheFlagProvider":
+ """Construct the HyperCache flag-definition provider for this deploy.
+
+ Single source of truth shared by PostHogConfig.ready() (WSGI) and
+ initialize_self_capture_api_token() (ASGI). Callers assign the result to
+ posthoganalytics.flag_definition_cache_provider and handle loading themselves.
+ """
+ from products.feature_flags.backend.sdk_cache_provider import ( # noqa: PLC0415 — keeps the heavy dep off the import path
+ HyperCacheFlagProvider,
+ )
+
+ explicit_team_id = os.environ.get("POSTHOG_SELF_TEAM_ID")
+ if explicit_team_id:
+ # Operator override: pin the flag-definitions team explicitly.
+ # Truthiness, not `is not None`: an empty env var means "unset" and must
+ # fall through to the defaults below, not crash on int("").
+ return HyperCacheFlagProvider.for_static_team(int(explicit_team_id))
+ if settings.SELF_CAPTURE and not settings.E2E_TESTING:
+ # Local/self-hosted: read flag definitions from the dogfood team
+ # (project.teams.first()), resolved lazily once teams/migrations exist.
+ # Intentionally the FIRST team, not self-capture's current_team — see
+ # resolve_dogfood_flags_team().
+ return HyperCacheFlagProvider.for_dynamic_resolution(get_dogfood_flags_team_id)
+ # Cloud (SELF_CAPTURE off) or E2E: the canonical PostHog-internal team is 2.
+ return HyperCacheFlagProvider.for_static_team(2)
+
+
async def initialize_self_capture_api_token():
- """Configures `posthoganalytics` for self-capture, in an ASGI-compatible, async way."""
+ """Configure `posthoganalytics` for self-capture, ASGI-compatible (async).
+
+ Overwrites process-global SDK config (api_key, host, disabled, and the
+ flag-definition cache provider) from the DB-resolved self-capture team — the
+ async counterpart to PostHogConfig.ready()'s WSGI path. Mainly the local dev
+ self-capture bootstrap; also invoked by the Dagster PostHogAnalyticsResource.
+ """
team = await sync_to_async(resolve_self_capture_team)()
local_api_key = team.api_token if team else None
@@ -746,6 +780,16 @@ async def initialize_self_capture_api_token():
posthoganalytics.api_key = local_api_key
posthoganalytics.host = settings.SITE_URL
+ # ready() wires the flag-definition provider only when posthoganalytics is enabled at
+ # that point — true for WSGI but NOT for ASGI, where self-capture is deferred to here.
+ # Without this the ASGI process has no local flag definitions and falls back to a remote
+ # flags call against SITE_URL (unreachable server-side in dev), so feature_enabled()
+ # always returns False. Mirror ready() so ASGI evaluates flags from HyperCache too.
+ posthoganalytics.flag_definition_cache_provider = _build_flag_provider() # ty: ignore[invalid-assignment]
+
+ if posthoganalytics.feature_flag_definitions() is None:
+ await sync_to_async(posthoganalytics.load_feature_flags)()
+
BOTH_DEFAULTS_PRESENT_TTL_SECONDS = 24 * 60 * 60
ONE_DEFAULT_PRESENT_TTL_SECONDS = 30 * 60