: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
revert(frontend): remove the render app as update boot path (#119292)
Paul D'Ambraee6e49273186
diff --git a/frontend/src/index.test.tsx b/frontend/src/index.test.tsxindex 0729b0f27669..29dfe8d1141e 100644--- a/frontend/src/index.test.tsx+++ b/frontend/src/index.test.tsx@@ -59,8 +59,6 @@ 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()@@ -75,164 +73,97 @@ describe('app entry boot', () => {})}- 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 },- }- })-- 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'))- })- }-- expect(modulesLoaded).toEqual(['App', 'bootApp'])- expect(bootApp).not.toHaveBeenCalled()- expect(document.getElementById('root')).toBeEmptyDOMElement()-- await act(async () => stylesheet.resolve(true))+ 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(document.querySelector('[data-attr="boot-test-app"]')).toBeInTheDocument()- expect(bootApp).toHaveBeenCalledTimes(1)+ expect(modulesLoaded).toEqual(readyState === 'complete' ? ['App', 'bootApp'] : [])+ if (readyState === 'loading') {+ documentState.mockReturnValue('complete')+ await act(async () => {+ document.dispatchEvent(new Event('DOMContentLoaded'))+ })}- )- it.each(['loaded', 'absent'] as const)('boots when the stylesheet is %s', async (stylesheetState) => {- if (stylesheetState === 'absent') {- delete window.ESBUILD_CSS_READY- }- await loadEntry()+ expect(modulesLoaded).toEqual(['App', 'bootApp'])+ expect(bootApp).not.toHaveBeenCalled()+ expect(document.getElementById('root')).toBeEmptyDOMElement()- await act(async () => {- if (stylesheetState === 'loaded') {- stylesheet.resolve(true)- }- })+ await act(async () => stylesheet.resolve(true))expect(document.querySelector('[data-attr="boot-test-app"]')).toBeInTheDocument()expect(bootApp).toHaveBeenCalledTimes(1)- })-- 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 () => stylesheet.resolve(false))+ it.each(['loaded', 'absent'] as const)('boots when the stylesheet is %s', async (stylesheetState) => {+ if (stylesheetState === 'absent') {+ delete window.ESBUILD_CSS_READY+ }+ await loadEntry()- expect(document.querySelector('[role="alert"]')).toHaveTextContent('PostHog failed to load its styles.')- expect(document.querySelector('[data-attr="boot-test-app"]')).not.toBeInTheDocument()+ await act(async () => {+ if (stylesheetState === 'loaded') {+ stylesheet.resolve(true)+ }})- 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()+ expect(document.querySelector('[data-attr="boot-test-app"]')).toBeInTheDocument()+ expect(bootApp).toHaveBeenCalledTimes(1)+ })- await act(async () => {- await jest.advanceTimersByTimeAsync(1)- })- expect(document.querySelector('[data-attr="boot-test-app"]')).toBeInTheDocument()- expect(bootApp).toHaveBeenCalledTimes(1)+ 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)})- 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()- })- }+ await act(async () => stylesheet.resolve(false))- 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()+ expect(document.querySelector('[role="alert"]')).toHaveTextContent('PostHog failed to load its styles.')+ expect(document.querySelector('[data-attr="boot-test-app"]')).not.toBeInTheDocument()+ })- await act(async () => stylesheet.resolve(true))+ 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()- expect(document.querySelector('[role="alert"]')).toHaveTextContent('PostHog crashed while starting.')- expect(bootApp).not.toHaveBeenCalled()- }- )+ await act(async () => {+ await jest.advanceTimersByTimeAsync(1)+ })+ expect(document.querySelector('[data-attr="boot-test-app"]')).toBeInTheDocument()+ expect(bootApp).toHaveBeenCalledTimes(1)})- 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')+ 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})- stylesheet.resolve(true)- await jest.advanceTimersByTimeAsync(100)- expect(document.querySelector('[data-attr="boot-test-shell-fallback"]')).toBeInTheDocument()- } finally {- reactActEnvironment.IS_REACT_ACT_ENVIRONMENT = previousActEnvironment+ 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()}- })+ )})diff --git a/frontend/src/index.tsx b/frontend/src/index.tsxindex d6a58d2c0052..fe053105b8f8 100644--- a/frontend/src/index.tsx+++ b/frontend/src/index.tsx@@ -11,37 +11,20 @@ import { retryBootImport } from 'lib/utils/retryImport'import { RootErrorBoundary } from './RootErrorBoundary'import { ChunkLoadErrorBoundary } from './scenes/ChunkLoadErrorBoundary'-// 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 })+markBootPhase('entry')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')),- preloadAuthenticatedShell(),- ]).then(([appModule, bootModule]) => {+ ]).then((modules) => {// Marked here, not in the lazy() factory: React calls the factory only after the CSS gate in boot().markBootPhase('app_modules_loaded')- return [appModule, bootModule]+ return modules}))}@@ -78,66 +61,27 @@ function getAppRoot(): Root | null {return (window.__posthogAppRoot ??= createRoot(rootElement))}-function renderInBootBoundaries(content: JSX.Element): void {+function renderApp(): 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>{content}</ChunkLoadErrorBoundary>+ <ChunkLoadErrorBoundary>+ <Suspense+ fallback={+ <div className="Preloader" role="status" aria-label="Loading PostHog">+ <div className="Preloader__inner" />+ </div>+ }+ >+ <App />+ </Suspense>+ </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 fd8489fd0f1e..df64c77257e4 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -291,7 +291,6 @@ 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 Desktopdiff --git a/frontend/src/lib/utils/bootTiming.ts b/frontend/src/lib/utils/bootTiming.tsindex b249f4672875..79870900e1ce 100644--- a/frontend/src/lib/utils/bootTiming.ts+++ b/frontend/src/lib/utils/bootTiming.ts@@ -15,7 +15,6 @@ 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 1abd5e4537b0..ba62fce32cdf 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, useState } from 'react'+import React, { Suspense, useEffect, useLayoutEffect } 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 } from 'lib/utils/retryImport'+import { lazyWithRetry, retryImport } from 'lib/utils/retryImport'import { appLogic } from 'scenes/appLogic'import { appScenes } from 'scenes/appScenes'import { sceneLogic } from 'scenes/sceneLogic'@@ -26,11 +26,10 @@ 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 LazyAuthenticatedShell = React.lazy(() => loadAuthenticatedShell().then((shell) => ({ default: shell })))+const AuthenticatedShell = React.lazy(() => retryImport(() => import('./AuthenticatedShell')))// 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@@ -137,10 +136,6 @@ 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])@@ -158,7 +153,7 @@ function AppScene(): JSX.Element | null {: (cb: () => void) => setTimeout(cb, 200)idle(() => {void Promise.all([- loadAuthenticatedShell(),+ import('./AuthenticatedShell'),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.tsdeleted file mode 100644index 8e26bdffdd4b..000000000000--- a/frontend/src/scenes/authenticatedShellLoader.ts+++ /dev/null@@ -1,18 +0,0 @@-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-}