: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(frontend): serve the stable chunk build to logged-out pages behind a flag (#111280)
Paul D'Ambra2629966fdcc3
diff --git a/posthog/stable_chunks.py b/posthog/stable_chunks.pyindex b774cacac525..cecea7dd5f38 100644--- a/posthog/stable_chunks.py+++ b/posthog/stable_chunks.py@@ -1,5 +1,5 @@"""-Opt-in serving of the frontend build with stable chunk names.+Flag-gated serving of the frontend build with stable chunk names.The build writes a second copy of the app's JS in which chunks import each other through identityspecifiers, plus `stable-chunks-manifest.json` with the import map that resolves them (see@@ -20,6 +20,8 @@ from django.conf import settingsfrom django.http import HttpRequest, HttpResponseimport structlog+import posthoganalytics+from prometheus_client import Counterfrom posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exception@@ -30,6 +32,15 @@ STABLE_CHUNKS_PARAM = "stable_chunks"STABLE_CHUNKS_COOKIE = "ph_stable_chunks"STABLE_CHUNKS_FLAG = "stable-chunk-names"_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30+# A logged-out request has no person, so every logged-out request evaluates the flag with this one+# ID. A partial rollout therefore switches all logged-out pages on or off together.+LOGGED_OUT_FLAG_DISTINCT_ID = "stable-chunks-logged-out"++STABLE_CHUNKS_FALLBACK_COUNTER = Counter(+ "posthog_stable_chunks_fallback",+ "App shell requests that reload on the hashed build because the stable entry failed to load.",+ labelnames=["authenticated"],+)@frozen@@ -102,23 +113,47 @@ def _resolve_stable_chunks() -> Optional[StableChunks]:def stable_chunks_choice(request: HttpRequest, feature_flags: Optional[Mapping[str, Any]]) -> bool:"""- The query param wins, then the cookie, then the flag for a logged-in user. `feature_flags` are+ The query param wins, then the cookie, then the flag. For a logged-in user, `feature_flags` arethe ones bootstrapped into posthog-js, so events carry the flag value that picked the build.+ A logged-out request has no bootstrapped flags, so it evaluates the flag locally."""param = request.GET.get(STABLE_CHUNKS_PARAM)if param is not None:+ if param == "fallback":+ STABLE_CHUNKS_FALLBACK_COUNTER.labels(authenticated=str(request.user.is_authenticated).lower()).inc()return param == "1"cookie = request.COOKIES.get(STABLE_CHUNKS_COOKIE)if cookie in ("0", "1"):return cookie == "1"- if not request.user.is_authenticated or not feature_flags:+ if not request.user.is_authenticated:+ return _flag_enabled_for_logged_out_requests()++ if not feature_flags:return Falsereturn feature_flags.get(STABLE_CHUNKS_FLAG) is True+def _flag_enabled_for_logged_out_requests() -> bool:+ # Every logged-out app page runs this check, so a failure serves the hashed build instead of an error.+ try:+ return (+ posthoganalytics.feature_enabled(+ STABLE_CHUNKS_FLAG,+ LOGGED_OUT_FLAG_DISTINCT_ID,+ only_evaluate_locally=True,+ send_feature_flag_events=False,+ )+ is True+ )+ except Exception as e:+ logger.warning("stable_chunks_logged_out_flag_check_failed", error=str(e))+ capture_exception(e)+ return False++def stable_chunks_for_request(request: HttpRequest, feature_flags: Optional[Mapping[str, Any]]) -> Optional[StableChunks]:diff --git a/posthog/test/test_stable_chunks.py b/posthog/test/test_stable_chunks.pyindex 8b94f5deb4d6..b0174d2e3e04 100644--- a/posthog/test/test_stable_chunks.py+++ b/posthog/test/test_stable_chunks.py@@ -11,6 +11,7 @@ from django.http import HttpRequest, HttpResponsefrom django.test import RequestFactory, SimpleTestCase, override_settingsfrom parameterized import parameterized+from prometheus_client import REGISTRYfrom posthog.models import Userfrom posthog.stable_chunks import (@@ -73,7 +74,7 @@ class TestStableChunks(SimpleTestCase):[("param on beats a cookie off and the flag off", "?stable_chunks=1", "0", FLAG_OFF, True, True),("param off beats the flag on", "?stable_chunks=0", None, FLAG_ON, True, False),- ("fallback beats a cookie on", "?stable_chunks=fallback", "1", None, True, False),+ ("fallback beats a cookie on", "?stable_chunks=fallback", "1", None, False, False),("fallback beats the flag on", "?stable_chunks=fallback", None, FLAG_ON, True, False),("cookie on beats the flag off", "", "1", FLAG_OFF, True, True),("cookie off beats the flag on", "", "0", FLAG_ON, True, False),@@ -81,16 +82,47 @@ class TestStableChunks(SimpleTestCase):("flag off", "", None, FLAG_OFF, True, False),("flag without a local definition", "", None, {}, True, False),("flags not evaluated", "", None, None, True, False),- ("anonymous with the flag on", "", None, FLAG_ON, False, False),+ ("anonymous with the flag on", "", None, FLAG_ON, False, True),+ ("anonymous with the flag off", "", None, FLAG_OFF, False, False),+ ("anonymous without a local definition", "", None, {}, False, False),])- def test_choice_precedence(self, _name, query, cookie, feature_flags, authenticated, expected):+ def test_choice_precedence(+ self,+ _name: str,+ query: str,+ cookie: str | None,+ feature_flags: dict[str, bool] | None,+ authenticated: bool,+ expected: bool,+ ) -> None:request = RequestFactory().get(f"/{query}")request.user = User() if authenticated else AnonymousUser()if cookie:request.COOKIES[STABLE_CHUNKS_COOKIE] = cookie+ bootstrapped_flags = feature_flags if authenticated else None+ locally_evaluated_flags = {} if authenticated else (feature_flags or {})+ fallback_labels = {"authenticated": str(authenticated).lower()}+ fallbacks_before = REGISTRY.get_sample_value("posthog_stable_chunks_fallback_total", fallback_labels) or 0++ with patch(+ "posthoganalytics.feature_enabled",+ side_effect=lambda key, *_args, **_kwargs: locally_evaluated_flags.get(key),+ ) as feature_enabled:+ assert stable_chunks_choice(request, bootstrapped_flags) == expected++ for call in feature_enabled.call_args_list:+ assert call.kwargs["only_evaluate_locally"] is True+ assert call.kwargs["send_feature_flag_events"] is False+ fallbacks_after = REGISTRY.get_sample_value("posthog_stable_chunks_fallback_total", fallback_labels) or 0+ assert fallbacks_after - fallbacks_before == (1 if query == "?stable_chunks=fallback" else 0)++ def test_a_failing_logged_out_flag_check_serves_the_hashed_build(self) -> None:+ request = RequestFactory().get("/")+ request.user = AnonymousUser()- assert stable_chunks_choice(request, feature_flags) == expected+ with patch("posthoganalytics.feature_enabled", side_effect=RuntimeError("flag definitions unavailable")):+ assert stable_chunks_choice(request, None) is False@parameterized.expand([