: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
fix(data-warehouse): guard SQL editor writes against a disposed Monaco editor (#88918)
posthog[bot]a4fdbc152797
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 9809edcc1d91..e49f2a492fe9 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7283,7 +7283,7 @@ snapshots:scenes-app-inbox-scene--installing-self-driving--dark:hash: v1.k794b7964.9b4caff813eafd13634c23944b6864b2e5e780612b7c7582853b1641fd6069d6.BpcSU8wtvBqJ6wuJ1eDHKkzYRHbGFpA2FkvwTu64kkYscenes-app-inbox-scene--installing-self-driving--light:- hash: v1.k794b7964.453f01ffd0289dd1b08046837544243ec7ec9bda56c3f4abeec7c768fa18e821.UtCIrnnSZtamR7C4EyDiY3QNBoJq33ekC2bqcVXPKQs+ hash: v1.k794b7964.fc1d6c0f35936c2a9a59fe89dbc9fdd8bae321ef4a4cba09af26626522d606eb.Ben1AjqSzgVvRph3ykOT3OusF-gZBfMIiFyONV4k6hAscenes-app-inbox-scene--legacy--dark:hash: v1.k794b7964.82fb69396eaab9ceb5a1223541105145370974e4cbb950bfe12ff201770b628b.0CZuUPcENgOU_VVhM4Ooj3YUlrXnMNAWbFCT0JGQzWUscenes-app-inbox-scene--legacy--light:diff --git a/frontend/src/lib/monaco/CodeEditorImpl.tsx b/frontend/src/lib/monaco/CodeEditorImpl.tsxindex b888390cb23a..9db0478e3688 100644--- a/frontend/src/lib/monaco/CodeEditorImpl.tsx+++ b/frontend/src/lib/monaco/CodeEditorImpl.tsx@@ -181,9 +181,15 @@ export function CodeEditor({const vimStatusBarRef = useRef<HTMLDivElement | null>(null)const [realKey] = useState(() => codeEditorIndex++)+ // Monaco expects a string; a non-string `value` throws `t.create is not a function` deep in+ // its model setup. Serialize objects and arrays as pretty JSON so the content stays visible+ // (not `[object Object]`) and matches CodeEditorResizeable's height calc. Normalize once so+ // the editor and codeEditorLogic (which sends the value in metadata requests) agree on the+ // text. Keep null/undefined as-is so the editor stays uncontrolled.+ const normalizedValue = value == null || typeof value === 'string' ? value : JSON.stringify(value, null, 2)const builtCodeEditorLogic = codeEditorLogic({key: queryKey ?? `new/${realKey}`,- query: value ?? '',+ query: normalizedValue ?? '',metadataQuery: metadataQuery,metadataQueryOffset: metadataQueryOffset,language: editorProps.language ?? 'text',@@ -651,7 +657,7 @@ export function CodeEditor({key={queryKey}theme={isDarkModeOn ? 'vs-dark' : 'vs-light'}loading={<Spinner />}- value={value}+ value={normalizedValue}options={editorOptions}onMount={editorOnMount}{...editorProps}diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsxindex 7f1292106a51..d9aec6723ce1 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditor.tsx@@ -161,7 +161,7 @@ export function SQLEditor({}, [mode, tabId, queryPaneDefaultHeight])const [monacoAndEditor, setMonacoAndEditor] = useState(- null as [Monaco, importedEditor.IStandaloneCodeEditor] | null+ null as [Monaco, importedEditor.IStandaloneCodeEditor | null] | null)const [monaco, editor] = monacoAndEditor ?? []@@ -171,6 +171,21 @@ export function SQLEditor({}})+ // The SQL/BI view toggle and the sidebar "Query" action tear the editor widget down and+ // rebuild it while this scene stays mounted. Nothing else clears the cached reference, so the+ // logic keeps a disposed editor as a prop. Drop only the editor the instant Monaco disposes it,+ // and keep the Monaco namespace: `Uri` and `editor.createModel`/`getModel` stay valid after the+ // widget is gone, so createTab can still prepare a tab before the next editor mounts.+ useEffect(() => {+ if (!editor) {+ return+ }+ const disposable = editor.onDidDispose(() =>+ setMonacoAndEditor((current) => (current ? [current[0], null] : null))+ )+ return () => disposable.dispose()+ }, [editor])+const logic = sqlEditorLogic({tabId: tabId || '',mode,diff --git a/frontend/src/scenes/data-warehouse/editor/isEditorAlive.test.ts b/frontend/src/scenes/data-warehouse/editor/isEditorAlive.test.tsnew file mode 100644index 000000000000..ab1468e68684--- /dev/null+++ b/frontend/src/scenes/data-warehouse/editor/isEditorAlive.test.ts@@ -0,0 +1,26 @@+import type { editor } from 'monaco-editor'++import { isEditorAlive } from './sqlEditorLogic'++// A disposed Monaco editor drops its DOM node. `setModel` on it throws inside Monaco's+// `_attachModel` and crashes the React commit, so every write is gated on this check.+function makeEditor(domNode: unknown): editor.IStandaloneCodeEditor {+ return {+ getDomNode: () => domNode,+ } as unknown as editor.IStandaloneCodeEditor+}++describe('isEditorAlive', () => {+ it('is true for an editor with a DOM node, even without a model', () => {+ expect(isEditorAlive(makeEditor(document.createElement('div')))).toBe(true)+ })++ it('is false for a disposed editor that dropped its DOM node', () => {+ expect(isEditorAlive(makeEditor(null))).toBe(false)+ })++ it('is false for a missing editor', () => {+ expect(isEditorAlive(null)).toBe(false)+ expect(isEditorAlive(undefined)).toBe(false)+ })+})diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex 1962cd283a0a..0a2cb3ebdfe2 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -178,6 +178,8 @@ function createMockEditor(): any {getModel: () => null,getSelection: () => null,getPosition: () => null,+ // A live editor has a DOM node; the logic reads this to skip writes to a disposed editor.+ getDomNode: () => document.createElement('div'),}}diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsxindex 936013c617de..48f7b4245f66 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx@@ -229,6 +229,17 @@ export function renderQueryOutline(node.style.height = `${maxBottom - minTop + padY * 2}px`}+// A disposed Monaco editor drops its DOM node, but the cached `props.editor` reference lingers.+// `IStandaloneCodeEditor` has no `isDisposed()`, so a null DOM node is the reliable disposed signal.+// Writing to a disposed editor (e.g. `setModel`) throws inside Monaco's `_attachModel` and crashes+// the React commit, so gate every such write on this check. A live editor without a model still+// passes — a fresh tab binds its first model here.+export function isEditorAlive(+ editorInstance: editor.IStandaloneCodeEditor | null | undefined+): editorInstance is editor.IStandaloneCodeEditor {+ return !!editorInstance && editorInstance.getDomNode() !== null+}+function clearQueryOutlineOverlay(cache: sqlEditorLogicType['cache'],fallbackEditor?: editor.IStandaloneCodeEditor | null@@ -1904,7 +1915,9 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([model = props.monaco.editor.createModel(query, 'hogQL', uri)cache.createdModels = cache.createdModels || []cache.createdModels.push(model)- props.editor?.setModel(model)+ if (isEditorAlive(props.editor)) {+ props.editor.setModel(model)+ }initModel(model,codeEditorLogic({@@ -1946,7 +1959,9 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([actions.enforceConnectionRawQueryMode()// Focus the editor after creating a new tab- props.editor?.focus()+ if (isEditorAlive(props.editor)) {+ props.editor.focus()+ }},setSourceQuery: ({ sourceQuery }) => {if (!values.activeTab) {@@ -3771,7 +3786,6 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([// Bump the generation counter so any still-running invocation bails out before// applying stale decorations. Each run owns its own `generation` token.const generation = ++cache.decorationGeneration- const isStale = (): boolean => generation !== cache.decorationGenerationconst editorInstance = props.editorif (!editorInstance?.getPosition || !editorInstance?.getModel) {@@ -3783,6 +3797,12 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([return}+ // A run bails when a newer run superseded it, or when the model was disposed while it+ // awaited the parser or metadata. Switching to the BI view disposes the tab model but+ // keeps this logic mounted, so the generation counter never advances, and+ // `getPositionAt` throws "Model is disposed!" on a dead model.+ const isStale = (): boolean => generation !== cache.decorationGeneration || model.isDisposed()+const fullText = values.queryInput ?? ''const queries = splitQueries(fullText)const cursorOffset = model.getOffsetAt(position)@@ -3829,7 +3849,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([offset: number): Promise<{ range: IRange | null; decorations: editor.IModelDeltaDecoration[] }> => {const subquery = await findInnermostSelectAtOffset(activeQuery.query, offset, activeQuery.start)- if (!subquery) {+ if (!subquery || isStale()) {return { range: null, decorations: [] }}const subStart = model.getPositionAt(subquery.start)