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.

perf(frontend): scope the stable chunk import map on logged-out pages (#117784)

posthog[bot]a3b9101c398f
diff --git a/frontend/bin/loggedOutScenes.mjs b/frontend/bin/loggedOutScenes.mjs
new file mode 100644
index 000000000000..e9c27c06f9c5
--- /dev/null
+++ b/frontend/bin/loggedOutScenes.mjs
@@ -0,0 +1,69 @@
+import fs from 'node:fs'
+import path from 'node:path'
+
+/**
+ * The scenes a logged-out page can show: the scenes with `onlyUnauthenticated` or
+ * `allowUnauthenticated` in scenes/scenes.ts that have a loader. The stable chunk build puts only
+ * these scenes' chunks into the import map of a logged-out page. bin/loggedOutScenes.test.ts fails
+ * when this list and scenes/scenes.ts disagree.
+ */
+export const LOGGED_OUT_SCENES = [
+ 'AgenticAccountMismatch',
+ 'AgenticAuthorize',
+ 'CodeCanvasLink',
+ 'CodeChannelLink',
+ 'CodeLoopLink',
+ 'CodeTaskLink',
+ 'InviteSignup',
+ 'Login',
+ 'Login2FA',
+ 'OAuthAuthorize',
+ 'OrganizationCreationConfirm',
+ 'PasswordReset',
+ 'PasswordResetComplete',
+ 'PreflightCheck',
+ 'Signup',
+ 'TwoFactorReset',
+ 'Unsubscribe',
+ 'VercelConnect',
+ 'VerifyEmail',
+]
+
+// The files that map a scene to its loader, as `[Scene.Name]: () => import('…')` or `Name: () => import('…')`.
+const SCENE_REGISTRIES = ['src/scenes/appScenes.ts', 'src/productScenes.tsx']
+const SCENE_LOADER = /(?:\[Scene\.(\w+)\]|(\w+)):\s*\(\)\s*=>\s*import\(\s*'([^']+)'\s*\)/g
+
+/** A module path relative to the frontend directory, without its extension or a trailing `/index`. */
+export function moduleKey(modulePath) {
+ return path.posix
+ .normalize(modulePath)
+ .replace(/\.[cm]?[jt]sx?$/, '')
+ .replace(/\/index$/, '')
+}
+
+// The tsconfig.json path aliases that scene loaders use, relative to the frontend directory.
+const PATH_ALIASES = { 'products/': '../products/', 'scenes/': 'src/scenes/', 'lib/': 'src/lib/', '~/': 'src/' }
+
+function resolveLoader(registry, specifier) {
+ if (specifier.startsWith('.')) {
+ return path.posix.join(path.posix.dirname(registry), specifier)
+ }
+ const alias = Object.keys(PATH_ALIASES).find((prefix) => specifier.startsWith(prefix))
+ if (!alias) {
+ throw new Error(`stable chunks: cannot resolve the scene loader '${specifier}' in ${registry}`)
+ }
+ return PATH_ALIASES[alias] + specifier.slice(alias.length)
+}
+
+/** Scene name -> module key of its loader, for every scene with a loader. */
+export function sceneModules(frontendDir) {
+ const modules = new Map()
+ for (const registry of SCENE_REGISTRIES) {
+ const source = fs.readFileSync(path.resolve(frontendDir, registry), 'utf8')
+ for (const [, sceneEnumName, sceneKey, specifier] of source.matchAll(SCENE_LOADER)) {
+ const modulePath = path.relative(frontendDir, path.resolve(frontendDir, resolveLoader(registry, specifier)))
+ modules.set(sceneEnumName ?? sceneKey, moduleKey(modulePath.split(path.sep).join('/')))
+ }
+ }
+ return modules
+}
diff --git a/frontend/bin/loggedOutScenes.test.ts b/frontend/bin/loggedOutScenes.test.ts
new file mode 100644
index 000000000000..c63a5e96a583
--- /dev/null
+++ b/frontend/bin/loggedOutScenes.test.ts
@@ -0,0 +1,20 @@
+import path from 'node:path'
+
+import { preloadedScenes, sceneConfigurations } from 'scenes/scenes'
+
+import { LOGGED_OUT_SCENES, sceneModules } from './loggedOutScenes.mjs'
+
+describe('LOGGED_OUT_SCENES', () => {
+ // A logged-out scene missing from the list has no import map entries for its chunks on the stable
+ // chunk build, so its page reloads on the hashed build every time.
+ it('lists every scene with a loader that a logged-out page can show', () => {
+ const scenesWithLoaders = sceneModules(path.resolve(__dirname, '..'))
+ const loggedOutScenes = Object.entries(sceneConfigurations)
+ .filter(([, config]) => config.onlyUnauthenticated || config.allowUnauthenticated)
+ .map(([scene]) => scene)
+ .filter((scene) => !(scene in preloadedScenes))
+
+ expect([...LOGGED_OUT_SCENES].sort()).toEqual(loggedOutScenes.sort())
+ expect(LOGGED_OUT_SCENES.filter((scene) => !scenesWithLoaders.has(scene))).toEqual([])
+ })
+})
diff --git a/frontend/bin/stableChunkNames.mjs b/frontend/bin/stableChunkNames.mjs
index c506929576af..2554fb78ff12 100644
--- a/frontend/bin/stableChunkNames.mjs
+++ b/frontend/bin/stableChunkNames.mjs
@@ -4,6 +4,8 @@ import path from 'node:path'
import { CHUNK_IMPORT_GLOBAL } from '@posthog/esbuilder/cssLoader.mjs'
+import { moduleKey } from './loggedOutScenes.mjs'
+
/**
* Stable chunk names.
*
@@ -135,10 +137,63 @@ export function planStableChunks(outputs, readSource, distPrefix = 'dist/', prel
return { plan, imports }
}
+/**
+ * The import map specifiers a logged-out page can reach. The walk starts at the chunk of `entry`
+ * and follows every import, except a dynamic import of a module in `signedInModules`. Modules are
+ * module keys (see loggedOutScenes.mjs). Each module in `loggedOutModules` must be reached.
+ *
+ * `outputs` is the esbuild metafile's `outputs`, and `plan` is the plan from planStableChunks.
+ */
+export function loggedOutSpecifiers(
+ outputs,
+ plan,
+ { entry, loggedOutModules, signedInModules, cssSpecifiersByOutput }
+) {
+ const moduleOf = (output) => (output.entryPoint ? moduleKey(output.entryPoint) : null)
+ const start = Object.keys(outputs).find(
+ (outputPath) => outputPath.endsWith('.js') && moduleOf(outputs[outputPath]) === moduleKey(entry)
+ )
+ if (!start) {
+ throw new Error(`stable chunks: no output chunk for the entry ${entry}`)
+ }
+ const reached = new Set([start])
+ const queue = [start]
+ while (queue.length > 0) {
+ for (const { path: target, kind } of outputs[queue.pop()].imports || []) {
+ const output = outputs[target]
+ if (!output || !target.endsWith('.js') || reached.has(target)) {
+ continue
+ }
+ if (kind === 'dynamic-import' && signedInModules.has(moduleOf(output))) {
+ continue
+ }
+ reached.add(target)
+ queue.push(target)
+ }
+ }
+
+ // A logged-out scene that the walk misses would load with no import map entries for its chunks.
+ const reachedModules = new Set([...reached].map((outputPath) => moduleOf(outputs[outputPath])))
+ const unreached = [...loggedOutModules].filter((module) => !reachedModules.has(module))
+ if (unreached.length > 0) {
+ throw new Error(`stable chunks: logged-out scenes not reachable from ${entry}: ${unreached.join(', ')}`)
+ }
+
+ const specifiers = new Set()
+ for (const outputPath of reached) {
+ specifiers.add(`${SPECIFIER_PREFIX}${plan.get(outputPath).identity}`)
+ for (const specifier of cssSpecifiersByOutput.get(outputPath) ?? []) {
+ specifiers.add(specifier)
+ }
+ }
+ return [...specifiers].sort()
+}
+
/**
* 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.
+ * `entrypoints` the absolute paths of the entry files, as `buildOrWatch` returns them. `loggedOut`
+ * holds the options for loggedOutSpecifiers. Without it, every page gets the full import map.
*/
export function writeStableChunks({
absWorkingDir,
@@ -149,6 +204,7 @@ export function writeStableChunks({
preludes = new Map(),
extraImports = {},
eagerCss = [],
+ loggedOut = null,
}) {
const distDir = path.resolve(absWorkingDir, 'dist')
const { plan, imports } = planStableChunks(
@@ -190,6 +246,8 @@ export function writeStableChunks({
const manifest = {
imports,
eagerCss: eagerCss.map((file) => `static/${file}`),
+ // The backend renders only these import map entries for a logged-out page.
+ loggedOutImports: loggedOut ? loggedOutSpecifiers(outputs, plan, loggedOut) : null,
preload: {
js: (preloadManifest?.js || []).map(toStableUrl),
authenticatedJs: (preloadManifest?.authenticatedJs || []).map(toStableUrl),
diff --git a/frontend/bin/stableChunkNames.test.ts b/frontend/bin/stableChunkNames.test.ts
index 174af9779137..b7b29ef24ab1 100644
--- a/frontend/bin/stableChunkNames.test.ts
+++ b/frontend/bin/stableChunkNames.test.ts
@@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSyn
import { tmpdir } from 'node:os'
import path from 'node:path'
-import { planStableChunks, stableFileName, writeStableChunks } from './stableChunkNames.mjs'
+import { loggedOutSpecifiers, planStableChunks, stableFileName, writeStableChunks } from './stableChunkNames.mjs'
// Two chunks: an entry that imports a shared chunk, the way esbuild writes them with publicPath /static.
const OUTPUTS = {
@@ -185,4 +185,64 @@ describe('planStableChunks', () => {
expect(writeAndReadMap(prelude)).toBe(expectedMappings)
})
})
+
+ describe('loggedOutSpecifiers', () => {
+ // The entry imports App, which lazy-loads a logged-out scene, a signed-in scene and a helper.
+ const WALK_OUTPUTS = {
+ 'dist/index-AAAA1111.js': {
+ entryPoint: 'src/index.tsx',
+ imports: [{ path: 'dist/App-BBBB2222.js', kind: 'dynamic-import' }],
+ },
+ 'dist/App-BBBB2222.js': {
+ entryPoint: 'src/scenes/App.tsx',
+ imports: [
+ { path: 'dist/Login-CCCC3333.js', kind: 'dynamic-import' },
+ { path: 'dist/Insight-DDDD4444.js', kind: 'dynamic-import' },
+ { path: 'dist/helper-EEEE5555.js', kind: 'dynamic-import' },
+ ],
+ },
+ 'dist/Login-CCCC3333.js': {
+ entryPoint: 'src/scenes/Login.tsx',
+ imports: [{ path: 'dist/chunk-FFFF6666.js', kind: 'import-statement' }],
+ },
+ 'dist/Insight-DDDD4444.js': {
+ entryPoint: '../products/insights/Insight.tsx',
+ imports: [{ path: 'dist/chunk-GGGG7777.js', kind: 'import-statement' }],
+ },
+ 'dist/helper-EEEE5555.js': { entryPoint: 'src/lib/helper.ts', imports: [] },
+ 'dist/chunk-FFFF6666.js': { inputs: { 'src/lib/form.ts': {} }, imports: [] },
+ 'dist/chunk-GGGG7777.js': { inputs: { 'src/lib/chart.ts': {} }, imports: [] },
+ }
+ const walkPlan = planStableChunks(WALK_OUTPUTS, () => 'export {}', 'dist/').plan
+ const specifierOf = (outputPath: string): string => `@c/${walkPlan.get(outputPath)!.identity}`
+ const walk = (loggedOutModules: string[]): string[] =>
+ loggedOutSpecifiers(WALK_OUTPUTS, walkPlan, {
+ entry: 'src/index.tsx',
+ loggedOutModules: new Set(loggedOutModules),
+ signedInModules: new Set(['../products/insights/Insight']),
+ cssSpecifiersByOutput: new Map([
+ ['dist/Login-CCCC3333.js', ['@css/login']],
+ ['dist/Insight-DDDD4444.js', ['@css/insight']],
+ ]),
+ })
+
+ it('keeps what a logged-out page can load and drops the chunks of signed-in scenes', () => {
+ expect(walk(['src/scenes/Login'])).toEqual(
+ [
+ ...[
+ 'dist/index-AAAA1111.js',
+ 'dist/App-BBBB2222.js',
+ 'dist/Login-CCCC3333.js',
+ 'dist/helper-EEEE5555.js',
+ 'dist/chunk-FFFF6666.js',
+ ].map(specifierOf),
+ '@css/login',
+ ].sort()
+ )
+ })
+
+ it('fails when a logged-out scene is not reachable from the entry', () => {
+ expect(() => walk(['src/scenes/Login', 'src/scenes/Renamed'])).toThrow('src/scenes/Renamed')
+ })
+ })
})
diff --git a/frontend/build.mjs b/frontend/build.mjs
index a8b6a1151bb2..c60f4b3c383a 100755
--- a/frontend/build.mjs
+++ b/frontend/build.mjs
@@ -16,6 +16,8 @@ import {
startDevServer,
} from '@posthog/esbuilder'
+import { AUTHENTICATED_SHELL, ENTRY } from './bin/bootEntries.mjs'
+import { LOGGED_OUT_SCENES, moduleKey, sceneModules } from './bin/loggedOutScenes.mjs'
import { writeStableChunks } from './bin/stableChunkNames.mjs'
import { buildCssGroups } from './bin/stableCss.mjs'
import { cssPrelude, CSS_SPECIFIER_PREFIX, planCssGroups } from './bin/stableCssPlan.mjs'
@@ -150,6 +152,15 @@ await buildInParallel(
[...cssFiles].map(([group, file]) => [`${CSS_SPECIFIER_PREFIX}${group}`, `static/${file}`])
),
eagerCss: cssPlan.eager.map((group) => cssFiles.get(group)),
+ loggedOut: {
+ ...loggedOutImportMapScope(),
+ cssSpecifiersByOutput: new Map(
+ [...cssPlan.lazyGroupsByEntry].map(([file, groups]) => [
+ file,
+ groups.map((group) => `${CSS_SPECIFIER_PREFIX}${group}`),
+ ])
+ ),
+ },
})
removeUnlinkedStylesheets(__dirname, buildResponse.outputs, 'src/index.tsx')
}
@@ -181,6 +192,19 @@ await buildInParallel(
}
)
+/** Which modules a logged-out page loads, for the logged-out import map. See loggedOutSpecifiers. */
+function loggedOutImportMapScope() {
+ const scenes = sceneModules(__dirname)
+ const missing = LOGGED_OUT_SCENES.filter((scene) => !scenes.has(scene))
+ if (missing.length > 0) {
+ throw new Error(`stable chunks: no scene loader for the logged-out scenes ${missing.join(', ')}`)
+ }
+ const loggedOutModules = new Set(LOGGED_OUT_SCENES.map((scene) => scenes.get(scene)))
+ const signedInModules = new Set([...scenes.values()].filter((module) => !loggedOutModules.has(module)))
+ signedInModules.add(moduleKey(AUTHENTICATED_SHELL))
+ return { entry: ENTRY, loggedOutModules, signedInModules }
+}
+
/**
* Write dist/preload-manifest.json, read by the Django backend (posthog/utils.py) to emit
* <link rel="preload"/"modulepreload"> tags so the boot chain (CSS, font, App and
diff --git a/frontend/src/lib/utils/isChunkLoadError.test.ts b/frontend/src/lib/utils/isChunkLoadError.test.ts
index 04ae416fb72e..b1dae7e59d26 100644
--- a/frontend/src/lib/utils/isChunkLoadError.test.ts
+++ b/frontend/src/lib/utils/isChunkLoadError.test.ts
@@ -23,6 +23,34 @@ describe('isChunkLoadError', () => {
{ name: 'Error', message: 'Importing a module script failed.' },
true,
],
+ [
+ 'Chrome unmapped stable chunk specifier',
+ {
+ name: 'TypeError',
+ message:
+ 'Failed to resolve module specifier "@c/c0A1B2C3D4E". Relative references must start with either "/", "./", or "../".',
+ },
+ true,
+ ],
+ [
+ 'Firefox unmapped stable chunk specifier',
+ {
+ name: 'TypeError',
+ message:
+ 'The specifier “@c/c0A1B2C3D4E” was a bare specifier, but was not remapped to anything. Relative module specifiers must start with “./”, “../” or “/”.',
+ },
+ true,
+ ],
+ [
+ 'Safari unmapped stable chunk specifier',
+ { name: 'TypeError', message: "Module name, '@c/c0A1B2C3D4E' does not resolve to a valid URL." },
+ true,
+ ],
+ [
+ 'unmapped specifier outside the stable chunk build',
+ { name: 'TypeError', message: 'Failed to resolve module specifier "lodash".' },
+ false,
+ ],
['generic TypeError', { name: 'TypeError', message: 'undefined is not a function' }, false],
['unrelated Error', { name: 'Error', message: 'something else' }, false],
['error with no name or message', {}, false],
diff --git a/frontend/src/lib/utils/isChunkLoadError.ts b/frontend/src/lib/utils/isChunkLoadError.ts
index 9c1f39e75a1d..ca9deee4b72c 100644
--- a/frontend/src/lib/utils/isChunkLoadError.ts
+++ b/frontend/src/lib/utils/isChunkLoadError.ts
@@ -4,6 +4,8 @@
* - esbuild/Vite: message contains `'Failed to fetch dynamically imported module'`
* - Firefox: native `TypeError: error loading dynamically imported module: <url>` (deferred import of a now-deleted chunk after a deploy)
* - WebKit/Safari: `Importing a module script failed.` (module script fails to load, e.g. transient network failure)
+ * - stable chunk build: a native `TypeError` that names an `@c/` specifier the page's import map does not hold
+ * (a logged-out page gets only the logged-out part of the map, see posthog/stable_chunks.py)
*
* Safari's/Firefox's generic network TypeErrors (`isGenericNetworkTypeError`) are also a failed
* `import()`'s shape in those browsers, but the message can't tell that apart from an unrelated
@@ -12,6 +14,9 @@
*/
const markedChunkLoadErrors = new WeakSet<object>()
+// Chrome, Firefox and Safari quote the specifier with ", “ or ' in their unresolved-specifier messages.
+const UNMAPPED_STABLE_CHUNK_SPECIFIER = /["“'](@c\/[A-Za-z0-9]+)["”']/
+
export function markAsChunkLoadError(error: unknown): void {
if (!error || typeof error !== 'object') {
return
@@ -41,6 +46,14 @@ export function isGenericNetworkTypeError(error: unknown): boolean {
)
}
+export function unmappedStableChunkSpecifier(error: unknown): string | null {
+ const info = getErrorInfo(error)
+ if (info?.name !== 'TypeError') {
+ return null
+ }
+ return UNMAPPED_STABLE_CHUNK_SPECIFIER.exec(info.message)?.[1] ?? null
+}
+
export function isChunkLoadError(error: unknown): boolean {
const info = getErrorInfo(error)
if (!info) {
@@ -52,6 +65,7 @@ export function isChunkLoadError(error: unknown): boolean {
info.name === 'ChunkLoadError' ||
info.message.includes('Failed to fetch dynamically imported module') ||
info.message.includes('Importing a module script failed') ||
- (isTypeError && info.message.includes('error loading dynamically imported module'))
+ (isTypeError && info.message.includes('error loading dynamically imported module')) ||
+ unmappedStableChunkSpecifier(error) !== null
)
}
diff --git a/frontend/src/lib/utils/stableChunks.test.ts b/frontend/src/lib/utils/stableChunks.test.ts
index 77f471ad047c..11c28b1d5445 100644
--- a/frontend/src/lib/utils/stableChunks.test.ts
+++ b/frontend/src/lib/utils/stableChunks.test.ts
@@ -20,22 +20,31 @@ describe('reloadAfterChunkLoadError', () => {
})
it('reloads the same page on the default build', () => {
- reloadAfterChunkLoadError()
+ reloadAfterChunkLoadError(new TypeError('Failed to resolve module specifier "@c/Abc123".'))
expect(reload).toHaveBeenCalledTimes(1)
expect(replace).not.toHaveBeenCalled()
})
- it('loads the page on the default build when the stable build fails, keeping the rest of the URL', () => {
+ it.each([
+ [
+ 'a chunk that failed to load',
+ new TypeError('Failed to fetch dynamically imported module: /static/chunk.js'),
+ 'https://us.posthog.com/project/1/dashboard?tab=a&stable_chunks=fallback#panel=x',
+ ],
+ [
+ 'a chunk missing from the import map',
+ new TypeError('Failed to resolve module specifier "@c/Abc123". Relative references must start with "/".'),
+ 'https://us.posthog.com/project/1/dashboard?tab=a&stable_chunks=fallback&stable_chunks_unmapped=%40c%2FAbc123#panel=x',
+ ],
+ ])('loads the page on the default build after %s, keeping the rest of the URL', (_name, error, expectedUrl) => {
const importMap = document.createElement('script')
importMap.type = 'importmap'
document.head.appendChild(importMap)
- reloadAfterChunkLoadError()
+ reloadAfterChunkLoadError(error)
expect(reload).not.toHaveBeenCalled()
- expect(replace).toHaveBeenCalledWith(
- 'https://us.posthog.com/project/1/dashboard?tab=a&stable_chunks=fallback#panel=x'
- )
+ expect(replace).toHaveBeenCalledWith(expectedUrl)
})
})
diff --git a/frontend/src/lib/utils/stableChunks.ts b/frontend/src/lib/utils/stableChunks.ts
index f13388308c5d..12ebf3904d11 100644
--- a/frontend/src/lib/utils/stableChunks.ts
+++ b/frontend/src/lib/utils/stableChunks.ts
@@ -1,3 +1,5 @@
+import { unmappedStableChunkSpecifier } from './isChunkLoadError'
+
/** Only the stable chunk build renders an import map (see posthog/stable_chunks.py). */
export function isStableChunkBuild(): boolean {
return document.querySelector('script[type="importmap"]') !== null
@@ -8,13 +10,19 @@ export function isStableChunkBuild(): boolean {
* import map and fails again while a new stable chunk is not reachable, so the reload asks for the
* default build. The server always serves the default build for ?stable_chunks=fallback and stores
* no choice for it, so this cannot loop, and the next page load tries the stable build again.
+ * The reload names a specifier that the import map did not hold, so the server can tell a page
+ * whose import map misses a chunk apart from a chunk that failed to load.
*/
-export function reloadAfterChunkLoadError(): void {
+export function reloadAfterChunkLoadError(error: unknown): void {
if (!isStableChunkBuild()) {
window.location.reload()
return
}
const url = new URL(window.location.href)
url.searchParams.set('stable_chunks', 'fallback')
+ const unmapped = unmappedStableChunkSpecifier(error)
+ if (unmapped) {
+ url.searchParams.set('stable_chunks_unmapped', unmapped)
+ }
window.location.replace(url.toString())
}
diff --git a/frontend/src/scenes/ChunkLoadErrorBoundary.tsx b/frontend/src/scenes/ChunkLoadErrorBoundary.tsx
index 565ff8c41324..058847ebf523 100644
--- a/frontend/src/scenes/ChunkLoadErrorBoundary.tsx
+++ b/frontend/src/scenes/ChunkLoadErrorBoundary.tsx
@@ -58,7 +58,7 @@ export class ChunkLoadErrorBoundary extends Component<ChunkLoadErrorBoundaryProp
if (this.props.reload) {
this.props.reload()
} else {
- reloadAfterChunkLoadError()
+ reloadAfterChunkLoadError(error)
}
}
diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsx
index 0f0722beef70..fa3fca2b9a0d 100644
--- a/frontend/src/scenes/sceneLogic.tsx
+++ b/frontend/src/scenes/sceneLogic.tsx
@@ -331,8 +331,8 @@ export interface sceneLogicActions {
sceneId: string
sceneKey: string | undefined
}
- reloadBrowserDueToImportError: () => {
- value: true
+ reloadBrowserDueToImportError: (error: unknown) => {
+ error: unknown
}
resetUnavailableHomepage: (pathname: string) => {
pathname: string
@@ -484,7 +484,7 @@ export const sceneLogic = kea<sceneLogicType>([
sceneKey,
params,
}),
- reloadBrowserDueToImportError: true,
+ reloadBrowserDueToImportError: (error: unknown) => ({ error }),
setHomepage: (tab: SceneTab | null, homepageSource?: 'dashboards list') => ({ tab, homepageSource }),
homepageSaved: (tab: SceneTab | null) => ({ tab }),
@@ -1071,7 +1071,7 @@ export const sceneLogic = kea<sceneLogicType>([
actions.setScene(Scene.ErrorNetwork, undefined, emptySceneParams, clickedLink)
} else {
console.error('App assets regenerated. Reloading this page.')
- actions.reloadBrowserDueToImportError()
+ actions.reloadBrowserDueToImportError(error)
}
return
}
@@ -1119,8 +1119,8 @@ export const sceneLogic = kea<sceneLogicType>([
}
actions.setScene(sceneId, sceneKey, params, clickedLink || wasNotLoaded, exportedScene)
},
- reloadBrowserDueToImportError: () => {
- reloadAfterChunkLoadError()
+ reloadBrowserDueToImportError: ({ error }) => {
+ reloadAfterChunkLoadError(error)
},
})),
diff --git a/posthog/stable_chunks.py b/posthog/stable_chunks.py
index cecea7dd5f38..1daa28864e59 100644
--- a/posthog/stable_chunks.py
+++ b/posthog/stable_chunks.py
@@ -11,6 +11,7 @@ pages render exactly as before.
"""
import os
+import re
import json
from collections.abc import Mapping
from functools import lru_cache
@@ -29,6 +30,7 @@ from posthog.exceptions_capture import capture_exception
logger = structlog.get_logger(__name__)
STABLE_CHUNKS_PARAM = "stable_chunks"
+STABLE_CHUNKS_UNMAPPED_PARAM = "stable_chunks_unmapped"
STABLE_CHUNKS_COOKIE = "ph_stable_chunks"
STABLE_CHUNKS_FLAG = "stable-chunk-names"
_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30
@@ -39,8 +41,9 @@ 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"],
+ labelnames=["authenticated", "reason"],
)
+_STABLE_CHUNK_SPECIFIER = re.compile(r"@c/[A-Za-z0-9]+")
@frozen
@@ -51,11 +54,16 @@ class StableChunks:
authenticated_preload_js_urls: tuple[str, ...]
# The split eager stylesheets, in link order. Empty for a build that does not split its CSS.
eager_css_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 specifiers a logged-out page can reach. None for a build that does not scope its import map.
+ logged_out_specifiers: Optional[frozenset[str]] = None
+
+ def import_map_json(self, js_url: str, logged_out: bool = False) -> str:
+ imports = self.imports
+ if logged_out and self.logged_out_specifiers is not None:
+ imports = {
+ specifier: path for specifier, path in imports.items() if specifier in self.logged_out_specifiers
+ }
+ import_map = json.dumps({"imports": {specifier: f"{js_url}/{path}" for specifier, path in 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")
@@ -80,6 +88,7 @@ def read_stable_chunks_manifest(manifest_path: str) -> Optional[StableChunks]:
js = preload.get("js", [])
authenticated_js = preload.get("authenticatedJs", [])
eager_css = manifest.get("eagerCss", [])
+ logged_out_imports = manifest.get("loggedOutImports")
if not (
isinstance(imports, dict)
and imports
@@ -88,6 +97,13 @@ def read_stable_chunks_manifest(manifest_path: str) -> Optional[StableChunks]:
and isinstance(authenticated_js, list)
and isinstance(eager_css, list)
and all(isinstance(url, str) for url in [*js, *authenticated_js, *eager_css])
+ and (
+ logged_out_imports is None
+ or (
+ isinstance(logged_out_imports, list)
+ and all(isinstance(specifier, str) for specifier in logged_out_imports)
+ )
+ )
):
raise ValueError("stable chunks manifest fields have unexpected types")
return StableChunks(
@@ -95,6 +111,7 @@ def read_stable_chunks_manifest(manifest_path: str) -> Optional[StableChunks]:
preload_js_urls=tuple(js),
authenticated_preload_js_urls=tuple(authenticated_js),
eager_css_urls=tuple(eager_css),
+ logged_out_specifiers=frozenset(logged_out_imports) if logged_out_imports is not None else None,
)
except Exception as e:
logger.warning("stable_chunks_manifest_unreadable", manifest_path=manifest_path, error=str(e))
@@ -111,6 +128,18 @@ def _resolve_stable_chunks() -> Optional[StableChunks]:
)
+def _count_fallback(request: HttpRequest) -> None:
+ unmapped = request.GET.get(STABLE_CHUNKS_UNMAPPED_PARAM, "")
+ is_unmapped = _STABLE_CHUNK_SPECIFIER.fullmatch(unmapped) is not None
+ if is_unmapped:
+ # Never log the path: reset and invite links carry their credential in it.
+ logger.warning("stable_chunks_unmapped_specifier", specifier=unmapped)
+ STABLE_CHUNKS_FALLBACK_COUNTER.labels(
+ authenticated=str(request.user.is_authenticated).lower(),
+ reason="unmapped_specifier" if is_unmapped else "load_failed",
+ ).inc()
+
+
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
@@ -120,7 +149,7 @@ def stable_chunks_choice(request: HttpRequest, feature_flags: Optional[Mapping[s
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()
+ _count_fallback(request)
return param == "1"
cookie = request.COOKIES.get(STABLE_CHUNKS_COOKIE)
diff --git a/posthog/test/test_stable_chunks.py b/posthog/test/test_stable_chunks.py
index b0174d2e3e04..a52875e82cc4 100644
--- a/posthog/test/test_stable_chunks.py
+++ b/posthog/test/test_stable_chunks.py
@@ -12,6 +12,7 @@ from django.test import RequestFactory, SimpleTestCase, override_settings
from parameterized import parameterized
from prometheus_client import REGISTRY
+from structlog.testing import capture_logs
from posthog.models import User
from posthog.stable_chunks import (
@@ -41,6 +42,7 @@ class TestStableChunks(SimpleTestCase):
("empty imports", {**VALID_MANIFEST, "imports": {}}, False),
("preload url is not a string", {**VALID_MANIFEST, "preload": {"js": [1], "authenticatedJs": []}}, False),
("eager css url is not a string", {**VALID_MANIFEST, "eagerCss": [1]}, False),
+ ("logged-out import is not a string", {**VALID_MANIFEST, "loggedOutImports": [1]}, False),
]
)
def test_manifest_problems_fall_back_to_the_default_build(self, _name, manifest, expect_stable):
@@ -102,7 +104,7 @@ class TestStableChunks(SimpleTestCase):
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()}
+ fallback_labels = {"authenticated": str(authenticated).lower(), "reason": "load_failed"}
fallbacks_before = REGISTRY.get_sample_value("posthog_stable_chunks_fallback_total", fallback_labels) or 0
with patch(
@@ -117,6 +119,41 @@ class TestStableChunks(SimpleTestCase):
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)
+ @parameterized.expand(
+ [
+ ("a chunk that failed to load", "?stable_chunks=fallback", "load_failed"),
+ (
+ "a chunk missing from the import map",
+ "?stable_chunks=fallback&stable_chunks_unmapped=@c/Abc123",
+ "unmapped_specifier",
+ ),
+ ("a value that is not a specifier", "?stable_chunks=fallback&stable_chunks_unmapped=<b>", "load_failed"),
+ ]
+ )
+ def test_a_fallback_counts_why_it_reloaded(self, _name: str, query: str, reason: str) -> None:
+ request = RequestFactory().get(f"/{query}")
+ request.user = AnonymousUser()
+ labels = {"authenticated": "false", "reason": reason}
+ before = REGISTRY.get_sample_value("posthog_stable_chunks_fallback_total", labels) or 0
+
+ assert stable_chunks_choice(request, None) is False
+
+ assert REGISTRY.get_sample_value("posthog_stable_chunks_fallback_total", labels) == before + 1
+
+ def test_an_unmapped_specifier_is_logged_without_the_page_path(self) -> None:
+ request = RequestFactory().get(
+ "/reset/0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b/fake-reset-token"
+ "?stable_chunks=fallback&stable_chunks_unmapped=@c/Abc123"
+ )
+ request.user = AnonymousUser()
+
+ with capture_logs() as logs:
+ stable_chunks_choice(request, None)
+
+ assert [log for log in logs if log["event"] == "stable_chunks_unmapped_specifier"] == [
+ {"event": "stable_chunks_unmapped_specifier", "specifier": "@c/Abc123", "log_level": "warning"}
+ ]
+
def test_a_failing_logged_out_flag_check_serves_the_hashed_build(self) -> None:
request = RequestFactory().get("/")
request.user = AnonymousUser()
@@ -170,6 +207,24 @@ class TestStableChunks(SimpleTestCase):
assert context["preload_css_url"] == ""
assert context["stable_preload_css_urls"] == stable.eager_css_urls
+ @parameterized.expand(
+ [
+ ("only its part of the map", frozenset({"@c/eAAAA"}), {"@c/eAAAA"}),
+ ("the whole map from a build with no logged-out part", None, {"@c/eAAAA", "@c/eBBBB"}),
+ ]
+ )
+ def test_a_logged_out_page_renders(self, _name, logged_out_specifiers, expected_specifiers):
+ stable = StableChunks(
+ imports={"@c/eAAAA": "static/index-S0000000000.js", "@c/eBBBB": "static/Insight-S1111111111.js"},
+ preload_js_urls=(),
+ authenticated_preload_js_urls=(),
+ logged_out_specifiers=logged_out_specifiers,
+ )
+
+ context = self._context_with_stable_chunks(stable)
+
+ assert set(json.loads(context["stable_chunks_importmap"])["imports"]) == expected_specifiers
+
def test_no_eager_css_urls_keeps_the_single_preload_link(self):
stable = StableChunks(
imports={"@c/eAAAA": "static/index-S0000000000.js"}, preload_js_urls=(), authenticated_preload_js_urls=()
@@ -208,8 +263,12 @@ class TestStableChunksChoiceSurvivesTheRequest(APIBaseTest):
)
def test_the_flag_picks_the_build_it_bootstraps(self, _name, query, flags, expect_stable):
request = self._user_request(query)
+ # The logged-out part of the map leaves the entry out, so only the whole map holds it.
stable = StableChunks(
- imports={"@c/eAAAA": "static/index-S0000000000.js"}, preload_js_urls=(), authenticated_preload_js_urls=()
+ imports={"@c/eAAAA": "static/index-S0000000000.js"},
+ preload_js_urls=(),
+ authenticated_preload_js_urls=(),
+ logged_out_specifiers=frozenset(),
)
with (
@@ -219,6 +278,10 @@ class TestStableChunksChoiceSurvivesTheRequest(APIBaseTest):
context = get_context_for_template("index.html", request)
assert context.get("stable_chunks", False) == expect_stable
+ if expect_stable:
+ assert json.loads(context["stable_chunks_importmap"])["imports"] == {
+ "@c/eAAAA": f"{context['js_url']}/static/index-S0000000000.js"
+ }
assert context["posthog_bootstrap"].get("featureFlags") == flags
get_all_flags.assert_called_once()
assert get_all_flags.call_args.kwargs["only_evaluate_locally"] is True
diff --git a/posthog/utils.py b/posthog/utils.py
index affdd602c62e..46a57eb1e595 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -762,7 +762,9 @@ def _build_template_context(
stable_chunks = stable_chunks_for_request(request, posthog_bootstrap.get("featureFlags"))
if stable_chunks:
context["stable_chunks"] = True
- context["stable_chunks_importmap"] = stable_chunks.import_map_json(context["js_url"])
+ context["stable_chunks_importmap"] = stable_chunks.import_map_json(
+ context["js_url"], logged_out=not is_authenticated
+ )
context["preload_js_urls"] = stable_chunks.preload_urls(is_authenticated)
if stable_chunks.eager_css_urls:
# The stable page links its split stylesheets and loads the full one only as a fallback.