: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): let a feature flag roll out the stable chunk build (#106564)
Paul D'Ambra1fc927d58041
diff --git a/common/esbuilder/utils.mjs b/common/esbuilder/utils.mjsindex 452f4e44721c..7a32638c3799 100644--- a/common/esbuilder/utils.mjs+++ b/common/esbuilder/utils.mjs@@ -98,16 +98,17 @@ export function copyIndexHtml(// The stable entry may already have run some stable chunks when it fails, and the default// entry would then run a second copy of those modules. So the stable variant reloads the page// on the default build instead. The server always serves the default build for- // ?stable_chunks=0 and clears the opt-in cookie, so the reload cannot loop.+ // ?stable_chunks=fallback, so the reload cannot loop, and it stores no choice, so the next+ // navigation tries the stable build again.const entryFallback = isStable? `var url = new URL(window.location.href)- url.searchParams.set('stable_chunks', '0')+ url.searchParams.set('stable_chunks', 'fallback')window.location.replace(url.toString())`: `await import((window.JS_URL || '') + '/static/' + ${JSON.stringify(jsFileFallback)})`const scriptCode = `- // The server has already applied ?stable_chunks (it sets or clears the opt-in cookie),+ // The server has already applied ?stable_chunks (1 and 0 also set the choice cookie),// so drop it from the address bar. A bookmarked or shared URL must not keep forcing a build.if (window.location.search.indexOf('stable_chunks=') !== -1) {var cleanUrl = new URL(window.location.href)diff --git a/posthog/stable_chunks.py b/posthog/stable_chunks.pyindex c11884c2905a..b774cacac525 100644--- a/posthog/stable_chunks.py+++ b/posthog/stable_chunks.py@@ -6,15 +6,15 @@ specifiers, plus `stable-chunks-manifest.json` with the import map that resolvesfrontend/bin/stableChunkNames.mjs). A chunk's URL then changes only when its own code changes,so a deploy no longer makes returning users download every chunk that imports a changed one.-Serving it is opt-in per browser while it is tested: `?stable_chunks=1` sets a cookie and-`?stable_chunks=0` clears it. Without the cookie, or without a readable manifest, pages render-exactly as before.+Which build a request gets is decided by `stable_chunks_choice`. Without a readable manifest,+pages render exactly as before."""import osimport json+from collections.abc import Mappingfrom functools import lru_cache-from typing import Optional+from typing import Any, Optionalfrom django.conf import settingsfrom django.http import HttpRequest, HttpResponse@@ -28,6 +28,7 @@ logger = structlog.get_logger(__name__)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@@ -99,27 +100,39 @@ def _resolve_stable_chunks() -> Optional[StableChunks]:)-def stable_chunks_opted_in(request: HttpRequest) -> bool:+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 ones bootstrapped into posthog-js, so events carry the flag value that picked the build.+ """param = request.GET.get(STABLE_CHUNKS_PARAM)if param is not None:return param == "1"- return request.COOKIES.get(STABLE_CHUNKS_COOKIE) == "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:+ return False++ return feature_flags.get(STABLE_CHUNKS_FLAG) is True-def stable_chunks_for_request(request: HttpRequest) -> Optional[StableChunks]:- return _resolve_stable_chunks() if stable_chunks_opted_in(request) else None+def stable_chunks_for_request(+ request: HttpRequest, feature_flags: Optional[Mapping[str, Any]]+) -> Optional[StableChunks]:+ return _resolve_stable_chunks() if stable_chunks_choice(request, feature_flags) else Nonedef persist_stable_chunks_choice(request: HttpRequest, response: HttpResponse) -> None:param = request.GET.get(STABLE_CHUNKS_PARAM)- if param == "1":+ if param in ("0", "1"):response.set_cookie(STABLE_CHUNKS_COOKIE,- "1",+ param,max_age=_COOKIE_MAX_AGE_SECONDS,secure=request.is_secure(),httponly=True,samesite="Lax",)- elif param == "0":- response.delete_cookie(STABLE_CHUNKS_COOKIE)diff --git a/posthog/test/test_stable_chunks.py b/posthog/test/test_stable_chunks.pyindex b051b3c54fa1..2807535a5025 100644--- a/posthog/test/test_stable_chunks.py+++ b/posthog/test/test_stable_chunks.py@@ -7,17 +7,19 @@ from unittest.mock import patchfrom django.contrib.auth.models import AnonymousUserfrom django.contrib.sessions.middleware import SessionMiddleware-from django.http import HttpResponse+from django.http import HttpRequest, HttpResponsefrom django.test import RequestFactory, SimpleTestCase, override_settingsfrom parameterized import parameterized+from posthog.models import Userfrom posthog.stable_chunks import (STABLE_CHUNKS_COOKIE,+ STABLE_CHUNKS_FLAG,StableChunks,persist_stable_chunks_choice,read_stable_chunks_manifest,- stable_chunks_opted_in,+ stable_chunks_choice,)from posthog.utils import get_context_for_template, render_template@@ -26,6 +28,8 @@ VALID_MANIFEST = {"preload": {"js": ["static/index-S0000000000.js"], "authenticatedJs": ["static/chunk-S1111111111.js"]},"eagerCss": ["static/stylesEagerTailwind-AAAA1111.css", "static/stylesEagerApp-BBBB2222.css"],}+FLAG_ON = {STABLE_CHUNKS_FLAG: True}+FLAG_OFF = {STABLE_CHUNKS_FLAG: False}class TestStableChunks(SimpleTestCase):@@ -67,23 +71,32 @@ class TestStableChunks(SimpleTestCase):@parameterized.expand([- ("param on", "?stable_chunks=1", None, True),- ("param off overrides the cookie", "?stable_chunks=0", "1", False),- ("cookie on", "", "1", True),- ("nothing set", "", None, False),+ ("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 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),+ ("flag on", "", None, FLAG_ON, True, True),+ ("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),])- def test_opt_in(self, _name, query, cookie, expected):+ def test_choice_precedence(self, _name, query, cookie, feature_flags, authenticated, expected):request = RequestFactory().get(f"/{query}")+ request.user = User() if authenticated else AnonymousUser()if cookie:request.COOKIES[STABLE_CHUNKS_COOKIE] = cookie- assert stable_chunks_opted_in(request) == expected+ assert stable_chunks_choice(request, feature_flags) == expected@parameterized.expand([("param on stores the choice for 30 days", "?stable_chunks=1", "1", 60 * 60 * 24 * 30),- ("param off expires the cookie", "?stable_chunks=0", "", 0),+ ("param off stores the opt-out for 30 days", "?stable_chunks=0", "0", 60 * 60 * 24 * 30),+ ("fallback leaves the cookie alone", "?stable_chunks=fallback", None, None),("no param leaves the cookie alone", "", None, None),])@@ -96,7 +109,7 @@ class TestStableChunks(SimpleTestCase):cookie = response.cookies.get(STABLE_CHUNKS_COOKIE)assert (cookie.value if cookie else None) == expected_valueassert (cookie["max-age"] if cookie else None) == expected_max_age- if expected_value == "1":+ if expected_value:assert cookie is not None# Only the server reads the choice, so scripts on the page never need it.assert cookie["httponly"] is True@@ -136,14 +149,44 @@ class TestStableChunks(SimpleTestCase):class TestStableChunksChoiceSurvivesTheRequest(APIBaseTest):+ def _user_request(self, query: str) -> HttpRequest:+ request = RequestFactory().get(f"/{query}")+ SessionMiddleware(lambda _request: HttpResponse()).process_request(request)+ request.user = self.user+ return request+@parameterized.expand([("opting in", "1"), ("opting out", "0")])def test_rendering_a_page_persists_the_choice(self, _name, param):# Any template exercises this: render_template persists the choice for every page it# returns, and the app shell template only exists after a frontend build.- request = RequestFactory().get(f"/?stable_chunks={param}")- SessionMiddleware(lambda _request: HttpResponse()).process_request(request)- request.user = self.user+ request = self._user_request(f"?stable_chunks={param}")response = render_template("sso_reauth_complete.html", request)- assert response.cookies[STABLE_CHUNKS_COOKIE].value == ("1" if param == "1" else "")+ assert response.cookies[STABLE_CHUNKS_COOKIE].value == param++ @parameterized.expand(+ [+ ("flag on", "", FLAG_ON, True),+ ("flag off", "", FLAG_OFF, False),+ ("flag without a local definition", "", {}, False),+ ("flag evaluation failed", "", None, False),+ ("fallback with the flag on", "?stable_chunks=fallback", FLAG_ON, False),+ ]+ )+ def test_the_flag_picks_the_build_it_bootstraps(self, _name, query, flags, expect_stable):+ request = self._user_request(query)+ stable = StableChunks(+ imports={"@c/eAAAA": "static/index-S0000000000.js"}, preload_js_urls=(), authenticated_preload_js_urls=()+ )++ with (+ patch("posthoganalytics.get_all_flags", return_value=flags) as get_all_flags,+ patch("posthog.stable_chunks._resolve_stable_chunks", return_value=stable),+ ):+ context = get_context_for_template("index.html", request)++ assert context.get("stable_chunks", False) == expect_stable+ assert json.loads(context["posthog_bootstrap"]).get("featureFlags") == flags+ get_all_flags.assert_called_once()+ assert get_all_flags.call_args.kwargs["only_evaluate_locally"] is Truediff --git a/posthog/utils.py b/posthog/utils.pyindex 23e5c9fb3aeb..023be8161a1a 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -746,7 +746,7 @@ def _build_template_context(context["preload_css_url"], context["preload_js_urls"], context["preload_font_url"] = _resolve_entry_assets(is_authenticated)- stable_chunks = stable_chunks_for_request(request)+ stable_chunks = stable_chunks_for_request(request, posthog_bootstrap.get("featureFlags"))if stable_chunks:context["stable_chunks"] = Truecontext["stable_chunks_importmap"] = stable_chunks.import_map_json(context["js_url"])