: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
feat(notebooks): run pure-sql nodes on clickhouse without a sandbox (#72362)
Sinan Kucukkoseler9faaff2e45c7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 0cefca7eca8a..c3d1b6eb7304 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6427,17 +6427,17 @@ snapshots:scenes-app-notebooks--bullet-list--light:hash: v1.k794b7964.1a8843ddd26ea3b72013b7fee8836d009f5d71558f397da48e7cdee3c28dbcae.hvFFmea_bm1gBo7xMpoXXD_1Pz4lCO64eTVDfc9Lohoscenes-app-notebooks--collapsed-headings--dark:- hash: v1.k794b7964.a294cb50e76f02875e0d8aa526499cce6506b013d5930be0acf0618220f83c1b.016QmLl1Trjeo0C-YrsC6ZQJCFZy4n4WE1H2nHlu1aI+ hash: v1.k794b7964.aa5a612e65bb07ecdc69012cb6d8815691f7c8cdbaaa1e6cb2a79f80dd48c733.98F8j02JyWfZfX0sCUWkl5kN5iPbD06gmS0GycFj-BEscenes-app-notebooks--collapsed-headings--light:- hash: v1.k794b7964.4073ee7cd2a8ef71ca5554d9304fe54c48cce4cf1b57639e2249d55b67f9c9ed.JTdhkXxIPtBNrd0I2DGB-E5-VxOEapUmbY2Q7TYQzx4+ hash: v1.k794b7964.6d825c028024bd46bc104fccb3ff65a9850f49f3d2a600498c7523cd6fd10ff5.1pbZhaUdYM_vrgvp3BtrGVWG__COl7avdlsGW1LNSksscenes-app-notebooks--empty-notebook--dark:hash: v1.k794b7964.fa1d770a20cfd16bcdc9b3661bf47cfbaa9b38a4a33e2c497d724de07c499e9e.XfAAGxqctmjMUe848vJXbOi7APYCtDaZp9R8TYTcQKwscenes-app-notebooks--empty-notebook--light:hash: v1.k794b7964.e9b9755ff30dbb54305cf86daa403b7d9b3a8cd4990379c494b2fb122930d71b.xtARpz4io9Df4iMJYEhzVUB9Bv5kSAk986fHdyzhScYscenes-app-notebooks--flattened-table--dark:- hash: v1.k794b7964.4af1850ffcbd00ddac474e062be344b485d9ae95109465b4233ba53fb1ef50ac.LIOTcUH-F0AtaRoXCi1reMKt3gbdYF6DIg2LKrMji_c+ hash: v1.k794b7964.e073958f489aea9dfa538cbf710039eb9d88541603df2523ea283d9f5c68ecad.96-dcNYghaw4yfNLkya02wH5bErS0_vJdxiwdD8DsKoscenes-app-notebooks--flattened-table--light:- hash: v1.k794b7964.7e08ec9949fcf8ba179a68332dc9ec65e4995b5757cb2e5f7399220d4e32110d.r2KBOe1mWHbmiN-V1CdB36vcl56JnDLfbAV3RvEcylI+ hash: v1.k794b7964.ca65edcd4d23f163928f3519b282283c3641acace4abedb3dc1c34832be78be7.zZ-cBPlgrln4u3wjUUxvX6_jtZ_oH2kKd7QoJWfiEwQscenes-app-notebooks--headings--dark:hash: v1.k794b7964.0d4d36634319774a86df08522142076fe37b2cdf87b4c654950004218a1e3136.RkxpWeXla9IIpBOVfi7ZsPtUaSWzEWFltzdtsn1egAQscenes-app-notebooks--headings--light:@@ -6455,9 +6455,9 @@ snapshots:scenes-app-notebooks--numbered-list--light:hash: v1.k794b7964.a7c359b0c62468903ee153f7d554332ffb23ddeb5823f8772cbbc9bdda85ef39.vqBNXyRaDc-oPTu-JlCeXZXDW3hlVysSsDe1vCbkFbkscenes-app-notebooks--recordings-playlist--dark:- hash: v1.k794b7964.2581859c81615ca1f017290f7b86eaec8d1203f32dd6e0fb1bbeb2c337d5bb75.ProVqyNuxcc6_f8mfSJUJMEYn2Rn3LWCTT5OLKk1lLk+ hash: v1.k794b7964.bf39c6b292425894510288542c473b5d926f648af56fb9ee305715c560c06f86.rvD4Bs7KFJXywUr9a7FeSgzuIijEfgvh7EYIEBk3C8wscenes-app-notebooks--recordings-playlist--light:- hash: v1.k794b7964.de5626e727565daa0be4e02937d39c36a43fe82b85799c0d2f91304439095b91.bUKmiskhzemuQnEA4r75ET4WcbKkawJt-FaaiWhfr0Y+ hash: v1.k794b7964.c0528384e510106068f1ec51cc84d089e229266f1af6913a7476f5072f834735.p9LDdbG6BWtaPK7MQt1_Muv90yc3wrAr6Xe9mBoNNsQscenes-app-notebooks--text-formats--dark:hash: v1.k794b7964.6ba17ee8c1d8e0b4095b903100109314b701baa0a4956ca272f2b26f4d37879b.J-tNiP80EM3tE0ZaOdrZZ3vzZnEK1UdW5afDzziYijQscenes-app-notebooks--text-formats--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 8b30dd900583..1854ae55e1d6 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -4942,6 +4942,9 @@ const api = {media?: { mime_type: string; data: string }[]} | nullerror: string | null+ // Direct (no-sandbox) runs only: the full capped row set for client-side paging,+ // present while the backend's query result is alive (~20 min).+ rows?: (string | number | null)[][]}> {return await new ApiRequest().notebook(notebookId).withAction(`sql_v2/runs/${runId}`).get()},diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsxindex 7a14e5215d28..c17b90030095 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx@@ -1,5 +1,5 @@import { useActions, useMountedLogic, useValues } from 'kea'-import { useMemo, useRef } from 'react'+import { useEffect, useMemo, useRef } from 'react'import { IconCornerDownRight, IconPlayFilled } from '@posthog/icons'@@ -21,6 +21,10 @@ import { NotebookDataframeResult } from './pythonExecution'// path, with sibling SQLV2 frames materialized as pandas frames. A separate node type from// the legacy ph-python cell (in-browser kernel) so the two flows never share run wiring.+// The default node height only fits a couple of table rows; grow to this once output lands+// so results and figures aren't clipped and the user doesn't have to resize by hand to read them.+const RESULT_MIN_HEIGHT = 300+export type NotebookNodePythonV2Attributes = {code: string// The dataframe name this cell's result is exposed as to later cells.@@ -66,6 +70,7 @@ const Component = ({isStale,isChainRunning,staleDownstreamCount,+ pendingKernelStart,} = useValues(dataLogic)const { setPage, setPageSize, runStaleChain } = useActions(dataLogic)@@ -84,12 +89,27 @@ const Component = ({? pageResult.has_more: (result?.has_more ?? (result?.first_page ?? []).length >= SQL_V2_DEFAULT_PAGE_SIZE)+ const hasStreamOutput = !!(result?.stdout || result?.stderr || result?.media?.length)++ // Grow a still-default (too-short) node the first time output lands so it's readable without+ // a manual resize. Only grows below the target and only on fresh output, so a deliberate+ // resize (or a taller reload) is left untouched.+ const hadOutputRef = useRef(hasStreamOutput || !!dataframeResult)+ useEffect(() => {+ const hasOutput = hasStreamOutput || !!dataframeResult+ if (hasOutput && !hadOutputRef.current) {+ if (typeof attributes.height !== 'number' || attributes.height < RESULT_MIN_HEIGHT) {+ updateAttributes({ height: RESULT_MIN_HEIGHT })+ }+ }+ hadOutputRef.current = hasOutput+ // oxlint-disable-next-line exhaustive-deps+ }, [dataframeResult, hasStreamOutput])+if (!expanded) {return null}- const hasStreamOutput = !!(result?.stdout || result?.stderr || result?.media?.length)-return (<div data-attr="notebook-node-python-v2" className="flex h-full min-h-0 flex-col"><div@@ -110,6 +130,9 @@ const Component = ({/></div>) : null}+ {isRunning && pendingKernelStart ? (+ <div className="shrink-0 px-2 pt-1 text-xs text-muted">Starting compute sandbox…</div>+ ) : null}{hasStreamOutput ? (<div className="shrink-0 space-y-2 px-2 pt-1" onClick={(event) => event.stopPropagation()}>{result?.stdout ? (diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsxindex 02756b35a24e..eac19a252b3b 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx@@ -1,5 +1,5 @@import { useActions, useMountedLogic, useValues } from 'kea'-import { useMemo } from 'react'+import { useEffect, useMemo, useRef } from 'react'import { IconCornerDownRight } from '@posthog/icons'@@ -47,6 +47,32 @@ export type NotebookNodeSQLV2Attributes = {// Matches the SQL editor output pane's default so charts land at v1-node size.const VIZ_MIN_HEIGHT = 350+// The default node height only fits a couple of table rows; grow to this once a result lands+// so the output isn't clipped and the user doesn't have to resize by hand to read it.+const RESULT_MIN_HEIGHT = 300++// The dataframe name is referenced as a bare SQL table name and becomes a Python variable+// when a python cell reads the frame, so it must be a plain identifier. Empty is fine —+// the cell is then display-only.+const VALID_RETURN_VARIABLE = /^[A-Za-z_][A-Za-z0-9_]*$/+const returnVariableValidationError = (returnVariable: string): string | null => {+ if (!returnVariable || VALID_RETURN_VARIABLE.test(returnVariable)) {+ return null+ }+ const suggestion = returnVariable.replace(/[^A-Za-z0-9_]/g, '_').replace(/^(?=\d)/, '_')+ const hint = VALID_RETURN_VARIABLE.test(suggestion) ? ` Try ${suggestion}.` : ''+ // Call out only the rule that was actually broken so a name like `people-df` isn't told it+ // "can't start with a number" when the real problem is the hyphen.+ const startsWithDigit = /^\d/.test(returnVariable)+ const hasInvalidChars = /[^A-Za-z0-9_]/.test(returnVariable)+ const reason =+ startsWithDigit && hasInvalidChars+ ? "Use letters, numbers, and underscores, and don't start with a number."+ : startsWithDigit+ ? "The name can't start with a number."+ : 'Use letters, numbers, and underscores.'+ return `${reason}${hint}`+}const toDataframeResult = (result: NotebookNodeSQLV2Result): NotebookDataframeResult => {const columns = result.columns ?? []@@ -101,6 +127,7 @@ const Component = ({isStale,isChainRunning,staleDownstreamCount,+ pendingKernelStart,} = useValues(dataLogic)const { setPage, setPageSize, runStaleChain } = useActions(dataLogic)@@ -108,6 +135,7 @@ const Component = ({title.trim() || getCellLabel(nodeIndex, nodeType) || 'SQL'const result = attributes.result ?? null+ const returnVariableError = returnVariableValidationError(attributes.returnVariable ?? '')// Page 1 at the default size comes straight from the envelope; other pages re-query CH.const dataframeResult = useMemo(() => {if (pageResult) {@@ -136,6 +164,22 @@ const Component = ({[attributes.vizQuery, attributes.code])+ // Grow a still-default (too-short) node the first time a result lands so it's readable+ // without a manual resize. Only grows below the target and only on a fresh result, so a+ // deliberate resize (or a taller reload) is left untouched.+ const hadResultRef = useRef(!!result)+ useEffect(() => {+ const hasResult = !!dataframeResult+ if (hasResult && !hadResultRef.current) {+ const target = activeTab === OutputTab.Visualization ? VIZ_MIN_HEIGHT : RESULT_MIN_HEIGHT+ if (typeof attributes.height !== 'number' || attributes.height < target) {+ updateAttributes({ height: target })+ }+ }+ hadResultRef.current = hasResult+ // oxlint-disable-next-line exhaustive-deps+ }, [dataframeResult])+if (!expanded) {return null}@@ -160,6 +204,9 @@ const Component = ({/></div>) : null}+ {isRunning && pendingKernelStart ? (+ <div className="shrink-0 px-2 pt-1 text-xs text-muted">Starting compute sandbox…</div>+ ) : null}{runError ? (<div className="p-2 text-xs font-mono text-danger whitespace-pre-wrap">{runError}</div>) : dataframeResult && cachedResults ? (@@ -250,11 +297,14 @@ const Component = ({<inputtype="text"// A dataframe name other SQL nodes reference by table name (`from sql_df`).+ // Optional: left empty, the cell is display-only and exports nothing.className="rounded border border-border px-1.5 py-0.5 text-xs font-mono bg-bg-light text-default focus:outline-none focus:ring-1 focus:ring-primary"value={attributes.returnVariable ?? ''}onChange={(event) => updateAttributes({ returnVariable: event.target.value })}+ placeholder="Dataframe name (optional)"spellCheck={false}/>+ {returnVariableError ? <span className="text-danger">{returnVariableError}</span> : null}{sqlV2ReturnVariableUsage.length > 0 ? (<span className="text-muted">Used in{' '}@@ -291,7 +341,7 @@ const Settings = ({hasResult: !!attributes.result,getContent: () => notebookLogic.values.content ?? null,})- const { isRunning, isInterrupting, operationBlockReason } = useValues(dataLogic)+ const { isRunning, isInterrupting, operationBlockReason, activeRunLane } = useValues(dataLogic)const { runQuery, interruptRun } = useActions(dataLogic)return (@@ -304,8 +354,10 @@ const Settings = ({onRunQuery={(code) => runQuery(code, collectSqlV2Refs(notebookLogic.values.content, nodeId))}runQueryLoading={isRunning}runQueryDisabledReason={operationBlockReason ?? undefined}- runQueryTooltip="Run SQL (v2) query"- onCancelQuery={interruptRun}+ runQueryTooltip="Run SQL query"+ // Direct (no-sandbox) runs cannot be cancelled — there is no kernel to signal;+ // they finish on their own bounded schedule. Stop applies to kernel-lane runs only.+ onCancelQuery={activeRunLane === 'kernel' ? interruptRun : undefined}cancelQueryLoading={isInterrupting}/>)@@ -313,7 +365,7 @@ const Settings = ({export const NotebookNodeSQLV2 = createPostHogWidgetNode<NotebookNodeSQLV2Attributes>({nodeType: NotebookNodeType.SQLV2,- titlePlaceholder: 'SQL (v2)',+ titlePlaceholder: 'SQL',Component,heightEstimate: 120,minHeight: 80,@@ -323,8 +375,10 @@ export const NotebookNodeSQLV2 = createPostHogWidgetNode<NotebookNodeSQLV2Attribcode: {default: '',},+ // Optional: empty means the cell binds no dataframe (display-only). Existing cells+ // carry their persisted name ('sql_df' was the old default) and keep exporting it.returnVariable: {- default: 'sql_df',+ default: '',},runId: {default: null,diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.tsindex dda8182ba2f3..8e6da593fd17 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.test.ts@@ -1,6 +1,10 @@import { buildMarkdownNotebookContent, serializeMarkdownNotebookComponent } from '../Notebook/markdownNotebookV2'import { NotebookNodeType } from '../types'-import { buildNotebookDependencyGraph, extractPythonIdentifiers } from './notebookNodeContent'+import {+ buildNotebookDependencyGraph,+ collectNotebookFrameNodes,+ extractPythonIdentifiers,+} from './notebookNodeContent'describe('buildNotebookDependencyGraph', () => {const sqlV2Node = (nodeId: string, returnVariable: string, code: string): Record<string, unknown> => ({@@ -41,6 +45,49 @@ describe('buildNotebookDependencyGraph', () => {expect(graph.upstreamSourcesByNode['c'].sql_df.nodeId).toEqual('a')})+ it('an unnamed SQL cell is not browsable as a dataframe', () => {+ // The schema browser lists document-derived frames; a blank-name cell binds no+ // dataframe, so it must not appear (nor push a real 'sql_df' cell to 'sql_df_2').+ const content = {+ type: 'doc',+ content: [sqlV2Node('blank', '', 'select 1'), sqlV2Node('named', 'sql_df', 'select id from events')],+ }+ const frames = collectNotebookFrameNodes(content)+ expect(frames.map((frame) => frame.name)).toEqual(['sql_df'])+ expect(frames[0].nodeId).toEqual('named')+ })++ it('an unnamed SQL cell exports nothing and reserves no name', () => {+ // The dataframe name is optional: a blank-name cell is display-only, and it must not+ // squat the 'sql_df' default (which would misroute references to a named sibling).+ const content = {+ type: 'doc',+ content: [+ sqlV2Node('blank', '', 'select 1'),+ sqlV2Node('named', 'sql_df', 'select id from events'),+ sqlV2Node('reader', 'joined', 'select * from sql_df'),+ ],+ }+ const graph = buildNotebookDependencyGraph(content)+ expect(graph.nodesById['blank'].exports).toEqual([])+ expect(graph.nodesById['named'].exports).toEqual(['sql_df'])+ expect(graph.upstreamSourcesByNode['reader'].sql_df.nodeId).toEqual('named')+ })++ it('an invalid SQL frame name binds nothing (not exported, not browsable)', () => {+ // A non-empty but invalid name like `people-df` can never be referenced (bare+ // `people-df` is not a valid identifier), so it must not enter the dependency+ // graph or the schema browser as an export the way a valid name does.+ const content = {+ type: 'doc',+ content: [sqlV2Node('bad', 'people-df', 'select 1'), sqlV2Node('ok', 'sql_df', 'select id from events')],+ }+ const graph = buildNotebookDependencyGraph(content)+ expect(graph.nodesById['bad'].exports).toEqual([])+ expect(graph.nodesById['ok'].exports).toEqual(['sql_df'])+ expect(collectNotebookFrameNodes(content).map((frame) => frame.name)).toEqual(['sql_df'])+ })+it('links PythonV2 cells in both directions (python reads sql, sql joins the python frame)', () => {// Journey 10 staleness walks these edges: without PythonV2 in the graph, running a// SQL cell never marks its Python dependents stale, and vice versa.diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.tsindex 9788afac93c3..e0fc94b2517c 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts@@ -258,6 +258,14 @@ export const resolveSqlV2ReturnVariable = (returnVariable: string): string => {return returnVariable.trim() || 'sql_df'}+// A dataframe name is referenced as a bare SQL table name and becomes a Python variable, so+// only a plain identifier can ever be referenced. A blank name is display-only; a non-blank+// but invalid one (e.g. `people-df`) is treated the same way for collection — it exports+// nothing, so it never pollutes the dependency graph or schema browser with an unusable name.+const SQL_V2_FRAME_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/+export const isReferenceableSqlV2FrameName = (returnVariable: string): boolean =>+ SQL_V2_FRAME_NAME.test(returnVariable.trim())+const buildUniqueSqlV2ReturnVariable = (baseReturnVariable: string, used: Set<string>): string => {const normalizedBase = normalizeSqlIdentifier(baseReturnVariable)if (!used.has(normalizedBase)) {@@ -280,10 +288,20 @@ export const getUniqueSqlV2ReturnVariable = (fallbackReturnVariable: string): string => {const used = new Set<string>()- let resolvedReturnVariable = resolveSqlV2ReturnVariable(fallbackReturnVariable)+ let resolvedReturnVariable = isReferenceableSqlV2FrameName(fallbackReturnVariable)+ ? resolveSqlV2ReturnVariable(fallbackReturnVariable)+ : ''let resolvedFromNodes = falsenodes.forEach((node) => {+ // An unnamed or invalid cell binds no dataframe: it claims no name and needs none reserved.+ if (!node.returnVariable) {+ if (node.nodeId === nodeId) {+ resolvedReturnVariable = ''+ resolvedFromNodes = true+ }+ return+ }const baseReturnVariable = resolveSqlV2ReturnVariable(node.returnVariable)const uniqueReturnVariable = buildUniqueSqlV2ReturnVariable(baseReturnVariable, used)used.add(normalizeSqlIdentifier(uniqueReturnVariable))@@ -294,7 +312,7 @@ export const getUniqueSqlV2ReturnVariable = (}})- if (!resolvedFromNodes) {+ if (!resolvedFromNodes && resolvedReturnVariable) {resolvedReturnVariable = buildUniqueSqlV2ReturnVariable(resolvedReturnVariable, used)}@@ -365,11 +383,15 @@ export const collectSqlV2Nodes = (content?: JSONContent | null): SqlV2NodeSummarif (node.type === NotebookNodeType.SQLV2) {const attrs = node.attrs ?? {}const code = typeof attrs.code === 'string' ? attrs.code : ''- const baseReturnVariable = resolveSqlV2ReturnVariable(- typeof attrs.returnVariable === 'string' ? attrs.returnVariable : 'sql_df'- )- const returnVariable = buildUniqueSqlV2ReturnVariable(baseReturnVariable, usedReturnVariables)- usedReturnVariables.add(normalizeSqlIdentifier(returnVariable))+ // A missing attribute predates the optional name (legacy default); an explicit+ // blank or invalid one binds no dataframe (nothing can reference it).+ const rawReturnVariable = typeof attrs.returnVariable === 'string' ? attrs.returnVariable : 'sql_df'+ const returnVariable = isReferenceableSqlV2FrameName(rawReturnVariable)+ ? buildUniqueSqlV2ReturnVariable(resolveSqlV2ReturnVariable(rawReturnVariable), usedReturnVariables)+ : ''+ if (returnVariable) {+ usedReturnVariables.add(normalizeSqlIdentifier(returnVariable))+ }nodes.push({nodeId: attrs.nodeId ?? '',code,@@ -476,27 +498,33 @@ export const collectNotebookFrameNodes = (content?: JSONContent | null): Notebooif (node.type === NotebookNodeType.SQLV2 || node.type === NotebookNodeType.PythonV2) {const attrs = node.attrs ?? {}const isSql = node.type === NotebookNodeType.SQLV2- const rawReturnVariable = typeof attrs.returnVariable === 'string' ? attrs.returnVariable : ''- let name: string+ // A missing SQL attribute predates the optional name (legacy 'sql_df' default);+ // an explicit blank or invalid one binds no dataframe — nothing to browse.+ const rawReturnVariable =+ typeof attrs.returnVariable === 'string' ? attrs.returnVariable : isSql ? 'sql_df' : ''+ let name: string | nullif (isSql) {- name = buildUniqueSqlV2ReturnVariable(- resolveSqlV2ReturnVariable(rawReturnVariable),- usedReturnVariables- )- usedReturnVariables.add(normalizeSqlIdentifier(name))+ name = isReferenceableSqlV2FrameName(rawReturnVariable)+ ? buildUniqueSqlV2ReturnVariable(resolveSqlV2ReturnVariable(rawReturnVariable), usedReturnVariables)+ : null+ if (name) {+ usedReturnVariables.add(normalizeSqlIdentifier(name))+ }} else {name = rawReturnVariable.trim() || 'df'}- const result = attrs.result ?? null- nodes.push({- nodeId: attrs.nodeId ?? '',- name,- nodeType: isSql ? 'sql' : 'python',- columns: frameNodeColumns(result),- rowCount: typeof result?.row_count === 'number' ? result.row_count : null,- hasRun: Boolean(result),- code: typeof attrs.code === 'string' ? attrs.code : '',- })+ if (name) {+ const result = attrs.result ?? null+ nodes.push({+ nodeId: attrs.nodeId ?? '',+ name,+ nodeType: isSql ? 'sql' : 'python',+ columns: frameNodeColumns(result),+ rowCount: typeof result?.row_count === 'number' ? result.row_count : null,+ hasRun: Boolean(result),+ code: typeof attrs.code === 'string' ? attrs.code : '',+ })+ }}if (node.type === NotebookNodeType.MarkdownNotebook) {expandMarkdownNotebookNodesOfTypes(node, [NotebookNodeType.SQLV2, NotebookNodeType.PythonV2]).forEach(walk)@@ -771,11 +799,17 @@ export const buildNotebookDependencyGraph = (content?: JSONContent | null): Noteif (node.type === NotebookNodeType.SQLV2) {const attrs = node.attrs ?? {}sqlV2Index += 1- const baseReturnVariable = resolveSqlV2ReturnVariable(- typeof attrs.returnVariable === 'string' ? attrs.returnVariable : 'sql_df'- )- const returnVariable = buildUniqueSqlV2ReturnVariable(baseReturnVariable, usedSqlV2ReturnVariables)- usedSqlV2ReturnVariables.add(normalizeSqlIdentifier(returnVariable))+ // Blank or invalid name = display-only cell: it exports nothing (see collectSqlV2Nodes).+ const rawReturnVariable = typeof attrs.returnVariable === 'string' ? attrs.returnVariable : 'sql_df'+ const returnVariable = isReferenceableSqlV2FrameName(rawReturnVariable)+ ? buildUniqueSqlV2ReturnVariable(+ resolveSqlV2ReturnVariable(rawReturnVariable),+ usedSqlV2ReturnVariables+ )+ : ''+ if (returnVariable) {+ usedSqlV2ReturnVariables.add(normalizeSqlIdentifier(returnVariable))+ }const code = typeof attrs.code === 'string' ? attrs.code : ''nodes.push({nodeId: attrs.nodeId ?? '',diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.tsindex fc3334d52bb3..bb0a8e062994 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts@@ -2,10 +2,12 @@ import { expectLogic } from 'kea-test-utils'import api from 'lib/api'import { JSONContent } from 'lib/components/RichContentEditor/types'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { initKeaTests } from '~/test/init'import { buildMarkdownNotebookContent, serializeMarkdownNotebookComponent } from '../Notebook/markdownNotebookV2'+import { notebookSettingsLogic } from '../Notebook/notebookSettingsLogic'import { NotebookNodeType } from '../types'import { collectSqlV2Refs, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'@@ -67,9 +69,18 @@ describe('notebookNodeSQLV2Logic', () => {expect(collectSqlV2Refs(document, 'self')).toEqual({ sql_df: hogql('a'), sql_df_2: hogql('b') })})- it('resolves blank names to the default the dependency graph shows', () => {- const document = doc(sqlNode('a', ''), sqlNode('b', ' '))- expect(collectSqlV2Refs(document, 'self')).toEqual({ sql_df: hogql('a'), sql_df_2: hogql('b') })+ it('skips unnamed cells and lets a named sibling keep the default name', () => {+ // The dataframe name is optional: a blank-name cell is display-only and exports+ // nothing — and it must not push a real 'sql_df' cell into a disambiguated name.+ const document = doc(sqlNode('a', ''), sqlNode('b', ' '), sqlNode('c', 'sql_df'))+ expect(collectSqlV2Refs(document, 'self')).toEqual({ sql_df: hogql('c') })+ })++ it('skips cells with an invalid (non-identifier) name', () => {+ // `people-df` can never be referenced as a bare table name, so it must not be+ // offered as a ref that a downstream cell would fail to resolve.+ const document = doc(sqlNode('a', 'people-df'), sqlNode('b', 'good_df'))+ expect(collectSqlV2Refs(document, 'self')).toEqual({ good_df: hogql('b') })})it('finds SQLV2 nodes nested inside other content', () => {@@ -119,6 +130,60 @@ describe('notebookNodeSQLV2Logic', () => {})})+ describe('execution lanes', () => {+ it('pages a direct run client-side from the rows the result poll returned', async () => {+ // The server page endpoint refuses hogql runs; losing the local slice would+ // strand every page beyond the envelope's first.+ const rows = Array.from({ length: 120 }, (_, index) => [index])+ resultSpy.mockResolvedValue({+ status: 'done',+ result: {+ columns: ['a'],+ types: [['a', 'Int64']],+ row_count: 50,+ first_page: rows.slice(0, 50),+ has_more: true,+ },+ error: null,+ rows,+ })+ const pageSpy = jest.spyOn(api.notebooks, 'sqlV2RunPage')+ mount({ runId: 'r1', hasResult: false })+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.directRows?.rows).toHaveLength(120)++ logic.actions.setPage(3)+ await expectLogic(logic).toFinishAllListeners()+ expect(pageSpy).not.toHaveBeenCalled()+ expect(logic.values.pageResult).toEqual({+ columns: ['a'],+ types: [['a', 'Int64']],+ rows: rows.slice(100, 120),+ has_more: false,+ })+ })++ it('opens the kernel panel and notifies for a kernel-lane run, and not for a direct one', async () => {+ // Scenario B: a run that needs the sandbox must surface the provisioning wait;+ // a pure-SQL run must never pop the panel or toast (it needs no sandbox at all).+ const toastSpy = jest.spyOn(lemonToast, 'info')+ mount()+ logic.actions.runQuery('select 1')+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.activeRunLane).toEqual('direct')+ expect(notebookSettingsLogic.findMounted()?.values.showKernelInfo).toBe(false)+ expect(logic.values.pendingKernelStart).toBe(false)+ expect(toastSpy).not.toHaveBeenCalled()++ logic.actions.runQuery('select * from new_events', { new_events: { node_id: 'py', kind: 'local' } })+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.activeRunLane).toEqual('kernel')+ expect(notebookSettingsLogic.findMounted()?.values.showKernelInfo).toBe(true)+ expect(logic.values.pendingKernelStart).toBe(true)+ expect(toastSpy).toHaveBeenCalledWith(expect.stringContaining('Starting a compute sandbox'))+ })+ })+it('rejects blank code before dispatching a run', async () => {mount()logic.actions.runQuery(' ')diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.tsindex 0afe38539518..3943baaabe1b 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts@@ -17,10 +17,17 @@ import api from 'lib/api'import { JSONContent } from 'lib/components/RichContentEditor/types'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { notebookKernelInfoLogic } from '../Notebook/notebookKernelInfoLogic'import { notebookNodeStalenessLogic } from '../Notebook/notebookNodeStalenessLogic'import { NotebookOperation, notebookOperationsLogic } from '../Notebook/notebookOperationsLogic'+import { notebookSettingsLogic } from '../Notebook/notebookSettingsLogic'import { NotebookNodeType } from '../types'-import { buildNotebookDependencyGraph, collectPythonKernelNodes, collectSqlV2Nodes } from './notebookNodeContent'+import {+ buildNotebookDependencyGraph,+ collectPythonKernelNodes,+ collectSqlV2Nodes,+ extractDuckSqlTables,+} from './notebookNodeContent'import { NotebookNodeSQLV2Result } from './NotebookNodeSQLV2'export type SqlV2RunRef = {@@ -42,7 +49,8 @@ export type SqlV2RunRef = {export function collectSqlV2Refs(doc: JSONContent | null | undefined, selfNodeId: string): Record<string, SqlV2RunRef> {const refs: Record<string, SqlV2RunRef> = {}for (const node of collectSqlV2Nodes(doc)) {- if (node.nodeId && node.nodeId !== selfNodeId) {+ // An unnamed cell (blank dataframe name) is display-only: nothing can reference it.+ if (node.nodeId && node.nodeId !== selfNodeId && node.returnVariable) {refs[node.returnVariable] = { node_id: node.nodeId, kind: 'hogql' }}}@@ -68,6 +76,18 @@ export type NotebookNodeSQLV2Page = {has_more: boolean}+// The full capped row set a direct (ClickHouse, no-sandbox) run returns with its result,+// held in memory for client-side paging — never persisted into the document.+export type NotebookNodeSQLV2DirectRows = {+ columns: string[]+ types: [string, string][]+ rows: (string | number | null)[][]+}++// Which execution lane the node's current run took: 'direct' runs on ClickHouse with no+// sandbox (no Stop affordance, client-side paging); 'kernel' runs in the sandbox.+export type SqlV2RunLane = 'direct' | 'kernel'+export interface RunQueryOptions {nodeType?: 'hogql' | 'python'outputName?: string@@ -97,6 +117,8 @@ export interface notebookNodeSQLV2LogicValues {staleNodeIds: Record<string, true> // notebookNodeStalenessLogicactiveOperation: NotebookOperation | null // notebookOperationsLogicisBusy: boolean // notebookOperationsLogic+ activeRunLane: SqlV2RunLane | null+ directRows: NotebookNodeSQLV2DirectRows | nullisInterrupting: booleanisRunning: booleanisStale: boolean@@ -105,6 +127,7 @@ export interface notebookNodeSQLV2LogicValues {pageLoading: booleanpageResult: NotebookNodeSQLV2Page | nullpageSize: number+ pendingKernelStart: booleanrunError: string | nullstaleDownstreamCount: number}@@ -145,6 +168,9 @@ export interface notebookNodeSQLV2LogicActions {startOperation: (operation: NotebookOperation) => {operation: NotebookOperation} // notebookOperationsLogic+ setShowKernelInfo: (showKernelInfo: boolean) => {+ showKernelInfo: boolean+ } // notebookSettingsLogicinterruptRun: () => {value: true}@@ -163,6 +189,12 @@ export interface notebookNodeSQLV2LogicActions {opts: RunQueryOptionsrefs: Record<string, SqlV2RunRef>}+ setActiveRunLane: (activeRunLane: SqlV2RunLane) => {+ activeRunLane: SqlV2RunLane+ }+ setDirectRows: (directRows: NotebookNodeSQLV2DirectRows | null) => {+ directRows: NotebookNodeSQLV2DirectRows | null+ }setIsInterrupting: (isInterrupting: boolean) => {isInterrupting: boolean}@@ -181,6 +213,9 @@ export interface notebookNodeSQLV2LogicActions {setPageSize: (pageSize: number) => {pageSize: number}+ setPendingKernelStart: (pendingKernelStart: boolean) => {+ pendingKernelStart: boolean+ }setRunError: (runError: string | null) => {runError: string | null}@@ -225,6 +260,8 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([['startOperation', 'finishOperation', 'finishNodeOperations'],notebookNodeStalenessLogic({ shortId: props.notebookShortId }),['nodeRunFinished', 'dispatchChainRun', 'runStaleChain', 'registerChainNode', 'unregisterChainNode'],+ notebookSettingsLogic,+ ['setShowKernelInfo'],],})),actions({@@ -249,6 +286,9 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([setPageResult: (pageResult: NotebookNodeSQLV2Page | null) => ({ pageResult }),setPageLoading: (pageLoading: boolean) => ({ pageLoading }),resetPaging: true,+ setDirectRows: (directRows: NotebookNodeSQLV2DirectRows | null) => ({ directRows }),+ setActiveRunLane: (activeRunLane: SqlV2RunLane) => ({ activeRunLane }),+ setPendingKernelStart: (pendingKernelStart: boolean) => ({ pendingKernelStart }),}),reducers({// Tracks the run being in progress; driven by the run's status, not a socket lifecycle.@@ -311,6 +351,29 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([resetPaging: () => false,},],+ // Session-local rows for client-side paging of direct runs; a new run invalidates them.+ directRows: [+ null as NotebookNodeSQLV2DirectRows | null,+ {+ setDirectRows: (_, { directRows }) => directRows,+ runQuery: () => null,+ },+ ],+ activeRunLane: [+ null as SqlV2RunLane | null,+ {+ setActiveRunLane: (_, { activeRunLane }) => activeRunLane,+ },+ ],+ // A kernel-lane run was submitted while no kernel was known to be up: the backend is+ // provisioning the sandbox; drives the "Starting compute sandbox…" caption.+ pendingKernelStart: [+ false,+ {+ setPendingKernelStart: (_, { pendingKernelStart }) => pendingKernelStart,+ stopPolling: () => false,+ },+ ],}),listeners(({ props, actions, cache, values }) => {// One operation at a time across the whole notebook (see notebookOperationsLogic);@@ -318,6 +381,17 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([const runOperation: NotebookOperation = { id: `${props.nodeId}:run`, nodeId: props.nodeId, kind: 'run' }const pageOperation: NotebookOperation = { id: `${props.nodeId}:page`, nodeId: props.nodeId, kind: 'page' }+ // Slice a page out of the in-memory direct-run rows — no network, no operation lock.+ const sliceDirectRows = (rows: NotebookNodeSQLV2DirectRows, page: number, pageSize: number): void => {+ const start = (page - 1) * pageSize+ actions.setPageResult({+ columns: rows.columns,+ types: rows.types,+ rows: rows.rows.slice(start, start + pageSize),+ has_more: start + pageSize < rows.rows.length,+ })+ }+const loadCurrentPage = async (): Promise<void> => {const { page, pageSize } = valuesconst runId = props.runId@@ -329,6 +403,10 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([actions.setPageResult(null)return}+ if (values.directRows) {+ sliceDirectRows(values.directRows, page, pageSize)+ return+ }// The pagination UI is disabled while the notebook is busy; this guards the// programmatic path. A same-node re-page supersedes (stale response discarded below).if (values.isBusy && values.activeOperation?.id !== pageOperation.id) {@@ -340,6 +418,26 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([const fetchId = (cache.pageFetchId = (cache.pageFetchId ?? 0) + 1)actions.setPageLoading(true)try {+ // A direct run keeps its full row set on the result endpoint while the backend's+ // query result is alive — recover it once (e.g. after a reload) and page locally+ // from then on. Kernel runs return no rows here and fall through to server paging.+ try {+ const recovered = await api.notebooks.sqlV2RunResult(props.notebookShortId, runId)+ if (recovered.status === 'done' && recovered.rows) {+ const directRows: NotebookNodeSQLV2DirectRows = {+ columns: recovered.result?.columns ?? [],+ types: recovered.result?.types ?? [],+ rows: recovered.rows,+ }+ actions.setDirectRows(directRows)+ if (cache.pageFetchId === fetchId) {+ sliceDirectRows(directRows, page, pageSize)+ }+ return+ }+ } catch {+ // Recovery is best-effort; the server page below reports real errors.+ }const pageResult = await api.notebooks.sqlV2RunPage(props.notebookShortId, runId, {offset: (page - 1) * pageSize,limit: pageSize,@@ -386,6 +484,26 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([actions.nodeRunFinished(props.nodeId, 'failed', null)return}+ // Which lane will this run take? Mirrors the backend's routing: python always+ // needs the kernel; SQL needs it only when it reads a local (python-made) frame.+ // The backend stays authoritative — this only drives the Stop affordance and+ // the kernel panel, never dispatch.+ const isKernelLane =+ opts.nodeType === 'python' ||+ extractDuckSqlTables(code).some((name) => refs[name]?.kind === 'local')+ actions.setActiveRunLane(isKernelLane ? 'kernel' : 'direct')+ if (isKernelLane) {+ // The backend provisions the sandbox itself when none is running; open the+ // kernel panel so the user can watch it come up instead of guessing.+ const kernelKnownRunning =+ notebookKernelInfoLogic.findMounted({ shortId: props.notebookShortId })?.values.isRunning ??+ false+ if (!kernelKnownRunning) {+ actions.setShowKernelInfo(true)+ actions.setPendingKernelStart(true)+ lemonToast.info('Starting a compute sandbox. The cell will run once it’s ready.')+ }+ }actions.startOperation(runOperation)try {const { run_id } = await api.notebooks.sqlV2Run(props.notebookShortId, {@@ -453,12 +571,22 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([}cache.pollInFlight = truetry {- const { status, result, error } = await api.notebooks.sqlV2RunResult(props.notebookShortId, runId)+ const { status, result, error, rows } = await api.notebooks.sqlV2RunResult(+ props.notebookShortId,+ runId+ )// A newer run started while this poll was in flight — its result and poller// must win, so drop this stale response instead of overwriting/stopping it.if (runId !== cache.activeRunId) {return}+ // Once the kernel panel reports the sandbox up, the wait is execution, not startup.+ if (+ values.pendingKernelStart &&+ notebookKernelInfoLogic.findMounted({ shortId: props.notebookShortId })?.values.isRunning+ ) {+ actions.setPendingKernelStart(false)+ }const envelopeResult: NotebookNodeSQLV2Result | null = result? {columns: result.columns ?? [],@@ -472,6 +600,17 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([}: nullif (status === 'done') {+ // A direct run's full capped row set arrives with the result — keep it+ // in memory for client-side paging (kernel runs return no rows here).+ actions.setDirectRows(+ rows+ ? {+ columns: result?.columns ?? [],+ types: result?.types ?? [],+ rows,+ }+ : null+ )props.updateAttributes({ result: envelopeResult })// A fresh envelope replaces whatever page the user had drilled into.actions.resetPaging()diff --git a/frontend/src/scenes/notebooks/Notebook/Notebook.scss b/frontend/src/scenes/notebooks/Notebook/Notebook.scssindex 5ee23b2648b4..2ecdca1d1982 100644--- a/frontend/src/scenes/notebooks/Notebook/Notebook.scss+++ b/frontend/src/scenes/notebooks/Notebook/Notebook.scss@@ -554,7 +554,9 @@}.Notebook__markdown-v2 .MarkdownNotebook__canvas {- padding-bottom: 6rem;+ // Generous trailing space so the last cell can scroll up off the bottom edge —+ // room to breathe while editing a cell near the end of the notebook.+ padding-bottom: max(18rem, 40vh);}.NotebookColumn--left.NotebookColumn--showing {diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsxindex 554e9ff0e38e..2b6555a41479 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.test.tsx@@ -1,5 +1,7 @@import { render } from '@testing-library/react'+import { FEATURE_FLAGS } from 'lib/constants'+import { NotebookNodeType } from '../types'import { KNOWN_NODES } from '../utils'import {@@ -7,12 +9,31 @@ import {RealNotebookNodeEdit,getEditableNodeAttributeKeys,getMarkdownNodeAttributeLabel,+ getMarkdownRegistryForFeatureFlags,getQueryTitle,getSerializableAttributeInputValue,getSerializableProps,} from './markdownNotebookRegistry'describe('markdownNotebookRegistry', () => {+ describe('getMarkdownRegistryForFeatureFlags', () => {+ it('offers a single SQL and Python cell, gated by the revamped notebooks flag', () => {+ // The unified insert surface: SQLV2 ("SQL") and PythonV2 ("Python") are the only+ // insertable code cells with the flag on; the legacy SQL/Python cells and the+ // legacy query node render but must never be insertable in markdown notebooks.+ const flagOn = getMarkdownRegistryForFeatureFlags({ [FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS]: true })+ expect(flagOn.components.SQLV2.insertCommand).toBeTruthy()+ expect(flagOn.components.PythonV2.insertCommand).toBeTruthy()+ for (const legacyTag of ['Query', 'Python', 'DuckSQL', 'HogQLSQL']) {+ expect(flagOn.components[legacyTag].insertCommand).toBeUndefined()+ }++ const flagOff = getMarkdownRegistryForFeatureFlags({})+ expect(flagOff.components.SQLV2.insertCommand).toBeUndefined()+ expect(flagOff.components.PythonV2.insertCommand).toBeUndefined()+ })+ })+it('does not make real notebook nodes mutually exclusive in markdown notebooks', () => {expect(NOTEBOOK_MARKDOWN_REGISTRY.components.Recording.exclusiveEditPanel).toBeUndefined()expect(NOTEBOOK_MARKDOWN_REGISTRY.components.FeatureFlag.exclusiveEditPanel).toBeUndefined()diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsxindex 281d4d413acf..48efddf8bd1d 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx@@ -173,7 +173,9 @@ export const MARKDOWN_NODE_DEFINITIONS: {{tagName: 'SQLV2',category: 'SQL',- label: 'SQL (v2)',+ // The single SQL node once the legacy SQL cells are deprecated (they render but+ // are not insertable), so it reads as plain "SQL" in the insert menu.+ label: 'SQL',insertCommand: {aliases: ['data', 'sql'],// New cells get a durable nodeId up front: parsed markdown block ids are contentdiff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.pyindex f7133cbe149b..043b6b1e5634 100644--- a/products/notebooks/backend/presentation/views/notebook.py+++ b/products/notebooks/backend/presentation/views/notebook.py@@ -72,6 +72,7 @@ from products.notebooks.backend.sql_v2 import (is_sql_v2_enabled,sql_v2_page_lock_key,)+from products.notebooks.backend.sql_v2_direct import enqueue_direct_run, sync_direct_runfrom products.notebooks.backend.sql_v2_references import (SQLV2Ref,SQLV2ReferenceError,@@ -1086,18 +1087,23 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD)try:- start_sql_v2_run_workflow(- SQLV2RunInput(- run_id=str(run.id),- notebook_short_id=notebook.short_id,- team_id=self.team_id,- user_id=user.id if isinstance(user, User) else None,- code=run_code,- node_type=node_type,- output_name=output_name,- inputs=inputs,+ if node_type == NotebookNodeRun.NodeType.HOGQL:+ # Direct lane: a pure-HogQL run never touches the sandbox — it rides the+ # async query manager, and the run-result poll advances the row.+ enqueue_direct_run(self.team, user if isinstance(user, User) else None, run)+ else:+ start_sql_v2_run_workflow(+ SQLV2RunInput(+ run_id=str(run.id),+ notebook_short_id=notebook.short_id,+ team_id=self.team_id,+ user_id=user.id if isinstance(user, User) else None,+ code=run_code,+ node_type=node_type,+ output_name=output_name,+ inputs=inputs,+ ))- )except Exception:logger.exception("notebook_sql_v2_run_start_failed", notebook_short_id=notebook.short_id)run.status = NotebookNodeRun.Status.FAILED@@ -1134,16 +1140,22 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDif run is None:raise Http404()+ # Direct (hogql) runs have no callback: this poll advances the row from the async+ # query status, and while the manager's result is alive it also returns the full+ # capped row set for client-side paging (`rows`, absent once expired).+ rows = sync_direct_run(run)+# Interrupted runs keep their envelope too: the walkthrough (Journey 9) promises the# captured stdout/stderr arrive with the final envelope even when the user stopped it.has_result = run.status in (NotebookNodeRun.Status.DONE, NotebookNodeRun.Status.INTERRUPTED)- return Response(- {- "status": run.status,- "result": run.envelope if has_result else None,- "error": run.error or None,- }- )+ payload: dict[str, Any] = {+ "status": run.status,+ "result": run.envelope if has_result else None,+ "error": run.error or None,+ }+ if rows is not None:+ payload["rows"] = rows+ return Response(payload)@extend_schema(exclude=True)@action(@@ -1191,17 +1203,15 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDreturn Response({"detail": "stale"}, status=409)if run.node_type == NotebookNodeRun.NodeType.HOGQL:- # Runs recorded before the code column existed (default "") have no query to page.- # Send that to the kernel and it round-trips into an opaque "page fetch failed"; catch- # it here with guidance instead.- if not run.code.strip():- return Response(- {"detail": "This result predates page support — re-run the query to page through it."},- status=400,- )+ # SQL results page client-side over the capped row set the run-result poll+ # serves (the direct lane); server paging remains only for kernel frames.+ return Response(+ {"detail": "SQL results are paged in the browser. Re-run the query to reload its rows."},+ status=400,+ )# A kernel run (python/duckdb) pages by slicing its result frame in the sandbox, so it# needs the result_id its envelope advertised — no frame written means nothing to page.- elif not run.result_id:+ if not run.result_id:return Response({"detail": "This result has no pageable frame — re-run the node."}, status=400)# An out-of-cache page holds this worker synchronously for up to the kernel timeout,@@ -1256,6 +1266,21 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD# Already terminal: idempotent noop; the client just reads the outcome.return Response({"status": run.status})+ if run.node_type == NotebookNodeRun.NodeType.HOGQL:+ # A direct (hogql) run has no kernel to signal and no cancellation — the query+ # runs to its bounded completion. Mark the row abandoned; the guarded update+ # yields to a completion that already landed, and sync_direct_run's own guard+ # can never overwrite this interrupt afterwards.+ NotebookNodeRun.objects.for_team(self.team_id).filter(+ id=run.id, status=NotebookNodeRun.Status.RUNNING+ ).update(+ status=NotebookNodeRun.Status.INTERRUPTED,+ error="Run stopped.",+ updated_at=now(),+ )+ run.refresh_from_db()+ return Response({"status": run.status})+try:known = interrupt_sql_v2_run(notebook, user if isinstance(user, User) else None, run)except SQLV2KernelNotRunning:diff --git a/products/notebooks/backend/sandbox/kernel/envelope.py b/products/notebooks/backend/sandbox/kernel/envelope.pyindex 1dafabc88ed6..ea1fde2ea260 100644--- a/products/notebooks/backend/sandbox/kernel/envelope.py+++ b/products/notebooks/backend/sandbox/kernel/envelope.py@@ -35,7 +35,7 @@ def json_safe_rows(rows: Sequence[Sequence[Any]]) -> list[list[Any]]:def from_columns_and_rows(columns: list[str],- rows: list[tuple[Any, ...]],+ rows: Sequence[Sequence[Any]],types: list[list[str]] | None = None,has_more: bool = False,) -> dict[str, Any]:diff --git a/products/notebooks/backend/sql_v2_data_plane.py b/products/notebooks/backend/sql_v2_data_plane.pyindex f2e5321e28b3..78895e78d7fa 100644--- a/products/notebooks/backend/sql_v2_data_plane.py+++ b/products/notebooks/backend/sql_v2_data_plane.py@@ -37,6 +37,7 @@ from posthog.models import Team, Userfrom products.notebooks.backend import frame_storefrom products.notebooks.backend.models import Notebookfrom products.notebooks.backend.sql_v2 import verify_data_plane_token+from products.notebooks.backend.sql_v2_direct import wrap_hogql_page_queryfrom products.notebooks.backend.sql_v2_serializers import NotebookSQLV2DataPlaneRequestSerializerlogger = structlog.get_logger(__name__)@@ -138,14 +139,7 @@ def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:except ExposedHogQLError as exc:return JsonResponse({"error": str(exc)}, status=400)- # Wrap rather than mutate the user's query: the outer LIMIT/OFFSET caps the page- # regardless of the query's own shape (set queries, its own LIMIT, etc.).- # The inner query is validated HogQL (parsed above) and the wrapper is re-parsed as HogQL- # downstream, so there is no raw-SQL injection; limit/offset are int()-cast.- # The newline before the closing paren keeps a trailing line comment (`-- …`) in the- # user's query from swallowing the wrapper.- # nosemgrep: semgrep.rules.security.hogql-fstring-audit- wrapped = f"select * from ({data['query']}\n) limit {int(data['limit'])} offset {int(data['offset'])}"+ wrapped = wrap_hogql_page_query(data["query"], limit=data["limit"], offset=data["offset"])if data["delivery"] == "object":if frame_store.is_enabled():diff --git a/products/notebooks/backend/sql_v2_direct.py b/products/notebooks/backend/sql_v2_direct.pynew file mode 100644index 000000000000..ec6fc96d3375--- /dev/null+++ b/products/notebooks/backend/sql_v2_direct.py@@ -0,0 +1,178 @@+"""The SQLV2 direct lane: pure-HogQL runs executed with no sandbox.++A SQL node whose refs are all hogql (node_type "hogql" after `resolve_sql_node_run`)+never needs the kernel — its inlined query runs on the same async query manager the+data plane already uses, enqueued straight from run dispatch. The manager's query_id+is derived from the run id (not the run id itself — see `notebook_direct_query_id`),+so no state beyond the run row is needed; the run-result poll advances the row from+the query status (`sync_direct_run`) because the manager has no completion callback.++Kernel-lane runs (python/duckdb) keep the Temporal -> sandbox dispatch in sql_v2.py.+"""++import hmac+import hashlib+from typing import TYPE_CHECKING, Any++from django.conf import settings+from django.utils import timezone++import structlog++from posthog.clickhouse.client.execute_async import QueryNotFoundError, enqueue_process_query_task, get_query_status+from posthog.clickhouse.query_tagging import Feature, Product, tags_context++from products.notebooks.backend.models import NotebookNodeRun+from products.notebooks.backend.sandbox.kernel import envelope as kernel_envelope+from products.notebooks.backend.sql_v2 import DISPLAY_PAGE_LIMIT, RESULT_CACHE_ROWS++if TYPE_CHECKING:+ from posthog.models import Team, User++logger = structlog.get_logger(__name__)++# How long a RUNNING direct run may lack a query status before the poll marks it failed.+# The manager writes the initial status synchronously at enqueue, so a missing status means+# it expired (its TTL is 20 min) or the run predates the direct lane (a kernel-executed+# hogql run, whose callback should land well within this window).+DIRECT_RUN_RESULT_GRACE_SECONDS = 600+++def notebook_direct_query_id(run_id: str) -> str:+ """A private async-manager query id for a direct run, derived from the run id.++ Not the run id itself. The run id is client-visible (it's in the notebook document+ and lands in the query log as client_query_id), and the async-manager status endpoint+ returns a query's cached rows to any team member with query access. Using the run id+ as the query id would put it in that shared namespace, letting a caller read a run's+ rows through the generic /query/<id>/ endpoint (bypassing the notebook + per-user+ warehouse checks) or poison them by enqueuing a colliding client_query_id. Deriving an+ unpublished id from SECRET_KEY keeps the run id out of the namespace; it's deterministic+ so the poll recomputes it with nothing stored.+ """+ return hmac.new(+ settings.SECRET_KEY.encode(),+ f"notebook-direct-query:{run_id}".encode(),+ hashlib.sha256,+ ).hexdigest()+++def wrap_hogql_page_query(query: str, limit: int, offset: int) -> str:+ """Cap a HogQL query with an outer LIMIT/OFFSET, without mutating it.++ Wrapping caps the page regardless of the query's own shape (set queries, its own+ LIMIT, etc.). The inner query is validated HogQL and the wrapper is re-parsed as+ HogQL downstream, so there is no raw-SQL injection; limit/offset are int()-cast.+ The newline before the closing paren keeps a trailing line comment (`-- …`) in the+ user's query from swallowing the wrapper.+ """+ # nosemgrep: semgrep.rules.security.hogql-fstring-audit+ return f"select * from ({query}\n) limit {int(limit)} offset {int(offset)}"+++def enqueue_direct_run(team: "Team", user: "User | None", run: NotebookNodeRun) -> None:+ """Enqueue a direct (hogql) run on the async query manager.++ The same engine the data plane rides for sandbox fetches — user-threaded HogQL+ access control, the per-team concurrency limiter, and the Redis status/result+ store all come with it. Fetches one extra row past the cache ceiling so+ `sync_direct_run` can detect has_more, mirroring the kernel's capped fetch.+ """+ wrapped = wrap_hogql_page_query(run.code, limit=RESULT_CACHE_ROWS + 1, offset=0)+ with tags_context(product=Product.NOTEBOOKS, feature=Feature.QUERY, team_id=team.id):+ enqueue_process_query_task(+ team=team,+ user_id=user.id if user else None,+ query_json={"kind": "HogQLQuery", "query": wrapped},+ query_id=notebook_direct_query_id(str(run.id)),+ # A Run click always executes; never serve a stale cached result.+ refresh_requested=True,+ # Dispatch normally rides transaction.on_commit, which never fires inside+ # a test transaction — run inline there, like the manager's own tests do.+ _test_only_bypass_celery=settings.TEST,+ )+++def _finish_direct_run(+ run: NotebookNodeRun, status: NotebookNodeRun.Status, envelope: dict | None, error: str | None+) -> bool:+ """Move a RUNNING run to a terminal state; return whether this call won the transition.++ Guarded on the current status so concurrent pollers are idempotent and a completed+ query can never overwrite an interrupt — the opposite of the kernel callback's+ deliberate upsert, because here nothing later holds a truer outcome. Refreshes+ `run` either way so the caller always sees the row that won.+ """+ updated = (+ NotebookNodeRun.objects.for_team(run.team_id)+ .filter(id=run.id, status=NotebookNodeRun.Status.RUNNING)+ .update(+ status=status,+ envelope=envelope,+ result_id=(envelope or {}).get("result_id"),+ error=error,+ updated_at=timezone.now(),+ )+ )+ run.refresh_from_db()+ return bool(updated)+++def sync_direct_run(run: NotebookNodeRun) -> list[list[Any]] | None:+ """Advance a direct (hogql) run from its async query status and return its transient rows.++ Called from the run-result poll. A RUNNING run whose query completed is moved to+ DONE/FAILED here (the manager has no callback); a DONE run keeps serving its full+ capped row set for client-side paging while the manager's result is alive (~20 min).+ Returns None when no rows are available — including for kernel-executed hogql runs,+ which never had a query status. Mutates `run` in place on a transition.+ """+ if run.node_type != NotebookNodeRun.NodeType.HOGQL:+ return None+ if run.status not in (NotebookNodeRun.Status.RUNNING, NotebookNodeRun.Status.DONE):+ return None++ try:+ status = get_query_status(team_id=run.team_id, query_id=notebook_direct_query_id(str(run.id)))+ except QueryNotFoundError:+ age_seconds = (timezone.now() - run.created_at).total_seconds()+ if run.status == NotebookNodeRun.Status.RUNNING and age_seconds > DIRECT_RUN_RESULT_GRACE_SECONDS:+ # The watchdog the kernel lane never had: with no status left to complete+ # this run, waiting longer cannot help.+ _finish_direct_run(+ run,+ NotebookNodeRun.Status.FAILED,+ envelope=None,+ error="The query expired before completing. Re-run it.",+ )+ return None++ if not status.complete:+ return None+ if status.error:+ if run.status == NotebookNodeRun.Status.RUNNING:+ message = status.error_message or "Query execution failed."+ _finish_direct_run(run, NotebookNodeRun.Status.FAILED, envelope=None, error=message)+ return None++ results: dict[str, Any] = status.results or {}+ columns = [str(column) for column in (results.get("columns") or [])]+ types = [[str(name), str(type_name)] for name, type_name in (results.get("types") or [])]+ raw_rows = results.get("results") or []+ # Mirror the kernel's capped fetch: the +1 row past the ceiling only signals has_more.+ fetched_has_more = len(raw_rows) > RESULT_CACHE_ROWS+ rows = kernel_envelope.json_safe_rows(raw_rows[:RESULT_CACHE_ROWS])++ if run.status == NotebookNodeRun.Status.RUNNING:+ envelope = kernel_envelope.from_columns_and_rows(+ columns,+ rows[:DISPLAY_PAGE_LIMIT],+ types,+ has_more=fetched_has_more or len(rows) > DISPLAY_PAGE_LIMIT,+ )+ _finish_direct_run(run, NotebookNodeRun.Status.DONE, envelope=envelope, error=None)+ # Lost transitions land here too (an interrupt, or another poller); the+ # refreshed row's status decides whether the rows may be served.+ if run.status != NotebookNodeRun.Status.DONE:+ return None+ return rowsdiff --git a/products/notebooks/backend/sql_v2_kernel_architecture.md b/products/notebooks/backend/sql_v2_kernel_architecture.mdindex fd9da557e215..d650c2f6efd0 100644--- a/products/notebooks/backend/sql_v2_kernel_architecture.md+++ b/products/notebooks/backend/sql_v2_kernel_architecture.md@@ -117,10 +117,10 @@ Python node execution uses `get_ipython().run_cell(code)` inside a capture conteA DuckDB node is then just: register any not-yet-registered file-backed inputs, `_ph.duck.sql(code)`, bind the result relation to `output_name` (as a registered DuckDB view + lazily-materializable frame), envelope with a capped preview. The result stays lazy in DuckDB until a downstream Python node calls for pandas.-The routing rule the server applies per run (from the walkthrough, now concrete):+The routing rule (from the walkthrough, now concrete) — applied by the **backend at dispatch**, not by the server:-- `node.type == hogql` and **all** inputs are `hogql` → push to CH: data-plane page fetch only, kernel untouched.-- anything else (Python node, DuckDB node, or a HogQL node would go here if we ever allow HogQL over local frames — we don't; that's what DuckDB syntax is for) → materialize `hogql` inputs to frame files, run in the kernel.+- `node.type == hogql` and **all** inputs are `hogql` → the **direct lane** (`sql_v2_direct.py`): the backend enqueues the inlined query on the async query manager and the run never reaches the sandbox at all — no kernel required, results land on the run row via the result poll. This amends walkthrough decision 4 ("the sandbox drives execution"): the backend routes, and the sandbox drives only kernel-lane runs. The server's own hogql handling (capped fetch, result cache, `/page` re-query) remains only for runs dispatched before the direct lane and is slated for removal.+- anything else (Python node, DuckDB node, or a HogQL node would go here if we ever allow HogQL over local frames — we don't; that's what DuckDB syntax is for) → materialize `hogql` inputs to frame files, run in the kernel. Dispatch provisions the kernel itself when none is running (the run is the user's ask for compute; the panel is presentation, not a prerequisite).## Result store and pagingdiff --git a/products/notebooks/backend/sql_v2_result_delivery.md b/products/notebooks/backend/sql_v2_result_delivery.mdindex 1ec83efe7b6d..601c58bc3cda 100644--- a/products/notebooks/backend/sql_v2_result_delivery.md+++ b/products/notebooks/backend/sql_v2_result_delivery.md@@ -4,24 +4,45 @@ How a SQLV2 node learns that its run finished and gets the result envelope.## Current approach: FE short-poll (implemented)-The run result is written durably to `NotebookNodeRun` (Postgres) by the sandbox-callback. The frontend node polls a cheap read endpoint until the run reaches a-terminal state.+The run result is written durably to `NotebookNodeRun` (Postgres). How it gets+there depends on the lane:++- **Kernel-lane runs (python/duckdb)**: the sandbox callback writes the envelope,+ as before.+- **Direct-lane runs (hogql, no sandbox — `sql_v2_direct.py`)**: the run rides the+ async query manager (the same engine the data plane uses), which has no+ completion callback, so the result poll itself advances the row: it reads the+ query status by `query_id = run_id` and applies a **guarded** transition+ (`filter(status=RUNNING).update(...)`) — idempotent under concurrent pollers,+ and a completed query can never overwrite an interrupt. A RUNNING run whose+ query status is gone (20-min TTL) fails after a grace window — the watchdog the+ kernel lane never had. While the manager's result is alive, the poll response+ also carries `rows` (the full capped set, ≤300) for client-side paging.++The frontend node polls a cheap read endpoint until the run reaches a terminal+state.- **Backend:** `GET .../sql_v2/runs/<run_id>` returns `{status, result, error}`- by reading the `NotebookNodeRun` row (one indexed query). No held connection,+ (+ transient `rows` for direct runs) by reading the `NotebookNodeRun` row (one+ indexed query, plus one Redis status read for direct runs). No held connection,no busy-loop.- **Frontend:** the node polls that endpoint (~1s) while it has a `runId` and therun is `running`; stops on `done`/`failed`/`interrupted`. In-progress state isderived from the run status, so it survives remounts and reloads. The poll timerlives in `cache.disposables` (auto-cleanup + pause on hidden tab).-- **Interrupt (Journey 9):** `POST .../sql_v2/runs/<run_id>/interrupt` proxies a- run-scoped stop to the kernel-server; the terminal state (`interrupted`) still- arrives via the callback → run row → poll, keeping one source of truth. The- interrupted envelope carries the stdout/stderr captured before the stop, and the- result endpoint surfaces it like a `done` envelope. When no kernel is reachable- the endpoint marks the run `interrupted` itself, so a user can always break out- of a RUNNING-forever row (there is no backend watchdog yet).+- **Interrupt (Journey 9):** for kernel-lane runs,+ `POST .../sql_v2/runs/<run_id>/interrupt` proxies a run-scoped stop to the+ kernel-server; the terminal state (`interrupted`) still arrives via the+ callback → run row → poll, keeping one source of truth. The interrupted+ envelope carries the stdout/stderr captured before the stop, and the result+ endpoint surfaces it like a `done` envelope. When no kernel is reachable the+ endpoint marks the run `interrupted` itself, so a user can always break out of+ a RUNNING-forever row (the kernel lane has no backend watchdog). For+ **direct (hogql) runs** there is nothing to signal and no cancellation: the+ endpoint marks the row abandoned immediately (the query runs to its bounded+ completion; the guarded poll transition can't overwrite the interrupt), and the+ UI hides Stop for these runs. Real cancellation (`cancel_query`: Celery revoke+ plus CH KILL) is a one-call upgrade if long queries warrant it.Chosen because the result is a **single terminal value**, not a live event stream.Polling a durable row is simpler than SSE and inherently resilient to connection@@ -116,12 +137,14 @@ reads stay stateless.## Where the full result lives-**Now: a capped in-memory cache in the kernel-server (hogql runs).** A run fetches up to-`RESULT_CACHE_ROWS` (300) rows in one ClickHouse query; the kernel-server keeps-them per run (LRU over the last 20 runs). `/page` requests within the cache are-local slices — no ClickHouse work, no held backend workers. Paging beyond the-cache, or after a kernel restart emptied it, falls back to a LIMIT/OFFSET-re-query through the data plane.+**Now: client-side for hogql runs.** A direct run fetches up to+`RESULT_CACHE_ROWS` (300) rows in one ClickHouse query; the full capped set rides+the result poll (`rows`) while the manager's Redis result is alive (~20 min), and+the browser pages it locally — the server page endpoint refuses hogql runs.+After expiry or reload only the envelope's `first_page` remains, with a re-run+affordance — the same model the legacy SQL editor uses (one clamped fetch,+client-side pages). The kernel-server's per-run hogql cache and `/page` re-query+still exist but serve only pre-direct-lane runs; both are slated for removal.**Kernel runs (python/duckdb) page from the on-sandbox result store.** The kernelwrites each produced frame to `/data/results/<result_id>.arrow`; `/page` requestsdiff --git a/products/notebooks/backend/temporal/sql_v2.py b/products/notebooks/backend/temporal/sql_v2.pyindex 6d3f4d25b8b7..34eebdd1e55c 100644--- a/products/notebooks/backend/temporal/sql_v2.py+++ b/products/notebooks/backend/temporal/sql_v2.py@@ -15,6 +15,7 @@ from temporalio import activity, common, workflowfrom posthog.models.user import Userfrom posthog.temporal.common.base import PostHogWorkflow+from products.notebooks.backend.kernel_runtime import get_kernel_runtimefrom products.notebooks.backend.models import Notebook, NotebookNodeRunfrom products.notebooks.backend.sql_v2 import SQLV2KernelNotRunning, dispatch_sql_v2_run@@ -53,10 +54,20 @@ def dispatch_sql_v2_run_activity(input: SQLV2RunInput) -> None:inputs=input.inputs,)except SQLV2KernelNotRunning:- # Terminal — retrying won't start the kernel. Mark failed; the SSE stream surfaces it.- run.status = NotebookNodeRun.Status.FAILED- run.error = "Kernel is not running. Start the instance first."- run.save(update_fields=["status", "error", "updated_at"])+ # No running kernel: provision one and dispatch again — a kernel-lane run is the+ # user's explicit ask for compute, so it must not dead-end on "press Start first".+ # A provisioning failure raises out of the activity; Temporal retries, and+ # exhaustion marks the run failed via the workflow's catch.+ get_kernel_runtime(notebook, user).ensure()+ dispatch_sql_v2_run(+ notebook,+ user,+ run,+ input.code,+ node_type=input.node_type,+ output_name=input.output_name,+ inputs=input.inputs,+ )@activity.defn(name="notebook-sandbox-cmd-mark-failed")@@ -78,7 +89,9 @@ class NotebookSQLV2RunWorkflow(PostHogWorkflow):await workflow.execute_activity(dispatch_sql_v2_run_activity,input,- start_to_close_timeout=timedelta(seconds=60),+ # Long enough for a cold sandbox provision (Modal pull + kernel boot),+ # which dispatch now performs itself when no kernel is running.+ start_to_close_timeout=timedelta(minutes=5),retry_policy=common.RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=2)),)except Exception:diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.pyindex 404c254cb842..2704cf6460d9 100644--- a/products/notebooks/backend/test/test_sql_v2.py+++ b/products/notebooks/backend/test/test_sql_v2.py@@ -20,6 +20,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterized+from posthog.clickhouse.client.execute_async import QueryNotFoundErrorfrom posthog.constants import AvailableFeaturefrom posthog.models.organization import OrganizationMembershipfrom posthog.models.scoping import team_scope@@ -52,6 +53,7 @@ from products.notebooks.backend.sql_v2 import ()from products.notebooks.backend.sql_v2_callback import MAX_ENVELOPE_BYTESfrom products.notebooks.backend.sql_v2_data_plane import _rows_to_arrow_bytes+from products.notebooks.backend.sql_v2_direct import notebook_direct_query_id, sync_direct_runfrom products.notebooks.backend.temporal.sql_v2 import (SQLV2RunInput,dispatch_sql_v2_run_activity,@@ -298,17 +300,77 @@ class TestSQLV2Run(APIBaseTest):self.run_url = f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/run/"@patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)- def test_run_creates_row_and_starts_workflow(self, _mock_enabled, mock_start):+ def test_sql_run_takes_the_direct_lane_not_the_sandbox(self, _mock_enabled, mock_enqueue, mock_start):+ # A pure-SQL run must never require a sandbox: no Temporal workflow, no kernel.response = self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1"}, format="json")self.assertEqual(response.status_code, 200)run_id = response.json()["run_id"]run = NotebookNodeRun.objects.for_team(self.team.id).get(id=run_id)self.assertEqual(run.status, NotebookNodeRun.Status.RUNNING)- # Paging re-queries the run's stored code, so losing it here breaks every page fetch.+ # The direct result poll and any future re-query read the run's stored code.self.assertEqual(run.code, "select 1")- mock_start.assert_called_once()- self.assertEqual(str(mock_start.call_args.args[0].run_id), run_id)+ mock_enqueue.assert_called_once()+ self.assertEqual(str(mock_enqueue.call_args.args[2].id), run_id)+ mock_start.assert_not_called()+ self.assertFalse(KernelRuntime.objects.filter(team=self.team).exists())++ @patch("products.notebooks.backend.sql_v2_direct.enqueue_process_query_task")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_direct_enqueue_threads_user_and_private_query_id(self, _mock_enabled, mock_enqueue):+ # user_id drives HogQL/warehouse access control downstream (a userless run fails+ # closed). The query_id must be the private derived id, never the client-visible+ # run_id — using the run_id would expose a run's rows through the generic query+ # endpoint and let a colliding client_query_id poison them.+ response = self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1"}, format="json")+ self.assertEqual(response.status_code, 200)+ run_id = response.json()["run_id"]+ kwargs = mock_enqueue.call_args.kwargs+ self.assertEqual(kwargs["user_id"], self.user.id)+ self.assertNotEqual(kwargs["query_id"], run_id)+ self.assertEqual(kwargs["query_id"], notebook_direct_query_id(run_id))+ self.assertTrue(kwargs["refresh_requested"])+ self.assertIn("select 1", kwargs["query_json"]["query"])++ @patch("products.notebooks.backend.sql_v2_direct.get_query_status", side_effect=QueryNotFoundError())+ def test_a_query_status_under_the_run_id_cannot_poison_the_run(self, mock_status):+ # The vuln being closed: a collaborator enqueues a query with client_query_id =+ # run_id, then polls while the run is RUNNING. The poll must look up the private+ # derived id, not the run_id, so the attacker's rows are never adopted.+ with team_scope(self.team.id):+ run = NotebookNodeRun.objects.create(+ team=self.team, notebook=self.notebook, node_id="n1", status=NotebookNodeRun.Status.RUNNING+ )+ sync_direct_run(run)+ self.assertEqual(mock_status.call_args.kwargs["query_id"], notebook_direct_query_id(str(run.id)))+ self.assertNotEqual(mock_status.call_args.kwargs["query_id"], str(run.id))++ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_sql_run_completes_direct_with_no_kernel(self, _mock_enabled, mock_start):+ # End to end through the real async query manager (inline in tests): run a SQL+ # node with no kernel anywhere, then poll the result to completion.+ response = self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1 as a"}, format="json")+ self.assertEqual(response.status_code, 200)+ run_id = response.json()["run_id"]++ result_url = f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/runs/{run_id}/"+ body = self.client.get(result_url).json()+ self.assertEqual(body["status"], NotebookNodeRun.Status.DONE)+ envelope = body["result"]+ self.assertEqual(envelope["status"], "ok")+ self.assertEqual(envelope["columns"], ["a"])+ self.assertEqual(envelope["first_page"], [[1]])+ self.assertEqual(envelope["row_count"], 1)+ self.assertFalse(envelope["has_more"])+ self.assertTrue(envelope["result_id"])+ # The full capped row set rides the poll for client-side paging, on repeat polls too.+ self.assertEqual(body["rows"], [[1]])+ self.assertEqual(self.client.get(result_url).json()["rows"], [[1]])++ mock_start.assert_not_called()+ self.assertFalse(KernelRuntime.objects.filter(team=self.team).exists())@patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)@@ -339,11 +401,11 @@ class TestSQLV2Run(APIBaseTest):status=NotebookNodeRun.Status.DONE,)- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)- def test_run_inlines_referenced_nodes_last_run_query_as_ctes(self, _mock_enabled, mock_start):- # Paging re-queries run.code, so the stored + dispatched query must already carry the- # referenced definitions as CTEs — and it must be each node's last run, not its live text.+ def test_run_inlines_referenced_nodes_last_run_query_as_ctes(self, _mock_enabled, mock_enqueue):+ # The direct lane executes run.code verbatim, so the stored query must already carry+ # the referenced definitions as CTEs — and it must be each node's last run, not its live text.self._record_done_run("node-df1", "select id from events")self._record_done_run("node-df2", "select id from persons")response = self.client.post(@@ -359,11 +421,11 @@ class TestSQLV2Run(APIBaseTest):run = NotebookNodeRun.objects.for_team(self.team.id).get(id=response.json()["run_id"])self.assertIn("WITH df1 AS (SELECT id FROM events)", run.code)self.assertIn("df2 AS (SELECT id FROM persons)", run.code)- self.assertEqual(mock_start.call_args.args[0].code, run.code)+ mock_enqueue.assert_called_once()- @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ @patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)- def test_run_uses_the_latest_done_run_of_a_referenced_node(self, _mock_enabled, mock_start):+ def test_run_uses_the_latest_done_run_of_a_referenced_node(self, _mock_enabled, _mock_enqueue):# An edited-then-rerun upstream: only its most recent run should be inlined.with freeze_time("2026-07-04T00:00:00Z"):self._record_done_run("node-df1", "select 1 as old_col")@@ -503,11 +565,11 @@ class TestSQLV2Run(APIBaseTest):)@patch(- "products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow",- side_effect=RuntimeError("temporal unavailable"),+ "products.notebooks.backend.presentation.views.notebook.enqueue_direct_run",+ side_effect=RuntimeError("redis unavailable"),)@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)- def test_run_marks_failed_when_workflow_start_fails(self, _mock_enabled, _mock_start):+ def test_run_marks_failed_when_direct_enqueue_fails(self, _mock_enabled, _mock_enqueue):response = self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1"}, format="json")self.assertEqual(response.status_code, 503)run = NotebookNodeRun.objects.for_team(self.team.id).filter(notebook=self.notebook).first()@@ -627,11 +689,20 @@ class TestSQLV2RunPage(APIBaseTest):{"offset": offset, "limit": limit},)+ def _create_kernel_run(self, status=NotebookNodeRun.Status.DONE, node_id="n1") -> NotebookNodeRun:+ return self._create_run(+ status=status,+ node_id=node_id,+ code="df1.head()",+ node_type=NotebookNodeRun.NodeType.PYTHON,+ result_id="11111111-1111-1111-1111-111111111111",+ )+@patch("products.notebooks.backend.presentation.views.notebook.fetch_sql_v2_page")@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)def test_returns_page_from_kernel(self, _mock_enabled, mock_fetch):mock_fetch.return_value = {"columns": ["a"], "types": [["a", "Int64"]], "rows": [[51]], "has_more": False}- run = self._create_run()+ run = self._create_kernel_run()response = self._get(str(run.id))self.assertEqual(response.status_code, 200)self.assertEqual(response.json()["rows"], [[51]])@@ -652,18 +723,19 @@ class TestSQLV2RunPage(APIBaseTest):@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)def test_kernel_not_running_returns_503(self, _mock_enabled):# No KernelRuntime exists, so the real fetch path raises SQLV2KernelNotRunning.- run = self._create_run()+ run = self._create_kernel_run()response = self._get(str(run.id))self.assertEqual(response.status_code, 503)@patch("products.notebooks.backend.presentation.views.notebook.fetch_sql_v2_page")@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)- def test_empty_code_run_is_rejected_before_reaching_the_kernel(self, _mock_enabled, mock_fetch):- # Pre-migration runs stored code="" — paging must fail clearly, not round-trip to an opaque error.- run = self._create_run(code="")+ def test_hogql_run_paging_is_retired(self, _mock_enabled, mock_fetch):+ # SQL results page client-side over the rows the result poll serves; the server+ # page endpoint must refuse hogql runs instead of round-tripping to a kernel.+ run = self._create_run()response = self._get(str(run.id))self.assertEqual(response.status_code, 400)- self.assertIn("re-run", response.json()["detail"])+ self.assertIn("Re-run", response.json()["detail"])mock_fetch.assert_not_called()@patch("products.notebooks.backend.presentation.views.notebook.fetch_sql_v2_page")@@ -702,7 +774,7 @@ class TestSQLV2RunPage(APIBaseTest):# Each out-of-cache page fetch holds a web worker for up to the kernel timeout, so a# user with a fetch already in flight must be rejected instead of stacking workers.mock_fetch.return_value = {"columns": [], "types": [], "rows": [], "has_more": False}- run = self._create_run()+ run = self._create_kernel_run()lock_key = sql_v2_page_lock_key(self.team.id, self.user.id)cache.add(lock_key, True, timeout=10)try:@@ -873,18 +945,66 @@ class TestSQLV2RunResult(APIBaseTest):_restrict_query_access(self)self.assertEqual(self.client.get(self._url(str(run.id))).status_code, 403)+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_running_direct_run_expires_to_failed_after_grace(self, _mock_enabled):+ # A RUNNING hogql run with no query status left can never complete — this poll is+ # its watchdog. Within the grace window it keeps waiting (covers pre-deploy+ # kernel-executed hogql runs whose callback is still due).+ with freeze_time("2026-07-01T00:00:00Z"):+ expired = self._create_run(NotebookNodeRun.Status.RUNNING)+ body = self.client.get(self._url(str(expired.id))).json()+ self.assertEqual(body["status"], NotebookNodeRun.Status.FAILED)+ self.assertIn("expired", body["error"])++ young = self._create_run(NotebookNodeRun.Status.RUNNING)+ body = self.client.get(self._url(str(young.id))).json()+ self.assertEqual(body["status"], NotebookNodeRun.Status.RUNNING)++ @patch("products.notebooks.backend.sql_v2_direct.get_query_status")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_query_error_fails_the_direct_run_with_its_message(self, _mock_enabled, mock_status):+ # An errored query must fail the run with the user-facing message, or the node+ # polls a RUNNING row forever.+ mock_status.return_value = SimpleNamespace(complete=True, error=True, error_message="Query exceeds time budget")+ run = self._create_run(NotebookNodeRun.Status.RUNNING)+ body = self.client.get(self._url(str(run.id))).json()+ self.assertEqual(body["status"], NotebookNodeRun.Status.FAILED)+ self.assertEqual(body["error"], "Query exceeds time budget")++ @patch("products.notebooks.backend.sql_v2_direct.get_query_status")+ def test_completed_query_never_overwrites_an_interrupt(self, mock_status):+ # The race: the user interrupts while a poller holds a stale RUNNING row and the+ # query then completes. The guarded transition must let the interrupt stand.+ run = self._create_run(NotebookNodeRun.Status.RUNNING)+ stale = NotebookNodeRun.objects.for_team(self.team.id).get(id=run.id)+ NotebookNodeRun.objects.for_team(self.team.id).filter(id=run.id).update(+ status=NotebookNodeRun.Status.INTERRUPTED+ )+ mock_status.return_value = SimpleNamespace(+ complete=True,+ error=False,+ error_message=None,+ results={"columns": ["a"], "types": [["a", "Int64"]], "results": [[1]]},+ )+ self.assertIsNone(sync_direct_run(stale))+ reloaded = NotebookNodeRun.objects.for_team(self.team.id).get(id=run.id)+ self.assertEqual(reloaded.status, NotebookNodeRun.Status.INTERRUPTED)+ self.assertIsNone(reloaded.envelope)+class TestSQLV2RunInterrupt(APIBaseTest):def setUp(self):super().setUp()self.notebook = Notebook.objects.create(team=self.team, short_id="nbint01")with team_scope(self.team.id):+ # A kernel-lane run: interrupt round-trips to the kernel only for these.self.node_run = NotebookNodeRun.objects.create(team=self.team,notebook=self.notebook,node_id="n1",status=NotebookNodeRun.Status.RUNNING,- code="select event from events",+ code="df1.head()",+ node_type=NotebookNodeRun.NodeType.PYTHON,)def _url(self, run_id: str) -> str:@@ -986,6 +1106,30 @@ class TestSQLV2RunInterrupt(APIBaseTest):self.assertIn("detail", response.json())self.assertEqual(self._reload_run().status, NotebookNodeRun.Status.RUNNING)+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ @patch("products.notebooks.backend.sql_v2.requests.post")+ def test_direct_sql_run_interrupt_marks_without_kernel(self, mock_post, _mock_enabled):+ # A direct (hogql) run has no kernel to signal: interrupt marks the row abandoned+ # immediately, even when a live kernel exists for this user.+ self._create_runtime()+ with team_scope(self.team.id):+ sql_run = NotebookNodeRun.objects.create(+ team=self.team,+ notebook=self.notebook,+ node_id="n2",+ status=NotebookNodeRun.Status.RUNNING,+ code="select 1",+ )++ response = self.client.post(self._url(str(sql_run.id)))++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json()["status"], NotebookNodeRun.Status.INTERRUPTED)+ mock_post.assert_not_called()+ reloaded = NotebookNodeRun.objects.for_team(self.team.id).get(id=sql_run.id)+ self.assertEqual(reloaded.status, NotebookNodeRun.Status.INTERRUPTED)+ self.assertTrue(reloaded.error)+@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)def test_run_from_another_notebook_is_404(self, _mock_enabled):# IDOR guard: a run id from a different notebook must not be interruptible (or even@@ -1024,10 +1168,28 @@ class TestSQLV2Activities(APIBaseTest):def _reload(self, run: NotebookNodeRun) -> NotebookNodeRun:return NotebookNodeRun.objects.for_team(self.team.id).get(id=run.id)- def test_dispatch_activity_marks_failed_without_kernel(self):+ @patch("products.notebooks.backend.temporal.sql_v2.dispatch_sql_v2_run")+ @patch("products.notebooks.backend.temporal.sql_v2.get_kernel_runtime")+ def test_dispatch_activity_provisions_kernel_when_missing(self, mock_get_runtime, mock_dispatch):+ # Scenario B: a kernel-lane run with no kernel must provision one and dispatch,+ # not dead-end on "start the instance first".+ mock_dispatch.side_effect = [SQLV2KernelNotRunning(), None]run = self._create_run()dispatch_sql_v2_run_activity(self._run_input(run))- self.assertEqual(self._reload(run).status, NotebookNodeRun.Status.FAILED)+ mock_get_runtime.return_value.ensure.assert_called_once()+ self.assertEqual(mock_dispatch.call_count, 2)+ self.assertEqual(self._reload(run).status, NotebookNodeRun.Status.RUNNING)++ @patch("products.notebooks.backend.temporal.sql_v2.dispatch_sql_v2_run", side_effect=SQLV2KernelNotRunning())+ @patch("products.notebooks.backend.temporal.sql_v2.get_kernel_runtime")+ def test_dispatch_activity_raises_when_provisioning_fails(self, mock_get_runtime, _mock_dispatch):+ # A provisioning failure must raise out of the activity so Temporal retries and,+ # on exhaustion, the workflow marks the run failed — never a silent RUNNING row.+ mock_get_runtime.return_value.ensure.side_effect = RuntimeError("no sandbox capacity")+ run = self._create_run()+ with self.assertRaises(RuntimeError):+ dispatch_sql_v2_run_activity(self._run_input(run))+ self.assertEqual(self._reload(run).status, NotebookNodeRun.Status.RUNNING)@patch("products.notebooks.backend.sql_v2._server_version")@patch("products.notebooks.backend.sql_v2.requests.post")diff --git a/pyproject.toml b/pyproject.tomlindex b69709068d8e..e11bd5033178 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -589,6 +589,7 @@ ignore_imports = ["products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.python_analysis","products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.query_validation","products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2",+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_direct","products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_references","products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_serializers","products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.temporal.client",