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(sql-editor): stop measuring every line of the active query on scroll (#78998)

Kyle Swank85ede51078ae
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ff0b5fcc025d..f4beed122d24 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5043,9 +5043,9 @@ snapshots:
products-workflows-customerioimportmodal--step-4-track-not-configured--light:
hash: v1.k794b7964.0954891b73cdc0b1bce1275fa11a5fa4af2055b83b518bce82f3fde886097659.mgEq2W8sZg7x-vt8z2EpwEHPBGRzPI1GWtn-9tu-46o
queries-webvitals--web-vitals--dark:
- hash: v1.k794b7964.a6d69dfd4718ccc9c5b9610eb2e92f2253ff222f58b5f8f2e17324273c0d3540.PwlwzgyyuTCXAXrqbEIumf0BYHMgEgkMTnF7RMeARWw
+ hash: v1.k794b7964.48327775c34a8754e434a53828b33347eeef44af293d4e95a46c0ed628213ee8.pOw3j0vJibdK8umATaWRR3xd9JlS6hcJYf3POABQ464
queries-webvitals--web-vitals--light:
- hash: v1.k794b7964.9ee33a37c9dc8e70a61fba6ae6df1149dd3b879f632f5a0a4681d82ec1924446.f2YdyidQkukjaRYXqfWMNmkrJ1A4n5GiD3LauixzibU
+ hash: v1.k794b7964.78ded4dbdf1721276a7e00949b507b270d3a57a90a827970c4bb6a613abba458.OZh0w0xN4ZKozqD0BLkv2Gxdg-1A_mM3GsLldgj82ac
queries-webvitalspathbreakdown--web-vitals-path-breakdown--dark:
hash: v1.k794b7964.5ad75695030b31559f83a36380a7c83078678002c669a23b450bd9a5d134ae70.BJSO9CULjFh8KlWBnKsep0Ep6jtur0r4s3T3_0YHjPs
queries-webvitalspathbreakdown--web-vitals-path-breakdown--light:
@@ -6479,9 +6479,9 @@ snapshots:
scenes-app-mcp-analytics--activity--light:
hash: v1.k794b7964.7153b1283f0cae6130fabfd5ad0b357eace4038543f642eb3d39d7e955347b19.DAm06XBnoG0jIbLm05PyMGn0LWaJfn8f9SOPqN_1KGc
scenes-app-mcp-analytics--dashboard--dark:
- hash: v1.k794b7964.05490a43bcb92252f0270f3302f92f2ef896f9373e9a832e2a166714f4ea9e9d.hZfs_sWw_pq-GRMv5LKpUxYktqR8xoniQdom5iIW7Xw
+ hash: v1.k794b7964.fa3e40c46ac63c60a51e1896fefe41ff5050fc8b03eb978986b3593206719c33.FEGHgKuz5-9JZ9UcWiUFhjjndx7-ysHEYmKf7VBXGyk
scenes-app-mcp-analytics--dashboard--light:
- hash: v1.k794b7964.49f850b518aa783296b3d178c4335a14048651a65980d230e22f2d140176b149.GdW1N70CXyKtRCe88ML3fwlrrHTXrIJ58dXsp7VIN6g
+ hash: v1.k794b7964.8085bf3b0d7cf70cfcdbc11a9ca9ae2823f07271a03230fa7e22b343ebbdf4c1.hG5BDPQ_aqdiioaYbf5Z1SjuAJSM2nzbJWupyc1VtUk
scenes-app-mcp-analytics--dashboard-with-menu-bar--dark:
hash: v1.k794b7964.53e903ed1eede907e906eb0a64cce280f685c41e4d5600b21b5719316720bf55.xEmtMNyC6k7Dxe8jqsZVXGePczRmMYF1Z4ZNKk9qv30
scenes-app-mcp-analytics--dashboard-with-menu-bar--light:
diff --git a/frontend/src/scenes/data-warehouse/editor/renderQueryOutline.test.ts b/frontend/src/scenes/data-warehouse/editor/renderQueryOutline.test.ts
index 57fa9148b72e..1e7be2c6bf9f 100644
--- a/frontend/src/scenes/data-warehouse/editor/renderQueryOutline.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/renderQueryOutline.test.ts
@@ -2,10 +2,15 @@ import type { editor, IRange } from 'monaco-editor'
import { renderQueryOutline } from './sqlEditorLogic'
+const LINE_HEIGHT = 18
+
// Minimal Monaco stand-in whose `getLineMaxColumn` throws for out-of-range lines,
// exactly like the real editor: that throw ("Illegal value for lineNumber") is the
// crash we're guarding against when a paste/edit shrinks the model under a stale range.
-function makeEditor(lineCount: number): editor.IStandaloneCodeEditor {
+function makeEditor(
+ lineCount: number,
+ visibleRanges?: { startLineNumber: number; endLineNumber: number }[]
+): { editorInstance: editor.IStandaloneCodeEditor; getScrolledVisiblePosition: jest.Mock } {
const model = {
getLineCount: () => lineCount,
getLineMaxColumn: (line: number) => {
@@ -15,10 +20,17 @@ function makeEditor(lineCount: number): editor.IStandaloneCodeEditor {
return 20
},
}
- return {
+ const getScrolledVisiblePosition = jest.fn(() => ({ left: 0, top: 0, height: LINE_HEIGHT }))
+ const editorInstance = {
getModel: () => model,
- getScrolledVisiblePosition: () => ({ left: 0, top: 0, height: 18 }),
+ getScrolledVisiblePosition,
+ getScrollTop: () => 0,
+ getTopForPosition: (line: number) => (line - 1) * LINE_HEIGHT,
+ getBottomForLineNumber: (line: number) => line * LINE_HEIGHT,
+ ...(visibleRanges ? { getVisibleRanges: () => visibleRanges } : {}),
} as unknown as editor.IStandaloneCodeEditor
+
+ return { editorInstance, getScrolledVisiblePosition }
}
describe('renderQueryOutline', () => {
@@ -26,8 +38,51 @@ describe('renderQueryOutline', () => {
const node = document.createElement('div')
// Model has 2 lines, but the cached range still spans 5 (e.g. after a paste removed lines).
const staleRange: IRange = { startLineNumber: 1, startColumn: 1, endLineNumber: 5, endColumn: 10 }
+ const { editorInstance } = makeEditor(2)
- expect(() => renderQueryOutline(makeEditor(2), node, staleRange)).not.toThrow()
+ expect(() => renderQueryOutline(editorInstance, node, staleRange)).not.toThrow()
expect(node.style.display).toBe('block')
})
+
+ it('only measures rendered lines, not the whole range', () => {
+ const node = document.createElement('div')
+ // A 900-line statement with only ~10 lines on screen: measuring every line would
+ // force a synchronous Monaco view render per call, which is what made scrolling lag.
+ const { editorInstance, getScrolledVisiblePosition } = makeEditor(900, [
+ { startLineNumber: 400, endLineNumber: 409 },
+ ])
+ const range: IRange = { startLineNumber: 1, startColumn: 1, endLineNumber: 900, endColumn: 10 }
+
+ renderQueryOutline(editorInstance, node, range)
+
+ // Two calls per visible line, and nothing for the 890 off-screen ones.
+ expect(getScrolledVisiblePosition).toHaveBeenCalledTimes(20)
+ expect(node.style.display).toBe('block')
+ })
+
+ it('spans the full range vertically even when most of it is off screen', () => {
+ const node = document.createElement('div')
+ const { editorInstance } = makeEditor(900, [{ startLineNumber: 400, endLineNumber: 409 }])
+ const range: IRange = { startLineNumber: 1, startColumn: 1, endLineNumber: 900, endColumn: 10 }
+
+ renderQueryOutline(editorInstance, node, range)
+
+ // Vertical extent comes from layout math over the whole range, so it isn't clamped
+ // to the viewport the way the horizontal measurement is.
+ expect(node.style.top).toBe('-1px')
+ expect(node.style.height).toBe(`${900 * LINE_HEIGHT + 2}px`)
+ })
+
+ it('hides the overlay when no rendered line intersects the range', () => {
+ const node = document.createElement('div')
+ const { editorInstance, getScrolledVisiblePosition } = makeEditor(900, [
+ { startLineNumber: 800, endLineNumber: 809 },
+ ])
+ const range: IRange = { startLineNumber: 1, startColumn: 1, endLineNumber: 100, endColumn: 10 }
+
+ renderQueryOutline(editorInstance, node, range)
+
+ expect(getScrolledVisiblePosition).not.toHaveBeenCalled()
+ expect(node.style.display).toBe('none')
+ })
})
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index c74ea0186840..b7a06627f427 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -136,7 +136,8 @@ export interface SqlEditorLogicProps {
// Monaco renders inline decorations per-line, so we can't get a single rectangular
// border from a className. Instead, we maintain an absolutely-positioned `div`
// inside the editor's overlay layer and recompute its bounding box from the pixel
-// positions of the range's start/end on each line.
+// positions of the range's start/end on each line. Runs on every scroll frame, so it
+// stays off the DOM wherever the geometry can be derived from layout math instead.
export function renderQueryOutline(
editorInstance: editor.IStandaloneCodeEditor,
node: HTMLElement,
@@ -148,11 +149,6 @@ export function renderQueryOutline(
return
}
- let minLeft = Infinity
- let maxRight = -Infinity
- let minTop = Infinity
- let maxBottom = -Infinity
-
// The cached range can outlive the document it was computed against: a paste or edit
// that removes lines shrinks the model, but this render path runs on scroll/layout
// without re-clamping. Passing an out-of-range line to `getLineMaxColumn` throws
@@ -160,8 +156,34 @@ export function renderQueryOutline(
const lineCount = model.getLineCount()
const startLine = Math.max(1, Math.min(range.startLineNumber, lineCount))
const endLine = Math.max(1, Math.min(range.endLineNumber, lineCount))
+ const startColumn = Math.min(range.startColumn, model.getLineMaxColumn(startLine))
+
+ // Vertical extent is pure layout math and monotonic in line number, so the range's own
+ // first/last line always bound it — no per-line scan, and no DOM reads. `getBottomForLineNumber`
+ // measures past the end of the wrapped line, which is exactly what a wrapped range needs.
+ const scrollTop = editorInstance.getScrollTop()
+ const minTop = editorInstance.getTopForPosition(startLine, startColumn) - scrollTop
+ const maxBottom = editorInstance.getBottomForLineNumber(endLine) - scrollTop
+
+ // Horizontal extent has to come from `getScrolledVisiblePosition`, which is expensive:
+ // each call forces a synchronous Monaco view render and reads client rects. Only scan
+ // lines that are actually rendered — for off-screen lines Monaco returns a placeholder
+ // pinned to the gutter edge anyway, so clamping here is more accurate, not less.
+ // Folding can yield several ranges; we only need the outer bounds, and don't assume ordering.
+ const visibleRanges = editorInstance.getVisibleRanges?.() ?? []
+ let loopStart = startLine
+ let loopEnd = endLine
+ if (visibleRanges.length) {
+ const firstVisibleLine = Math.min(...visibleRanges.map((r) => r.startLineNumber))
+ const lastVisibleLine = Math.max(...visibleRanges.map((r) => r.endLineNumber))
+ loopStart = Math.max(startLine, firstVisibleLine)
+ loopEnd = Math.min(endLine, lastVisibleLine)
+ }
+
+ let minLeft = Infinity
+ let maxRight = -Infinity
- for (let line = startLine; line <= endLine; line++) {
+ for (let line = loopStart; line <= loopEnd; line++) {
const lineMaxColumn = model.getLineMaxColumn(line)
const leftCol = Math.min(line === startLine ? range.startColumn : 1, lineMaxColumn)
const rightCol = line === endLine ? Math.min(range.endColumn, lineMaxColumn) : lineMaxColumn
@@ -179,24 +201,10 @@ export function renderQueryOutline(
if (endVis.left > maxRight) {
maxRight = endVis.left
}
- if (startVis.top < minTop) {
- minTop = startVis.top
- }
- // With wordWrap on, a single model line can span multiple visual rows: `endVis`
- // sits on a later row than `startVis`. Take the max bottom of both so the outline
- // covers the wrapped tail. Width on wrapped lines is still approximate — the
- // mid-rows could extend past either anchor — but the bottom must be correct or
- // wrapped queries get clipped vertically.
- const startBottom = startVis.top + startVis.height
- const endBottom = endVis.top + endVis.height
- if (startBottom > maxBottom) {
- maxBottom = startBottom
- }
- if (endBottom > maxBottom) {
- maxBottom = endBottom
- }
}
+ // No rendered line intersects the range — it's scrolled fully out of view, so there's
+ // nothing to frame.
if (minLeft === Infinity) {
node.style.display = 'none'
return
@@ -221,6 +229,12 @@ function clearQueryOutlineOverlay(
cache.layoutDisposable?.dispose()
cache.layoutDisposable = null
+ if (cache.outlineRafId != null) {
+ cancelAnimationFrame(cache.outlineRafId)
+ cache.outlineRafId = null
+ }
+ cache.scheduleOutlineRender = null
+
if (cache.queryOutlineWidget) {
try {
;(cache.queryOutlineEditor ?? fallbackEditor)?.removeOverlayWidget(cache.queryOutlineWidget)
@@ -1431,17 +1445,26 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
// Reposition the overlay on scroll and layout/resize. These don't change the
// range, only its pixel coordinates, so we skip the SQL parsing path entirely.
+ // Monaco fires scroll events per wheel tick, several per frame, and repositioning
+ // reads editor geometry — so coalesce to one render per frame.
+ cache.scheduleOutlineRender = (): void => {
+ if (cache.outlineRafId != null) {
+ return
+ }
+ cache.outlineRafId = requestAnimationFrame(() => {
+ cache.outlineRafId = null
+ if (cache.queryOutlineRange) {
+ renderQueryOutline(editorInstance, outlineNode, cache.queryOutlineRange)
+ }
+ })
+ }
cache.scrollDisposable?.dispose()
cache.scrollDisposable = editorInstance.onDidScrollChange(() => {
- if (cache.queryOutlineRange) {
- renderQueryOutline(editorInstance, outlineNode, cache.queryOutlineRange)
- }
+ cache.scheduleOutlineRender?.()
})
cache.layoutDisposable?.dispose()
cache.layoutDisposable = editorInstance.onDidLayoutChange(() => {
- if (cache.queryOutlineRange) {
- renderQueryOutline(editorInstance, outlineNode, cache.queryOutlineRange)
- }
+ cache.scheduleOutlineRender?.()
})
}
}),
@@ -3761,8 +3784,9 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
)
}
- // Single query — outline the innermost subquery at the cursor (which collapses
- // to the whole SELECT when there is no nested subquery).
+ // Single query — outline the innermost subquery at the cursor. A flat query with no
+ // nested SELECT around the cursor gets no outline at all: `findInnermostSelectAtOffset`
+ // needs at least two enclosing SELECTs and returns null otherwise.
if (queries.length <= 1) {
const singleQuery = queries.length === 1 ? queries[0] : null
// Offset must be the statement's start in the full text, not 0 — otherwise leading
diff --git a/playwright/e2e/sql-editor-typing-perf.spec.ts b/playwright/e2e/sql-editor-typing-perf.spec.ts
index 4312243df7e7..3e092d7e2f5d 100644
--- a/playwright/e2e/sql-editor-typing-perf.spec.ts
+++ b/playwright/e2e/sql-editor-typing-perf.spec.ts
@@ -3,14 +3,15 @@ import { Page } from '@playwright/test'
import { SqlInsight } from '../page-models/insights/sqlInsight'
import { expect, PlaywrightWorkspaceSetupResult, test } from '../utils/workspace-test-base'
-// Manual performance benchmark for typing latency in the SQL editor on a long query.
-// Not part of the CI suite (perf numbers are machine-dependent and would be flaky as an
-// assertion) — gated behind RUN_PERF_BENCH so it is skipped unless run explicitly:
+// Manual performance benchmarks for the SQL editor on a long query: typing latency, and
+// scroll latency. Not part of the CI suite (perf numbers are machine-dependent and would be
+// flaky as an assertion) — gated behind RUN_PERF_BENCH so they are skipped unless run
+// explicitly:
//
// RUN_PERF_BENCH=1 BASE_URL='http://localhost:8010' \
// pnpm --filter=@posthog/playwright exec playwright test sql-editor-typing-perf --workers 1
//
-// It types a fixed burst of keystrokes into a large query and reports main-thread long-task
+// Each test drives a fixed burst of input at a large query and reports main-thread long-task
// time via PerformanceObserver. To compare before/after a change, run it, `git stash` the
// change, run again, then `git stash pop` — the printed numbers are the result, not pass/fail.
@@ -19,6 +20,12 @@ const TYPE_MARKER = 'perfbenchmark'
const TYPE_CHARS = TYPE_MARKER.repeat(6) // 78 keystrokes
const TYPE_DELAY_MS = 40 // faster than the 150ms decoration debounce, so coalescing is visible
+// Monaco emits a scroll event per wheel tick. Ticks land faster than a 60fps frame so that
+// per-event work has to compete with painting, which is what makes coalescing measurable.
+const SCROLL_TICKS = 60
+const SCROLL_DELTA_PX = 120
+const SCROLL_TICK_DELAY_MS = 8
+
interface TypingStats {
// Primary: main-thread jank. A requestAnimationFrame loop runs during the burst; whenever a
// frame is delayed past 16.7ms the main thread was too busy to paint. frameBlockedMs sums
@@ -67,6 +74,24 @@ function buildLargeQuery(): string {
].join('\n')
}
+// The scroll benchmark needs a different shape of query than the typing one. The active-query
+// outline overlay is repositioned on every scroll event and has to bound its whole range, so the
+// cost scales with how many lines that range covers. The range is the *innermost SELECT
+// containing the cursor* — and `findInnermostSelectAtOffset` returns null unless at least two
+// SELECTs enclose the cursor, so a flat top-level query draws no outline at all and would measure
+// nothing. Hence: a trivial outer SELECT wrapping a very long inner one, with the cursor parked
+// inside the inner one. Must be syntactically valid HogQL or the outline never resolves; unknown
+// column names are fine, since this only needs to parse, not resolve.
+const SCROLL_QUERY_LINES = 900
+
+function buildNestedLongQuery(): string {
+ const columns = Array.from({ length: SCROLL_QUERY_LINES }, (_, i) => ` sum(metric_${i}) AS agg_${i}`).join(
+ ',\n'
+ )
+
+ return `SELECT sub.agg_0\nFROM (\n SELECT\n${columns}\n FROM events\n) AS sub`
+}
+
async function startMeasuring(page: Page): Promise<void> {
await page.evaluate(() => {
const w = window as any
@@ -132,7 +157,7 @@ async function goToSqlEditor(page: Page): Promise<void> {
.catch(() => {})
}
-test.describe('SQL editor typing performance', () => {
+test.describe('SQL editor performance', () => {
test.describe.configure({ mode: 'serial' })
test.setTimeout(180000)
test.skip(!process.env.RUN_PERF_BENCH, 'Perf benchmark — run manually with RUN_PERF_BENCH=1')
@@ -183,4 +208,59 @@ test.describe('SQL editor typing performance', () => {
console.log(`\n[SQL editor typing perf] ${summary}\n`)
})
})
+
+ test('measure main-thread blocking while scrolling a long query', async ({ page }, testInfo) => {
+ const editorArea = page.getByTestId('hogql-query-editor')
+
+ await test.step('load a long nested query into the editor', async () => {
+ // Load via the editor's own `q` hash param instead of typing the query in. The editor
+ // restores whichever query was last open, so writing into it is not reproducible — a
+ // stale (and much larger) document from an earlier run gets measured instead.
+ await page.goto('/sql#q=' + encodeURIComponent(buildNestedLongQuery()))
+ await expect(page.getByTestId('editor-scene')).toBeVisible({ timeout: 60000 })
+ await expect(editorArea).toBeVisible()
+ // Let the initial parse + metadata request settle so warm-up cost is not measured.
+ await page.waitForTimeout(3000)
+ })
+
+ await test.step('put the cursor inside the long inner SELECT', async () => {
+ // Lines are: 1 `SELECT sub.agg_0`, 2 `FROM (`, 3 `SELECT`, 4+ the columns. Landing on
+ // line 5 puts the cursor inside the inner SELECT, so the outline spans ~900 lines.
+ await editorArea.click()
+ await page.keyboard.press('ControlOrMeta+Home')
+ for (let i = 0; i < 4; i++) {
+ await page.keyboard.press('ArrowDown')
+ }
+ await page.keyboard.press('End')
+ })
+
+ await test.step('confirm the active-query outline is showing', async () => {
+ // Without an active outline the scroll handler early-returns and this benchmark
+ // measures nothing at all, so fail loudly rather than print a misleading 0.
+ const outline = editorArea.locator('.active-query-outline')
+ await expect(outline).toBeVisible({ timeout: 15000 })
+ })
+
+ await test.step('scroll a fixed burst and measure main-thread blocking', async () => {
+ const box = await editorArea.boundingBox()
+ expect(box).not.toBeNull()
+ await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2)
+
+ await startMeasuring(page)
+ for (let i = 0; i < SCROLL_TICKS; i++) {
+ await page.mouse.wheel(0, SCROLL_DELTA_PX)
+ await page.waitForTimeout(SCROLL_TICK_DELAY_MS)
+ }
+ await page.waitForTimeout(600) // let any trailing work run
+ const stats = await stopMeasuring(page)
+
+ const summary =
+ `wheelTicks=${SCROLL_TICKS} ` +
+ `frameBlockedMs=${stats.frameBlockedMs} maxFrameGapMs=${stats.maxFrameGapMs} ` +
+ `frames=${stats.frames} eventMaxMs=${stats.eventMaxMs} longTasks=${stats.longTasks}`
+ testInfo.annotations.push({ type: 'scroll-perf', description: summary })
+ // eslint-disable-next-line no-console
+ console.log(`\n[SQL editor scroll perf] ${summary}\n`)
+ })
+ })
})