: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
perf(frontend): render the app as an update behind a flag (#119225)
Paul D'Ambra40f523a8f6f1
diff --git a/frontend/src/index.test.tsx b/frontend/src/index.test.tsxindex 29dfe8d1141e..0729b0f27669 100644--- a/frontend/src/index.test.tsx+++ b/frontend/src/index.test.tsx@@ -59,6 +59,8 @@ describe('app entry boot', () => {await act(async () => window.__posthogAppRoot?.unmount())delete window.__posthogAppRootdelete window.ESBUILD_CSS_READY+ delete window.POSTHOG_USER_IDENTITY_WITH_FLAGS+ delete window.POSTHOG_APP_CONTEXTdocument.body.innerHTML = ''jest.clearAllTimers()jest.useRealTimers()@@ -73,97 +75,164 @@ describe('app entry boot', () => {})}- it.each(['complete', 'loading'] as const)(- 'loads modules while CSS is pending after the document is %s',- async (readyState) => {- const documentState = jest.spyOn(document, 'readyState', 'get').mockReturnValue(readyState)- await loadEntry()-- expect(modulesLoaded).toEqual(readyState === 'complete' ? ['App', 'bootApp'] : [])- if (readyState === 'loading') {- documentState.mockReturnValue('complete')- await act(async () => {- document.dispatchEvent(new Event('DOMContentLoaded'))- })+ describe.each([+ ['the lazy app path', false],+ ['the render as update path', true],+ ])('on %s', (_path, renderAppAsUpdate) => {+ beforeEach(() => {+ window.POSTHOG_USER_IDENTITY_WITH_FLAGS = {+ featureFlags: { 'boot-render-app-as-update': renderAppAsUpdate },}+ })- expect(modulesLoaded).toEqual(['App', 'bootApp'])- expect(bootApp).not.toHaveBeenCalled()- expect(document.getElementById('root')).toBeEmptyDOMElement()+ it.each(['complete', 'loading'] as const)(+ 'loads modules while CSS is pending after the document is %s',+ async (readyState) => {+ const documentState = jest.spyOn(document, 'readyState', 'get').mockReturnValue(readyState)+ await loadEntry()- await act(async () => stylesheet.resolve(true))+ expect(modulesLoaded).toEqual(readyState === 'complete' ? ['App', 'bootApp'] : [])+ if (readyState === 'loading') {+ documentState.mockReturnValue('complete')+ await act(async () => {+ document.dispatchEvent(new Event('DOMContentLoaded'))+ })+ }- expect(document.querySelector('[data-attr="boot-test-app"]')).toBeInTheDocument()- expect(bootApp).toHaveBeenCalledTimes(1)- }- )+ expect(modulesLoaded).toEqual(['App', 'bootApp'])+ expect(bootApp).not.toHaveBeenCalled()+ expect(document.getElementById('root')).toBeEmptyDOMElement()- it.each(['loaded', 'absent'] as const)('boots when the stylesheet is %s', async (stylesheetState) => {- if (stylesheetState === 'absent') {- delete window.ESBUILD_CSS_READY- }- await loadEntry()+ await act(async () => stylesheet.resolve(true))- await act(async () => {- if (stylesheetState === 'loaded') {- stylesheet.resolve(true)+ expect(document.querySelector('[data-attr="boot-test-app"]')).toBeInTheDocument()+ expect(bootApp).toHaveBeenCalledTimes(1)}- })+ )- expect(document.querySelector('[data-attr="boot-test-app"]')).toBeInTheDocument()- expect(bootApp).toHaveBeenCalledTimes(1)- })+ it.each(['loaded', 'absent'] as const)('boots when the stylesheet is %s', async (stylesheetState) => {+ if (stylesheetState === 'absent') {+ delete window.ESBUILD_CSS_READY+ }+ await loadEntry()- it.each([- ['within the render gate', 0],- ['after a stall let the app render', 6000],- ])('offers a reload instead of an unstyled app when every stylesheet URL fails %s', async (_case, stallMs) => {- await loadEntry()- await act(async () => {- await jest.advanceTimersByTimeAsync(stallMs)- })+ await act(async () => {+ if (stylesheetState === 'loaded') {+ stylesheet.resolve(true)+ }+ })- await act(async () => stylesheet.resolve(false))+ expect(document.querySelector('[data-attr="boot-test-app"]')).toBeInTheDocument()+ expect(bootApp).toHaveBeenCalledTimes(1)+ })- expect(document.querySelector('[role="alert"]')).toHaveTextContent('PostHog failed to load its styles.')- expect(document.querySelector('[data-attr="boot-test-app"]')).not.toBeInTheDocument()- })+ it.each([+ ['within the render gate', 0],+ ['after a stall let the app render', 6000],+ ])('offers a reload instead of an unstyled app when every stylesheet URL fails %s', async (_case, stallMs) => {+ await loadEntry()+ await act(async () => {+ await jest.advanceTimersByTimeAsync(stallMs)+ })- it('boots after five seconds if the stylesheet stays pending', async () => {- await loadEntry()- await act(async () => {- await jest.advanceTimersByTimeAsync(4999)- })- expect(bootApp).not.toHaveBeenCalled()- expect(document.getElementById('root')).toBeEmptyDOMElement()+ await act(async () => stylesheet.resolve(false))- await act(async () => {- await jest.advanceTimersByTimeAsync(1)+ expect(document.querySelector('[role="alert"]')).toHaveTextContent('PostHog failed to load its styles.')+ expect(document.querySelector('[data-attr="boot-test-app"]')).not.toBeInTheDocument()})- expect(document.querySelector('[data-attr="boot-test-app"]')).toBeInTheDocument()- expect(bootApp).toHaveBeenCalledTimes(1)- })-- it.each(['scenes/App', 'scenes/bootApp'])(- 'shows an early %s failure through the boot error boundary after CSS is ready',- async (failingModule) => {- jest.spyOn(console, 'error').mockImplementation(() => {})- const error = new Error('Boot dependency failed')- jest.doMock(failingModule, () => {- throw error- })+ it('boots after five seconds if the stylesheet stays pending', async () => {await loadEntry()await act(async () => {- await jest.advanceTimersByTimeAsync(0)+ await jest.advanceTimersByTimeAsync(4999)})- expect(document.getElementById('root')).toBeEmptyDOMElement()expect(bootApp).not.toHaveBeenCalled()+ expect(document.getElementById('root')).toBeEmptyDOMElement()- await act(async () => stylesheet.resolve(true))+ await act(async () => {+ await jest.advanceTimersByTimeAsync(1)+ })+ expect(document.querySelector('[data-attr="boot-test-app"]')).toBeInTheDocument()+ expect(bootApp).toHaveBeenCalledTimes(1)+ })- expect(document.querySelector('[role="alert"]')).toHaveTextContent('PostHog crashed while starting.')- expect(bootApp).not.toHaveBeenCalled()+ if (renderAppAsUpdate) {+ it('preloads the authenticated shell for a logged-in user before App renders', async () => {+ window.POSTHOG_APP_CONTEXT = { current_user: { id: 1 } } as any+ const loadOrder: string[] = []+ const loadAuthenticatedShell = jest.fn(async () => {+ loadOrder.push('shell')+ })+ jest.doMock('scenes/authenticatedShellLoader', () => ({ loadAuthenticatedShell }))+ jest.doMock('scenes/App', () => ({+ App: (): JSX.Element => {+ loadOrder.push('app-rendered')+ return <div data-attr="boot-test-app" />+ },+ }))++ await loadEntry()+ await act(async () => stylesheet.resolve(true))++ expect(loadAuthenticatedShell).toHaveBeenCalledTimes(1)+ expect(loadOrder).toEqual(['shell', 'app-rendered'])+ expect(document.querySelector('[data-attr="boot-test-app"]')).toBeInTheDocument()+ })+ }++ it.each(['scenes/App', 'scenes/bootApp'])(+ 'shows an early %s failure through the boot error boundary after CSS is ready',+ async (failingModule) => {+ jest.spyOn(console, 'error').mockImplementation(() => {})+ const error = new Error('Boot dependency failed')+ jest.doMock(failingModule, () => {+ throw error+ })++ await loadEntry()+ await act(async () => {+ await jest.advanceTimersByTimeAsync(0)+ })+ expect(document.getElementById('root')).toBeEmptyDOMElement()+ expect(bootApp).not.toHaveBeenCalled()++ await act(async () => stylesheet.resolve(true))++ expect(document.querySelector('[role="alert"]')).toHaveTextContent('PostHog crashed while starting.')+ expect(bootApp).not.toHaveBeenCalled()+ }+ )+ })++ it('commits the app without waiting for the suspense fallback throttle when a child suspends', async () => {+ // React skips the throttle inside act(), so this case renders without it.+ // React captures setTimeout when it loads, so load it again under the fake timers for the throttle to use them.+ await act(async () => window.__posthogAppRoot?.unmount())+ const fakeTimerReactDom = jest.requireActual<typeof import('react-dom/client')>('react-dom/client')+ jest.doMock('react-dom/client', () => fakeTimerReactDom)+ window.__posthogAppRoot = fakeTimerReactDom.createRoot(document.getElementById('root')!)+ const reactActEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+ const previousActEnvironment = reactActEnvironment.IS_REACT_ACT_ENVIRONMENT+ reactActEnvironment.IS_REACT_ACT_ENVIRONMENT = false+ const NeverLoads = React.lazy(() => new Promise<{ default: React.ComponentType }>(() => {}))+ jest.doMock('scenes/App', () => ({+ App: (): JSX.Element => (+ <React.Suspense fallback={<div data-attr="boot-test-shell-fallback" />}>+ <NeverLoads />+ </React.Suspense>+ ),+ }))+ window.POSTHOG_USER_IDENTITY_WITH_FLAGS = { featureFlags: { 'boot-render-app-as-update': true } }+ try {+ await jest.isolateModulesAsync(async () => {+ await import('./index')+ })+ stylesheet.resolve(true)+ await jest.advanceTimersByTimeAsync(100)++ expect(document.querySelector('[data-attr="boot-test-shell-fallback"]')).toBeInTheDocument()+ } finally {+ reactActEnvironment.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment}- )+ })})diff --git a/frontend/src/index.tsx b/frontend/src/index.tsxindex fe053105b8f8..d6a58d2c0052 100644--- a/frontend/src/index.tsx+++ b/frontend/src/index.tsx@@ -11,20 +11,37 @@ import { retryBootImport } from 'lib/utils/retryImport'import { RootErrorBoundary } from './RootErrorBoundary'import { ChunkLoadErrorBoundary } from './scenes/ChunkLoadErrorBoundary'-markBootPhase('entry')+// pinned: feature flag key, also listed in FEATURE_FLAGS. The entry reads the server-evaluated bootstrap flags directly,+// because posthog-js has not started yet and lib/constants would make the entry chunk much larger.+const RENDER_APP_AS_UPDATE_FLAG = 'boot-render-app-as-update'+const renderAppAsUpdate = !!window.POSTHOG_USER_IDENTITY_WITH_FLAGS?.featureFlags?.[RENDER_APP_AS_UPDATE_FLAG]++markBootPhase('entry', { render_app_as_update: renderAppAsUpdate })type AppModules = [typeof import('scenes/App'), typeof import('scenes/bootApp')]let appModulesPromise: Promise<AppModules> | undefined+// A logged-in first render shows the authenticated shell. Loading the shell with the app modules lets that render+// show it without suspending. If this load fails, the shell loads lazily instead and reports its own error.+function preloadAuthenticatedShell(): Promise<unknown> {+ if (!renderAppAsUpdate || !window.POSTHOG_APP_CONTEXT?.current_user) {+ return Promise.resolve()+ }+ return import('scenes/authenticatedShellLoader')+ .then(({ loadAuthenticatedShell }) => loadAuthenticatedShell())+ .catch(() => {})+}+function loadAppModules(): Promise<AppModules> {return (appModulesPromise ??= Promise.all([retryBootImport(() => import('scenes/App')),retryBootImport(() => import('scenes/bootApp')),- ]).then((modules) => {+ preloadAuthenticatedShell(),+ ]).then(([appModule, bootModule]) => {// Marked here, not in the lazy() factory: React calls the factory only after the CSS gate in boot().markBootPhase('app_modules_loaded')- return modules+ return [appModule, bootModule]}))}@@ -61,27 +78,66 @@ function getAppRoot(): Root | null {return (window.__posthogAppRoot ??= createRoot(rootElement))}-function renderApp(): void {+function renderInBootBoundaries(content: JSX.Element): void {getAppRoot()?.render(<RootErrorBoundary>{/* Auto-reloads once on a chunk-load failure (stale deploy). Repeated or non-chunkerrors bubble to RootErrorBoundary, which reports them and shows the failure UI. */}- <ChunkLoadErrorBoundary>- <Suspense- fallback={- <div className="Preloader" role="status" aria-label="Loading PostHog">- <div className="Preloader__inner" />- </div>- }- >- <App />- </Suspense>- </ChunkLoadErrorBoundary>+ <ChunkLoadErrorBoundary>{content}</ChunkLoadErrorBoundary></RootErrorBoundary>)}+function ThrowBootError({ error }: { error: unknown }): never {+ throw error+}++let showingStylesheetFailure = false++const preloader = (+ <div className="Preloader" role="status" aria-label="Loading PostHog">+ <div className="Preloader__inner" />+ </div>+)++function renderApp(): void {+ if (!renderAppAsUpdate) {+ renderInBootBoundaries(+ <Suspense fallback={preloader}>+ <App />+ </Suspense>+ )+ return+ }+ renderInBootBoundaries(preloader)+ // App renders as a plain update, not as a lazy component that resolves a Suspense fallback. A render that+ // resolves a fallback is a retry, and when such a render shows a new fallback (the authenticated shell's lazy+ // children do), React holds its commit until 500ms after the previous fallback appeared.+ loadAppModules()+ .then(([appModule, bootModule]) => {+ if (showingStylesheetFailure) {+ return null+ }+ bootModule.bootApp()+ markBootPhase('app_booted')+ return appModule.App+ })+ .then(+ (LoadedApp) => {+ if (LoadedApp && !showingStylesheetFailure) {+ renderInBootBoundaries(<LoadedApp />)+ }+ },+ (error) => {+ if (!showingStylesheetFailure) {+ renderInBootBoundaries(<ThrowBootError error={error} />)+ }+ }+ )+}+function renderStylesheetFailure(): void {+ showingStylesheetFailure = truegetAppRoot()?.render(<div className="Preloader" role="alert"><div>diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 32ec6e0b9ccb..fd8489fd0f1e 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -291,6 +291,7 @@ export const FEATURE_FLAGS = {BACKFILL_WORKFLOWS_DESTINATION: 'backfill-workflows-destination', // owner: #team-batch-exportsBILLING_ALERTS: 'billing-alerts', // owner: #team-billing, gates the Billing > Alerts tabBILLING_REAL_TIME_USAGE: 'billing-real-time-usage', // owner: #team-billing, gates the Real-time usage scene+ BOOT_RENDER_APP_AS_UPDATE: 'boot-render-app-as-update', // owner: @pauldambra, see `src/index.tsx`, renders App as a plain update so React does not throttle the first logged-in commitBROADCASTS_AI_FIRST_NEW: 'broadcasts-ai-first-new', // owner: @dmarchuk #team-workflowsBUSINESS_KNOWLEDGE_GITHUB_REPOS: 'business-knowledge-github-repos', // owner: @veryayskiy #team-conversationsCANVAS_COMMENTS: 'posthog-desktop-canvas-comments', // owner: @k11kirky, shows canvas comments and selection comments on web canvases, shared with PostHog Desktop@@ -571,8 +572,8 @@ export const FEATURE_FLAGS = {TAXONOMIC_FILTER_SEARCH_INTENT: 'taxonomic-filter-search-intent', // owner: @pauldambra multivariate=control,banner,promote, classifies a picker search with the decision model. control changes nothing, banner suggests the right tab, promote moves the predicted group to the top of the All tabTAXONOMIC_FILTER_VALUE_SEARCH_GATING: 'taxonomic-filter-value-search-gating', // owner: @pauldambraTEXT_CARD_WORD_ART: 'text-card-word-art', // owner: @jonmcwest, gates the word art insert button in dashboard text cards- TODAY_RAIL_NAV: 'today-rail-nav', // owner: @k11kirky, replaces the left navigation with a rail (Home, Spaces, Library, Tools) and makes the Today page the homepageTODAY_PULSE_RANKING: 'today-pulse-ranking',+ TODAY_RAIL_NAV: 'today-rail-nav', // owner: @k11kirky, replaces the left navigation with a rail (Home, Spaces, Library, Tools) and makes the Today page the homepageTODAY_REPORT_JEV: 'today-report-jev', // owner: @puemos, asks the decision model to label the problem, cause and fix in a Today report, to mark the numbers a source states, and to pick the code excerpt a finding describesTOOLBAR_PAID_HEATMAPS: 'toolbar-paid-heatmaps', // owner: #team-web-analyticsTRACING: 'tracing', // owner: #team-apm (@jonmcwest, @frankh)diff --git a/frontend/src/lib/utils/bootTiming.ts b/frontend/src/lib/utils/bootTiming.tsindex 79870900e1ce..b249f4672875 100644--- a/frontend/src/lib/utils/bootTiming.ts+++ b/frontend/src/lib/utils/bootTiming.ts@@ -15,6 +15,7 @@ export type BootPhase =export interface BootContext {scene?: stringlogged_in?: boolean+ render_app_as_update?: boolean}const phaseTimes: Partial<Record<BootPhase, number>> = {}diff --git a/frontend/src/scenes/App.tsx b/frontend/src/scenes/App.tsxindex ba62fce32cdf..1abd5e4537b0 100644--- a/frontend/src/scenes/App.tsx+++ b/frontend/src/scenes/App.tsx@@ -1,7 +1,7 @@import { Tooltip as BaseTooltip } from '@base-ui/react/tooltip'import { BindLogic, useMountedLogic, useValues } from 'kea'import posthog from 'posthog-js'-import React, { Suspense, useEffect, useLayoutEffect } from 'react'+import React, { Suspense, useEffect, useLayoutEffect, useState } from 'react'import { Slide, ToastContainer } from 'react-toastify'import { PostHogProvider } from '@posthog/react'@@ -15,7 +15,7 @@ import { autofillReleaseLogic } from 'lib/memory/autofillReleaseLogic'import { OAuthCallback } from 'lib/oauth/OAuthCallback'import { oauthLogic } from 'lib/oauth/oauthLogic'import { markBootPhase } from 'lib/utils/bootTiming'-import { lazyWithRetry, retryImport } from 'lib/utils/retryImport'+import { lazyWithRetry } from 'lib/utils/retryImport'import { appLogic } from 'scenes/appLogic'import { appScenes } from 'scenes/appScenes'import { sceneLogic } from 'scenes/sceneLogic'@@ -26,10 +26,11 @@ import { ErrorBoundary } from '~/layout/ErrorBoundary'import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { AuthenticatedShellFallback } from './AuthenticatedShellFallback'+import { getLoadedAuthenticatedShell, loadAuthenticatedShell } from './authenticatedShellLoader'import { ChunkLoadErrorBoundary } from './ChunkLoadErrorBoundary'import { mountSupportRouter } from './mountSupportRouter'-const AuthenticatedShell = React.lazy(() => retryImport(() => import('./AuthenticatedShell')))+const LazyAuthenticatedShell = React.lazy(() => loadAuthenticatedShell().then((shell) => ({ default: shell })))// Lazy for the same reason as AuthenticatedShell: the gate renders SceneTitleSection, whose static// graph is most of the authenticated navigation. Importing it here put ~3.7 MiB of logged-in UI on@@ -136,6 +137,10 @@ function AppScene(): JSX.Element | null {useValues(sceneLogic)const { showingDelayedSpinner } = useValues(appLogic)const { isDarkModeOn } = useValues(themeLogic)+ // A shell that suspends on the first logged-in render makes React hold that commit for its fallback throttle.+ // The entry loads the shell first for a logged-in page, so render it directly. The choice is fixed for the+ // lifetime of this component, because a change of component type would remount the whole shell.+ const [AuthenticatedShell] = useState(() => getLoadedAuthenticatedShell() ?? LazyAuthenticatedShell)// App mounts this component on the first commit where appLogic's `showApp` is true.useLayoutEffect(() => markBootPhase('app_ready', { logged_in: !!user }), [user])@@ -153,7 +158,7 @@ function AppScene(): JSX.Element | null {: (cb: () => void) => setTimeout(cb, 200)idle(() => {void Promise.all([- import('./AuthenticatedShell'),+ loadAuthenticatedShell(),import('lib/components/ProductEmptyState/ProductEmptyStateGate'),]).catch(() => {/* prefetch is best-effort; the real Suspense load will surface failures */diff --git a/frontend/src/scenes/authenticatedShellLoader.ts b/frontend/src/scenes/authenticatedShellLoader.tsnew file mode 100644index 000000000000..8e26bdffdd4b--- /dev/null+++ b/frontend/src/scenes/authenticatedShellLoader.ts@@ -0,0 +1,18 @@+import { retryImport } from 'lib/utils/retryImport'++import type AuthenticatedShell from './AuthenticatedShell'++type AuthenticatedShellComponent = typeof AuthenticatedShell++let loadedAuthenticatedShell: AuthenticatedShellComponent | null = null++export function loadAuthenticatedShell(): Promise<AuthenticatedShellComponent> {+ return retryImport(() => import('./AuthenticatedShell')).then(({ default: shell }) => {+ loadedAuthenticatedShell = shell+ return shell+ })+}++export function getLoadedAuthenticatedShell(): AuthenticatedShellComponent | null {+ return loadedAuthenticatedShell+}