: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): load query node renderers where they render (#127333)
Paul D'Ambracb0e778fd593
diff --git a/frontend/bin/check-eager-graph.mjs b/frontend/bin/check-eager-graph.mjsindex e0f46362bda1..d8bdf8bb93d3 100644--- a/frontend/bin/check-eager-graph.mjs+++ b/frontend/bin/check-eager-graph.mjs@@ -197,6 +197,9 @@ const ROOTS = [// A hit means a module imports re2js directly again.'node_modules/re2js/',KEA_TEST_UTILS,+ // Query loads each node renderer in its own chunk. The debug renderers draw only on the debug scene.+ 'src/scenes/debug/HogDebug.tsx',+ 'src/queries/QueryEditor/QueryEditor.tsx',],},{@@ -255,6 +258,12 @@ const ROOTS = [// A hit means a module imports re2js directly again.'node_modules/re2js/',KEA_TEST_UTILS,+ // The scene draws only a data table. Query loads every other node renderer in its own chunk.+ 'src/queries/nodes/InsightViz/InsightViz.tsx',+ 'src/queries/nodes/DataVisualization/DataVisualization.tsx',+ 'src/queries/nodes/WebOverview/WebOverview.tsx',+ 'src/scenes/debug/HogDebug.tsx',+ 'src/queries/QueryEditor/QueryEditor.tsx',],},{@@ -273,6 +282,9 @@ const ROOTS = [// A hit means a module imports re2js directly again.'node_modules/re2js/',KEA_TEST_UTILS,+ // Query loads each node renderer in its own chunk. The debug renderers draw only on the debug scene.+ 'src/scenes/debug/HogDebug.tsx',+ 'src/queries/QueryEditor/QueryEditor.tsx',],},{diff --git a/frontend/bin/layer-baseline.txt b/frontend/bin/layer-baseline.txtindex 31ca16f05d49..69fa281033bb 100644--- a/frontend/bin/layer-baseline.txt+++ b/frontend/bin/layer-baseline.txt@@ -339,9 +339,6 @@ frontend/src/products.tsx -> frontend/src/queries/examples.tsfrontend/src/products.tsx -> products/ai_observability/frontend/clusters/constants.tsfrontend/src/products.tsx -> products/ai_observability/frontend/scoreDefinitions/scoreDefinitionNavigation.tsfrontend/src/products.tsx -> products/error_tracking/frontend/settingsRedirects.ts-frontend/src/queries/Query/Query.tsx -> frontend/src/scenes/debug/HogDebug.tsx-frontend/src/queries/Query/Query.tsx -> products/endpoints/frontend/nodes/index.ts-frontend/src/queries/Query/Query.tsx -> products/metrics/frontend/nodes/index.tsfrontend/src/queries/nodes/DataNode/TestAccountFilters.tsx -> frontend/src/scenes/settings/environment/filterTestAccountDefaultsLogic.tsfrontend/src/queries/nodes/DataNode/dataNodeLogic.ts -> frontend/src/scenes/insights/insightLogic.tsxfrontend/src/queries/nodes/DataTable/BackToSource.tsx -> frontend/src/scenes/insights/summarizeInsight.tsdiff --git a/frontend/src/lib/components/Cards/InsightCard/QueryCard.tsx b/frontend/src/lib/components/Cards/InsightCard/QueryCard.tsxindex c53ffa264d0c..1d10a2a3ca04 100644--- a/frontend/src/lib/components/Cards/InsightCard/QueryCard.tsx+++ b/frontend/src/lib/components/Cards/InsightCard/QueryCard.tsx@@ -1,3 +1,5 @@+import './InsightCard.scss'+import clsx from 'clsx'import { BuiltLogic, LogicWrapper, useValues } from 'kea'import React, { useState } from 'react'diff --git a/frontend/src/lib/utils/retryImport.test.ts b/frontend/src/lib/utils/retryImport.test.tsindex 38c568984b41..ae59d8d7893f 100644--- a/frontend/src/lib/utils/retryImport.test.ts+++ b/frontend/src/lib/utils/retryImport.test.ts@@ -1,5 +1,22 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import { Component as ReactComponent, ReactNode, Suspense, createElement } from 'react'+import { isChunkLoadError } from './isChunkLoadError'-import { retryBootImport, retryImport } from './retryImport'+import { lazyWithPreload, retryBootImport, retryImport } from './retryImport'++class FailedBoundary extends ReactComponent<{ children: ReactNode }, { failed: boolean }> {+ override state = { failed: false }++ static getDerivedStateFromError(): { failed: boolean } {+ return { failed: true }+ }++ override render(): ReactNode {+ return this.state.failed ? createElement('span', null, 'failed') : this.props.children+ }+}describe('retryImport', () => {beforeEach(() => {@@ -84,4 +101,79 @@ describe('retryImport', () => {expect(factory).toHaveBeenCalledTimes(3)expect(isChunkLoadError(error)).toBe(true)})++ describe('lazyWithPreload', () => {+ beforeEach(() => {+ jest.useRealTimers()+ })++ afterEach(() => {+ cleanup()+ })++ const Greeting = ({ name }: { name: string }): JSX.Element => createElement('span', null, `hello ${name}`)++ const renderInSuspense = (Component: (props: { name: string }) => JSX.Element): void => {+ render(+ createElement(+ Suspense,+ { fallback: createElement('span', null, 'loading') },+ createElement(Component, { name: 'max' })+ )+ )+ }++ it.each([+ { preloaded: true, firstPaint: 'hello max' },+ { preloaded: false, firstPaint: 'loading' },+ ])('preloaded=$preloaded shows "$firstPaint" on first paint', async ({ preloaded, firstPaint }) => {+ const factory = jest.fn().mockResolvedValue({ default: Greeting })+ const { Component, preload } = lazyWithPreload(factory)+ if (preloaded) {+ await preload()+ }++ renderInSuspense(Component)++ expect(screen.getByText(firstPaint)).toBeInTheDocument()+ expect(await screen.findByText('hello max')).toBeInTheDocument()+ expect(factory).toHaveBeenCalledTimes(1)+ })++ it('loads again on render after a failed preload', async () => {+ const factory = jest.fn().mockRejectedValueOnce(new Error('boom')).mockResolvedValue({ default: Greeting })+ const { Component, preload } = lazyWithPreload(factory)+ await preload()++ renderInSuspense(Component)++ expect(await screen.findByText('hello max')).toBeInTheDocument()+ expect(factory).toHaveBeenCalledTimes(2)+ })++ it('reports a render-time failure to the boundary, then loads again on a later remount', async () => {+ jest.spyOn(console, 'error').mockImplementation(() => {})+ const now = jest.spyOn(Date, 'now').mockReturnValue(1_000_000)+ const factory = jest.fn().mockRejectedValueOnce(new Error('boom')).mockResolvedValue({ default: Greeting })+ const { Component } = lazyWithPreload(factory)++ render(+ createElement(+ FailedBoundary,+ null,+ createElement(Suspense, { fallback: null }, createElement(Component, { name: 'max' }))+ )+ )+ expect(await screen.findByText('failed')).toBeInTheDocument()+ expect(factory).toHaveBeenCalledTimes(1)+ cleanup()++ now.mockReturnValue(1_002_000)+ renderInSuspense(Component)++ expect(await screen.findByText('hello max')).toBeInTheDocument()+ expect(factory).toHaveBeenCalledTimes(2)+ now.mockRestore()+ })+ })})diff --git a/frontend/src/lib/utils/retryImport.ts b/frontend/src/lib/utils/retryImport.tsindex bf0897c42ad4..7c952c23304b 100644--- a/frontend/src/lib/utils/retryImport.ts+++ b/frontend/src/lib/utils/retryImport.ts@@ -1,4 +1,4 @@-import { ComponentType, LazyExoticComponent, lazy } from 'react'+import { ComponentProps, ComponentType, LazyExoticComponent, createElement, lazy, useState } from 'react'import { isChunkLoadError, isGenericNetworkTypeError, markAsChunkLoadError } from 'lib/utils/isChunkLoadError'@@ -77,3 +77,65 @@ export function lazyWithRetry<T extends ComponentType<any>>(): LazyExoticComponent<T> {return lazy(() => retryImport(factory))}++export interface PreloadableComponent<T extends ComponentType<any>> {+ Component: (props: ComponentProps<T>) => JSX.Element+ /** Starts the chunk download. Resolves when it ends, also on a failure, which the render path reports. */+ preload: () => Promise<void>+}++const LAZY_REMOUNT_RETRY_AFTER_MS = 1000++/**+ * `lazyWithRetry` plus a `preload()` that a logic can call as soon as it knows the component will render,+ * so the chunk downloads in parallel with the data. A component that mounts after the chunk has loaded+ * renders at once and never shows its Suspense fallback.+ */+export function lazyWithPreload<T extends ComponentType<any>>(+ factory: () => Promise<{ default: T }>+): PreloadableComponent<T> {+ let loaded: T | null = null+ let pending: Promise<{ default: T }> | null = null+ let rejectedAt: number | null = null+ const load = (): Promise<{ default: T }> => {+ pending ??= retryImport(factory).then(+ (module) => {+ loaded = module.default+ return module+ },+ (error) => {+ pending = null+ rejectedAt = Date.now()+ throw error+ }+ )+ return pending+ }+ let Lazy = lazy(load)++ // React caches a rejection inside the lazy wrapper, so a remount after a failure needs a new one.+ // React also re-renders a suspended mount when its import rejects. A new wrapper on that re-render+ // would start another import at once, so a failing chunk would loop and never reach the error boundary.+ const currentLazy = (): typeof Lazy => {+ if (rejectedAt !== null && Date.now() - rejectedAt >= LAZY_REMOUNT_RETRY_AFTER_MS) {+ rejectedAt = null+ Lazy = lazy(load)+ }+ return Lazy+ }++ function Component(props: ComponentProps<T>): JSX.Element {+ // Decided once per mount: switching from the lazy wrapper to the loaded component would remount it.+ const [Resolved] = useState(() => loaded ?? currentLazy())+ return createElement(Resolved as ComponentType<ComponentProps<T>>, props)+ }++ return {+ Component,+ preload: () =>+ load().then(+ () => undefined,+ () => undefined+ ),+ }+}diff --git a/frontend/src/queries/Query/Query.test.tsx b/frontend/src/queries/Query/Query.test.tsxindex 418c2697d6c2..3592804e33e3 100644--- a/frontend/src/queries/Query/Query.test.tsx+++ b/frontend/src/queries/Query/Query.test.tsx@@ -1,6 +1,6 @@import '@testing-library/jest-dom'-import { render } from '@testing-library/react'+import { cleanup, render } from '@testing-library/react'import { InsightVizNode, NodeKind } from '~/queries/schema/schema-general'@@ -11,9 +11,8 @@ const insightVizQueryCalls: InsightVizNode[] = []jest.mock('~/queries/nodes/InsightViz/InsightViz', () => ({InsightViz: (props: { query: InsightVizNode }) => {insightVizQueryCalls.push(props.query)- return <div data-testid="insight-viz" />+ return <div data-attr="insight-viz" />},- insightVizDataNodeKey: () => 'test-key',}))jest.mock('~/layout/ErrorBoundary', () => ({@@ -36,11 +35,16 @@ describe('Query', () => {insightVizQueryCalls.length = 0})- it('immediately uses propsQuery on re-render when controlled via setQuery (no stale localQuery)', () => {+ afterEach(() => {+ cleanup()+ })++ it('immediately uses propsQuery on re-render when controlled via setQuery (no stale localQuery)', async () => {const originalQuery = makeInsightVizQuery()const setQuery = jest.fn()- const { rerender } = render(<Query query={originalQuery} setQuery={setQuery} uniqueKey="test" />)+ const { rerender, findByTestId } = render(<Query query={originalQuery} setQuery={setQuery} uniqueKey="test" />)+ await findByTestId('insight-viz')insightVizQueryCalls.length = 0@@ -52,20 +56,22 @@ describe('Query', () => {expect(insightVizQueryCalls[0]).toBe(updatedQuery)})- it('uses propsQuery when readOnly is true', () => {+ it('uses propsQuery when readOnly is true', async () => {const query = makeInsightVizQuery({personsOnEventsMode: 'person_id_override_properties_joined',})- render(<Query query={query} readOnly uniqueKey="test" />)+ const { findByTestId } = render(<Query query={query} readOnly uniqueKey="test" />)+ await findByTestId('insight-viz')expect(insightVizQueryCalls[0]).toBe(query)})- it('syncs updated propsQuery via useEffect when uncontrolled', () => {+ it('syncs updated propsQuery via useEffect when uncontrolled', async () => {const originalQuery = makeInsightVizQuery()- const { rerender } = render(<Query query={originalQuery} uniqueKey="test" />)+ const { rerender, findByTestId } = render(<Query query={originalQuery} uniqueKey="test" />)+ await findByTestId('insight-viz')insightVizQueryCalls.length = 0diff --git a/frontend/src/queries/Query/Query.tsx b/frontend/src/queries/Query/Query.tsxindex 6ce0f36bac63..3ed69cbcc221 100644--- a/frontend/src/queries/Query/Query.tsx+++ b/frontend/src/queries/Query/Query.tsx@@ -1,17 +1,14 @@import { BuiltLogic, LogicWrapper } from 'kea'-import { Suspense, useEffect, useState } from 'react'+import { ReactNode, Suspense, useEffect, useState } from 'react'import { LemonDivider } from 'lib/lemon-ui/LemonDivider'import { Spinner } from 'lib/lemon-ui/Spinner'-import { lazyWithRetry } from 'lib/utils/retryImport'-import { HogDebug } from 'scenes/debug/HogDebug'+import { ChunkLoadErrorBoundary } from 'scenes/ChunkLoadErrorBoundary'import { ErrorBoundary } from '~/layout/ErrorBoundary'import { DataNode } from '~/queries/nodes/DataNode/DataNode'import { DataTable } from '~/queries/nodes/DataTable/DataTable'-import { InsightViz, insightVizDataNodeKey } from '~/queries/nodes/InsightViz/InsightViz'-import { WebOverview } from '~/queries/nodes/WebOverview/WebOverview'-import { QueryEditor } from '~/queries/QueryEditor/QueryEditor'+import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'import {isDataTableNode,isDataVisualizationNode,@@ -31,11 +28,6 @@ import {} from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'-import { EndpointsUsageOverviewNode, EndpointsUsageTrendsNode } from 'products/endpoints/frontend/nodes'-import { MetricsHistogramQueryNode, MetricsQueryNode } from 'products/metrics/frontend/nodes'--import { DataTableVisualization } from '../nodes/DataVisualization/DataVisualization'-import { SavedInsight } from '../nodes/SavedInsight/SavedInsight'import {isEndpointsUsageOverviewQuery,isEndpointsUsageTrendsQuery,@@ -46,18 +38,48 @@ import {isWebVitalsPathBreakdownQuery,isWebVitalsQuery,} from '../utils'+import {+ DataVisualizationRenderer,+ EndpointsUsageOverviewRenderer,+ EndpointsUsageTrendsRenderer,+ HogDebugRenderer,+ InsightVizRenderer,+ MarketingAnalyticsOverviewRenderer,+ MetricsHistogramQueryRenderer,+ MetricsQueryRenderer,+ QueryEditorRenderer,+ SavedInsightRenderer,+ WebOverviewRenderer,+ WebVitalsPathBreakdownRenderer,+ WebVitalsRenderer,+} from './queryNodeRenderers'-const MarketingAnalyticsOverview = lazyWithRetry(() =>- import('scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview').then(- (m) => ({ default: m.MarketingAnalyticsOverview })+// The fallback fills the slot the renderer will fill, so the page does not jump when the chunk arrives.+const CHART_FALLBACK = 'h-full min-h-80'+const TILE_ROW_FALLBACK = 'h-24'++function LazyQueryNode({+ fallbackClassName,+ children,+}: {+ fallbackClassName: string+ children: ReactNode+}): JSX.Element {+ return (+ <ChunkLoadErrorBoundary>+ {/* The image exporter waits for every .Spinner to detach, so a Spinner fallback stops it capturing the page before this chunk loads. */}+ <Suspense+ fallback={+ <div className={`flex w-full items-center justify-center ${fallbackClassName}`}>+ <Spinner className="text-3xl" />+ </div>+ }+ >+ {children}+ </Suspense>+ </ChunkLoadErrorBoundary>)-)-const WebVitals = lazyWithRetry(() =>- import('~/queries/nodes/WebVitals/WebVitals').then((m) => ({ default: m.WebVitals }))-)-const WebVitalsPathBreakdown = lazyWithRetry(() =>- import('../nodes/WebVitals/WebVitalsPathBreakdown').then((m) => ({ default: m.WebVitalsPathBreakdown }))-)+}export interface QueryProps<Q extends Node> {/** An optional key to identify the query */@@ -147,141 +169,159 @@ export function Query<Q extends Node>(props: QueryProps<Q>): JSX.Element | null)} else if (isDataVisualizationNode(query)) {component = (- <DataTableVisualization- attachTo={props.attachTo}- query={query}- setQuery={setQuery as unknown as (query: VisualizationNode) => void}- cachedResults={props.cachedResults}- uniqueKey={uniqueKey}- context={queryContext}- readOnly={readOnly}- embedded={embedded}- inSharedMode={inSharedMode}- editMode={!!editMode}- filtersOverride={filtersOverride}- variablesOverride={props.variablesOverride}- />+ <LazyQueryNode fallbackClassName={CHART_FALLBACK}>+ <DataVisualizationRenderer.Component+ attachTo={props.attachTo}+ query={query}+ setQuery={setQuery as unknown as (query: VisualizationNode) => void}+ cachedResults={props.cachedResults}+ uniqueKey={uniqueKey}+ context={queryContext}+ readOnly={readOnly}+ embedded={embedded}+ inSharedMode={inSharedMode}+ editMode={!!editMode}+ filtersOverride={filtersOverride}+ variablesOverride={props.variablesOverride}+ />+ </LazyQueryNode>)} else if (isSavedInsightNode(query)) {component = (- <SavedInsight- attachTo={props.attachTo}- query={query}- context={queryContext}- readOnly={readOnly}- editMode={!!editMode}- embedded={embedded}- />+ <LazyQueryNode fallbackClassName={CHART_FALLBACK}>+ <SavedInsightRenderer.Component+ attachTo={props.attachTo}+ query={query}+ context={queryContext}+ readOnly={readOnly}+ editMode={!!editMode}+ embedded={embedded}+ />+ </LazyQueryNode>)} else if (isInsightVizNode(query)) {component = (- <InsightViz- attachTo={props.attachTo}- query={query}- setQuery={setQuery as unknown as (query: InsightVizNode) => void}- context={queryContext}- readOnly={readOnly}- editMode={!!editMode}- uniqueKey={uniqueKey}- cachedResults={props.cachedResults}- embedded={embedded}- inSharedMode={inSharedMode}- filtersOverride={filtersOverride}- variablesOverride={variablesOverride}- />+ <LazyQueryNode fallbackClassName={CHART_FALLBACK}>+ <InsightVizRenderer.Component+ attachTo={props.attachTo}+ query={query}+ setQuery={setQuery as unknown as (query: InsightVizNode) => void}+ context={queryContext}+ readOnly={readOnly}+ editMode={!!editMode}+ uniqueKey={uniqueKey}+ cachedResults={props.cachedResults}+ embedded={embedded}+ inSharedMode={inSharedMode}+ filtersOverride={filtersOverride}+ variablesOverride={variablesOverride}+ />+ </LazyQueryNode>)} else if (isMetricsQuery(query)) {component = (- <MetricsQueryNode- attachTo={props.attachTo}- query={query}- cachedResults={props.cachedResults}- context={queryContext}- embedded={embedded}- editMode={!!editMode && !readOnly}- setQuery={setQuery as unknown as (query: MetricsQuery) => void}- />+ <LazyQueryNode fallbackClassName={CHART_FALLBACK}>+ <MetricsQueryRenderer.Component+ attachTo={props.attachTo}+ query={query}+ cachedResults={props.cachedResults}+ context={queryContext}+ embedded={embedded}+ editMode={!!editMode && !readOnly}+ setQuery={setQuery as unknown as (query: MetricsQuery) => void}+ />+ </LazyQueryNode>)} else if (isMetricsHistogramQuery(query)) {component = (- <MetricsHistogramQueryNode- attachTo={props.attachTo}- query={query}- cachedResults={props.cachedResults}- context={queryContext}- embedded={embedded}- />+ <LazyQueryNode fallbackClassName={CHART_FALLBACK}>+ <MetricsHistogramQueryRenderer.Component+ attachTo={props.attachTo}+ query={query}+ cachedResults={props.cachedResults}+ context={queryContext}+ embedded={embedded}+ />+ </LazyQueryNode>)} else if (isEndpointsUsageOverviewQuery(query)) {component = (- <EndpointsUsageOverviewNode- attachTo={props.attachTo}- query={query}- cachedResults={props.cachedResults}- context={queryContext}- />+ <LazyQueryNode fallbackClassName={TILE_ROW_FALLBACK}>+ <EndpointsUsageOverviewRenderer.Component+ attachTo={props.attachTo}+ query={query}+ cachedResults={props.cachedResults}+ context={queryContext}+ />+ </LazyQueryNode>)} else if (isEndpointsUsageTrendsQuery(query)) {component = (- <EndpointsUsageTrendsNode- attachTo={props.attachTo}- query={query}- cachedResults={props.cachedResults}- context={queryContext}- />+ <LazyQueryNode fallbackClassName={CHART_FALLBACK}>+ <EndpointsUsageTrendsRenderer.Component+ attachTo={props.attachTo}+ query={query}+ cachedResults={props.cachedResults}+ context={queryContext}+ />+ </LazyQueryNode>)} else if (isWebOverviewQuery(query)) {component = (- <WebOverview- attachTo={props.attachTo}- query={query}- cachedResults={props.cachedResults}- context={queryContext}- uniqueKey={uniqueKey}- />+ <LazyQueryNode fallbackClassName={TILE_ROW_FALLBACK}>+ <WebOverviewRenderer.Component+ attachTo={props.attachTo}+ query={query}+ cachedResults={props.cachedResults}+ context={queryContext}+ uniqueKey={uniqueKey}+ />+ </LazyQueryNode>)} else if (isMarketingAnalyticsAggregatedQuery(query)) {component = (- <Suspense fallback={<Spinner />}>- <MarketingAnalyticsOverview+ <LazyQueryNode fallbackClassName={TILE_ROW_FALLBACK}>+ <MarketingAnalyticsOverviewRenderer.ComponentattachTo={props.attachTo}query={query}cachedResults={props.cachedResults}context={queryContext}uniqueKey={uniqueKey}/>- </Suspense>+ </LazyQueryNode>)} else if (isWebVitalsQuery(query)) {component = (- <Suspense fallback={<Spinner />}>- <WebVitals+ <LazyQueryNode fallbackClassName={CHART_FALLBACK}>+ <WebVitalsRenderer.ComponentattachTo={props.attachTo}query={query}cachedResults={props.cachedResults}context={queryContext}/>- </Suspense>+ </LazyQueryNode>)} else if (isWebVitalsPathBreakdownQuery(query)) {component = (- <Suspense fallback={<Spinner />}>- <WebVitalsPathBreakdown+ <LazyQueryNode fallbackClassName={CHART_FALLBACK}>+ <WebVitalsPathBreakdownRenderer.ComponentattachTo={props.attachTo}query={query}cachedResults={props.cachedResults}context={queryContext}/>- </Suspense>+ </LazyQueryNode>)} else if (isHogQuery(query)) {component = (- <HogDebug- attachTo={props.attachTo}- query={query}- setQuery={setQuery as (query: any) => void}- queryKey={String(uniqueKey)}- />+ <LazyQueryNode fallbackClassName={CHART_FALLBACK}>+ <HogDebugRenderer.Component+ attachTo={props.attachTo}+ query={query}+ setQuery={setQuery as (query: any) => void}+ queryKey={String(uniqueKey)}+ />+ </LazyQueryNode>)} else {component = <DataNode attachTo={props.attachTo} query={query} cachedResults={props.cachedResults} />@@ -292,11 +332,13 @@ export function Query<Q extends Node>(props: QueryProps<Q>): JSX.Element | null<>{queryContext.showQueryEditor ? (<>- <QueryEditor- query={JSON.stringify(query)}- setQuery={(stringQuery) => setQuery?.(JSON.parse(stringQuery), true)}- context={queryContext}- />+ <LazyQueryNode fallbackClassName={CHART_FALLBACK}>+ <QueryEditorRenderer.Component+ query={JSON.stringify(query)}+ setQuery={(stringQuery) => setQuery?.(JSON.parse(stringQuery), true)}+ context={queryContext}+ />+ </LazyQueryNode><div className="my-4"><LemonDivider /></div>diff --git a/frontend/src/queries/Query/queryNodeRenderers.ts b/frontend/src/queries/Query/queryNodeRenderers.tsnew file mode 100644index 000000000000..d973dbe19fc5--- /dev/null+++ b/frontend/src/queries/Query/queryNodeRenderers.ts@@ -0,0 +1,60 @@+import { lazyWithPreload } from 'lib/utils/retryImport'++// Each renderer loads in its own chunk, so a scene ships only the node kinds it draws.+// A scene that draws a kind on first paint calls its `preload()` when the scene logic mounts.++export const InsightVizRenderer = lazyWithPreload(() =>+ import('~/queries/nodes/InsightViz/InsightViz').then((m) => ({ default: m.InsightViz }))+)++export const DataVisualizationRenderer = lazyWithPreload(() =>+ import('~/queries/nodes/DataVisualization/DataVisualization').then((m) => ({+ default: m.DataTableVisualization,+ }))+)++export const SavedInsightRenderer = lazyWithPreload(() =>+ import('~/queries/nodes/SavedInsight/SavedInsight').then((m) => ({ default: m.SavedInsight }))+)++export const WebOverviewRenderer = lazyWithPreload(() =>+ import('~/queries/nodes/WebOverview/WebOverview').then((m) => ({ default: m.WebOverview }))+)++export const MetricsQueryRenderer = lazyWithPreload(() =>+ import('products/metrics/frontend/nodes').then((m) => ({ default: m.MetricsQueryNode }))+)++export const MetricsHistogramQueryRenderer = lazyWithPreload(() =>+ import('products/metrics/frontend/nodes').then((m) => ({ default: m.MetricsHistogramQueryNode }))+)++export const EndpointsUsageOverviewRenderer = lazyWithPreload(() =>+ import('products/endpoints/frontend/nodes').then((m) => ({ default: m.EndpointsUsageOverviewNode }))+)++export const EndpointsUsageTrendsRenderer = lazyWithPreload(() =>+ import('products/endpoints/frontend/nodes').then((m) => ({ default: m.EndpointsUsageTrendsNode }))+)++export const MarketingAnalyticsOverviewRenderer = lazyWithPreload(() =>+ import('scenes/web-analytics/tabs/marketing-analytics/frontend/components/MarketingAnalyticsOverview/MarketingAnalyticsOverview').then(+ (m) => ({ default: m.MarketingAnalyticsOverview })+ )+)++export const WebVitalsRenderer = lazyWithPreload(() =>+ import('~/queries/nodes/WebVitals/WebVitals').then((m) => ({ default: m.WebVitals }))+)++export const WebVitalsPathBreakdownRenderer = lazyWithPreload(() =>+ import('~/queries/nodes/WebVitals/WebVitalsPathBreakdown').then((m) => ({ default: m.WebVitalsPathBreakdown }))+)++export const HogDebugRenderer = lazyWithPreload(() =>+ import('scenes/debug/HogDebug').then((m) => ({ default: m.HogDebug }))+)++export const QueryEditorRenderer = lazyWithPreload(() =>+ import('~/queries/QueryEditor/QueryEditor').then((m) => ({ default: m.QueryEditor }))+)diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsxindex 5a5bb6db01ad..8ee4fbd6cd0c 100644--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx@@ -8,6 +8,7 @@ import { IconGear } from '@posthog/icons'import { LemonBanner, LemonButton, LemonDivider } from '@posthog/lemon-ui'import { createXAxisTickCallback } from '@posthog/quill-charts'+import 'lib/components/Cards/InsightCard/InsightCard.scss'import { ExportButton } from 'lib/components/ExportButton/ExportButton'import { getResultMenuPoint, isResultMenuContextMenu, replayAsClick } from 'lib/components/ResultMenu/resultMenuTrigger'import { PART_OF_WHOLE_DISPLAY_TYPES } from 'lib/constants'diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex 06536fa62b0b..a6f9fd17160e 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -90,6 +90,7 @@ import { insightsModel } from '~/models/insightsModel'import { variableDataLogic } from '~/queries/nodes/DataVisualization/Components/Variables/variableDataLogic'import { Variable } from '~/queries/nodes/DataVisualization/types'import { filterVariablesReferencedInQuery } from '~/queries/nodes/InsightViz/queryUtils'+import { DataVisualizationRenderer, InsightVizRenderer } from '~/queries/Query/queryNodeRenderers'import {BreakdownFilter,CompareFilter,@@ -4433,6 +4434,9 @@ export const dashboardLogic = kea<dashboardLogicType>([})),events(({ actions, props, values, cache }) => ({afterMount: () => {+ // Insight and SQL tiles render through these. Fetch them alongside the dashboard itself.+ void InsightVizRenderer.preload()+ void DataVisualizationRenderer.preload()// NOTE: initial dashboard load is done after variables are loaded in initialVariablesLoadedif (!Number.isFinite(props.id)) {actions.dashboardNotFound()diff --git a/frontend/src/scenes/insights/insightSceneLogic.test.ts b/frontend/src/scenes/insights/insightSceneLogic.test.tsindex 97280d93dc80..aae2322b481d 100644--- a/frontend/src/scenes/insights/insightSceneLogic.test.ts+++ b/frontend/src/scenes/insights/insightSceneLogic.test.ts@@ -24,6 +24,9 @@ import { DashboardFilter, HogQLVariable, InsightVizNode, NodeKind, ProductKey }import { initKeaTests } from '~/test/init'import { ActivityScope, CohortType, DashboardType, InsightShortId, InsightType, ItemMode } from '~/types'+// The logic preloads the chart renderers on mount. No test here draws one, and loading them takes seconds.+jest.mock('~/queries/Query/queryNodeRenderers')+const Insight12 = '12' as InsightShortIdconst Insight42 = '42' as InsightShortIddiff --git a/frontend/src/scenes/insights/insightSceneLogic.tsx b/frontend/src/scenes/insights/insightSceneLogic.tsxindex 0c5a33a842fd..86ebc30ae15b 100644--- a/frontend/src/scenes/insights/insightSceneLogic.tsx+++ b/frontend/src/scenes/insights/insightSceneLogic.tsx@@ -2,6 +2,7 @@ import {MakeLogicType,BuiltLogic,actions,+ afterMount,connect,kea,listeners,@@ -42,6 +43,7 @@ import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigatiimport { sceneLayoutLogic } from '~/layout/scenes/sceneLayoutLogic'import { dashboardsModel } from '~/models/dashboardsModel'import { getDefaultQuery } from '~/queries/nodes/InsightViz/utils'+import { DataVisualizationRenderer, InsightVizRenderer } from '~/queries/Query/queryNodeRenderers'import { isDataTableNode, isInsightVizNode } from '~/queries/schema/node-guards'import { checkLatestVersionsOnQuery } from '~/queries/schema/query-versions'import {@@ -1029,4 +1031,9 @@ export const insightSceneLogic = kea<insightSceneLogicType>([setInsightMode: actionToUrl,}}),+ afterMount(() => {+ // An insight is a chart or a SQL visualization. Fetch both renderers alongside the insight itself.+ void InsightVizRenderer.preload()+ void DataVisualizationRenderer.preload()+ }),])diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsxindex 4ab3cdb73720..ae65ff08f125 100644--- a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx+++ b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.tsx@@ -1,3 +1,5 @@+import '~/queries/nodes/InsightViz/InsightViz.scss'+import clsx from 'clsx'import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'import React, { Suspense, useEffect, useState } from 'react'diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsxindex 97edec04d00b..339d7e01a74f 100644--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx@@ -50,6 +50,7 @@ import { userLogic } from 'scenes/userLogic'import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'import { WEB_VITALS_COLORS, WEB_VITALS_THRESHOLDS } from '~/queries/nodes/WebVitals/definitions'import { hogqlQuery } from '~/queries/query'+import { InsightVizRenderer, WebOverviewRenderer } from '~/queries/Query/queryNodeRenderers'import {ActionConversionGoal,ActionsNode,@@ -3206,6 +3207,9 @@ export const webAnalyticsLogic: LogicWrapper<webAnalyticsLogicType> = kea<webAna// start the loaders after mounting the logicafterMount(({ actions }) => {+ // The default tab draws the overview tiles and insight charts. Fetch them alongside the tile queries.+ void InsightVizRenderer.preload()+ void WebOverviewRenderer.preload()actions.loadShouldShowGeoIPQueries()}),diff --git a/products/ai_observability/frontend/tags/AIObservabilityTag.tsx b/products/ai_observability/frontend/tags/AIObservabilityTag.tsxindex 98fc7da8c396..4cd527a6b6c4 100644--- a/products/ai_observability/frontend/tags/AIObservabilityTag.tsx+++ b/products/ai_observability/frontend/tags/AIObservabilityTag.tsx@@ -19,6 +19,7 @@ import {Tooltip,} from '@posthog/lemon-ui'+import 'lib/components/Cards/InsightCard/InsightCard.scss'import { AccessControlAction } from 'lib/components/AccessControlAction'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'diff --git a/products/ai_observability/frontend/tags/AIObservabilityTagsScene.tsx b/products/ai_observability/frontend/tags/AIObservabilityTagsScene.tsxindex 5c6131a1fe7a..07617ab4151f 100644--- a/products/ai_observability/frontend/tags/AIObservabilityTagsScene.tsx+++ b/products/ai_observability/frontend/tags/AIObservabilityTagsScene.tsx@@ -16,6 +16,7 @@ import {} from '@posthog/lemon-ui'import { Button } from '@posthog/quill'+import 'lib/components/Cards/InsightCard/InsightCard.scss'import { AccessControlAction } from 'lib/components/AccessControlAction'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { FEATURE_FLAGS } from 'lib/constants'diff --git a/products/business_intelligence/frontend/BIDashboardTile.test.tsx b/products/business_intelligence/frontend/BIDashboardTile.test.tsxindex a681d9282efa..37d7affe83b7 100644--- a/products/business_intelligence/frontend/BIDashboardTile.test.tsx+++ b/products/business_intelligence/frontend/BIDashboardTile.test.tsx@@ -5,6 +5,7 @@ import { act, cleanup, render, screen, waitFor } from '@testing-library/react'import { InsightCard } from 'lib/components/Cards/InsightCard/InsightCard'import { useMocks } from '~/mocks/jest'+import { DataVisualizationRenderer, InsightVizRenderer } from '~/queries/Query/queryNodeRenderers'import { BIConfig, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'import { HogQLQuery, NodeKind, RefreshType } from '~/queries/schema/schema-general'import { insightOnDashboard, tileFromInsight } from '~/scenes/dashboard/dashboardLogic.testHelpers'@@ -16,6 +17,10 @@ import { BIDashboardTile } from './BIDashboardTile'import { buildBIQuery, DEFAULT_BI_CONFIG } from './biEditorTypes'describe('dashboard worksheet query execution', () => {+ beforeAll(async () => {+ await Promise.all([InsightVizRenderer.preload(), DataVisualizationRenderer.preload()])+ })+afterEach(cleanup)it.each(['tile', 'card'])(diff --git a/products/product_analytics/frontend/insights/home/HomeTabChartCard.tsx b/products/product_analytics/frontend/insights/home/HomeTabChartCard.tsxindex abe9e9d0783f..d8500f0b992d 100644--- a/products/product_analytics/frontend/insights/home/HomeTabChartCard.tsx+++ b/products/product_analytics/frontend/insights/home/HomeTabChartCard.tsx@@ -1,3 +1,4 @@+import '~/queries/nodes/InsightViz/InsightViz.scss'import './HomeTabChartCard.scss'import { useValues } from 'kea'diff --git a/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsx b/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsxindex 970182541b1f..868f80bb3e47 100644--- a/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsx+++ b/products/product_analytics/frontend/insights/home/HomeTabDefault.test.tsx@@ -18,6 +18,7 @@ import trendsNumber from '~/mocks/fixtures/api/projects/team_id/insights/trendsNimport { useMocks } from '~/mocks/jest'import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'import { performQuery } from '~/queries/query'+import { InsightVizRenderer } from '~/queries/Query/queryNodeRenderers'import { isInsightQueryNode, isRetentionQuery, isTrendsQuery } from '~/queries/schema/node-guards'import type { DataNode } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'@@ -42,6 +43,10 @@ jest.mock('~/queries/nodes/InsightViz/InsightVizDisplay', () => ({const mockedQuery = jest.mocked(performQuery)describe('HomeTabDefault query reuse', () => {+ beforeAll(async () => {+ await InsightVizRenderer.preload()+ })+beforeEach(() => {initKeaTests()savedInsightsLogic.mount()diff --git a/products/replay_vision/frontend/replay_scanners/components/ObservationsOverTimeCard.tsx b/products/replay_vision/frontend/replay_scanners/components/ObservationsOverTimeCard.tsxindex 00ee626850b6..54f302d23901 100644--- a/products/replay_vision/frontend/replay_scanners/components/ObservationsOverTimeCard.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ObservationsOverTimeCard.tsx@@ -1,5 +1,6 @@import { useMemo } from 'react'+import 'lib/components/Cards/InsightCard/InsightCard.scss'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { cn } from 'lib/utils/css-classes'diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsxindex 12dff1e79b63..0a44679e2de7 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsx@@ -1,6 +1,8 @@import { useActions, useValues } from 'kea'import { useCallback, useMemo } from 'react'+import 'lib/components/Cards/InsightCard/InsightCard.scss'+import { InsightVizNode, NodeKind, ProductKey, TrendsQuery } from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'import {