: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(sql-editor): stop long queries freezing the editor on every keystroke (#80144)
Kyle Swanka49aba8b331e
diff --git a/frontend/bin/bench-sql-editor.mjs b/frontend/bin/bench-sql-editor.mjsnew file mode 100644index 000000000000..2f9818dc80a1--- /dev/null+++ b/frontend/bin/bench-sql-editor.mjs@@ -0,0 +1,275 @@+// Before/after benchmark for the SQL editor on a long query. Measures user-visible main-thread+// blocking on the three paths that matter, so a fix can be shown to help the edit/cursor paths+// without regressing the scroll path that PR #78998 fixed.+//+// Needs a local Storybook on :6006 (pnpm storybook).+// node frontend/bin/bench-sql-editor.mjs --lines 900+//+// Reports, per phase, `blockedMs` (sum of each frame gap over the 16.7ms budget) and `maxGapMs`+// (the longest single stall — the number a user actually feels as a freeze).+import { readFileSync } from 'node:fs'+import { chromium } from 'playwright'++const args = Object.fromEntries(+ process.argv+ .slice(2)+ .join(' ')+ .split('--')+ .filter(Boolean)+ .map((s) => s.trim().split(/\s+/))+ .map(([k, v]) => [k, v ?? 'true'])+)+const LINES = parseInt(args.lines ?? '900', 10)+const SCROLL_TICKS = 60+// Storybook serves the app from vite, but the parser worker is a separate esbuild bundle served+// from /static in production, so Storybook 404s it and the manager silently falls back to the main+// thread. Serve a prebuilt bundle to the page so the worker path is the one measured. Build it with:+// node_modules/.pnpm/esbuild@*/node_modules/esbuild/bin/esbuild \+// frontend/src/scenes/data-warehouse/editor/hogqlParserWorker.ts \+// --bundle --format=esm --outfile=/tmp/hogqlParserWorker.js+// Pass --no-worker to skip that and measure the fallback instead.+const WORKER_BUNDLE = args['no-worker'] ? null : (args.worker ?? '/tmp/hogqlParserWorker.js')++const STORY =+ 'http://localhost:6006/iframe.html?id=scenes-app-data-warehouse-sql-editor--top-tools-per-server&viewMode=story'++// A trivial outer SELECT wrapping one very long inner SELECT, so two SELECTs enclose the cursor+// and the active-query outline draws (findInnermostSelectAtOffset returns null otherwise).+// The `-- edit target` line sits *inside* the inner SELECT: typing there keeps the query valid+// (an invalid query makes the parser fail fast and hides the very cost we are measuring) and+// keeps the cursor inside the inner SELECT so the outline stays up.+function buildQuery(lines) {+ const columns = Array.from({ length: lines }, (_, i) => ` sum(metric_${i}) AS agg_${i}`).join(',\n')+ return `SELECT sub.agg_0\nFROM (\n SELECT\n${columns}\n -- edit target\n FROM events\n) AS sub`+}++const sleep = (ms) => new Promise((r) => setTimeout(r, ms))+const FRAME_BUDGET = 1000 / 60++async function main() {+ const browser = await chromium.launch()+ const context = await browser.newContext({+ viewport: { width: 1600, height: 900 },+ permissions: ['clipboard-read', 'clipboard-write'],+ })+ const page = await context.newPage()+ await page.addInitScript(() => {+ window.__PERF_MONACO_HOOK__ = true+ })++ // Track worker creation so a silent fallback to the main thread cannot be mistaken for a fix.+ const createdWorkerUrls = []+ page.on('worker', (w) => createdWorkerUrls.push(w.url()))++ let workerBundleServed = 0+ if (WORKER_BUNDLE) {+ const body = readFileSync(WORKER_BUNDLE, 'utf8')+ await page.route('**/hogqlParserWorker.js', async (route) => {+ workerBundleServed+++ await route.fulfill({ body, contentType: 'text/javascript' })+ })+ }++ await page.goto(STORY, { waitUntil: 'load', timeout: 120000 })+ await page.waitForSelector('.monaco-editor', { timeout: 120000 })+ await page.waitForFunction(() => (window.__monacoEditors ?? []).length > 0, { timeout: 60000 })++ await page.evaluate(() => {+ const w = window+ w.__ed = () => w.__monacoEditors[w.__monacoEditors.length - 1]+ // Resolve once N consecutive frames come in under budget, i.e. the main thread went idle.+ w.__quiesce = (frames = 30, maxGapMs = 20, timeoutMs = 60000) =>+ new Promise((resolve) => {+ const start = performance.now()+ let quiet = 0+ let last = performance.now()+ const step = (t) => {+ const gap = t - last+ last = t+ quiet = gap <= maxGapMs ? quiet + 1 : 0+ if (quiet >= frames || performance.now() - start > timeoutMs) {+ resolve(Math.round(performance.now() - start))+ return+ }+ requestAnimationFrame(step)+ }+ requestAnimationFrame(step)+ })+ w.__start = () => {+ w.__frames = []+ w.__marks = []+ w.__mark = (label) => w.__marks.push({ label, t: performance.now() })+ const loop = (t) => {+ w.__frames.push(t)+ w.__raf = requestAnimationFrame(loop)+ }+ w.__raf = requestAnimationFrame(loop)+ }+ w.__stop = () => {+ cancelAnimationFrame(w.__raf)+ return { frames: w.__frames, marks: w.__marks }+ }+ })++ // Load the fixture by clipboard paste. keyboard.insertText is treated as typed input, so+ // Monaco re-indents every line and the indentation compounds (a 32KB fixture lands as a 3.2MB+ // document of whitespace); setValue/executeEdits gets reverted because `value` is kea-controlled.+ const query = buildQuery(LINES)+ for (let attempt = 1; attempt <= 4; attempt++) {+ await page.evaluate(async (q) => await navigator.clipboard.writeText(q), query)+ await page.evaluate(() => window.__ed().focus())+ await sleep(300)+ await page.keyboard.press('ControlOrMeta+a')+ await page.keyboard.press('ControlOrMeta+v')+ try {+ await page.waitForFunction((n) => window.__ed().getModel().getValueLength() === n, query.length, {+ timeout: 20000,+ })+ break+ } catch {+ if (attempt === 4) {+ throw new Error('fixture never landed cleanly')+ }+ }+ }++ // Park the cursor at the end of the `-- edit target` line, inside the inner SELECT.+ const editLine = query.split('\n').findIndex((l) => l.includes('-- edit target')) + 1+ await page.evaluate((line) => {+ const ed = window.__ed()+ ed.focus()+ ed.setPosition({ lineNumber: line, column: ed.getModel().getLineMaxColumn(line) })+ }, editLine)++ // Wait for the outline itself, not for the main thread to go quiet. Once the parse runs in a+ // worker the main thread goes quiet almost immediately, long before the result arrives.+ await page+ .waitForFunction(() => document.querySelector('.active-query-outline')?.style.display === 'block', undefined, {+ timeout: 120000,+ })+ .catch(() => {})+ await page.evaluate(() => window.__quiesce(45, 20, 120000))+ await sleep(1000)++ const outline = await page.evaluate(() => {+ const n = document.querySelector('.active-query-outline')+ return n ? { display: n.style.display, height: n.style.height } : null+ })+ if (outline?.display !== 'block') {+ throw new Error(`no outline drawn — benchmark would measure the wrong thing: ${JSON.stringify(outline)}`)+ }++ await page.evaluate(() => window.__start())++ // Phase 1 — cursor move only, no edit. Nothing about the document changed.+ await page.evaluate(() => window.__quiesce())+ await page.evaluate(() => window.__mark('cursor-move'))+ await page.keyboard.press('ArrowUp')+ const cursorQuiesceMs = await page.evaluate(() => window.__quiesce())++ // Phase 2 — one keystroke inside the comment, document stays valid. Moving the parse off the+ // main thread trades a freeze for latency, so time how long the outline takes to catch up too.+ // Re-park the cursor at the end of the edit-target comment. Phase 1's ArrowUp leaves it partway+ // along a much longer column line, and pressing Enter there splits an expression in two, which+ // makes the query invalid — the parser then fails fast and the phase measures nothing.+ await page.evaluate((line) => {+ const ed = window.__ed()+ ed.focus()+ ed.setPosition({ lineNumber: line, column: ed.getModel().getLineMaxColumn(line) })+ }, editLine)+ await page.evaluate(() => window.__quiesce())+ await sleep(1500)++ // Pressing Enter adds a line inside the inner SELECT, so the outline's own height has to grow+ // by one line. Watching for that (rather than any style change, which a scroll also causes)+ // is what proves the parse result actually came back and was applied.+ const heightBeforeEdit = await page.evaluate(() => document.querySelector('.active-query-outline').style.height)+ await page.evaluate(() => window.__mark('edit'))+ const editAt = Date.now()+ await page.keyboard.press('Enter')+ const editQuiesceMs = await page.evaluate(() => window.__quiesce())+ let outlineUpdateMs = null+ for (let i = 0; i < 300; i++) {+ const h = await page.evaluate(() => document.querySelector('.active-query-outline').style.height)+ if (h !== heightBeforeEdit) {+ outlineUpdateMs = Date.now() - editAt+ break+ }+ await sleep(100)+ }++ // Phase 3 — the scroll burst PR #78998 fixed. Must not regress.+ await page.evaluate(() => window.__ed().setScrollTop(0))+ await sleep(500)+ const box = await page.locator('.monaco-editor').first().boundingBox()+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2)+ await page.evaluate(() => window.__quiesce())+ for (let i = 0; i < SCROLL_TICKS; i++) {+ await page.evaluate((n) => window.__mark(`scroll-${n}`), i)+ await page.mouse.wheel(0, 120)+ await sleep(8)+ }+ await page.evaluate(() => window.__mark('scroll-end'))+ await sleep(600)++ const raw = await page.evaluate(() => window.__stop())+ await browser.close()++ const slice = (from, to) => {+ let blocked = 0+ let maxGap = 0+ for (let i = 1; i < raw.frames.length; i++) {+ const t = raw.frames[i]+ if (t < from || t > to) {+ continue+ }+ const gap = raw.frames[i] - raw.frames[i - 1]+ blocked += Math.max(0, gap - FRAME_BUDGET)+ maxGap = Math.max(maxGap, gap)+ }+ return { blockedMs: Math.round(blocked), maxGapMs: Math.round(maxGap) }+ }+ const at = (label) => raw.marks.find((m) => m.label === label)?.t+ const seg = (label, next) => slice(at(label), next ? at(next) : Infinity)++ const scrollTicks = Array.from({ length: SCROLL_TICKS }, (_, i) =>+ slice(at(`scroll-${i}`), at(i === SCROLL_TICKS - 1 ? 'scroll-end' : `scroll-${i + 1}`))+ )+ const scrollTotal = scrollTicks.reduce((a, s) => a + s.blockedMs, 0)++ console.info(+ JSON.stringify(+ {+ lines: LINES,+ chars: query.length,+ outlineHeight: outline.height,+ parserWorker: {+ requested: !!WORKER_BUNDLE,+ bundleServed: workerBundleServed,+ created: createdWorkerUrls.filter((u) => u.includes('hogqlParserWorker')).length,+ },+ cursorMove: { ...seg('cursor-move', 'edit'), settleMs: cursorQuiesceMs },+ edit: {+ ...seg('edit', 'scroll-0'),+ settleMs: editQuiesceMs,+ // How long until the outline reflects the edit. Blocking work makes this small+ // but freezes the UI; off-thread work makes it larger and keeps the UI alive.+ outlineUpdateMs,+ },+ scroll: {+ blockedMs: scrollTotal,+ maxGapMs: Math.max(...scrollTicks.map((s) => s.maxGapMs)),+ firstTickBlockedMs: scrollTicks[0].blockedMs,+ steadyBlockedMs: scrollTotal - scrollTicks[0].blockedMs,+ },+ },+ null,+ 1+ )+ )+}++main().catch((e) => {+ console.error('FAILED:', e.message)+ process.exit(1)+})diff --git a/frontend/bin/diagnose-first-scroll.mjs b/frontend/bin/diagnose-first-scroll.mjsnew file mode 100644index 000000000000..b3eab5d58a51--- /dev/null+++ b/frontend/bin/diagnose-first-scroll.mjs@@ -0,0 +1,376 @@+// Diagnostic driver for the SQL editor "initial scroll delay". Not part of any suite —+// throwaway harness, run against a local Storybook (pnpm storybook) on :6006.+//+// node frontend/bin/diagnose-first-scroll.mjs --lines 900 --arm baseline+//+// Arms: baseline | no-outline | no-sticky | no-folding | no-wrap | stub-hpos | stub-vpos | no-border+import { chromium } from 'playwright'++const args = Object.fromEntries(+ process.argv+ .slice(2)+ .join(' ')+ .split('--')+ .filter(Boolean)+ .map((s) => s.trim().split(/\s+/))+ .map(([k, v]) => [k, v ?? 'true'])+)+const LINES = parseInt(args.lines ?? '900', 10)+const ARM = args.arm ?? 'baseline'+const PROFILE = args.profile === 'true'++const STORY =+ 'http://localhost:6006/iframe.html?id=scenes-app-data-warehouse-sql-editor--top-tools-per-server&viewMode=story'++// Same shape as the playwright benchmark fixture: a trivial outer SELECT wrapping one very long+// inner SELECT, so `findInnermostSelectAtOffset` finds two enclosing SELECTs and the outline draws.+// Leading comment line is an autocomplete-safe place to type.+function buildQuery(lines) {+ const columns = Array.from({ length: lines }, (_, i) => ` sum(metric_${i}) AS agg_${i}`).join(',\n')+ return `-- edit target top\nSELECT sub.agg_0\nFROM (\n SELECT\n${columns}\n FROM events\n) AS sub`+}++const sleep = (ms) => new Promise((r) => setTimeout(r, ms))++async function main() {+ const browser = await chromium.launch()+ const context = await browser.newContext({+ viewport: { width: 1600, height: 900 },+ permissions: ['clipboard-read', 'clipboard-write'],+ })+ const page = await context.newPage()++ await page.addInitScript(() => {+ window.__PERF_MONACO_HOOK__ = true+ })+ if (ARM === 'no-mutobs') {+ await page.addInitScript(() => {+ const orig = MutationObserver.prototype.observe+ MutationObserver.prototype.observe = function (target, opts) {+ if (target === document.body && opts?.subtree && opts?.childList) {+ return+ }+ return orig.call(this, target, opts)+ }+ })+ }++ const errors = []+ page.on('pageerror', (e) => errors.push(String(e)))++ await page.goto(STORY, { waitUntil: 'load', timeout: 120000 })+ await page.waitForSelector('.monaco-editor', { timeout: 120000 })+ await page.waitForFunction(() => (window.__monacoEditors ?? []).length > 0, { timeout: 60000 })++ // In-page helpers.+ await page.evaluate(() => {+ const w = window+ w.__ed = () => w.__monacoEditors[w.__monacoEditors.length - 1]+ w.__quiesce = (frames = 30, maxGapMs = 20, timeoutMs = 20000) =>+ new Promise((resolve) => {+ const start = performance.now()+ let quiet = 0+ let last = performance.now()+ const step = (t) => {+ const gap = t - last+ last = t+ quiet = gap <= maxGapMs ? quiet + 1 : 0+ if (quiet >= frames || performance.now() - start > timeoutMs) {+ resolve(Math.round(performance.now() - start))+ return+ }+ requestAnimationFrame(step)+ }+ requestAnimationFrame(step)+ })+ w.__start = () => {+ w.__frames = []+ w.__marks = []+ w.__longTasks = []+ w.__mark = (label) => w.__marks.push({ label, t: performance.now() })+ const loop = (t) => {+ w.__frames.push(t)+ w.__raf = requestAnimationFrame(loop)+ }+ w.__raf = requestAnimationFrame(loop)+ w.__ltObs = new PerformanceObserver((l) => {+ for (const e of l.getEntries()) {+ w.__longTasks.push({ startTime: e.startTime, duration: e.duration })+ }+ })+ w.__ltObs.observe({ type: 'longtask' })+ }+ w.__stop = () => {+ cancelAnimationFrame(w.__raf)+ w.__ltObs?.disconnect()+ return { frames: w.__frames, marks: w.__marks, longTasks: w.__longTasks }+ }+ })++ // Load the fixture through the real edit path. Setting the model directly does not stick —+ // the editor's `value` prop is controlled by kea, so the next render reverts it. The paste+ // occasionally lands before Monaco has focus, so verify and retry.+ // Load the fixture by clipboard paste. The two obvious alternatives both fail: keyboard+ // insertText is treated as typed input, so Monaco re-indents every line and the indentation+ // compounds (a 32KB fixture lands as a 3.2MB document of leading whitespace), and+ // setValue/executeEdits gets reverted a beat later because the editor's `value` prop is+ // controlled by kea.+ const query = buildQuery(LINES)+ const wantChars = query.length+ for (let attempt = 1; attempt <= 4; attempt++) {+ await page.evaluate(async (q) => await navigator.clipboard.writeText(q), query)+ await page.evaluate(() => window.__ed().focus())+ await sleep(300)+ await page.keyboard.press('ControlOrMeta+a')+ await page.keyboard.press('ControlOrMeta+v')+ try {+ await page.waitForFunction((n) => window.__ed().getModel().getValueLength() === n, wantChars, {+ timeout: 15000,+ })+ break+ } catch {+ if (attempt === 4) {+ const got = await page.evaluate(() => window.__ed().getModel().getValueLength())+ throw new Error(`fixture never landed cleanly: wanted ${wantChars} chars, got ${got}`)+ }+ }+ }+ await page.evaluate(() => window.__quiesce(45, 20, 25000))+ await sleep(1500)++ // Park the cursor. Line 1 is the comment, 2 `SELECT sub.agg_0`, 3 `FROM (`, 4 `SELECT`,+ // 5+ the columns. Line 6 sits inside the inner SELECT (outline draws); line 2 sits in the+ // outer one only, where findInnermostSelectAtOffset returns null (no outline).+ const cursorLine = ARM === 'no-outline' ? 2 : 6+ await page.evaluate((line) => {+ const ed = window.__ed()+ ed.focus()+ ed.setPosition({ lineNumber: line, column: ed.getModel().getLineMaxColumn(line) })+ }, cursorLine)+ if (ARM !== 'no-outline') {+ await page+ .waitForFunction(+ () => document.querySelector('.active-query-outline')?.style.display === 'block',+ undefined,+ { timeout: 30000 }+ )+ .catch(() => {})+ }+ await sleep(1200)++ const outlineCount = await page.locator('.active-query-outline').count()+ const outlineBox = await page+ .evaluate(() => {+ const n = document.querySelector('.active-query-outline')+ return n ? { h: n.style.height, display: n.style.display } : null+ })+ .catch(() => null)+ if (ARM !== 'no-outline' && (!outlineCount || outlineBox?.display === 'none')) {+ const d = await page.evaluate(() => ({+ diag: window.__diag ?? 'decoration path NEVER RAN',+ lines: window.__ed().getModel().getLineCount(),+ pos: window.__ed().getPosition(),+ visible: window.__ed().getVisibleRanges(),+ }))+ throw new Error(+ `no active-query outline drawn (count=${outlineCount} box=${JSON.stringify(outlineBox)}) ${JSON.stringify(d)}`+ )+ }+ if (ARM === 'no-outline' && outlineBox && outlineBox.display !== 'none') {+ throw new Error('expected no outline for the no-outline arm')+ }++ // Arm-specific toggles.+ if (ARM === 'no-sticky') {+ await page.evaluate(() => window.__ed().updateOptions({ stickyScroll: { enabled: false } }))+ }+ if (ARM === 'no-folding') {+ await page.evaluate(() => window.__ed().updateOptions({ folding: false }))+ }+ if (ARM === 'no-wrap') {+ await page.evaluate(() => window.__ed().updateOptions({ wordWrap: 'off' }))+ }+ if (ARM === 'stub-hpos') {+ await page.evaluate(() => {+ window.__ed().getScrolledVisiblePosition = () => ({ left: 0, top: 0, height: 18 })+ })+ }+ if (ARM === 'stub-vpos') {+ await page.evaluate(() => {+ const ed = window.__ed()+ ed.getTopForPosition = () => 0+ ed.getBottomForLineNumber = () => 400+ })+ }+ if (ARM === 'no-border') {+ await page.addStyleTag({ content: '.active-query-outline { border: none !important; }' })+ }++ const editorArea = page.locator('.monaco-editor').first()+ const box = await editorArea.boundingBox()+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2)++ const threeFrames = () =>+ page.evaluate(+ () =>+ new Promise((r) =>+ requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(() => r())))+ )+ )++ // Instrument the editor methods renderQueryOutline calls, so a spike can be attributed to+ // one of them without a profile.+ await page.evaluate(() => {+ const ed = window.__ed()+ window.__t = {}+ for (const m of ['getScrolledVisiblePosition', 'getTopForPosition', 'getBottomForLineNumber']) {+ const orig = ed[m].bind(ed)+ window.__t[m] = { n: 0, ms: 0, max: 0 }+ ed[m] = (...a) => {+ const t0 = performance.now()+ try {+ return orig(...a)+ } finally {+ const d = performance.now() - t0+ const s = window.__t[m]+ s.n+++ s.ms += d+ if (d > s.max) {+ s.max = d+ }+ }+ }+ }+ })++ // ---- cold first tick, straight after load ----+ await page.evaluate(() => window.__start())+ await page.evaluate(() => window.__mark('cold-tick'))+ await page.mouse.wheel(0, 120)+ await threeFrames()+ // ---- warm up, then a warm single tick as the baseline ----+ for (let i = 0; i < 15; i++) {+ await page.mouse.wheel(0, 120)+ await sleep(8)+ }+ await page.evaluate(() => window.__quiesce())+ await page.evaluate(() => window.__mark('warm-tick'))+ await page.mouse.wheel(0, 120)+ await threeFrames()+ await page.evaluate(() => window.__quiesce())++ // ---- the edit, then a no-scroll window (E1), then the first post-edit tick ----+ await page.evaluate(() => (window.__tReset = JSON.parse(JSON.stringify(window.__t))))+ let profile = null+ let cdp = null+ if (PROFILE) {+ cdp = await context.newCDPSession(page)+ await cdp.send('Profiler.enable')+ await cdp.send('Profiler.setSamplingInterval', { interval: 50 })+ await cdp.send('Profiler.start')+ }+ await page.evaluate(() => window.__mark('edit'))+ await page.keyboard.type('x') // inside `... AS agg_N` — no space/dot, so no autocomplete+ await page.evaluate(() => window.__mark('post-edit-no-scroll'))+ await sleep(1500) // E1: does the spike land here, with zero wheel events?+ const quiesceMs = await page.evaluate(() => window.__quiesce())+ if (PROFILE) {+ // The profile brackets the keystroke and everything its debounces trigger — no scroll.+ profile = (await cdp.send('Profiler.stop')).profile+ }+ await page.evaluate(() => window.__mark('post-edit-tick-0'))+ await page.mouse.wheel(0, 120)+ await threeFrames()+ for (let i = 1; i <= 5; i++) {+ await page.evaluate((n) => window.__mark(`post-edit-tick-${n}`), i)+ await page.mouse.wheel(0, 120)+ await threeFrames()+ }++ // A far jump reveals lines Monaco has never rendered or tokenized, unlike a 120px nudge.+ await page.evaluate(() => window.__quiesce())+ await page.evaluate(() => window.__mark('warm-bigjump'))+ await page.mouse.wheel(0, 20000)+ await threeFrames()+ await page.evaluate(() => window.__quiesce())+ await page.evaluate(() => window.__mark('edit2'))+ await page.keyboard.type('y')+ await page.evaluate(() => window.__quiesce())+ await page.evaluate(() => window.__mark('post-edit-bigjump'))+ await page.mouse.wheel(0, 20000)+ await threeFrames()+ await sleep(400)++ const raw = await page.evaluate(() => window.__stop())+ const methodTimes = await page.evaluate(() => ({ all: window.__t, atEdit: window.__tReset }))+ const parseTimes = await page.evaluate(() => window.__parseTimes ?? [])+ await browser.close()++ // ---- attribution ----+ const FRAME_BUDGET = 1000 / 60+ const slice = (from, to) => {+ let blocked = 0+ let maxGap = 0+ let n = 0+ for (let i = 1; i < raw.frames.length; i++) {+ const t = raw.frames[i]+ if (t < from || t > to) {+ continue+ }+ const gap = raw.frames[i] - raw.frames[i - 1]+ blocked += Math.max(0, gap - FRAME_BUDGET)+ maxGap = Math.max(maxGap, gap)+ n+++ }+ return { blockedMs: Math.round(blocked), maxGapMs: Math.round(maxGap), frames: n }+ }+ const segments = {}+ for (let i = 0; i < raw.marks.length; i++) {+ const from = raw.marks[i].t+ const to = raw.marks[i + 1]?.t ?? Infinity+ segments[raw.marks[i].label] = slice(from, to)+ }+ const perMethod = {}+ for (const k of Object.keys(methodTimes.all)) {+ perMethod[k] = {+ calls: methodTimes.all[k].n - methodTimes.atEdit[k].n,+ ms: +(methodTimes.all[k].ms - methodTimes.atEdit[k].ms).toFixed(2),+ maxMs: +methodTimes.all[k].max.toFixed(2),+ }+ }++ const out = {+ lines: LINES,+ arm: ARM,+ outlineHeight: outlineBox?.h ?? null,+ quiesceAfterEditMs: quiesceMs,+ segments,+ longTasks: raw.longTasks.map((l) => Math.round(l.duration)),+ methodTimesSinceEdit: perMethod,+ pageErrors: errors.slice(0, 3),+ parseTimes,+ }+ if (profile) {+ const byId = new Map(profile.nodes.map((n) => [n.id, n]))+ const self = new Map()+ for (let i = 0; i < profile.samples.length; i++) {+ const n = byId.get(profile.samples[i])+ if (!n) {+ continue+ }+ const cf = n.callFrame+ const key = `${cf.functionName || '(anon)'} @ ${(cf.url || '').split('/').pop()}:${cf.lineNumber}`+ self.set(key, (self.get(key) ?? 0) + (profile.timeDeltas[i] ?? 0) / 1000)+ }+ out.selfTimeTop = [...self]+ .map(([fn, ms]) => ({ fn, ms: +ms.toFixed(1) }))+ .sort((a, b) => b.ms - a.ms)+ .slice(0, 25)+ }+ console.info(JSON.stringify(out, null, 1))+}++main().catch((e) => {+ console.error('FAILED:', e.message)+ process.exit(1)+})diff --git a/frontend/bin/watch-workers.mjs b/frontend/bin/watch-workers.mjsnew file mode 100644index 000000000000..1061273f42b6--- /dev/null+++ b/frontend/bin/watch-workers.mjs@@ -0,0 +1,31 @@+#!/usr/bin/env node+// Build the web workers into dist/ and keep them fresh, for the Vite dev server.+//+// Vite serves the app in dev but never builds these — they are separate esbuild bundles the app+// loads by URL from /static (which Vite proxies to Django, which serves dist/). Without this,+// dist/ has no worker files at all locally, every `new Worker(...)` 404s, and each caller quietly+// falls back to doing its work on the main thread. That hides exactly the jank the workers exist+// to prevent, and it only shows up in production.+//+// Pass --dev to watch. Entry points come from workers.config.mjs, shared with the production build.+import * as path from 'path'+import { fileURLToPath } from 'url'++import { buildInParallel } from '@posthog/esbuilder'++import { WORKER_ENTRIES } from '../workers.config.mjs'++const __dirname = path.dirname(fileURLToPath(import.meta.url))+const frontendDir = path.resolve(__dirname, '..')++await buildInParallel(+ WORKER_ENTRIES.map(({ name, entryPoint, outfileName }) => ({+ name,+ absWorkingDir: frontendDir,+ entryPoints: [entryPoint],+ outfile: path.resolve(frontendDir, 'dist', outfileName),+ bundle: true,+ format: 'esm',+ writeMetaFile: false,+ }))+)diff --git a/frontend/build.mjs b/frontend/build.mjsindex 1ac2390eafc4..ce0ded138cc9 100755--- a/frontend/build.mjs+++ b/frontend/build.mjs@@ -16,6 +16,7 @@ import {} from '@posthog/esbuilder'import { finalizeToolbarBuild, getToolbarAppBuildConfig } from './toolbar-config.mjs'+import { WORKER_ENTRIES } from './workers.config.mjs'export const __dirname = path.dirname(fileURLToPath(import.meta.url))@@ -55,34 +56,13 @@ await buildInParallel(heavy: true,...common,},- {- name: 'Decompression Worker',- entryPoints: ['src/scenes/session-recordings/player/snapshot-processing/decompressionWorker.ts'],- format: 'esm',- outfile: path.resolve(__dirname, 'dist', 'decompressionWorker.js'),- ...common,- },- {- name: 'Monaco Editor Worker',- entryPoints: ['src/lib/monaco/workers/editor.worker.ts'],- format: 'esm',- outfile: path.resolve(__dirname, 'dist', 'monacoEditorWorker.js'),- ...common,- },- {- name: 'Monaco JSON Worker',- entryPoints: ['src/lib/monaco/workers/json.worker.ts'],+ ...WORKER_ENTRIES.map(({ name, entryPoint, outfileName }) => ({+ name,+ entryPoints: [entryPoint],format: 'esm',- outfile: path.resolve(__dirname, 'dist', 'monacoJsonWorker.js'),+ outfile: path.resolve(__dirname, 'dist', outfileName),...common,- },- {- name: 'Monaco TypeScript Worker',- entryPoints: ['src/lib/monaco/workers/ts.worker.ts'],- format: 'esm',- outfile: path.resolve(__dirname, 'dist', 'monacoTsWorker.js'),- ...common,- },+ })),{name: 'Exporter',entryPoints: {diff --git a/frontend/package.json b/frontend/package.jsonindex 41e499772500..75987429ca5f 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -48,7 +48,8 @@"check-toolbar-csp-eval": "node ./bin/check-toolbar-csp-eval.mjs","check-toolbar-graph": "node ./bin/check-toolbar-graph.mjs","check-toolbar-size": "node ./bin/check-toolbar-size.mjs",- "start-vite": "pnpm build:products && concurrently --kill-others-on-fail -n VITE,TOOLBAR -c green,magenta \"vite --host 0.0.0.0\" \"pnpm watch:toolbar\"",+ "start-vite": "pnpm build:products && concurrently --kill-others-on-fail -n VITE,TOOLBAR,WORKERS -c green,magenta,cyan \"vite --host 0.0.0.0\" \"pnpm watch:toolbar\" \"pnpm watch:workers\"",+ "watch:workers": "node ./bin/watch-workers.mjs --dev","watch:toolbar": "node ./bin/build-toolbar.mjs --dev","mobile-replay:web:schema:build:json": "ts-json-schema-generator -f ./tsconfig.json --path 'node_modules/posthog-js/dist/rrweb-types.d.ts' --type 'eventWithTime' --expose all --no-top-ref --no-type-check --out ./src/scenes/session-recordings/mobile-replay/schema/web/rr-web-schema.json && oxfmt ./src/scenes/session-recordings/mobile-replay/schema/web/rr-web-schema.json","mobile-replay:mobile:schema:build:json": "ts-json-schema-generator -f ./tsconfig.json --path './src/scenes/session-recordings/mobile-replay/mobile.types.ts' --type 'mobileEventWithTime' --expose all --no-top-ref --no-type-check --out ./src/scenes/session-recordings/mobile-replay/schema/mobile/rr-mobile-schema.json && oxfmt ./src/scenes/session-recordings/mobile-replay/schema/mobile/rr-mobile-schema.json",diff --git a/frontend/src/lib/monaco/CodeEditorImpl.tsx b/frontend/src/lib/monaco/CodeEditorImpl.tsxindex f1f7a7e9b100..479e39423840 100644--- a/frontend/src/lib/monaco/CodeEditorImpl.tsx+++ b/frontend/src/lib/monaco/CodeEditorImpl.tsx@@ -449,6 +449,13 @@ export function CodeEditor({}editorRef.current = editor+ // Perf-benchmark escape hatch. Monaco is otherwise unreachable from the page, so a+ // benchmark can neither time nor stub editor methods to isolate a cost. Inert unless a+ // harness sets the flag before load — see playwright/e2e/sql-editor-typing-perf.spec.ts.+ if ((window as any).__PERF_MONACO_HOOK__) {+ ;((window as any).__monacoEditors ??= []).push(editor)+ ;(window as any).__monaco = monaco+ }trackEditorModels(editor, monaco)setMonacoAndEditor([monaco, editor])initEditor(monaco, editor, editorProps, options ?? {}, builtCodeEditorLogic)diff --git a/frontend/src/scenes/data-warehouse/editor/hogqlAst.ts b/frontend/src/scenes/data-warehouse/editor/hogqlAst.tsnew file mode 100644index 000000000000..53a17fea429d--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/hogqlAst.ts@@ -0,0 +1,149 @@+import type { ASTNode } from '@posthog/hogql-parser'++// Walks over an already-parsed HogQL AST. Kept free of any parsing so the same code can run in+// the parser worker and in the main-thread fallback — the worker returns these small results+// instead of the AST itself, which runs to megabytes on a long query.++export interface AstRange {+ /** 0-based character offset within the parsed query text */+ start: number+ end: number+}++/**+ * Collect all SelectQuery/SelectSetQuery nodes whose position range contains the target offset.+ */+function collectSelectNodesAtOffset(node: unknown, targetOffset: number, results: ASTNode[]): void {+ if (node === null || node === undefined || typeof node !== 'object') {+ return+ }++ if (Array.isArray(node)) {+ for (const item of node) {+ collectSelectNodesAtOffset(item, targetOffset, results)+ }+ return+ }++ const astNode = node as ASTNode+ if (+ (astNode.node === 'SelectQuery' || astNode.node === 'SelectSetQuery') &&+ astNode.start?.offset != null &&+ astNode.end?.offset != null &&+ targetOffset >= astNode.start.offset &&+ targetOffset <= astNode.end.offset+ ) {+ results.push(astNode)+ }++ // Recurse into all object values+ for (const value of Object.values(astNode)) {+ if (typeof value === 'object' && value !== null) {+ collectSelectNodesAtOffset(value, targetOffset, results)+ }+ }+}++/**+ * Range of the innermost SELECT subquery containing the offset, or null when the offset is only+ * inside the outermost SELECT (no nesting).+ */+export function innermostSelectRangeFromAst(ast: ASTNode, localOffset: number): AstRange | null {+ if (ast.error || (ast.node !== 'SelectQuery' && ast.node !== 'SelectSetQuery')) {+ return null+ }++ const results: ASTNode[] = []+ collectSelectNodesAtOffset(ast, localOffset, results)++ // Need at least 2 matches (outer + inner) to have a subquery+ if (results.length < 2) {+ return null+ }++ // Pick the node with the smallest span. JSON key iteration order is not guaranteed+ // to produce children after siblings, so depth-by-order is unreliable — but for any+ // nested pair of SELECTs containing the cursor, the inner one always has a smaller+ // range than any ancestor.+ const innermost = results.reduce((smallest, candidate) => {+ const smallestSpan = smallest.end.offset - smallest.start.offset+ const candidateSpan = candidate.end.offset - candidate.start.offset+ return candidateSpan < smallestSpan ? candidate : smallest+ })++ return { start: innermost.start.offset, end: innermost.end.offset }+}++export const normalizeIdentifier = (identifier: string): string => {+ return identifier.replace(/[`"']/g, '').toLowerCase()+}++/** Collect all table names from a JoinExpr chain. */+const collectTablesFromJoinExpr = (joinExpr: ASTNode | null): string[] => {+ const tables: string[] = []+ let current = joinExpr+ while (current) {+ if (current.table?.node === 'Field') {+ tables.push((current.table.chain as string[]).join('.'))+ }+ current = current.next_join ?? null+ }+ return tables+}++/** Which columns of which selected tables the query's SELECT list references. */+export function tablesAndColumnsFromAst(ast: ASTNode): Record<string, Record<string, boolean>> {+ if (ast.error || ast.node !== 'SelectQuery') {+ return {}+ }++ const selectedTables = collectTablesFromJoinExpr(ast.select_from)+ if (selectedTables.length === 0) {+ return {}+ }++ const selectedColumnsByTable: Record<string, Record<string, boolean>> = {}+ const selectNodes: ASTNode[] = ast.select ?? []++ for (const node of selectNodes) {+ // Handle SELECT *+ if (node.node === 'Field' && node.chain.length === 1 && node.chain[0] === '*') {+ for (const table of selectedTables) {+ selectedColumnsByTable[table] = {+ '*': true,+ ...selectedColumnsByTable[table],+ }+ }+ continue+ }++ if (node.node === 'Field') {+ const chain = node.chain as string[]++ // table.column form+ if (chain.length >= 2) {+ const tablePrefix = chain.slice(0, -1).join('.')+ const col = chain[chain.length - 1]+ const tableKey = selectedTables.find(+ (table) => normalizeIdentifier(table) === normalizeIdentifier(tablePrefix)+ )+ if (tableKey) {+ selectedColumnsByTable[tableKey] = {+ [col]: true,+ ...selectedColumnsByTable[tableKey],+ }+ continue+ }+ }++ // Bare column — assign to first table+ const fallbackTable = selectedTables[0]+ selectedColumnsByTable[fallbackTable] = {+ [chain.join('.')]: true,+ ...selectedColumnsByTable[fallbackTable],+ }+ }+ }++ return selectedColumnsByTable+}diff --git a/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.test.ts b/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.test.tsnew file mode 100644index 000000000000..50083db9e893--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.test.ts@@ -0,0 +1,86 @@+// Parsing is a synchronous WASM call over the whole query — roughly 36ms per 1000 characters, so+// seconds on a long one. These cover the memoization that keeps it off the main thread when the+// text has not changed: without it, every cursor move in a long query re-parses the whole document+// and freezes the editor, and the decoration and table/column pipelines each pay for their own+// parse of the same text one debounce apart.+const parseSelectMock = jest.fn()+const initMock = jest.fn()++jest.mock('@posthog/hogql-parser', () => ({+ __esModule: true,+ default: () => {+ initMock()+ return Promise.resolve({ parseSelect: parseSelectMock })+ },+}))++describe('hogqlParserSingleton', () => {+ let parseSelect: (input: string, isInternal?: boolean) => Promise<string>++ beforeEach(async () => {+ jest.resetModules()+ parseSelectMock.mockReset()+ initMock.mockReset()+ parseSelectMock.mockImplementation((input: string) => `{"node":"SelectQuery","len":${input.length}}`)+ ;({ parseSelect } = await import('./hogqlParserSingleton'))+ })++ it('parses identical text once, however many times it is asked', async () => {+ // The cursor-move case: the editor re-requests a parse on every arrow key.+ const results = []+ for (let i = 0; i < 5; i++) {+ results.push(await parseSelect('SELECT 1 FROM events'))+ }++ expect(parseSelectMock).toHaveBeenCalledTimes(1)+ expect(new Set(results).size).toBe(1)+ })++ it('shares one parse between callers that ask while it is still running', async () => {+ // The decoration and table/column pipelines are ~50ms apart, far less than a long parse,+ // so the second caller arrives mid-flight. Caching resolved values alone would miss this.+ let release: (value: string) => void = () => {}+ parseSelectMock.mockImplementation(() => new Promise<string>((resolve) => (release = resolve)))++ const first = parseSelect('SELECT 1 FROM events')+ const second = parseSelect('SELECT 1 FROM events')+ // Both calls have to get past awaiting parser init before the underlying parse starts.+ await new Promise((resolve) => setTimeout(resolve, 0))+ release('{"node":"SelectQuery"}')++ expect(await first).toBe('{"node":"SelectQuery"}')+ expect(await second).toBe('{"node":"SelectQuery"}')+ expect(parseSelectMock).toHaveBeenCalledTimes(1)+ expect(initMock).toHaveBeenCalledTimes(1)+ })++ it.each([+ ['different text', 'SELECT 2 FROM events', undefined],+ ['the same text with a different isInternal', 'SELECT 1 FROM events', true],+ ])('parses again for %s', async (_label, input, isInternal) => {+ await parseSelect('SELECT 1 FROM events')+ await parseSelect(input, isInternal)++ expect(parseSelectMock).toHaveBeenCalledTimes(2)+ })++ it('retries after a failed parse instead of caching the rejection', async () => {+ parseSelectMock.mockRejectedValueOnce(new Error('boom'))++ await expect(parseSelect('SELECT 1 FROM events')).rejects.toThrow('boom')+ await expect(parseSelect('SELECT 1 FROM events')).resolves.toContain('SelectQuery')+ expect(parseSelectMock).toHaveBeenCalledTimes(2)+ })++ it('does not grow without bound as the query is edited', async () => {+ // Each cached entry retains the query text and an AST JSON roughly 12x its size, so the+ // cache has to forget old revisions rather than accumulate one per keystroke.+ for (let i = 0; i < 40; i++) {+ await parseSelect(`SELECT ${i} FROM events`)+ }+ // The oldest revision must have been evicted, so asking for it again re-parses.+ await parseSelect('SELECT 0 FROM events')++ expect(parseSelectMock).toHaveBeenCalledTimes(41)+ })+})diff --git a/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.ts b/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.tsindex d2ae643d3ba3..9cb25ebfaff3 100644--- a/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.ts+++ b/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.ts@@ -15,9 +15,51 @@ function getParser(): Promise<HogQLParser> {return parserPromise}-export async function parseSelect(input: string, isInternal?: boolean): Promise<string> {- const parser = await getParser()- return parser.parseSelect(input, isInternal)+// `parseSelect` is a synchronous WASM call over the whole query, so it blocks the main thread for+// roughly 36ms per 1000 characters — seconds on a long query. Two callers make that far worse than+// once per edit: the SQL editor re-parses on every cursor move even though the text has not+// changed, and its decoration and table/column pipelines parse the same text one debounce apart,+// so the second request arrives while the first parse is still running.+//+// Memoizing the last few results fixes both. The cache holds promises rather than resolved values+// so concurrent callers share one parse instead of racing. Entries are large (the AST JSON runs+// ~12x the query text), hence the small limit — the access pattern only ever needs the most recent+// text, so a bigger cache would cost memory without adding hits.+const PARSE_CACHE_LIMIT = 3++interface ParseCacheEntry {+ input: string+ isInternal: boolean+ result: Promise<string>+}++// Keyed by comparing the input directly rather than by building a composite key string: the inputs+// here are up to hundreds of KB, so hashing one on every lookup would be its own cost.+let parseSelectCache: ParseCacheEntry[] = []++export function parseSelect(input: string, isInternal?: boolean): Promise<string> {+ const normalizedIsInternal = !!isInternal+ const hitIndex = parseSelectCache.findIndex((e) => e.isInternal === normalizedIsInternal && e.input === input)+ if (hitIndex !== -1) {+ const [hit] = parseSelectCache.splice(hitIndex, 1)+ parseSelectCache.push(hit) // most-recently-used last+ return hit.result+ }++ const result = getParser()+ .then((parser) => parser.parseSelect(input, normalizedIsInternal))+ .catch((error) => {+ // A failed parse must not be cached — the next call should retry, and parser+ // initialization resets itself on failure.+ parseSelectCache = parseSelectCache.filter((e) => e.result !== result)+ throw error+ })++ parseSelectCache.push({ input, isInternal: normalizedIsInternal, result })+ if (parseSelectCache.length > PARSE_CACHE_LIMIT) {+ parseSelectCache.shift()+ }+ return result}export async function parseExpr(input: string, isInternal?: boolean): Promise<string> {diff --git a/frontend/src/scenes/data-warehouse/editor/hogqlParserWorker.ts b/frontend/src/scenes/data-warehouse/editor/hogqlParserWorker.tsnew file mode 100644index 000000000000..dc918d8363cb--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/hogqlParserWorker.ts@@ -0,0 +1,81 @@+import type { ASTNode } from '@posthog/hogql-parser'++import { type AstRange, innermostSelectRangeFromAst, tablesAndColumnsFromAst } from './hogqlAst'++// Parsing HogQL is a synchronous WASM call over the whole query — roughly 36ms per 1000+// characters, so seconds on a long one. On the main thread that freezes the editor after every+// edit, so it happens here instead.++export type HogqlParserQuestion =+ | { op: 'innermostSelect'; query: string; localOffset: number }+ | { op: 'tablesAndColumns'; query: string }++export type HogqlParserRequest = HogqlParserQuestion & { id: number }++export type HogqlParserResponse =+ | { type: 'ready' }+ | { id: number; result: AstRange | null | Record<string, Record<string, boolean>> }+ | { id: number; error: string }++let parserPromise: Promise<{ parseSelect: (input: string, isInternal?: boolean) => string }> | null = null++function getParser(): Promise<{ parseSelect: (input: string, isInternal?: boolean) => string }> {+ if (!parserPromise) {+ parserPromise = import('@posthog/hogql-parser')+ .then((mod) => mod.default())+ .catch((error) => {+ parserPromise = null // let the next request retry initialization+ throw error+ })+ }+ return parserPromise as Promise<{ parseSelect: (input: string, isInternal?: boolean) => string }>+}++// The two ops are driven by different debounces over the same text, and a cursor move re-asks for+// a range without changing the text at all. Holding the last AST here means those cost a walk+// instead of a parse — and the AST (megabytes of JSON) never has to reach the main thread.+let lastQuery: string | null = null+let lastAst: ASTNode | null = null++async function astFor(query: string): Promise<ASTNode | null> {+ if (lastQuery === query) {+ return lastAst+ }+ const parser = await getParser()+ let ast: ASTNode | null+ try {+ ast = JSON.parse(parser.parseSelect(query, false)) as ASTNode+ } catch {+ // Invalid SQL is expected while typing — cache the miss so we don't reparse it either.+ ast = null+ }+ lastQuery = query+ lastAst = ast+ return ast+}++self.onmessage = async (event: MessageEvent<HogqlParserRequest>): Promise<void> => {+ const request = event.data+ try {+ const ast = await astFor(request.query)+ if (!ast) {+ self.postMessage({+ id: request.id,+ result: request.op === 'innermostSelect' ? null : {},+ } satisfies HogqlParserResponse)+ return+ }+ const result =+ request.op === 'innermostSelect'+ ? innermostSelectRangeFromAst(ast, request.localOffset)+ : tablesAndColumnsFromAst(ast)+ self.postMessage({ id: request.id, result } satisfies HogqlParserResponse)+ } catch (error) {+ self.postMessage({+ id: request.id,+ error: error instanceof Error ? error.message : 'Unknown parser worker error',+ } satisfies HogqlParserResponse)+ }+}++self.postMessage({ type: 'ready' } satisfies HogqlParserResponse)diff --git a/frontend/src/scenes/data-warehouse/editor/hogqlParserWorkerManager.ts b/frontend/src/scenes/data-warehouse/editor/hogqlParserWorkerManager.tsnew file mode 100644index 000000000000..489884def8fb--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/hogqlParserWorkerManager.ts@@ -0,0 +1,138 @@+import { type AstRange, innermostSelectRangeFromAst, tablesAndColumnsFromAst } from './hogqlAst'+import { parseSelect } from './hogqlParserSingleton'+import type { HogqlParserQuestion, HogqlParserRequest, HogqlParserResponse } from './hogqlParserWorker'++// Runs the HogQL parse in a worker so a long query does not freeze the editor. Falls back to+// parsing on the main thread whenever the worker is unavailable — no Worker (jsdom), the bundle+// isn't served, init times out, or a request fails. The fallback is slow but correct, and it runs+// the same walkers as the worker, so behavior does not change with it.++const WORKER_URL = '/static/hogqlParserWorker.js'+const READY_TIMEOUT_MS = 5000+const REQUEST_TIMEOUT_MS = 60000++interface Pending {+ resolve: (value: any) => void+ reject: (error: Error) => void+ timer: ReturnType<typeof setTimeout>+}++let worker: Worker | null = null+let workerReady: Promise<Worker> | null = null+let workerUnavailable = false+let nextId = 0+const pending = new Map<number, Pending>()++function failAllPending(error: Error): void {+ for (const [, entry] of pending) {+ clearTimeout(entry.timer)+ entry.reject(error)+ }+ pending.clear()+}++function teardown(): void {+ worker?.terminate()+ worker = null+ workerReady = null+ workerUnavailable = true+}++function getWorker(): Promise<Worker> {+ if (workerReady) {+ return workerReady+ }++ workerReady = new Promise<Worker>((resolve, reject) => {+ if (typeof Worker === 'undefined') {+ reject(new Error('Worker is not available'))+ return+ }+ const created = new Worker(WORKER_URL, { type: 'module' })+ worker = created++ const timer = setTimeout(() => reject(new Error('Parser worker init timed out')), READY_TIMEOUT_MS)++ created.addEventListener('message', (event: MessageEvent<HogqlParserResponse>) => {+ const data = event.data+ if ('type' in data && data.type === 'ready') {+ clearTimeout(timer)+ resolve(created)+ return+ }+ if (!('id' in data)) {+ return+ }+ const entry = pending.get(data.id)+ if (!entry) {+ return+ }+ pending.delete(data.id)+ clearTimeout(entry.timer)+ if ('error' in data) {+ entry.reject(new Error(data.error))+ } else {+ entry.resolve(data.result)+ }+ })++ created.addEventListener('error', (event) => {+ clearTimeout(timer)+ const error = new Error(`Parser worker error: ${event.message}`)+ reject(error)+ failAllPending(error)+ teardown()+ })+ }).catch((error) => {+ teardown()+ throw error+ })++ return workerReady+}++async function ask(request: HogqlParserQuestion): Promise<any> {+ const active = await getWorker()+ const id = nextId+++ return await new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ pending.delete(id)+ reject(new Error('Parser worker request timed out'))+ }, REQUEST_TIMEOUT_MS)+ pending.set(id, { resolve, reject, timer })+ active.postMessage({ ...request, id } as HogqlParserRequest)+ })+}++/** Parse on the main thread. Blocks, so it is only for when the worker cannot be used. */+async function parseOnMainThread(query: string): Promise<any | null> {+ try {+ return JSON.parse(await parseSelect(query))+ } catch {+ return null+ }+}++export async function analyzeInnermostSelect(query: string, localOffset: number): Promise<AstRange | null> {+ if (!workerUnavailable) {+ try {+ return await ask({ op: 'innermostSelect', query, localOffset })+ } catch {+ // fall through to the main thread+ }+ }+ const ast = await parseOnMainThread(query)+ return ast ? innermostSelectRangeFromAst(ast, localOffset) : null+}++export async function analyzeTablesAndColumns(query: string): Promise<Record<string, Record<string, boolean>>> {+ if (!workerUnavailable) {+ try {+ return await ask({ op: 'tablesAndColumns', query })+ } catch {+ // fall through to the main thread+ }+ }+ const ast = await parseOnMainThread(query)+ return ast ? tablesAndColumnsFromAst(ast) : {}+}diff --git a/frontend/src/scenes/data-warehouse/editor/multiQueryUtils.ts b/frontend/src/scenes/data-warehouse/editor/multiQueryUtils.tsindex 6a2218be5f8d..e2d641e9a581 100644--- a/frontend/src/scenes/data-warehouse/editor/multiQueryUtils.ts+++ b/frontend/src/scenes/data-warehouse/editor/multiQueryUtils.ts@@ -1,6 +1,4 @@-import type { ASTNode } from '@posthog/hogql-parser'--import { parseSelect } from './hogqlParserSingleton'+import { analyzeInnermostSelect } from './hogqlParserWorkerManager'export interface QueryRange {/** The SQL text of this individual statement */@@ -152,41 +150,6 @@ export function findQueryAtCursor(queries: QueryRange[], cursorOffset: number):return best ?? queries[0]}-/**- * Recursively collect all SelectQuery/SelectSetQuery nodes from the AST- * whose position range contains the target offset.- */-function collectSelectNodesAtOffset(node: unknown, targetOffset: number, results: ASTNode[]): void {- if (node === null || node === undefined || typeof node !== 'object') {- return- }-- if (Array.isArray(node)) {- for (const item of node) {- collectSelectNodesAtOffset(item, targetOffset, results)- }- return- }-- const astNode = node as ASTNode- if (- (astNode.node === 'SelectQuery' || astNode.node === 'SelectSetQuery') &&- astNode.start?.offset != null &&- astNode.end?.offset != null &&- targetOffset >= astNode.start.offset &&- targetOffset <= astNode.end.offset- ) {- results.push(astNode)- }-- // Recurse into all object values- for (const value of Object.values(astNode)) {- if (typeof value === 'object' && value !== null) {- collectSelectNodesAtOffset(value, targetOffset, results)- }- }-}-/*** Find the innermost SELECT subquery at the given cursor offset within a query.* Returns null if the cursor is only in the outermost SELECT (no nesting).@@ -201,35 +164,15 @@ export async function findInnermostSelectAtOffset(queryStartOffset: number): Promise<QueryRange | null> {try {- const ast: ASTNode = JSON.parse(await parseSelect(query))- if (ast.error || (ast.node !== 'SelectQuery' && ast.node !== 'SelectSetQuery')) {+ const range = await analyzeInnermostSelect(query, cursorOffset - queryStartOffset)+ if (!range) {return null}- const localOffset = cursorOffset - queryStartOffset- const results: ASTNode[] = []- collectSelectNodesAtOffset(ast, localOffset, results)-- // Need at least 2 matches (outer + inner) to have a subquery- if (results.length < 2) {- return null- }-- // Pick the node with the smallest span. JSON key iteration order is not guaranteed- // to produce children after siblings, so depth-by-order is unreliable — but for any- // nested pair of SELECTs containing the cursor, the inner one always has a smaller- // range than any ancestor.- const innermost = results.reduce((smallest, candidate) => {- const smallestSpan = smallest.end.offset - smallest.start.offset- const candidateSpan = candidate.end.offset - candidate.start.offset- return candidateSpan < smallestSpan ? candidate : smallest- })- const text = query.slice(innermost.start.offset, innermost.end.offset)-return {- query: text,- start: queryStartOffset + innermost.start.offset,- end: queryStartOffset + innermost.end.offset,+ query: query.slice(range.start, range.end),+ start: queryStartOffset + range.start,+ end: queryStartOffset + range.end,}} catch {return nulldiff --git a/frontend/src/scenes/data-warehouse/editor/sql-utils.ts b/frontend/src/scenes/data-warehouse/editor/sql-utils.tsindex 622d5cccebe8..165b7c146f7d 100644--- a/frontend/src/scenes/data-warehouse/editor/sql-utils.ts+++ b/frontend/src/scenes/data-warehouse/editor/sql-utils.ts@@ -1,10 +1,6 @@-import type { ASTNode } from '@posthog/hogql-parser'+import { analyzeTablesAndColumns } from './hogqlParserWorkerManager'-import { parseSelect } from './hogqlParserSingleton'--export const normalizeIdentifier = (identifier: string): string => {- return identifier.replace(/[`"']/g, '').toLowerCase()-}+export { normalizeIdentifier } from './hogqlAst'export const queryUsesFiltersPlaceholder = (query: string | null): boolean => {if (!query) {@@ -66,91 +62,11 @@ export const queryUsesFiltersPlaceholder = (query: string | null): boolean => {return false}-/** Try to parse a SELECT query, returning the AST node or null on failure. */-const tryParseSelect = async (query: string): Promise<ASTNode | null> => {- try {- const result = JSON.parse(await parseSelect(query))- if (result.error || result.node !== 'SelectQuery') {- return null- }- return result as ASTNode- } catch {- return null- }-}--/** Collect all table names from a JoinExpr chain. */-const collectTablesFromJoinExpr = (joinExpr: ASTNode | null): string[] => {- const tables: string[] = []- let current = joinExpr- while (current) {- if (current.table?.node === 'Field') {- tables.push((current.table.chain as string[]).join('.'))- }- current = current.next_join ?? null- }- return tables-}-export const parseQueryTablesAndColumns = async (queryInput: string | null): Promise<Record<string, Record<string, boolean>>> => {if (!queryInput) {return {}}-- const ast = await tryParseSelect(queryInput)- if (!ast) {- return {}- }-- const selectedTables = collectTablesFromJoinExpr(ast.select_from)- if (selectedTables.length === 0) {- return {}- }-- const selectedColumnsByTable: Record<string, Record<string, boolean>> = {}- const selectNodes: ASTNode[] = ast.select ?? []-- for (const node of selectNodes) {- // Handle SELECT *- if (node.node === 'Field' && node.chain.length === 1 && node.chain[0] === '*') {- for (const table of selectedTables) {- selectedColumnsByTable[table] = {- '*': true,- ...selectedColumnsByTable[table],- }- }- continue- }-- if (node.node === 'Field') {- const chain = node.chain as string[]-- // table.column form- if (chain.length >= 2) {- const tablePrefix = chain.slice(0, -1).join('.')- const col = chain[chain.length - 1]- const tableKey = selectedTables.find(- (table) => normalizeIdentifier(table) === normalizeIdentifier(tablePrefix)- )- if (tableKey) {- selectedColumnsByTable[tableKey] = {- [col]: true,- ...selectedColumnsByTable[tableKey],- }- continue- }- }-- // Bare column — assign to first table- const fallbackTable = selectedTables[0]- selectedColumnsByTable[fallbackTable] = {- [chain.join('.')]: true,- ...selectedColumnsByTable[fallbackTable],- }- }- }-- return selectedColumnsByTable+ return await analyzeTablesAndColumns(queryInput)}diff --git a/frontend/workers.config.mjs b/frontend/workers.config.mjsnew file mode 100644index 000000000000..f7058d102d28--- /dev/null+++ b/frontend/workers.config.mjs@@ -0,0 +1,31 @@+// The web workers the app loads from /static at runtime, in one place so the production build+// (build.mjs) and the dev watcher (bin/watch-workers.mjs) cannot drift. Vite serves the app in+// dev but does not build these, so without the watcher they are simply absent locally and every+// worker silently falls back to the main thread.+export const WORKER_ENTRIES = [+ {+ name: 'Decompression Worker',+ entryPoint: 'src/scenes/session-recordings/player/snapshot-processing/decompressionWorker.ts',+ outfileName: 'decompressionWorker.js',+ },+ {+ name: 'HogQL Parser Worker',+ entryPoint: 'src/scenes/data-warehouse/editor/hogqlParserWorker.ts',+ outfileName: 'hogqlParserWorker.js',+ },+ {+ name: 'Monaco Editor Worker',+ entryPoint: 'src/lib/monaco/workers/editor.worker.ts',+ outfileName: 'monacoEditorWorker.js',+ },+ {+ name: 'Monaco JSON Worker',+ entryPoint: 'src/lib/monaco/workers/json.worker.ts',+ outfileName: 'monacoJsonWorker.js',+ },+ {+ name: 'Monaco TypeScript Worker',+ entryPoint: 'src/lib/monaco/workers/ts.worker.ts',+ outfileName: 'monacoTsWorker.js',+ },+]diff --git a/playwright/e2e/sql-editor-typing-perf.spec.ts b/playwright/e2e/sql-editor-typing-perf.spec.tsindex 3e092d7e2f5d..349da4172196 100644--- a/playwright/e2e/sql-editor-typing-perf.spec.ts+++ b/playwright/e2e/sql-editor-typing-perf.spec.ts@@ -37,6 +37,70 @@ interface TypingStats {// Secondary: worst single interaction latency + long-task count.eventMaxMs: numberlongTasks: number+ // Raw frame timestamps and labelled marks, so a single tick can be scored on its own. The+ // whole-burst aggregate above averages a one-off stall over 60 ticks and hides it — a 180ms+ // first tick reads as 3ms/tick, indistinguishable from noise.+ frameTimes: number[]+ marks: { label: string; t: number }[]+}++const FRAME_BUDGET_MS = 1000 / 60++/**+ * Blocked time and worst stall within a slice of the measured window. `frames` is reported so a+ * window that landed in the wrong place is obvious — a near-empty slice scores a flattering 0.+ */+function statsBetween(+ stats: TypingStats,+ from: number,+ to: number+): { blockedMs: number; maxGapMs: number; frames: number } {+ let blocked = 0+ let maxGap = 0+ let frames = 0+ for (let i = 1; i < stats.frameTimes.length; i++) {+ const t = stats.frameTimes[i]+ if (t < from || t > to) {+ continue+ }+ const gap = stats.frameTimes[i] - stats.frameTimes[i - 1]+ blocked += Math.max(0, gap - FRAME_BUDGET_MS)+ maxGap = Math.max(maxGap, gap)+ frames+++ }+ return { blockedMs: Math.round(blocked), maxGapMs: Math.round(maxGap), frames }+}++async function mark(page: Page, label: string): Promise<void> {+ await page.evaluate((l) => (window as any).__mark(l), label)+}++/**+ * Resolve once the main thread has been idle for `frames` consecutive frames, returning how long+ * that took. A fixed timeout either measures work that has not started yet or wastes time waiting;+ * the returned duration is itself a datum, being how long the editor stayed busy.+ */+async function waitForQuiescence(page: Page, frames = 30, maxGapMs = 20, timeoutMs = 30000): Promise<number> {+ return await page.evaluate(+ ([frameTarget, maxGap, timeout]) =>+ new Promise<number>((resolve) => {+ const start = performance.now()+ let quiet = 0+ let last = performance.now()+ const step = (t: number): void => {+ const gap = t - last+ last = t+ quiet = gap <= maxGap ? quiet + 1 : 0+ if (quiet >= frameTarget || performance.now() - start > timeout) {+ resolve(Math.round(performance.now() - start))+ return+ }+ requestAnimationFrame(step)+ }+ requestAnimationFrame(step)+ }),+ [frames, maxGapMs, timeoutMs]+ )}// Build a deterministic, large, deeply-nested query: 12 chained CTEs plus a 20-level nested@@ -98,6 +162,8 @@ async function startMeasuring(page: Page): Promise<void> {w.__frames = []w.__events = []w.__longTasks = []+ w.__marks = []+ w.__mark = (label: string): void => w.__marks.push({ label, t: performance.now() })const loop = (t: number): void => {w.__frames.push(t)w.__raf = requestAnimationFrame(loop)@@ -141,6 +207,8 @@ async function stopMeasuring(page: Page): Promise<TypingStats> {frames: frames.length,eventMaxMs: Math.round(events.length ? Math.max(...events) : 0),longTasks: (w.__longTasks || []).length,+ frameTimes: frames,+ marks: w.__marks || [],}})}@@ -157,6 +225,33 @@ async function goToSqlEditor(page: Page): Promise<void> {.catch(() => {})}+/**+ * Put the cursor immediately after the first occurrence of `needle`, via Monaco's own API.+ *+ * Keyboard navigation is not reliable for this: ControlOrMeta+End is Cmd+End on macOS, which Monaco+ * does not bind to end-of-document, so a "go to the end and walk up" sequence silently lands+ * somewhere near the top and the benchmark then edits whatever line it happened to find.+ */+async function placeCursorAfterText(page: Page, needle: string): Promise<number> {+ return await page.evaluate((text) => {+ const editor = (window as any).__monacoEditors?.at(-1)+ if (!editor) {+ throw new Error('Monaco handle missing — is __PERF_MONACO_HOOK__ set before load?')+ }+ const model = editor.getModel()+ for (let line = 1; line <= model.getLineCount(); line++) {+ const index = model.getLineContent(line).indexOf(text)+ if (index !== -1) {+ editor.focus()+ editor.setPosition({ lineNumber: line, column: index + text.length + 1 })+ editor.revealLineInCenter(line)+ return line+ }+ }+ throw new Error(`no line containing ${JSON.stringify(text)}`)+ }, needle)+}+test.describe('SQL editor performance', () => {test.describe.configure({ mode: 'serial' })test.setTimeout(180000)@@ -172,6 +267,11 @@ test.describe('SQL editor performance', () => {})test.beforeEach(async ({ page, playwrightSetup }) => {+ // Exposes the Monaco instance so the benchmarks can place the cursor exactly and time+ // editor methods. Must run before any navigation, since the app reads it as it mounts.+ await page.addInitScript(() => {+ ;(window as any).__PERF_MONACO_HOOK__ = true+ })await playwrightSetup.loginAndNavigateToTeam(page, workspace!)await goToSqlEditor(page)})@@ -183,7 +283,7 @@ test.describe('SQL editor performance', () => {await test.step('load the long query into the editor', async () => {await sqlInsight.writeQuery(buildLargeQuery())// Let the initial parse + metadata request settle so warm-up cost is not measured.- await page.waitForTimeout(2000)+ await waitForQuiescence(page)})await test.step('type a burst inside the leading comment and measure long tasks', async () => {@@ -220,18 +320,12 @@ test.describe('SQL editor performance', () => {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 waitForQuiescence(page)})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')+ // Anywhere inside the inner SELECT will do — the outline then spans its ~900 lines.+ await placeCursorAfterText(page, 'AS agg_0')})await test.step('confirm the active-query outline is showing', async () => {@@ -248,19 +342,111 @@ test.describe('SQL editor performance', () => {await startMeasuring(page)for (let i = 0; i < SCROLL_TICKS; i++) {+ await mark(page, `tick-${i}`)await page.mouse.wheel(0, SCROLL_DELTA_PX)await page.waitForTimeout(SCROLL_TICK_DELAY_MS)}+ await mark(page, 'tick-end')await page.waitForTimeout(600) // let any trailing work runconst stats = await stopMeasuring(page)+ // Score each tick on its own. The first tick after the editor has gone idle pays costs+ // the rest do not — a forced view render, a freshly invalidated layout — and the burst+ // total divides that by 60 until it looks like nothing.+ const markAt = (label: string): number => stats.marks.find((m) => m.label === label)?.t ?? 0+ const perTick = Array.from({ length: SCROLL_TICKS }, (_, i) =>+ statsBetween(stats, markAt(`tick-${i}`), markAt(i === SCROLL_TICKS - 1 ? 'tick-end' : `tick-${i + 1}`))+ )+ const firstTickBlockedMs = perTick[0].blockedMs+ const steadyBlockedMs = perTick.slice(1).reduce((sum, t) => sum + t.blockedMs, 0)+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 })+ const perTickSummary =+ `firstTickBlockedMs=${firstTickBlockedMs} steadyBlockedMs=${steadyBlockedMs} ` ++ `steadyPerTickMs=${(steadyBlockedMs / (SCROLL_TICKS - 1)).toFixed(1)} ` ++ `worstTickMs=${Math.max(...perTick.map((t) => t.blockedMs))}`+ testInfo.annotations.push({ type: 'scroll-perf', description: `${summary} ${perTickSummary}` })// eslint-disable-next-line no-console- console.log(`\n[SQL editor scroll perf] ${summary}\n`)+ console.log(`\n[SQL editor scroll perf] ${summary}\n[SQL editor scroll perf] ${perTickSummary}\n`)})})++ test('measure main-thread blocking on a cursor move and a single edit', async ({ page }, testInfo) => {+ // Both paths reach the HogQL parser, which runs over the whole query. A cursor move+ // changes no text at all, so any blocking there is pure waste; an edit has to reparse+ // once. Reported separately because they have different fixes and different budgets.+ const editorArea = page.getByTestId('hogql-query-editor')++ // Park just after the first column's alias, so the cursor-move phase's single ArrowDown+ // lands in the same column of the next line — the two lines are the same length — which is+ // just after `agg_1`. Typing there extends the alias to `agg_1x` and leaves the query valid.+ // That matters: an invalid query makes the parser fail fast, which reports as a perfect+ // score. (Appending at end-of-line instead would glue the character onto the *next*+ // column, which is exactly how this benchmark first measured a misleading zero.)+ // Note the outline only resolves with the cursor near the top of the range; the same+ // placement near the bottom leaves it hidden, which is worth a look on its own.++ await test.step('load a long nested query with the cursor inside the inner SELECT', async () => {+ await page.goto('/sql#q=' + encodeURIComponent(buildNestedLongQuery()))+ await expect(page.getByTestId('editor-scene')).toBeVisible({ timeout: 60000 })+ await expect(editorArea).toBeVisible()+ await waitForQuiescence(page)++ await placeCursorAfterText(page, 'AS agg_0')+ await expect(editorArea.locator('.active-query-outline')).toBeVisible({ timeout: 30000 })+ await waitForQuiescence(page)+ })++ await startMeasuring(page)++ // One action per phase, and the edit happens wherever the cursor move left us, so neither+ // phase has to reposition — repositioning is itself a cursor move, and its parse would land+ // in whichever window it happened to fall in.+ await test.step('move the cursor without changing any text', async () => {+ await mark(page, 'cursor-move')+ await page.keyboard.press('ArrowDown')+ await waitForQuiescence(page)+ })++ await test.step('type one character', async () => {+ await mark(page, 'edit')+ await page.keyboard.type('x')+ await waitForQuiescence(page)+ await mark(page, 'end')+ })++ const stats = await stopMeasuring(page)+ // A missing mark would silently produce a nonsense window (and a flattering 0), so refuse+ // to report rather than guess.+ const markAt = (label: string): number => {+ const found = stats.marks.find((m) => m.label === label)+ if (!found) {+ throw new Error(`benchmark mark '${label}' was never recorded`)+ }+ return found.t+ }+ const cursor = statsBetween(stats, markAt('cursor-move'), markAt('edit'))+ const edit = statsBetween(stats, markAt('edit'), markAt('end'))++ // Prove the keystroke landed where it was aimed. Without this an edit that missed the+ // editor — or hit the wrong line — reports as a perfect score. Checked against the model+ // rather than the DOM, since Monaco only renders the lines currently on screen.+ const edited = await page.evaluate(+ (needle) => (window as any).__monacoEditors.at(-1).getModel().getValue().includes(needle),+ 'AS agg_1x,'+ )+ expect(edited, 'expected the typed character to extend the alias on the agg_1 line').toBe(true)++ const summary =+ `queryLines=${SCROLL_QUERY_LINES} ` ++ `cursorMoveBlockedMs=${cursor.blockedMs} cursorMoveMaxGapMs=${cursor.maxGapMs} ` ++ `cursorMoveFrames=${cursor.frames} ` ++ `editBlockedMs=${edit.blockedMs} editMaxGapMs=${edit.maxGapMs} editFrames=${edit.frames}`+ testInfo.annotations.push({ type: 'edit-perf', description: summary })+ // eslint-disable-next-line no-console+ console.log(`\n[SQL editor edit perf] ${summary}\n`)+ })})diff --git a/playwright/e2e/sql-editor.spec.ts b/playwright/e2e/sql-editor.spec.tsindex 3d1946a63ef9..e200b3e8117a 100644--- a/playwright/e2e/sql-editor.spec.ts+++ b/playwright/e2e/sql-editor.spec.ts@@ -11,6 +11,9 @@ async function dismissQuickStart(page: Page): Promise<void> {}async function goToSqlEditor(page: Page): Promise<void> {+ await page.addInitScript(() => {+ ;(window as any).__PERF_MONACO_HOOK__ = true+ })await page.goto('/sql')await expect(page).toHaveURL(/\/sql(?:[?#].*)?$/)await expect(page.getByTestId('editor-scene')).toBeVisible({ timeout: 60000 })diff --git a/playwright/page-models/insights/sqlInsight.ts b/playwright/page-models/insights/sqlInsight.tsindex cac14fc5bfbf..1a2c73ad1c29 100644--- a/playwright/page-models/insights/sqlInsight.ts+++ b/playwright/page-models/insights/sqlInsight.ts@@ -19,11 +19,19 @@ export class SqlInsight {// CodeEditor lazy-loads monaco, so the container renders before the editor// mounts — clicking too early focuses nothing and insertText is lost.await editorArea.locator('[data-editor-ready="true"]').first().waitFor({ state: 'visible' })- await editorArea.click()- await this.page.keyboard.press('ControlOrMeta+a')- // Use insertText() to avoid Monaco autocomplete intercepting keystrokes- // during character-by-character typing (space is a trigger character).- await this.page.keyboard.insertText(query)++ // Monaco treats insertText as typed input, so autocomplete and auto-indent can corrupt a+ // large query. Its paste command updates the controlled model while inserting text verbatim.+ await this.page.evaluate((text) => {+ const editor = (window as any).__monacoEditors?.at(-1)+ const model = editor?.getModel()+ if (!editor || !model) {+ throw new Error('Monaco handle missing')+ }+ editor.focus()+ editor.setSelection(model.getFullModelRange())+ editor.trigger('keyboard', 'paste', { text })+ }, query)await this.page.keyboard.press('Escape')}