: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 stable chunk names behind an opt-in (#105531)
Paul D'Ambra5ea017ef1574
diff --git a/Dockerfile b/Dockerfileindex 932526eea7fc..cb61985f86a4 100644--- a/Dockerfile+++ b/Dockerfile@@ -83,6 +83,11 @@ COPY --from=frontend-build /code/frontend/dist /code/frontend/dist# "retained" and the .map files are kept in the image. Uses explicit && chaining rather than `set -e`,# which bash ignores inside a `||`-guarded subshell — any failing link drops us into the retained branch.#+# Two passes. The stable-name copies (`*-S<10 hex>.js`, see common/esbuilder/stableChunkNames.mjs) keep+# one URL for as long as their code is unchanged, so they must not carry the per-release id that the+# first pass injects. The second pass runs with no release flags and without GITHUB_ACTIONS, so the CLI+# resolves no release and injects only the chunk id, which it derives from the file's own content.+## The CLI installer is pinned to an immutable release tag and checksum-verified before execution:# the processed frontend/dist ships in the final image, so the CLI must not be mutable remote code.# To upgrade, change POSTHOG_CLI_VERSION and recompute the hash:@@ -118,12 +123,19 @@ RUN --mount=type=secret,id=posthog_upload_sourcemaps_cli_api_key \export PATH="/root/.posthog:$PATH" && \export POSTHOG_CLI_TOKEN="$(cat /run/secrets/posthog_upload_sourcemaps_cli_api_key)" && \export POSTHOG_CLI_ENV_ID=2 && \+ STABLE_CHUNKS='**/*-S[0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F].js' && \posthog-cli sourcemap process \--directory /code/frontend/dist \+ --exclude "$STABLE_CHUNKS" \--public-path-prefix /static \--release-mode event \--release-name posthog \- --release-version "${COMMIT_HASH:-unknown}" \+ --release-version "${COMMIT_HASH:-unknown}" && \+ env -u GITHUB_ACTIONS posthog-cli sourcemap process \+ --directory /code/frontend/dist \+ --include "$STABLE_CHUNKS" \+ --public-path-prefix /static \+ --release-mode event \); then \echo uploaded > /tmp/.sourcemaps-status; \else \diff --git a/common/esbuilder/stableChunkNames.mjs b/common/esbuilder/stableChunkNames.mjsnew file mode 100644index 000000000000..00ebeb52b874--- /dev/null+++ b/common/esbuilder/stableChunkNames.mjs@@ -0,0 +1,163 @@+import { createHash } from 'node:crypto'+import fs from 'node:fs'+import path from 'node:path'++/**+ * Stable chunk names.+ *+ * esbuild names a chunk by a hash of its bytes, and those bytes contain the hashed file names of+ * every chunk it imports. A change to one chunk therefore renames every chunk that imports it, up+ * to the entry, and returning users download all of them again after a deploy.+ *+ * This step writes a second copy of the app's JS in which chunks import each other through an+ * identity specifier (`@c/<identity>`) instead of a hashed path. An import map, rendered by the+ * backend, resolves each identity to its current file. A chunk's identity comes from the source+ * modules it contains, so it does not change when their code changes. A chunk's file name is a+ * hash of its own rewritten bytes, so it changes only when its own code changes.+ *+ * The copies sit next to esbuild's files in `dist/`, because some chunks resolve workers and wasm+ * files relative to `import.meta.url`. Their names (`<prefix>-S<10 hex>.js`) cannot collide with+ * esbuild's 8-character base32 hashes.+ */++export const SPECIFIER_PREFIX = '@c/'+export const STABLE_NAME_MARKER = 'S'++const SOURCE_MAP_COMMENT = /\n\/\/# sourceMappingURL=[^\n]*\s*$/++function shortHash(value) {+ return createHash('sha256').update(value).digest('hex').slice(0, 10).toUpperCase()+}++/**+ * Identity of an output chunk. Entry chunks use their entry point. Shared chunks use the set of+ * source modules esbuild placed in them, which is stable while the module graph is stable.+ */+export function chunkIdentity(output) {+ if (output.entryPoint) {+ return `e${shortHash(output.entryPoint)}`+ }+ return `c${shortHash(+ Object.keys(output.inputs || {})+ .sort()+ .join('\n')+ )}`+}++// A chunk path in import position: `from"…"`, `import"…"` and `import("…")`. Only these resolve through+// the import map. The same path passed to new URL(), fetch() or a Worker must stay a real URL.+const IMPORT_OF_PATH = /(\bfrom\s*|\bimport\s*\(?\s*)(["'])\/static\/([^"'\s]+?\.js)\2/g++/** Replaces every import of a known chunk by path with an import of its identity specifier. */+export function rewriteChunkSource(source, identityByFile) {+ return source.replace(SOURCE_MAP_COMMENT, '').replace(IMPORT_OF_PATH, (match, keyword, quote, file) => {+ if (!identityByFile.has(file)) {+ return match+ }+ const replacement = `${keyword}${quote}${SPECIFIER_PREFIX}${identityByFile.get(file)}${quote}`+ // Pad to the original byte length so every other offset in the file is unchanged and the+ // esbuild-emitted source map (which points at byte offsets) still lines up. `from"…"`,+ // `import"…"` and `import("…")` all allow whitespace after the closing quote.+ return replacement.padEnd(match.length, ' ')+ })+}++export function stableFileName(originalFile, rewrittenSource) {+ const prefix = originalFile.replace(/-[^-./]+\.js$/, '')+ // Only holds because chunkNames/entryNames in utils.mjs are `[name]-[hash]` for non-dev builds.+ // Fail loudly rather than silently producing a garbled name like `index.js-S....js`.+ if (prefix === originalFile) {+ throw new Error(`stable chunks: ${originalFile} does not end in the expected -<hash>.js suffix`)+ }+ return `${prefix}-${STABLE_NAME_MARKER}${shortHash(rewrittenSource)}.js`+}++/**+ * Plans the stable copy of a build. `outputs` is the esbuild metafile's `outputs`, and+ * `readSource(outputPath)` returns an output file's contents. Pure apart from `readSource`.+ *+ * Returns, per JS output, its identity, stable file name and rewritten source, plus the import+ * map.+ */+export function planStableChunks(outputs, readSource, distPrefix = 'dist/') {+ const jsOutputs = Object.entries(outputs).filter(([outputPath]) => outputPath.endsWith('.js'))+ const fileOf = (outputPath) => outputPath.slice(distPrefix.length)++ const identityByFile = new Map()+ const seen = new Map()+ for (const [outputPath, output] of jsOutputs) {+ let identity = chunkIdentity(output)+ if (seen.has(identity)) {+ // Two chunks with the same inputs cannot come out of one build, but an empty chunk+ // could. Fall back to the esbuild name: unique within the build, only less stable.+ console.warn(+ `stable chunks: identity collision for ${outputPath}, falling back to an esbuild-hash-derived name`+ )+ identity = `${identity}${shortHash(outputPath)}`+ }+ seen.set(identity, outputPath)+ identityByFile.set(fileOf(outputPath), identity)+ }++ const plan = new Map()+ const imports = {}+ for (const [outputPath] of jsOutputs) {+ const file = fileOf(outputPath)+ const rawSource = readSource(outputPath)+ const source = rewriteChunkSource(rawSource, identityByFile)+ // Every replacement preserves length, except an identity collision with a short entry name+ // (see rewriteChunkSource). When that happens the map's byte offsets no longer line up.+ const mapValid = source.length === rawSource.replace(SOURCE_MAP_COMMENT, '').length+ const identity = identityByFile.get(file)+ const stableFile = stableFileName(file, source)+ plan.set(outputPath, { identity, file, stableFile, source, mapValid })+ imports[`${SPECIFIER_PREFIX}${identity}`] = `static/${stableFile}`+ }+ return { plan, imports }+}++/**+ * Writes the stable copies and their source maps next to esbuild's output, and returns the+ * manifest the backend reads. `chunks` is the chunk map (scene name -> esbuild chunk hashes) and+ * `entrypoints` the absolute paths of the entry files, as `buildOrWatch` returns them.+ */+export function writeStableChunks({ absWorkingDir, outputs, chunks, entrypoints, preloadManifest }) {+ const distDir = path.resolve(absWorkingDir, 'dist')+ const { plan, imports } = planStableChunks(outputs, (outputPath) =>+ fs.readFileSync(path.resolve(absWorkingDir, outputPath), 'utf8')+ )++ const stableByFile = new Map([...plan.values()].map((entry) => [entry.file, entry.stableFile]))+ for (const { file, stableFile, source, mapValid } of plan.values()) {+ const mapFile = path.resolve(distDir, `${file}.map`)+ // A rewrite that changed the source's length invalidates the map's byte offsets, so serve+ // the source with no map rather than one that points at the wrong columns.+ const hasMap = fs.existsSync(mapFile) && mapValid+ fs.writeFileSync(+ path.resolve(distDir, stableFile),+ hasMap ? `${source}\n//# sourceMappingURL=${stableFile}.map\n` : source+ )+ if (hasMap) {+ fs.copyFileSync(mapFile, path.resolve(distDir, `${stableFile}.map`))+ }+ }++ const toStable = (file) => stableByFile.get(file) ?? file+ const chunkId = (file) => file.replace(/^chunk-/, '').replace(/\.js$/, '')+ const stableChunks = Object.fromEntries(+ Object.entries(chunks).map(([name, list]) => [name, list.map((hash) => chunkId(toStable(`chunk-${hash}.js`)))])+ )+ const stableEntrypoints = entrypoints.map((entrypoint) =>+ entrypoint.endsWith('.js') ? path.resolve(distDir, toStable(path.relative(distDir, entrypoint))) : entrypoint+ )+ const toStableUrl = (url) => `static/${toStable(url.replace(/^static\//, ''))}`+ const manifest = {+ imports,+ preload: {+ js: (preloadManifest?.js || []).map(toStableUrl),+ authenticatedJs: (preloadManifest?.authenticatedJs || []).map(toStableUrl),+ },+ }+ fs.writeFileSync(path.resolve(distDir, 'stable-chunks-manifest.json'), JSON.stringify(manifest))+ return { chunks: stableChunks, entrypoints: stableEntrypoints, manifest }+}diff --git a/common/esbuilder/stableChunkNames.test.ts b/common/esbuilder/stableChunkNames.test.tsnew file mode 100644index 000000000000..e073b11eb063--- /dev/null+++ b/common/esbuilder/stableChunkNames.test.ts@@ -0,0 +1,106 @@+import { planStableChunks, stableFileName } from './stableChunkNames.mjs'++// Two chunks: an entry that imports a shared chunk, the way esbuild writes them with publicPath /static.+const OUTPUTS = {+ 'dist/Scene-AAAA1111.js': { entryPoint: 'src/scenes/Scene.tsx', inputs: { 'src/scenes/Scene.tsx': {} } },+ 'dist/chunk-BBBB2222.js': { inputs: { 'src/lib/shared.ts': {}, 'src/lib/other.ts': {} } },+}++function plan(sources: Record<string, string>): Map<string, { stableFile: string; source: string; mapValid: boolean }> {+ return planStableChunks(OUTPUTS, (outputPath: string) => sources[outputPath]).plan+}++describe('planStableChunks', () => {+ const entry = (shared: string, own = 'render()'): Record<string, string> => ({+ 'dist/Scene-AAAA1111.js': `import{a}from"/static/chunk-BBBB2222.js";${own};new URL("/static/Inter-CCCC3333.woff2");new Worker(new URL("/static/chunk-BBBB2222.js"))`,+ 'dist/chunk-BBBB2222.js': shared,+ })++ // The point of the step: a changed chunk must not rename the chunks that import it, or returning+ // users download those again after every deploy.+ it.each([+ [+ 'keeps the importer when only the imported chunk changes',+ entry('export const a=1'),+ entry('export const a=2'),+ true,+ ],+ [+ 'renames the importer when its own code changes',+ entry('export const a=1'),+ entry('export const a=1', 'renderAgain()'),+ false,+ ],+ ])('%s', (_name, before, after, importerKeepsName) => {+ const [first, second] = [plan(before), plan(after)]+ expect(+ first.get('dist/Scene-AAAA1111.js')!.stableFile === second.get('dist/Scene-AAAA1111.js')!.stableFile+ ).toBe(importerKeepsName)+ })++ it('rewrites chunk imports to identity specifiers and leaves URLs alone', () => {+ const before = entry('export const a=1')+ const { source } = plan(before).get('dist/Scene-AAAA1111.js')!++ expect(source).toMatch(/from"@c\/c[0-9A-F]{10}"/)+ expect(source).not.toContain('from"/static/chunk-BBBB2222.js"')+ expect(source).toContain('new URL("/static/chunk-BBBB2222.js")')+ expect(source).toContain('"/static/Inter-CCCC3333.woff2"')+ })++ it('pads a shorter specifier so the rewritten source keeps its original length', () => {+ const before = entry('export const a=1')+ const { source, mapValid } = plan(before).get('dist/Scene-AAAA1111.js')!++ expect(source.length).toBe(before['dist/Scene-AAAA1111.js'].length)+ expect(source).toMatch(/from"@c\/c[0-9A-F]{10}" +;/)+ expect(mapValid).toBe(true)+ })++ describe('identity collisions', () => {+ afterEach(() => jest.restoreAllMocks())++ it('warns and falls back to a unique name when two chunks share an identity', () => {+ // Two chunks with no inputs hash to the same identity (see the comment in the source).+ const outputs = {+ 'dist/chunk-EEEE0000.js': {},+ 'dist/chunk-FFFF0000.js': {},+ }+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {})++ const { plan: collisionPlan } = planStableChunks(outputs, () => '')++ expect(warn).toHaveBeenCalledWith(expect.stringContaining('identity collision for dist/chunk-'))+ expect(collisionPlan.get('dist/chunk-EEEE0000.js')!.identity).not.toBe(+ collisionPlan.get('dist/chunk-FFFF0000.js')!.identity+ )+ })++ it('marks the map invalid when a collision fallback identity outgrows a short chunk name', () => {+ // Both empty-input chunks hash to the same identity; the second falls back to a longer+ // one (its own identity plus a hash of its output path), which can outgrow a short+ // original file name and make the replacement longer than the specifier it replaces.+ const outputs = {+ 'dist/c-a.js': {},+ 'dist/c-b.js': {},+ 'dist/e-x.js': { entryPoint: 'src/x.tsx', inputs: { 'src/x.tsx': {} } },+ }+ const sources: Record<string, string> = {+ 'dist/c-a.js': '',+ 'dist/c-b.js': '',+ 'dist/e-x.js': 'from"/static/c-b.js";render()',+ }+ jest.spyOn(console, 'warn').mockImplementation(() => {})++ const { plan: collisionPlan } = planStableChunks(outputs, (outputPath: string) => sources[outputPath])++ expect(collisionPlan.get('dist/e-x.js')!.mapValid).toBe(false)+ })+ })++ describe('stableFileName', () => {+ it('throws when the esbuild output name has no -<hash> suffix to replace', () => {+ expect(() => stableFileName('index.js', 'source')).toThrow(/does not end in the expected/)+ })+ })+})diff --git a/common/esbuilder/utils.mjs b/common/esbuilder/utils.mjsindex 135beba142b3..cf56333965a2 100644--- a/common/esbuilder/utils.mjs+++ b/common/esbuilder/utils.mjs@@ -74,7 +74,8 @@ export function copyIndexHtml(to = 'dist/index.html',entry = 'index',chunks = {},- entrypoints = []+ entrypoints = [],+ stable = null) {// Takes a html file, `from`, and some artifacts from esbuild, and injects// some javascript that will load these artifacts dynamically, based on an@@ -86,54 +87,69 @@ export function copyIndexHtml(// Docker image, but serve the js and it's dependencies from e.g. CloudFrontconst buildId = new Date().valueOf()- const relativeFiles = entrypoints.map((e) => path.relative(path.resolve(absWorkingDir, 'dist'), e))- const jsFile = relativeFiles.length > 0 ? relativeFiles.find((e) => e.endsWith('.js')) : `${entry}.js?t=${buildId}`- const cssFile =- relativeFiles.length > 0 ? relativeFiles.find((e) => e.endsWith('.css')) : `${entry}.css?t=${buildId}`-- const jsFileFallback = `${entry}.js?t=${buildId}`- const scriptCode = `- window.ESBUILD_LOAD_SCRIPT = async function (file) {- try {- await import((window.JS_URL || '') + '/static/' + file)- } catch (error) {- console.error('Error loading chunk: "' + file + '"')- console.error(error)- if (file === ${JSON.stringify(jsFile)} && file !== ${JSON.stringify(jsFileFallback)}) {- await import((window.JS_URL || '') + '/static/' + ${JSON.stringify(jsFileFallback)})+ const bootScript = (chunks, entrypoints, { isStable = false } = {}) => {+ const relativeFiles = entrypoints.map((e) => path.relative(path.resolve(absWorkingDir, 'dist'), e))+ const jsFile =+ relativeFiles.length > 0 ? relativeFiles.find((e) => e.endsWith('.js')) : `${entry}.js?t=${buildId}`+ const cssFile =+ relativeFiles.length > 0 ? relativeFiles.find((e) => e.endsWith('.css')) : `${entry}.css?t=${buildId}`++ const jsFileFallback = `${entry}.js?t=${buildId}`+ // 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.+ const entryFallback = isStable+ ? `+ var url = new URL(window.location.href)+ url.searchParams.set('stable_chunks', '0')+ 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),+ // 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)+ cleanUrl.searchParams.delete('stable_chunks')+ window.history.replaceState(window.history.state, '', cleanUrl.toString())+ }+ window.ESBUILD_LOAD_SCRIPT = async function (file) {+ try {+ await import((window.JS_URL || '') + '/static/' + file)+ } catch (error) {+ console.error('Error loading chunk: "' + file + '"')+ console.error(error)+ if (file === ${JSON.stringify(jsFile)} && file !== ${JSON.stringify(jsFileFallback)}) {${entryFallback}+ }}}+ window.ESBUILD_LOAD_SCRIPT(${JSON.stringify(jsFile)})+ `++ // Esbuild "chunks" a scene into possibly hundreds of tiny files. When we load the first few files,+ // they tell us which other files to load. This cascading loading is slow. That's why we cache+ // the list of chunks per scene, and load them all in parallel when a scene is loaded.+ //+ // The full map is written to its own content-hashed file in dist and fetched by the inline+ // loader, instead of being inlined into the HTML: the map is hundreds of KB that changed on+ // every deploy and had to be downloaded and parsed before the app could boot, on every page.++ // Don't use chunks in dev mode.+ // Django caches the generated index.html, and we'll end up loading the wrong chunks after one change.+ const chunksToServe = isDev ? {} : chunks+ const chunkMapFile = Object.keys(chunksToServe).length > 0 ? chunkMapFileName(entry, chunksToServe) : null+ if (chunkMapFile) {+ fse.writeFileSync(path.resolve(absWorkingDir, 'dist', chunkMapFile), chunkMapFileContents(chunksToServe))}- window.ESBUILD_LOAD_SCRIPT(${JSON.stringify(jsFile)})- `-- // Esbuild "chunks" a scene into possibly hundreds of tiny files. When we load the first few files,- // they tell us which other files to load. This cascading loading is slow. That's why we cache- // the list of chunks per scene, and load them all in parallel when a scene is loaded.- //- // The full map is written to its own content-hashed file in dist and fetched by the inline- // loader, instead of being inlined into the HTML: the map is hundreds of KB that changed on- // every deploy and had to be downloaded and parsed before the app could boot, on every page.-- // Don't use chunks in dev mode.- // Django caches the generated index.html, and we'll end up loading the wrong chunks after one change.- const chunksToServe = isDev ? {} : chunks- const chunkMapFile = Object.keys(chunksToServe).length > 0 ? chunkMapFileName(entry, chunksToServe) : null- if (chunkMapFile) {- fse.writeFileSync(path.resolve(absWorkingDir, 'dist', chunkMapFile), chunkMapFileContents(chunksToServe))- }- const chunkCode = Object.keys(chunks).length > 0 ? chunkLoaderScript(chunksToServe, chunkMapFile) : ''+ const chunkCode = Object.keys(chunks).length > 0 ? chunkLoaderScript(chunksToServe, chunkMapFile) : ''- // Fallback to non-hashed CSS (with cache-busting build ID) when the hashed version fails or- // stalls (e.g. CDN returns 403, or the request hangs). Mirrors the JS fallback above.- const cssFileFallback = `${entry}.css?t=${buildId}`- const cssLoader = cssFile ? cssLoaderScript(cssFile, cssFileFallback) : ''+ // Fallback to non-hashed CSS (with cache-busting build ID) when the hashed version fails or+ // stalls (e.g. CDN returns 403, or the request hangs). Mirrors the JS fallback above.+ const cssFileFallback = `${entry}.css?t=${buildId}`+ const cssLoader = cssFile ? cssLoaderScript(cssFile, cssFileFallback) : ''- fse.writeFileSync(- path.resolve(absWorkingDir, to),- fse.readFileSync(path.resolve(absWorkingDir, from), { encoding: 'utf-8' }).replace(- '</head>',- ` <script nonce="{{ request.csp_nonce }}" type="application/javascript">+ return `<script nonce="{{ request.csp_nonce }}" type="application/javascript">// The stylesheet link is added just below, at runtime, so a slow CSS fetch does// not hold up these boot scripts. The loader publishes window.ESBUILD_CSS_READY,// and the app entry waits on it before its first render, so React does not paint@@ -141,7 +157,20 @@ export function copyIndexHtml(${cssLoader}${scriptCode}${chunkCode}- </script>+ </script>`+ }++ // With stable chunk names built, the backend picks the boot variant per request. See+ // stableChunkNames.mjs and the stable_chunks context in posthog/utils.py.+ const scripts = stable+ ? `{% if stable_chunks %}${bootScript(stable.chunks, stable.entrypoints, { isStable: true })}{% else %}${bootScript(chunks, entrypoints)}{% endif %}`+ : bootScript(chunks, entrypoints)++ fse.writeFileSync(+ path.resolve(absWorkingDir, to),+ fse.readFileSync(path.resolve(absWorkingDir, from), { encoding: 'utf-8' }).replace(+ '</head>',+ ` ${scripts}</head>`))diff --git a/frontend/build.mjs b/frontend/build.mjsindex ebcd7ae15230..e7ea9a2042e0 100755--- a/frontend/build.mjs+++ b/frontend/build.mjs@@ -14,6 +14,7 @@ import {reportTopChunks,startDevServer,} from '@posthog/esbuilder'+import { writeStableChunks } from '@posthog/esbuilder/stableChunkNames.mjs'import { finalizeToolbarBuild, getToolbarAppBuildConfig } from './toolbar-config.mjs'import { WORKER_ENTRIES } from './workers.config.mjs'@@ -106,11 +107,21 @@ await buildInParallel(console.error('Could not get entrypoint for bundle "PostHog App."')throw new Error('Could not get entrypoint for bundle "PostHog App."')}+ let stable = nullif (!isDev) {reportTopChunks(buildResponse.outputs, { label: 'PostHog App chunks' })- writePreloadManifest(buildResponse.outputs)+ const preloadManifest = writePreloadManifest(buildResponse.outputs)+ // A throw here must fail the build: it reaches buildInParallel's catch, which+ // exits non-zero for non-dev builds. Keep it in this awaited call chain.+ stable = writeStableChunks({+ absWorkingDir: __dirname,+ outputs: buildResponse.outputs,+ chunks,+ entrypoints,+ preloadManifest,+ })}- writeIndexHtml(chunks, entrypoints)+ writeIndexHtml(chunks, entrypoints, stable)}if (config.name === 'Exporter') {@@ -184,6 +195,7 @@ export function writePreloadManifest(outputs = {}) {}}fs.writeFileSync(path.resolve(distDir, 'preload-manifest.json'), JSON.stringify(manifest, null, 2))+ return manifest}// EmojiPickerPanel loads frimousse's emoji data from /static/emoji rather than from a CDN. frimousse@@ -198,9 +210,11 @@ function copyEmojibaseData() {}}-export function writeIndexHtml(chunks = {}, entrypoints = []) {- copyIndexHtml(__dirname, 'src/index.html', 'dist/index.html', 'index', chunks, entrypoints)- copyIndexHtml(__dirname, 'src/layout.html', 'dist/layout.html', 'index', chunks, entrypoints)+export function writeIndexHtml(chunks = {}, entrypoints = [], stable = null) {+ copyIndexHtml(__dirname, 'src/index.html', 'dist/index.html', 'index', chunks, entrypoints, stable)+ // layout.html also gets the {% if stable_chunks %} boot branch, but posthog/utils.py only sets+ // stable_chunks for "index.html", so this branch never renders here; the {% else %} default runs.+ copyIndexHtml(__dirname, 'src/layout.html', 'dist/layout.html', 'index', chunks, entrypoints, stable)}export function writeExporterHtml(chunks = {}, entrypoints = []) {diff --git a/frontend/src/index.html b/frontend/src/index.htmlindex a0553957e937..f6c4640c6767 100644--- a/frontend/src/index.html+++ b/frontend/src/index.html@@ -36,6 +36,13 @@{# to a single copy. crossorigin matches the loader's fetch mode so one response is reused. #}<link rel="preload" href="{{ js_url }}/{{ preload_css_url }}" as="style" crossorigin="anonymous">{% endif %}+ {# Stable chunk names (opt-in, see posthog/stable_chunks.py): the import map must come before #}+ {# the modulepreload hints below, because browsers ignore an import map added after module #}+ {# loading has started. #}+ {% if stable_chunks_importmap %}+ {# nosemgrep: python.flask.security.xss.audit.template-unescaped-with-safe.template-unescaped-with-safe, generic.html-templates.security.var-in-script-tag.var-in-script-tag (import_map_json escapes every "<" to \u003c, so the JSON cannot end the script element) #}+ <script type="importmap" nonce="{{ request.csp_nonce }}">{{ stable_chunks_importmap|safe }}</script>+ {% endif %}{% for url in preload_js_urls %}<link rel="modulepreload" href="{{ js_url }}/{{ url }}">{% endfor %}diff --git a/posthog/stable_chunks.py b/posthog/stable_chunks.pynew file mode 100644index 000000000000..b84dbed28981--- /dev/null+++ b/posthog/stable_chunks.py@@ -0,0 +1,120 @@+"""+Opt-in 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 identity+specifiers, plus `stable-chunks-manifest.json` with the import map that resolves them (see+common/esbuilder/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.+"""++import os+import json+from functools import lru_cache+from typing import Optional++from django.conf import settings+from django.http import HttpRequest, HttpResponse++import structlog++from posthog.dataclasses import frozen+from posthog.exceptions_capture import capture_exception++logger = structlog.get_logger(__name__)++STABLE_CHUNKS_PARAM = "stable_chunks"+STABLE_CHUNKS_COOKIE = "ph_stable_chunks"+_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30+++@frozen+class StableChunks:+ # import map specifier -> file path relative to JS_URL+ imports: dict[str, str]+ preload_js_urls: tuple[str, ...]+ authenticated_preload_js_urls: tuple[str, ...]++ def import_map_json(self, js_url: str) -> str:+ import_map = json.dumps(+ {"imports": {specifier: f"{js_url}/{path}" for specifier, path in self.imports.items()}}+ )+ # The template renders this inside <script> with |safe, and js_url can follow the request+ # origin (get_js_url), so "<" must never reach the page unescaped.+ return import_map.replace("<", "\\u003c")++ def preload_urls(self, include_authenticated_shell: bool) -> tuple[str, ...]:+ urls = [*self.preload_js_urls, *(self.authenticated_preload_js_urls if include_authenticated_shell else ())]+ return tuple(dict.fromkeys(urls))+++def read_stable_chunks_manifest(manifest_path: str) -> Optional[StableChunks]:+ """+ Parse the manifest defensively. A missing or malformed manifest turns the opt-in off rather+ than breaking page rendering, and is reported, because the caller caches the result per process.+ """+ try:+ if not os.path.isfile(manifest_path):+ return None+ with open(manifest_path) as f:+ manifest = json.load(f)+ imports = manifest.get("imports")+ preload = manifest.get("preload", {})+ js = preload.get("js", [])+ authenticated_js = preload.get("authenticatedJs", [])+ if not (+ isinstance(imports, dict)+ and imports+ and all(isinstance(k, str) and isinstance(v, str) for k, v in imports.items())+ and isinstance(js, list)+ and isinstance(authenticated_js, list)+ and all(isinstance(url, str) for url in [*js, *authenticated_js])+ ):+ raise ValueError("stable chunks manifest fields have unexpected types")+ return StableChunks(+ imports=imports,+ preload_js_urls=tuple(js),+ authenticated_preload_js_urls=tuple(authenticated_js),+ )+ except Exception as e:+ logger.warning("stable_chunks_manifest_unreadable", manifest_path=manifest_path, error=str(e))+ capture_exception(e)+ return None+++@lru_cache(maxsize=1)+def _resolve_stable_chunks() -> Optional[StableChunks]:+ if settings.DEBUG or settings.TEST:+ return None+ return read_stable_chunks_manifest(+ os.path.join(settings.BASE_DIR, "frontend", "dist", "stable-chunks-manifest.json")+ )+++def stable_chunks_opted_in(request: HttpRequest) -> bool:+ param = request.GET.get(STABLE_CHUNKS_PARAM)+ if param is not None:+ return param == "1"+ return request.COOKIES.get(STABLE_CHUNKS_COOKIE) == "1"+++def stable_chunks_for_request(request: HttpRequest) -> Optional[StableChunks]:+ return _resolve_stable_chunks() if stable_chunks_opted_in(request) else None+++def persist_stable_chunks_choice(request: HttpRequest, response: HttpResponse) -> None:+ param = request.GET.get(STABLE_CHUNKS_PARAM)+ if param == "1":+ response.set_cookie(+ STABLE_CHUNKS_COOKIE,+ "1",+ 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_get_context_for_template.py b/posthog/test/test_get_context_for_template.pyindex beeb1a8b5722..aa811abb1d82 100644--- a/posthog/test/test_get_context_for_template.py+++ b/posthog/test/test_get_context_for_template.py@@ -14,10 +14,17 @@ from parameterized import parameterizedfrom posthog.api.tagged_item import set_tags_on_objectfrom posthog.models import UserHomeSettings+from posthog.stable_chunks import StableChunksfrom posthog.utils import get_context_for_templatefrom products.conversations.backend.services.identity import IDENTITY_CLAIM_MAX_AGE_SECONDS+STABLE_CHUNKS = StableChunks(+ imports={"@c/eAAAA": "static/index-S0000000000.js"},+ preload_js_urls=("static/index-S0000000000.js",),+ authenticated_preload_js_urls=("static/shell-S1111111111.js",),+)+class TestGetContextForTemplate(APIBaseTest):def test_get_context_for_template(self):@@ -135,3 +142,29 @@ class TestGetContextForTemplate(APIBaseTest):assert claims["email"]["value"] == self.user.email.lower()current_time = int(time.time())assert current_time < claims["email"]["expires_at"] <= current_time + IDENTITY_CLAIM_MAX_AGE_SECONDS++ @parameterized.expand(+ [+ ("opted in and logged in", True, True, ("static/index-S0000000000.js", "static/shell-S1111111111.js")),+ ("opted in and anonymous", True, False, ("static/index-S0000000000.js",)),+ ("not opted in", False, True, ()),+ ]+ )+ def test_only_an_opted_in_browser_boots_through_the_import_map(+ self, _name, opted_in, authenticated, expected_preload_js_urls+ ):+ request = RequestFactory().get("/?stable_chunks=1" if opted_in else "/")+ SessionMiddleware(lambda _request: HttpResponse()).process_request(request)+ request.user = self.user if authenticated else AnonymousUser()++ with mock.patch("posthog.stable_chunks._resolve_stable_chunks", return_value=STABLE_CHUNKS):+ context = get_context_for_template("index.html", request)++ assert context.get("stable_chunks", False) is opted_in+ assert context["preload_js_urls"] == expected_preload_js_urls+ if opted_in:+ assert json.loads(context["stable_chunks_importmap"]) == {+ "imports": {"@c/eAAAA": f"{context['js_url']}/static/index-S0000000000.js"}+ }+ else:+ assert "stable_chunks_importmap" not in contextdiff --git a/posthog/test/test_stable_chunks.py b/posthog/test/test_stable_chunks.pynew file mode 100644index 000000000000..d228d8c0fa53--- /dev/null+++ b/posthog/test/test_stable_chunks.py@@ -0,0 +1,107 @@+import json+import tempfile+from pathlib import Path++from posthog.test.base import APIBaseTest++from django.contrib.sessions.middleware import SessionMiddleware+from django.http import HttpResponse+from django.test import RequestFactory, SimpleTestCase++from parameterized import parameterized++from posthog.stable_chunks import (+ STABLE_CHUNKS_COOKIE,+ persist_stable_chunks_choice,+ read_stable_chunks_manifest,+ stable_chunks_opted_in,+)+from posthog.utils import render_template++VALID_MANIFEST = {+ "imports": {"@c/eAAAA": "static/index-S0000000000.js"},+ "preload": {"js": ["static/index-S0000000000.js"], "authenticatedJs": ["static/chunk-S1111111111.js"]},+}+++class TestStableChunks(SimpleTestCase):+ @parameterized.expand(+ [+ ("valid", VALID_MANIFEST, True),+ ("imports is not a mapping", {**VALID_MANIFEST, "imports": ["static/index.js"]}, False),+ ("empty imports", {**VALID_MANIFEST, "imports": {}}, False),+ ("preload url is not a string", {**VALID_MANIFEST, "preload": {"js": [1], "authenticatedJs": []}}, False),+ ]+ )+ def test_manifest_problems_fall_back_to_the_default_build(self, _name, manifest, expect_stable):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "stable-chunks-manifest.json"+ path.write_text(json.dumps(manifest))++ stable = read_stable_chunks_manifest(str(path))++ assert (stable is not None) == expect_stable+ if stable:+ assert json.loads(stable.import_map_json("https://cdn.example.com")) == {+ "imports": {"@c/eAAAA": "https://cdn.example.com/static/index-S0000000000.js"}+ }+ assert stable.preload_urls(include_authenticated_shell=False) == ("static/index-S0000000000.js",)++ def test_import_map_cannot_close_its_script_tag(self):+ with tempfile.TemporaryDirectory() as directory:+ path = Path(directory) / "stable-chunks-manifest.json"+ path.write_text(json.dumps(VALID_MANIFEST))+ stable = read_stable_chunks_manifest(str(path))++ assert stable is not None+ assert "</script>" not in stable.import_map_json("https://cdn.example.com</script><script>")++ @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),+ ]+ )+ def test_opt_in(self, _name, query, cookie, expected):+ request = RequestFactory().get(f"/{query}")+ if cookie:+ request.COOKIES[STABLE_CHUNKS_COOKIE] = cookie++ assert stable_chunks_opted_in(request) == 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),+ ("no param leaves the cookie alone", "", None, None),+ ]+ )+ def test_the_choice_is_persisted_on_the_response(self, _name, query, expected_value, expected_max_age):+ request = RequestFactory().get(f"/{query}")+ response = HttpResponse()++ persist_stable_chunks_choice(request, response)++ cookie = response.cookies.get(STABLE_CHUNKS_COOKIE)+ assert (cookie.value if cookie else None) == expected_value+ assert (cookie["max-age"] if cookie else None) == expected_max_age+ if expected_value == "1":+ assert cookie is not None+ # Only the server reads the choice, so scripts on the page never need it.+ assert cookie["httponly"] is True+++class TestStableChunksChoiceSurvivesTheRequest(APIBaseTest):+ @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++ response = render_template("sso_reauth_complete.html", request)++ assert response.cookies[STABLE_CHUNKS_COOKIE].value == ("1" if param == "1" else "")diff --git a/posthog/utils.py b/posthog/utils.pyindex 68ea60f76142..f4bb180a7330 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -59,6 +59,7 @@ from posthog.git import get_git_branch, get_git_commit_shortfrom posthog.metrics import KLUDGES_COUNTERfrom posthog.redis import get_clientfrom posthog.security.url_validation import has_ambiguous_authority+from posthog.stable_chunks import persist_stable_chunks_choice, stable_chunks_for_requestfrom products.feature_flags.backend.persisted_flags import get_dynamic_persisted_feature_flags@@ -741,9 +742,15 @@ def _build_template_context(# Only the SPA shell references these; other templates (exporter, layout, ...) load different bundlesif template_name == "index.html":+ is_authenticated = bool(request.user and request.user.is_authenticated)context["preload_css_url"], context["preload_js_urls"], context["preload_font_url"] = _resolve_entry_assets(- bool(request.user and request.user.is_authenticated)+ is_authenticated)+ stable_chunks = stable_chunks_for_request(request)+ if stable_chunks:+ context["stable_chunks"] = True+ context["stable_chunks_importmap"] = stable_chunks.import_map_json(context["js_url"])+ context["preload_js_urls"] = stable_chunks.preload_urls(is_authenticated)# Theme for the pre-React shell (critical CSS in index.html), mirroring the app's# themeLogic.isDarkModeOn: anonymous pages are always light, a missing theme_mode# means light, and only "system" defers to prefers-color-scheme.@@ -822,6 +829,7 @@ def render_template(response.status_code = status_codeif not request.user.is_anonymous:patch_cache_control(response, no_store=True)+ persist_stable_chunks_choice(request, response)return response