Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(notebooks): run Python nodes in the SQLV2 kernel (Journey 4) (#68502)

Sinan Kucukkoseler803791162d51
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 66a1a4532a7a..7caf08a70d56 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -4894,7 +4894,13 @@ const api = {
},
async sqlV2Run(
notebookId: NotebookType['short_id'],
- data: { node_id: string; code: string; refs?: Record<string, string> }
+ data: {
+ node_id: string
+ code: string
+ refs?: Record<string, string>
+ node_type?: 'hogql' | 'python'
+ output_name?: string
+ }
): Promise<{ run_id: string }> {
return await new ApiRequest().notebook(notebookId).withAction('sql_v2/run').create({ data })
},
@@ -4909,6 +4915,9 @@ const api = {
row_count?: number
first_page?: (string | number | null)[][]
has_more?: boolean
+ stdout?: string
+ stderr?: string
+ media?: { mime_type: string; data: string }[]
} | null
error: string | null
}> {
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx
new file mode 100644
index 000000000000..253fe3281de9
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePythonV2.tsx
@@ -0,0 +1,247 @@
+import { useActions, useMountedLogic, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { IconCornerDownRight, IconPlayFilled } from '@posthog/icons'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { CodeEditorResizeable } from 'lib/monaco/CodeEditorResizable'
+import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'
+
+import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'
+import { NotebookDataframeTable } from './components/NotebookDataframeTable'
+import { notebookNodeLogic } from './notebookNodeLogic'
+import type { NotebookNodeSQLV2Result } from './NotebookNodeSQLV2'
+import { SQL_V2_DEFAULT_PAGE_SIZE, collectSqlV2Refs, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'
+import { NotebookDataframeResult } from './pythonExecution'
+
+// The revamped Python cell: code runs in the notebook's sandbox kernel via the SQLV2 run
+// 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.
+
+export type NotebookNodePythonV2Attributes = {
+ code: string
+ // The dataframe name this cell's result is exposed as to later cells.
+ returnVariable: string
+ runId?: string | null
+ result?: NotebookNodeSQLV2Result | null
+}
+
+const toDataframeResult = (result: NotebookNodeSQLV2Result): NotebookDataframeResult => {
+ const columns = result.columns ?? []
+ const firstPage = result.first_page ?? []
+ return {
+ columns,
+ rows: firstPage.map((row) => Object.fromEntries(columns.map((column, index) => [column, row[index] ?? null]))),
+ rowCount: firstPage.length,
+ }
+}
+
+const Component = ({
+ attributes,
+ updateAttributes,
+}: NotebookNodeProps<NotebookNodePythonV2Attributes>): JSX.Element | null => {
+ const nodeLogic = useMountedLogic(notebookNodeLogic)
+ const { nodeId, notebookLogic, expanded } = useValues(nodeLogic)
+ const notebookShortId = notebookLogic.props.shortId
+
+ const dataLogic = notebookNodeSQLV2Logic({
+ nodeId,
+ notebookShortId,
+ updateAttributes,
+ runId: attributes.runId ?? null,
+ hasResult: !!attributes.result,
+ })
+ const { isRunning, runError, page, pageSize, pageResult, pageLoading, operationBlockReason } = useValues(dataLogic)
+ const { setPage, setPageSize } = useActions(dataLogic)
+
+ const result = attributes.result ?? null
+ const dataframeResult = useMemo(() => {
+ if (pageResult) {
+ return toDataframeResult({
+ columns: pageResult.columns,
+ row_count: pageResult.rows.length,
+ first_page: pageResult.rows,
+ })
+ }
+ return result && result.columns?.length ? toDataframeResult(result) : null
+ }, [pageResult, result])
+ const hasMorePages = pageResult
+ ? pageResult.has_more
+ : (result?.has_more ?? (result?.first_page ?? []).length >= SQL_V2_DEFAULT_PAGE_SIZE)
+
+ 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
+ className="flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto"
+ onMouseDown={(event) => event.stopPropagation()}
+ onDragStart={(event) => event.stopPropagation()}
+ >
+ {hasStreamOutput ? (
+ <div className="shrink-0 space-y-2 px-2 pt-1" onClick={(event) => event.stopPropagation()}>
+ {result?.stdout ? (
+ <pre className="text-xs font-mono whitespace-pre-wrap select-text m-0">{result.stdout}</pre>
+ ) : null}
+ {result?.stderr ? (
+ <pre className="text-xs font-mono whitespace-pre-wrap text-danger select-text m-0">
+ {result.stderr}
+ </pre>
+ ) : null}
+ {result?.media?.map((item, index) => (
+ <img
+ key={index}
+ src={`data:${item.mime_type};base64,${item.data}`}
+ alt="Python output"
+ className="max-w-full rounded border border-border bg-white"
+ />
+ ))}
+ </div>
+ ) : null}
+ {runError ? (
+ <div className="p-2 text-xs font-mono text-danger whitespace-pre-wrap">{runError}</div>
+ ) : dataframeResult ? (
+ <div className="min-h-0 flex-1 overflow-y-auto">
+ <NotebookDataframeTable
+ result={dataframeResult}
+ loading={isRunning || pageLoading}
+ page={page}
+ pageSize={pageSize}
+ hasMore={hasMorePages}
+ paginationDisabledReason={
+ pageLoading
+ ? 'Fetching page…'
+ : isRunning
+ ? 'Cell is running'
+ : (operationBlockReason ?? undefined)
+ }
+ onNextPage={() => setPage(page + 1)}
+ onPreviousPage={() => setPage(page - 1)}
+ onPageSizeChange={setPageSize}
+ />
+ </div>
+ ) : hasStreamOutput ? null : (
+ <div className="text-xs text-muted font-mono p-2">Run the cell to see execution results.</div>
+ )}
+ {attributes.runId ? (
+ <div className="shrink-0 px-2 pb-2 text-[10px] uppercase tracking-wide text-muted select-text">
+ run_id: {attributes.runId}
+ </div>
+ ) : null}
+ </div>
+ <div
+ className="flex shrink-0 items-center gap-2 text-xs text-muted border-t p-2"
+ onClick={(event) => event.stopPropagation()}
+ onMouseDown={(event) => event.stopPropagation()}
+ >
+ <span className="font-mono mt-0.5">
+ <IconCornerDownRight />
+ </span>
+ <input
+ type="text"
+ // The dataframe name this cell's result is exposed as to later cells.
+ 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 })}
+ spellCheck={false}
+ />
+ </div>
+ </div>
+ )
+}
+
+const Settings = ({
+ attributes,
+ updateAttributes,
+}: NotebookNodeAttributeProperties<NotebookNodePythonV2Attributes>): JSX.Element => {
+ const nodeLogic = useMountedLogic(notebookNodeLogic)
+ const { nodeId, notebookLogic } = useValues(nodeLogic)
+ const notebookShortId = notebookLogic.props.shortId
+
+ const dataLogic = notebookNodeSQLV2Logic({
+ nodeId,
+ notebookShortId,
+ updateAttributes,
+ runId: attributes.runId ?? null,
+ hasResult: !!attributes.result,
+ })
+ const { isRunning, operationBlockReason } = useValues(dataLogic)
+ const { runQuery } = useActions(dataLogic)
+
+ const run = (): void => {
+ // The refs map sibling SQLV2 frames; the backend materializes only the ones the code reads.
+ runQuery(attributes.code ?? '', collectSqlV2Refs(notebookLogic.values.content, nodeId), {
+ nodeType: 'python',
+ outputName: attributes.returnVariable,
+ })
+ }
+
+ return (
+ <div className="flex h-full min-h-0 flex-col">
+ {/* Mirrors the embedded SQL editor's toolbar (QueryWindow) so code cells look alike. */}
+ <div
+ className="flex w-full shrink-0 flex-row items-center gap-2 border-t border-b bg-white py-1 pl-2 pr-2 dark:bg-black"
+ onClick={(event) => event.stopPropagation()}
+ >
+ <LemonButton
+ data-attr="notebook-python-v2-run-button"
+ size="small"
+ type="primary"
+ icon={<IconPlayFilled color="var(--success)" />}
+ onClick={() => {
+ if (!isRunning) {
+ run()
+ }
+ }}
+ loading={isRunning}
+ disabledReason={operationBlockReason ?? undefined}
+ tooltip="Run Python (⌘⏎)"
+ >
+ Run
+ </LemonButton>
+ </div>
+ <div className="min-h-0 flex-1">
+ <CodeEditorResizeable
+ language="python"
+ value={typeof attributes.code === 'string' ? attributes.code : ''}
+ onChange={(value) => updateAttributes({ code: value ?? '' })}
+ onPressCmdEnter={run}
+ allowManualResize={false}
+ minHeight={160}
+ embedded
+ />
+ </div>
+ </div>
+ )
+}
+
+export const NotebookNodePythonV2 = createPostHogWidgetNode<NotebookNodePythonV2Attributes>({
+ nodeType: NotebookNodeType.PythonV2,
+ titlePlaceholder: 'Python',
+ Component,
+ heightEstimate: 120,
+ minHeight: 80,
+ resizeable: true,
+ startExpanded: true,
+ attributes: {
+ code: {
+ default: '',
+ },
+ returnVariable: {
+ default: 'df',
+ },
+ runId: {
+ default: null,
+ },
+ result: {
+ default: null,
+ },
+ },
+ Settings,
+ settingsPlacement: 'inline',
+ serializedText: (attrs) => attrs.code,
+})
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
index 85f307af4a15..c9b420eb63c9 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
@@ -19,12 +19,18 @@ import { notebookNodeLogic } from './notebookNodeLogic'
import { SQL_V2_DEFAULT_PAGE_SIZE, collectSqlV2Refs, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'
import { NotebookDataframeResult } from './pythonExecution'
+export type NotebookNodeSQLV2Media = { mime_type: string; data: string }
+
export type NotebookNodeSQLV2Result = {
columns: string[]
types?: [string, string][]
row_count: number
first_page: (string | number | null)[][]
has_more?: boolean
+ // Python node output: captured streams and rich media (e.g. matplotlib PNGs).
+ stdout?: string
+ stderr?: string
+ media?: NotebookNodeSQLV2Media[]
}
export type NotebookNodeSQLV2Attributes = {
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
index 2e432204975c..53f870a80624 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts
@@ -92,7 +92,7 @@ describe('notebookNodeSQLV2Logic', () => {
logic.actions.runQuery(' ')
await expectLogic(logic)
.toFinishAllListeners()
- .toMatchValues({ runError: 'Query is empty — type some HogQL first.', isRunning: false })
+ .toMatchValues({ runError: 'Nothing to run — type some code first.', isRunning: false })
expect(runSpy).not.toHaveBeenCalled()
})
@@ -106,6 +106,19 @@ describe('notebookNodeSQLV2Logic', () => {
expect(updateAttributes).toHaveBeenCalledWith({ nodeId: 'n1', runId: 'r1', result: null })
})
+ it('dispatches a python run with its node type and output name', async () => {
+ mount()
+ logic.actions.runQuery('df.head()', { sql_df: 'other' }, { nodeType: 'python', outputName: 'df' })
+ await expectLogic(logic).toDispatchActions(['runQuery', 'startPolling'])
+ expect(runSpy).toHaveBeenCalledWith('nb1', {
+ node_id: 'n1',
+ code: 'df.head()',
+ refs: { sql_df: 'other' },
+ node_type: 'python',
+ output_name: 'df',
+ })
+ })
+
it('maps a done envelope into the node result and stops the spinner', async () => {
resultSpy.mockResolvedValue({
status: 'done',
@@ -115,7 +128,16 @@ describe('notebookNodeSQLV2Logic', () => {
mount({ runId: 'r1', hasResult: false })
await expectLogic(logic).toFinishAllListeners()
expect(updateAttributes).toHaveBeenCalledWith({
- result: { columns: ['a'], types: [], row_count: 1, first_page: [[1]], has_more: false },
+ result: {
+ columns: ['a'],
+ types: [],
+ row_count: 1,
+ first_page: [[1]],
+ has_more: false,
+ stdout: '',
+ stderr: '',
+ media: [],
+ },
})
expect(logic.values.isRunning).toBe(false)
})
diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
index 7210cd62207b..7d9aaa9eaf0f 100644
--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts
@@ -36,6 +36,11 @@ export type NotebookNodeSQLV2Page = {
has_more: boolean
}
+export interface RunQueryOptions {
+ nodeType?: 'hogql' | 'python'
+ outputName?: string
+}
+
export interface NotebookNodeSQLV2LogicProps {
nodeId: string
notebookShortId: string
@@ -61,9 +66,14 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
],
})),
actions({
- // refs maps each named sibling node's dataframe name to its HogQL; the backend
- // inlines the ones this query references as CTEs (Journey 3).
- runQuery: (code: string, refs: Record<string, string> = {}) => ({ code, refs }),
+ // refs maps each named sibling node's dataframe name to its node id. A hogql node
+ // inlines the referenced ones as CTEs (Journey 3); a python node materializes the
+ // ones its code reads as pandas frames (Journey 4).
+ runQuery: (code: string, refs: Record<string, string> = {}, opts: RunQueryOptions = {}) => ({
+ code,
+ refs,
+ opts,
+ }),
startPolling: (runId: string) => ({ runId }),
pollResult: (runId: string) => ({ runId }),
stopPolling: true,
@@ -185,9 +195,9 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
return {
setPage: loadCurrentPage,
setPageSize: loadCurrentPage,
- runQuery: async ({ code, refs }) => {
+ runQuery: async ({ code, refs, opts }) => {
if (!code.trim()) {
- actions.setRunError('Query is empty — type some HogQL first.')
+ actions.setRunError('Nothing to run — type some code first.')
actions.setIsRunning(false)
return
}
@@ -204,6 +214,8 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
node_id: props.nodeId,
code,
refs,
+ node_type: opts.nodeType,
+ output_name: opts.outputName,
})
// Mark this as the active run so a still-in-flight poll from a previous run
// can't overwrite this result or stop this run's poller once it resolves.
@@ -258,6 +270,9 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([
row_count: result.row_count ?? 0,
first_page: result.first_page ?? [],
has_more: result.has_more ?? false,
+ stdout: result.stdout ?? '',
+ stderr: result.stderr ?? '',
+ media: result.media ?? [],
}
: null,
})
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
index bfe586218d03..6e1215ebc9c8 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx
@@ -21,6 +21,7 @@ import '../Nodes/NotebookNodePersonFeed/NotebookNodePersonFeed'
import '../Nodes/NotebookNodePersonProperties'
import '../Nodes/NotebookNodePlaylist'
import '../Nodes/NotebookNodePython'
+import '../Nodes/NotebookNodePythonV2'
import '../Nodes/NotebookNodeQuery'
import '../Nodes/NotebookNodeRecording'
import '../Nodes/NotebookNodeRelatedGroups'
@@ -111,6 +112,7 @@ const MARKDOWN_NODE_ATTRIBUTE_LABELS: Partial<Record<NotebookNodeType, Record<st
export const MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE: Partial<Record<string, NotebookNodeType>> = {
Query: NotebookNodeType.Query,
Python: NotebookNodeType.Python,
+ PythonV2: NotebookNodeType.PythonV2,
DuckSQL: NotebookNodeType.DuckSQL,
HogQLSQL: NotebookNodeType.HogQLSQL,
SQLV2: NotebookNodeType.SQLV2,
@@ -152,7 +154,20 @@ export const MARKDOWN_NODE_DEFINITIONS: {
insertCommand?: NotebookComponentDefinition['insertCommand']
}[] = [
{ tagName: 'Query', category: 'Insight' },
+ // Legacy in-browser-kernel Python cell: still renders where it exists, but new cells
+ // are always the revamped PythonV2 below, so it has no insertCommand.
{ tagName: 'Python', category: 'Code' },
+ // The revamped (sandbox-kernel) Python cell; insertion gated like SQLV2 in
+ // getMarkdownRegistryForFeatureFlags.
+ {
+ tagName: 'PythonV2',
+ category: 'Code',
+ label: 'Python',
+ insertCommand: {
+ aliases: ['python', 'py'],
+ defaultProps: () => ({ ...getDefaultPropsForNodeType(NotebookNodeType.PythonV2), nodeId: uuid() }),
+ },
+ },
{ tagName: 'DuckSQL', category: 'SQL', label: 'SQL (DuckDB)' },
{ tagName: 'HogQLSQL', category: 'SQL', label: 'SQL (HogQL)' },
// insertCommand makes it show in the markdown insert menu; the feature-flag gate in
@@ -251,7 +266,7 @@ export const NOTEBOOK_MARKDOWN_REGISTRY: NotebookComponentRegistry = createMarkd
export function getMarkdownRegistryForFeatureFlags(featureFlags: FeatureFlagsSet): NotebookComponentRegistry {
const hiddenTags: string[] = []
if (!featureFlags[FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS]) {
- hiddenTags.push('SQLV2')
+ hiddenTags.push('SQLV2', 'PythonV2')
}
if (hiddenTags.length === 0) {
@@ -300,6 +315,7 @@ export function getMarkdownNotebookNodeTitle(
}
if (
nodeType === NotebookNodeType.Python ||
+ nodeType === NotebookNodeType.PythonV2 ||
nodeType === NotebookNodeType.DuckSQL ||
nodeType === NotebookNodeType.HogQLSQL
) {
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
index 3e7b2ba82ec2..f779608134cc 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
@@ -46,6 +46,7 @@ const MARKDOWN_NOTEBOOK_NODE_ID = 'markdown-notebook-v2'
export const NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG: Partial<Record<NotebookNodeType, string>> = {
[NotebookNodeType.Query]: 'Query',
[NotebookNodeType.Python]: 'Python',
+ [NotebookNodeType.PythonV2]: 'PythonV2',
[NotebookNodeType.DuckSQL]: 'DuckSQL',
[NotebookNodeType.HogQLSQL]: 'HogQLSQL',
[NotebookNodeType.SQLV2]: 'SQLV2',
diff --git a/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx b/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx
index 291ef688a551..de1940b08997 100644
--- a/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx
+++ b/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx
@@ -26,6 +26,7 @@ export const fromNodeTypeToLabel: Omit<
[NotebookNodeType.Person]: 'Persons',
[NotebookNodeType.Query]: 'Queries',
[NotebookNodeType.Python]: 'Python',
+ [NotebookNodeType.PythonV2]: 'Python (v2)',
[NotebookNodeType.DuckSQL]: 'SQL (DuckDB)',
[NotebookNodeType.HogQLSQL]: 'SQL (HogQL)',
[NotebookNodeType.SQLV2]: 'SQL (v2)',
diff --git a/frontend/src/scenes/notebooks/nodeIcons.tsx b/frontend/src/scenes/notebooks/nodeIcons.tsx
index 261a83e3ce1c..98f95ed0de5f 100644
--- a/frontend/src/scenes/notebooks/nodeIcons.tsx
+++ b/frontend/src/scenes/notebooks/nodeIcons.tsx
@@ -33,6 +33,7 @@ export const NODE_ICONS: Partial<Record<NotebookNodeType, JSX.Element>> = {
[NotebookNodeType.DuckSQL]: <IconHogQL />,
[NotebookNodeType.SQLV2]: <IconHogQL />,
[NotebookNodeType.Python]: <IconPython />,
+ [NotebookNodeType.PythonV2]: <IconPython />,
[NotebookNodeType.Latex]: <IconSquareRoot />,
[NotebookNodeType.Recording]: <IconRewindPlay />,
[NotebookNodeType.RecordingPlaylist]: <IconRewindPlay />,
diff --git a/frontend/src/scenes/notebooks/types.ts b/frontend/src/scenes/notebooks/types.ts
index ad2f52befa48..df32a80dc408 100644
--- a/frontend/src/scenes/notebooks/types.ts
+++ b/frontend/src/scenes/notebooks/types.ts
@@ -48,6 +48,9 @@ export enum NotebookNodeType {
MarkdownNotebook = 'ph-markdown-notebook',
Query = 'ph-query',
Python = 'ph-python',
+ // The revamped Python cell: runs in the notebook's sandbox kernel via the SQLV2 run
+ // path, unlike the legacy ph-python node's in-browser kernel.
+ PythonV2 = 'ph-python-v2',
DuckSQL = 'ph-duck-sql',
HogQLSQL = 'ph-hogql-sql',
SQLV2 = 'ph-sql-v2',
diff --git a/frontend/src/scenes/notebooks/utils.ts b/frontend/src/scenes/notebooks/utils.ts
index 4b249e68cdb4..66187303ba1a 100644
--- a/frontend/src/scenes/notebooks/utils.ts
+++ b/frontend/src/scenes/notebooks/utils.ts
@@ -49,6 +49,7 @@ export const textContent = (node: RichContentNode): string => {
[NotebookNodeType.Person]: customOrTitleSerializer,
[NotebookNodeType.Query]: customOrTitleSerializer,
[NotebookNodeType.Python]: customOrTitleSerializer,
+ [NotebookNodeType.PythonV2]: customOrTitleSerializer,
[NotebookNodeType.DuckSQL]: customOrTitleSerializer,
[NotebookNodeType.HogQLSQL]: customOrTitleSerializer,
[NotebookNodeType.SQLV2]: customOrTitleSerializer,
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index ab988ced012b..3813048246ca 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -63,7 +63,11 @@ from products.notebooks.backend.sql_v2 import (
is_sql_v2_enabled,
sql_v2_page_lock_key,
)
-from products.notebooks.backend.sql_v2_references import SQLV2ReferenceError, resolve_sql_v2_references
+from products.notebooks.backend.sql_v2_references import (
+ SQLV2ReferenceError,
+ resolve_python_node_inputs,
+ resolve_sql_v2_references,
+)
from products.notebooks.backend.sql_v2_serializers import (
NotebookSQLV2PageRequestSerializer,
NotebookSQLV2RunRequestSerializer,
@@ -970,8 +974,15 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
last_run_code: dict[str, str | None] = {
name: code_by_node_id.get(node_id) for name, node_id in ref_node_ids.items()
}
+ node_type = serializer.validated_data["node_type"]
+ code = serializer.validated_data["code"]
+ output_name = serializer.validated_data["output_name"]
try:
- resolved_code = resolve_sql_v2_references(serializer.validated_data["code"], last_run_code)
+ if node_type == "python":
+ # A python node stores its code as-is; referenced frames become materialization inputs.
+ run_code, inputs = code, resolve_python_node_inputs(code, last_run_code)
+ else:
+ run_code, inputs = resolve_sql_v2_references(code, last_run_code), []
except SQLV2ReferenceError as e:
return Response({"detail": str(e)}, status=400)
@@ -979,7 +990,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
team_id=self.team_id,
notebook=notebook,
node_id=serializer.validated_data["node_id"],
- code=resolved_code,
+ code=run_code,
status=NotebookNodeRun.Status.RUNNING,
)
@@ -990,7 +1001,10 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
notebook_short_id=notebook.short_id,
team_id=self.team_id,
user_id=user.id if isinstance(user, User) else None,
- code=resolved_code,
+ code=run_code,
+ node_type=node_type,
+ output_name=output_name,
+ inputs=inputs,
)
)
except Exception:
diff --git a/products/notebooks/backend/sandbox/kernel/bootstrap.py b/products/notebooks/backend/sandbox/kernel/bootstrap.py
new file mode 100644
index 000000000000..f87c7cc08ade
--- /dev/null
+++ b/products/notebooks/backend/sandbox/kernel/bootstrap.py
@@ -0,0 +1,211 @@
+"""The `_ph` kernel session injected into the ipykernel namespace (Journey 4).
+
+(Not to be confused with the legacy stdout "notebook bridge" in kernel_runtime.py that
+this whole path replaces — nothing here smuggles RPCs over stdout. `run_node` reads
+server-fetched local Arrow files and returns a structured envelope.)
+
+Runs inside the sandbox's ipykernel — the process that owns compute and data, and holds
+no backend credentials (see sql_v2_kernel_architecture.md, "division of labor"). The
+kernel-server hands it a single call, `_ph.run_node(payload)`, per run.
+
+`run_node` for a Python node:
+ 1. registers the run's inputs — HogQL frames the server already streamed to local
+ Arrow files are mmapped into DuckDB and bound as pandas frames in the user namespace;
+ 2. runs the node's code through IPython (last-expression value, stdout/stderr,
+ tracebacks, matplotlib figures captured as PNGs);
+ 3. returns the result envelope (the kernel-server, not the kernel, POSTs it back);
+ 4. writes the produced frame to a local Arrow file so `/page` can slice it later.
+
+Heavy deps (duckdb/pandas/pyarrow/IPython) are imported at module load — this module only
+ever runs inside the kernel, where they are present, never on the kernel-server startup
+path (which stays stdlib + pyarrow). matplotlib loads eagerly at session construction so
+the Agg backend is forced before any user code can import pyplot itself.
+"""
+
+import io
+import os
+import json
+import uuid
+import base64
+import logging
+from typing import Any
+
+import duckdb
+import pandas as pd
+import pyarrow as pa
+from IPython.core.interactiveshell import InteractiveShell
+from IPython.utils.capture import capture_output
+
+from . import envelope
+
+logger = logging.getLogger(__name__)
+
+_DEFAULT_PREVIEW_ROWS = 50
+# The envelope is stored whole in a Postgres row (the full frame stays in a local Arrow
+# file), so every unbounded piece gets a cap here; the callback endpoint enforces a total
+# byte limit as the backstop.
+_STREAM_CAP_CHARS = 32_768
+_CELL_CAP_CHARS = 10_000
+_MEDIA_MAX_FIGURES = 8
+_MEDIA_TOTAL_CAP_CHARS = 4_000_000 # base64 chars across all figures (~3 MB of PNG bytes)
+
+
+def _truncate_stream(text: str, cap: int = _STREAM_CAP_CHARS) -> str:
+ if len(text) <= cap:
+ return text
+ return f"{text[:cap]}\n… [output truncated: exceeded {cap // 1024} KB]"
+
+
+def _load_headless_pyplot() -> Any:
+ # matplotlib is heavy and sandbox-only; keep it off the module import path (ruff TID253),
+ # and force the Agg backend before pyplot loads so figures render without a display.
+ import matplotlib # noqa: PLC0415 — heavy, sandbox-only
+
+ matplotlib.use("Agg")
+ import matplotlib.pyplot as plt # noqa: PLC0415 — heavy, sandbox-only
+
+ return plt
+
+
+class KernelSession:
+ """Owns the persistent DuckDB connection, the IPython shell, and the frame registry.
+
+ One instance lives for the kernel's lifetime; the user namespace and materialized
+ frames persist across runs (a frame one node makes is visible to the next).
+ """
+
+ def __init__(self, data_dir: str = "/data", shell: InteractiveShell | None = None) -> None:
+ self._frames_dir = os.path.join(data_dir, "frames")
+ self._results_dir = os.path.join(data_dir, "results")
+ self._duck_dir = os.path.join(data_dir, "duck")
+ for path in (self._frames_dir, self._results_dir, self._duck_dir):
+ os.makedirs(path, exist_ok=True)
+ self.duck = duckdb.connect(os.path.join(self._duck_dir, "duck.db"))
+ self.duck.execute(f"SET temp_directory = '{self._duck_dir}'") # spill big ops to disk
+ # In-kernel this is the ipykernel's own shell; in tests it's the process singleton.
+ self.shell = shell or InteractiveShell.instance()
+ self._registered: set[str] = set()
+ # Agg backend set now, before any user `import matplotlib.pyplot`, so plots stay headless.
+ self._plt = _load_headless_pyplot()
+
+ def run_node(self, payload: dict[str, Any]) -> dict[str, Any]:
+ node = payload.get("node") or {}
+ preview_rows = int(payload.get("page_limit") or _DEFAULT_PREVIEW_ROWS)
+ try:
+ self._register_inputs(payload.get("inputs") or [])
+ except Exception as exc: # noqa: BLE001 — a bad input must still produce an envelope
+ return envelope.from_python_execution(status="error", error=f"Input registration failed: {exc}")
+
+ self._plt.close("all") # start from a clean figure state so we only capture this run's plots
+ with capture_output() as captured:
+ execution = self.shell.run_cell(node.get("code") or "", store_history=False)
+
+ media, omitted_figures = self._collect_media()
+ stdout = _truncate_stream(captured.stdout)
+ stderr = _truncate_stream(captured.stderr)
+ if omitted_figures:
+ stderr += f"\n[{omitted_figures} figure(s) omitted: over the media size cap]"
+ if execution.error_in_exec is not None:
+ return envelope.from_python_execution(
+ status="error",
+ stdout=stdout,
+ stderr=stderr,
+ error=f"{type(execution.error_in_exec).__name__}: {execution.error_in_exec}",
+ media=media,
+ )
+
+ result_df = self._result_frame(node.get("output_name"), execution.result)
+ columns, types, rows, row_count, has_more = self._preview(result_df, preview_rows)
+ # result_id keys the on-disk frame for paging — only advertise one that actually exists.
+ result_id = self._write_result_frame(result_df) if result_df is not None else None
+ return envelope.from_python_execution(
+ status="ok",
+ stdout=stdout,
+ stderr=stderr,
+ columns=columns,
+ types=types,
+ rows=rows,
+ row_count=row_count,
+ has_more=has_more,
+ media=media,
+ result_id=result_id,
+ )
+
+ def _register_inputs(self, inputs: list[dict[str, Any]]) -> None:
+ for spec in inputs:
+ name = spec["name"]
+ kind = spec.get("kind")
+ if kind == "hogql":
+ # mmap the server-streamed frame; register zero-copy in DuckDB and bind pandas
+ # for Python code (the one step that materializes in RAM).
+ table = pa.ipc.open_file(spec["path"]).read_all()
+ self.duck.register(name, table)
+ self._registered.add(name)
+ self.shell.user_ns[name] = table.to_pandas()
+ elif kind == "local":
+ # Made by an earlier node in this kernel; it must already be present.
+ if name not in self.shell.user_ns and name not in self._registered:
+ raise KeyError(f"local frame '{name}' is not in the kernel")
+ else:
+ raise ValueError(f"unknown input kind '{kind}' for '{name}'")
+
+ def _result_frame(self, output_name: str | None, last_expression: Any) -> "pd.DataFrame | None":
+ # Prefer the explicitly named output; fall back to the cell's last-expression value.
+ if output_name:
+ candidate = self.shell.user_ns.get(output_name)
+ if isinstance(candidate, pd.DataFrame):
+ return candidate
+ if isinstance(last_expression, pd.DataFrame):
+ return last_expression
+ if isinstance(last_expression, pd.Series):
+ return last_expression.to_frame()
+ return None
+
+ def _preview(
+ self, df: "pd.DataFrame | None", limit: int
+ ) -> tuple[list[str], list[list[str]], list[list[Any]], int, bool]:
+ if df is None:
+ return [], [], [], 0, False
+ columns = [str(column) for column in df.columns]
+ types = [[str(column), str(dtype)] for column, dtype in zip(df.columns, df.dtypes)]
+ # to_json coerces numpy scalars, NaN and datetimes to JSON-native values in one pass.
+ rows = json.loads(df.head(limit).to_json(orient="values", date_format="iso"))
+ # The preview is display-only (paging reads the Arrow frame), so huge cells get clipped.
+ rows = [
+ [
+ f"{cell[:_CELL_CAP_CHARS]}…" if isinstance(cell, str) and len(cell) > _CELL_CAP_CHARS else cell
+ for cell in row
+ ]
+ for row in rows
+ ]
+ return columns, types, rows, int(len(df)), len(df) > limit
+
+ def _collect_media(self) -> tuple[list[dict[str, str]], int]:
+ """Capture open figures as base64 PNGs within the media budget; return (media, omitted count)."""
+ media: list[dict[str, str]] = []
+ budget = _MEDIA_TOTAL_CAP_CHARS
+ omitted = 0
+ for number in self._plt.get_fignums():
+ buffer = io.BytesIO()
+ self._plt.figure(number).savefig(buffer, format="png", bbox_inches="tight")
+ data = base64.b64encode(buffer.getvalue()).decode()
+ if len(media) >= _MEDIA_MAX_FIGURES or len(data) > budget:
+ omitted += 1
+ continue
+ budget -= len(data)
+ media.append({"mime_type": "image/png", "data": data})
+ self._plt.close("all")
+ return media, omitted
+
+ def _write_result_frame(self, df: "pd.DataFrame") -> str | None:
+ """Write the frame for later paging; return its result_id, or None if the write failed."""
+ result_id = str(uuid.uuid4())
+ try:
+ table = pa.Table.from_pandas(df, preserve_index=False)
+ with pa.OSFile(os.path.join(self._results_dir, f"{result_id}.arrow"), "wb") as sink:
+ with pa.ipc.new_file(sink, table.schema) as writer:
+ writer.write_table(table)
+ except Exception: # noqa: BLE001 — paging is best-effort; a write failure must not fail the run
+ logger.exception("nb_kernel result frame write failed")
+ return None
+ return result_id
diff --git a/products/notebooks/backend/sandbox/kernel/data_plane.py b/products/notebooks/backend/sandbox/kernel/data_plane.py
index eb6443e6ca31..0bd49a255ac8 100644
--- a/products/notebooks/backend/sandbox/kernel/data_plane.py
+++ b/products/notebooks/backend/sandbox/kernel/data_plane.py
@@ -8,6 +8,7 @@ the rows come back as an Arrow stream. No backend web worker waits on ClickHouse
only third-party dependency is pyarrow (present in the sandbox image).
"""
+import os
import json
import time
import urllib.error
@@ -31,6 +32,26 @@ def fetch_query_page(
url: str, token: str, query: str, limit: int, offset: int = 0
) -> tuple[list[str], list[tuple[Any, ...]], list[list[str]]]:
"""Run `query` through the data plane; return (columns, rows, types) of the capped page."""
+ return _table_to_rows_and_types(_request_table(url, token, query, limit, offset))
+
+
+def materialize_query_to_file(url: str, token: str, query: str, dest_path: str, limit: int, offset: int = 0) -> int:
+ """Fetch the full result of `query` and write it as a local Arrow IPC file for a Python/DuckDB node.
+
+ Returns the row count. The file is written to a temp name and renamed on success so a torn
+ write (e.g. a mid-stream failure) never leaves a half-frame the kernel could read.
+ """
+ table = _request_table(url, token, query, limit, offset)
+ temp_path = f"{dest_path}.partial"
+ with pa.OSFile(temp_path, "wb") as sink:
+ with pa.ipc.new_file(sink, table.schema) as writer:
+ writer.write_table(table)
+ os.replace(temp_path, dest_path)
+ return table.num_rows
+
+
+def _request_table(url: str, token: str, query: str, limit: int, offset: int) -> "pa.Table":
+ """POST the query and (once the async manager finishes) return the raw Arrow table."""
request = urllib.request.Request(
url,
data=json.dumps({"query": query, "limit": limit, "offset": offset}).encode(),
@@ -43,7 +64,7 @@ def fetch_query_page(
with urllib.request.urlopen(request, timeout=_REQUEST_TIMEOUT_SECONDS) as response:
if _is_arrow(response):
# A pre-async-manager backend answers the POST with the rows directly.
- return decode_arrow_stream(response)
+ return _read_table(response)
body = json.loads(response.read() or b"{}")
except urllib.error.HTTPError as exc:
raise DataPlaneError(_error_detail(exc)) from exc
@@ -55,10 +76,10 @@ def fetch_query_page(
query_id = body.get("query_id")
if not query_id:
raise DataPlaneError("Data plane did not accept the query")
- return _poll_for_result(f"{url.rstrip('/')}/{query_id}/", token)
+ return _poll_for_table(f"{url.rstrip('/')}/{query_id}/", token)
-def _poll_for_result(status_url: str, token: str) -> tuple[list[str], list[tuple[Any, ...]], list[list[str]]]:
+def _poll_for_table(status_url: str, token: str) -> "pa.Table":
request = urllib.request.Request(status_url, headers={"Authorization": f"Bearer {token}"}, method="GET")
deadline = time.monotonic() + _POLL_DEADLINE_SECONDS
interval = _POLL_INITIAL_INTERVAL_SECONDS
@@ -68,7 +89,7 @@ def _poll_for_result(status_url: str, token: str) -> tuple[list[str], list[tuple
# nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected
with urllib.request.urlopen(request, timeout=_REQUEST_TIMEOUT_SECONDS) as response:
if _is_arrow(response):
- return decode_arrow_stream(response)
+ return _read_table(response)
# 202 — still running.
except urllib.error.HTTPError as exc:
raise DataPlaneError(_error_detail(exc)) from exc
@@ -85,14 +106,22 @@ def _is_arrow(response: Any) -> bool:
return "arrow" in (response.headers.get("Content-Type") or "")
+def _read_table(source: Any) -> "pa.Table":
+ return pa.ipc.open_stream(source).read_all()
+
+
def decode_arrow_stream(source: Any) -> tuple[list[str], list[tuple[Any, ...]], list[list[str]]]:
- """Decode an Arrow IPC stream (file-like or bytes-like) into (columns, rows, types).
+ """Decode an Arrow IPC stream (file-like or bytes-like) into (columns, rows, types)."""
+ return _table_to_rows_and_types(_read_table(source))
+
+
+def _table_to_rows_and_types(table: "pa.Table") -> tuple[list[str], list[tuple[Any, ...]], list[list[str]]]:
+ """Turn an Arrow table into (columns, rows, types).
Types come from the `hogql_types` schema metadata the data plane attaches (the
real ClickHouse type names); when absent they are approximated from the Arrow
schema so the envelope always carries something usable for axis detection.
"""
- table = pa.ipc.open_stream(source).read_all()
columns = table.column_names
# Columnar → row tuples without to_pylist(), which would collapse duplicate column names.
column_values = [table.column(i).to_pylist() for i in range(table.num_columns)]
diff --git a/products/notebooks/backend/sandbox/kernel/envelope.py b/products/notebooks/backend/sandbox/kernel/envelope.py
index 7d3c09240df7..62065a561dd6 100644
--- a/products/notebooks/backend/sandbox/kernel/envelope.py
+++ b/products/notebooks/backend/sandbox/kernel/envelope.py
@@ -8,6 +8,7 @@ bounded preview only — never the full result (see sql_v2_result_delivery.md).
import math
import uuid
import datetime
+from collections.abc import Sequence
from typing import Any
@@ -28,7 +29,7 @@ def _json_cell(value: Any) -> Any:
return str(value)
-def json_safe_rows(rows: list[tuple[Any, ...]]) -> list[list[Any]]:
+def json_safe_rows(rows: Sequence[Sequence[Any]]) -> list[list[Any]]:
return [[_json_cell(cell) for cell in row] for row in rows]
@@ -51,3 +52,41 @@ def from_columns_and_rows(
def from_error(message: str) -> dict[str, Any]:
return {"status": "error", "error": message}
+
+
+def from_python_execution(
+ *,
+ status: str,
+ stdout: str = "",
+ stderr: str = "",
+ error: str | None = None,
+ columns: list[str] | None = None,
+ types: list[list[str]] | None = None,
+ rows: Sequence[Sequence[Any]] | None = None,
+ row_count: int = 0,
+ has_more: bool = False,
+ media: list[dict[str, str]] | None = None,
+ result_id: str | None = None,
+) -> dict[str, Any]:
+ """Envelope for a Python node run.
+
+ Carries the captured stdout/stderr and any matplotlib images alongside the bounded
+ table preview. `row_count` is the produced frame's full size (not len(rows), which is
+ only the previewed page); `result_id` keys the on-disk frame for later paging.
+ """
+ envelope: dict[str, Any] = {
+ "status": status,
+ "stdout": stdout,
+ "stderr": stderr,
+ "columns": columns or [],
+ "types": types or [],
+ "row_count": row_count,
+ "first_page": json_safe_rows(rows or []),
+ "has_more": has_more,
+ "media": media or [],
+ }
+ if error is not None:
+ envelope["error"] = error
+ if result_id is not None:
+ envelope["result_id"] = result_id
+ return envelope
diff --git a/products/notebooks/backend/sandbox/kernel/executor.py b/products/notebooks/backend/sandbox/kernel/executor.py
new file mode 100644
index 000000000000..35b46a1d7bcc
--- /dev/null
+++ b/products/notebooks/backend/sandbox/kernel/executor.py
@@ -0,0 +1,184 @@
+"""Owns the ipykernel child and runs Python nodes through it (Journey 4, arch build step 2).
+
+Sandbox-only: this is the one module that imports `jupyter_client` and drives a live
+kernel, both of which exist only in the notebook sandbox image — so it is exercised there,
+not in backend CI (the KernelSession.run_node compute it drives is unit-tested in-process
+in test_kernel_bootstrap). Everything network/credential-bearing stays in this process; the
+kernel receives only local file paths and node code, never a token (division of labor in
+sql_v2_kernel_architecture.md).
+
+Flow for a Python node:
+ 1. materialize each HogQL input — the server streams the full CH result to a local Arrow
+ file keyed by query_hash (reused when the upstream query is unchanged);
+ 2. hand the kernel `_ph.run_node(payload)` (paths only) and read back the envelope it writes;
+ 3. the caller (runner) POSTs that envelope to the backend callback.
+"""
+
+import os
+import json
+import time
+import queue
+import shutil
+import threading
+from typing import Any
+
+from jupyter_client import KernelManager
+
+from . import data_plane, envelope
+
+# Bounded full-frame fetch for materialization. True batch-streaming to disk (peak memory =
+# one record batch) is the arch-doc target; a high cap is the pragmatic first cut.
+_MATERIALIZE_ROW_CAP = 2_000_000
+_KERNEL_READY_TIMEOUT_SECONDS = 30
+_EXECUTE_TIMEOUT_SECONDS = 300
+_SHELL_POLL_SECONDS = 1.0
+
+
+class KernelExecutor:
+ """Lazily owns one ipykernel and serializes runs through it (one namespace, one run at a time)."""
+
+ def __init__(self, data_dir: str = "/data") -> None:
+ self._data_dir = data_dir
+ self._frames_dir = os.path.join(data_dir, "frames")
+ self._runs_dir = os.path.join(data_dir, "runs")
+ for path in (self._frames_dir, self._runs_dir):
+ os.makedirs(path, exist_ok=True)
+ self._km: KernelManager | None = None
+ self._kc: Any = None
+ self._lock = threading.Lock()
+
+ def run_python_node(self, payload: dict[str, Any]) -> dict[str, Any]:
+ with self._lock: # a kernel has one namespace — concurrent runs are meaningless
+ try:
+ self._ensure_kernel()
+ inputs = self._materialize_inputs(payload)
+ return self._invoke_run_node(payload, inputs)
+ except data_plane.DataPlaneError as exc:
+ return envelope.from_python_execution(status="error", error=str(exc))
+ except Exception as exc: # noqa: BLE001 — a run must always yield a callback envelope
+ return envelope.from_python_execution(status="error", error=f"Kernel run failed: {exc}")
+
+ def interrupt(self) -> None:
+ if self._km is not None:
+ self._km.interrupt_kernel()
+
+ def restart(self) -> None:
+ with self._lock:
+ if self._km is not None:
+ self._km.restart_kernel(now=True)
+ self._kc.wait_for_ready(timeout=_KERNEL_READY_TIMEOUT_SECONDS)
+ self._inject_session()
+
+ def _ensure_kernel(self) -> None:
+ if self._km is not None and self._km.is_alive():
+ return
+ if self._kc is not None:
+ # A crashed kernel leaves the old client's ZMQ sockets open — jupyter_client
+ # only closes them on an explicit stop_channels(), not on GC.
+ try:
+ self._kc.stop_channels()
+ except Exception: # noqa: BLE001 — best-effort teardown of a dead kernel's client
+ pass
+ self._kc = None
+ # sys.executable is the notebook venv python (the server runs under it), so the kernel
+ # inherits pandas/duckdb/pyarrow and the nb_kernel package on PYTHONPATH.
+ self._km = KernelManager(kernel_name="python3")
+ self._km.start_kernel()
+ self._kc = self._km.client()
+ self._kc.start_channels()
+ self._kc.wait_for_ready(timeout=_KERNEL_READY_TIMEOUT_SECONDS)
+ self._inject_session()
+
+ def _inject_session(self) -> None:
+ status = self._execute(
+ f"from nb_kernel.bootstrap import KernelSession\n_ph = KernelSession(data_dir={self._data_dir!r})\n"
+ )
+ if status != "ok":
+ raise RuntimeError("failed to initialize the kernel session")
+
+ def _materialize_inputs(self, payload: dict[str, Any]) -> list[dict[str, Any]]:
+ """Fetch each HogQL input to a local Arrow file; return the kernel-facing input specs (paths only)."""
+ kernel_inputs: list[dict[str, Any]] = []
+ for spec in payload.get("inputs") or []:
+ name = spec["name"]
+ if spec.get("kind") == "local":
+ kernel_inputs.append({"name": name, "kind": "local"})
+ continue
+ frame_path = os.path.join(self._frames_dir, f"{spec['query_hash']}.arrow")
+ if not os.path.exists(frame_path): # unchanged upstream query → reuse the frame
+ data_plane.materialize_query_to_file(
+ payload["data_plane_url"],
+ payload["data_plane_token"],
+ spec["query"],
+ frame_path,
+ limit=_MATERIALIZE_ROW_CAP,
+ )
+ kernel_inputs.append({"name": name, "kind": "hogql", "path": frame_path})
+ return kernel_inputs
+
+ def _invoke_run_node(self, payload: dict[str, Any], inputs: list[dict[str, Any]]) -> dict[str, Any]:
+ run_id = str(payload.get("run_id") or "run")
+ run_dir = os.path.join(self._runs_dir, run_id)
+ os.makedirs(run_dir, exist_ok=True)
+ payload_path = os.path.join(run_dir, "payload.json")
+ envelope_path = os.path.join(run_dir, "envelope.json")
+ # Credentials never cross into the kernel: it gets node code + local paths only.
+ kernel_payload = {"run_id": run_id, "node": payload.get("node") or {}, "inputs": inputs}
+ if payload.get("page_limit"):
+ kernel_payload["page_limit"] = payload["page_limit"]
+ try:
+ with open(payload_path, "w") as handle:
+ json.dump(kernel_payload, handle)
+ if os.path.exists(envelope_path):
+ os.remove(envelope_path)
+
+ status = self._execute(
+ "import json as __j\n"
+ f"with open({payload_path!r}) as __f:\n __payload = __j.load(__f)\n"
+ "__envelope = _ph.run_node(__payload)\n"
+ f"with open({envelope_path!r}, 'w') as __f:\n __j.dump(__envelope, __f)\n"
+ )
+ if status != "ok" or not os.path.exists(envelope_path):
+ return envelope.from_python_execution(
+ status="error", error="The kernel did not return a result (it may have crashed — try re-running)."
+ )
+ with open(envelope_path) as handle:
+ return json.load(handle)
+ finally:
+ # The payload/envelope files only matter within this call; result frames for
+ # paging live under /data/results, so the per-run dir must not accumulate.
+ shutil.rmtree(run_dir, ignore_errors=True)
+
+ def _execute(self, code: str) -> str:
+ """Run code in the kernel; return the execute_reply status ('ok'/'error').
+
+ Raises if the kernel dies or the run overruns the time budget (then the cell is
+ interrupted so the kernel is reusable for the next run).
+ """
+ msg_id = self._kc.execute(code, store_history=False, silent=True)
+ deadline = time.monotonic() + _EXECUTE_TIMEOUT_SECONDS
+ while time.monotonic() < deadline:
+ try:
+ reply = self._kc.get_shell_msg(timeout=_SHELL_POLL_SECONDS)
+ except queue.Empty:
+ if self._km is None or not self._km.is_alive():
+ raise RuntimeError("the kernel process died")
+ continue
+ if reply.get("parent_header", {}).get("msg_id") != msg_id:
+ continue # a stale reply from an earlier run
+ return str(reply.get("content", {}).get("status") or "error")
+ self.interrupt() # overran the budget — stop the cell so the kernel stays usable
+ raise RuntimeError("the kernel run exceeded the time limit")
+
+
+_executor: KernelExecutor | None = None
+_executor_lock = threading.Lock()
+
+
+def get_executor() -> KernelExecutor:
+ """Process-wide singleton — one kernel per sandbox (shared by all editors of the notebook)."""
+ global _executor
+ with _executor_lock:
+ if _executor is None:
+ _executor = KernelExecutor()
+ return _executor
diff --git a/products/notebooks/backend/sandbox/kernel/runner.py b/products/notebooks/backend/sandbox/kernel/runner.py
index 2ab3bda5e822..660f3ce102ea 100644
--- a/products/notebooks/backend/sandbox/kernel/runner.py
+++ b/products/notebooks/backend/sandbox/kernel/runner.py
@@ -36,11 +36,31 @@ _result_cache_lock = threading.Lock()
def execute_run(payload: dict[str, Any]) -> None:
- """Entry point for a /run request, invoked on a background thread."""
- result = _build_envelope(payload)
+ """Entry point for a /run request, invoked on a background thread.
+
+ Routing rule (sql_v2_kernel_architecture.md): a Python node runs in the ipykernel
+ (materialize inputs, run code); a pure-HogQL display node stays a capped data-plane
+ fetch and never touches the kernel.
+ """
+ node = payload.get("node") or {}
+ if node.get("type") == "python":
+ result = _run_python_node(payload)
+ else:
+ result = _build_envelope(payload)
_post_callback(payload["callback_url"], payload["callback_token"], result)
+def _run_python_node(payload: dict[str, Any]) -> dict[str, Any]:
+ # Deferred so the server startup path never imports jupyter_client (heavy, sandbox-only).
+ from . import executor # noqa: PLC0415 — keeps jupyter_client off the server import path
+
+ try:
+ return executor.get_executor().run_python_node(payload)
+ except Exception as exc: # noqa: BLE001 — a run must always produce a callback envelope
+ logger.exception("nb_kernel python node run failed")
+ return envelope.from_error(f"Python node failed in the sandbox: {exc}")
+
+
def _fetch_capped_page(payload: dict[str, Any], limit: int, offset: int) -> dict[str, Any]:
"""Fetch limit+1 rows through the data plane; the extra row only signals has_more."""
# Deferred so a broken pyarrow install degrades to a per-run error envelope
diff --git a/products/notebooks/backend/sandbox/kernel/server.py b/products/notebooks/backend/sandbox/kernel/server.py
index abea5e122842..0e70c5886600 100644
--- a/products/notebooks/backend/sandbox/kernel/server.py
+++ b/products/notebooks/backend/sandbox/kernel/server.py
@@ -35,7 +35,7 @@ class KernelServerHandler(BaseHTTPRequestHandler):
self._respond(404, {"error": "Not found"})
def do_POST(self) -> None:
- if self.path not in ("/run", "/page"):
+ if self.path not in ("/run", "/page", "/interrupt"):
self._respond(404, {"error": "Not found"})
return
try:
@@ -51,8 +51,18 @@ class KernelServerHandler(BaseHTTPRequestHandler):
threading.Thread(target=execute_run, args=(payload,), daemon=True).start()
self._respond(202, {"accepted": True})
return
+ if self.path == "/interrupt":
+ self._handle_interrupt()
+ return
self._handle_page(payload)
+ def _handle_interrupt(self) -> None:
+ # Deferred so the server startup path never imports jupyter_client (sandbox-only).
+ from . import executor # noqa: PLC0415 — keeps jupyter_client off the server import path
+
+ executor.get_executor().interrupt()
+ self._respond(200, {"interrupted": True})
+
def _handle_page(self, payload: dict[str, Any]) -> None:
from . import data_plane # noqa: PLC0415 — keep pyarrow off the server startup path
diff --git a/products/notebooks/backend/sql_v2.py b/products/notebooks/backend/sql_v2.py
index cc2a76412cb2..a0da0271c137 100644
--- a/products/notebooks/backend/sql_v2.py
+++ b/products/notebooks/backend/sql_v2.py
@@ -269,27 +269,42 @@ def ensure_sql_v2_server(notebook: Notebook, user: User | None) -> KernelRuntime
return runtime
-def dispatch_sql_v2_run(notebook: Notebook, user: User | None, run: NotebookNodeRun, code: str) -> None:
+def dispatch_sql_v2_run(
+ notebook: Notebook,
+ user: User | None,
+ run: NotebookNodeRun,
+ code: str,
+ node_type: str = "hogql",
+ output_name: str = "",
+ inputs: list[dict] | None = None,
+) -> None:
"""Dispatch a run to the in-sandbox kernel-server with a single authed HTTP POST.
- Returns as soon as the server accepts (202); the result arrives via the callback.
+ Returns as soon as the server accepts (202); the result arrives via the callback. A
+ python node carries the `node`/`inputs` shape the executor consumes; a hogql node keeps
+ the flat `code` the capped-fetch path reads — the two paths stay additive.
"""
runtime = ensure_sql_v2_server(notebook, user)
assert runtime.server_url # ensure_sql_v2_server always returns a runtime with a live server_url
command_token = mint_command_token(kernel_server_secret(str(runtime.id)), str(run.id))
user_id = user.id if isinstance(user, User) else None
+ payload: dict = {
+ "run_id": str(run.id),
+ "callback_url": build_callback_url(str(run.id)),
+ "callback_token": mint_callback_token(str(run.id), notebook.team_id),
+ "data_plane_url": build_data_plane_url(),
+ "data_plane_token": mint_data_plane_token(notebook.short_id, notebook.team_id, user_id),
+ "page_limit": DISPLAY_PAGE_LIMIT,
+ "cache_limit": RESULT_CACHE_ROWS,
+ }
+ if node_type == "python":
+ payload["node"] = {"type": "python", "code": code, "output_name": output_name}
+ payload["inputs"] = inputs or []
+ else:
+ payload["code"] = code
response = requests.post(
f"{runtime.server_url.rstrip('/')}/run",
- json={
- "run_id": str(run.id),
- "code": code,
- "callback_url": build_callback_url(str(run.id)),
- "callback_token": mint_callback_token(str(run.id), notebook.team_id),
- "data_plane_url": build_data_plane_url(),
- "data_plane_token": mint_data_plane_token(notebook.short_id, notebook.team_id, user_id),
- "page_limit": DISPLAY_PAGE_LIMIT,
- "cache_limit": RESULT_CACHE_ROWS,
- },
+ json=payload,
headers=_sandbox_auth_headers(runtime.server_connect_token, command_token),
timeout=_RUN_POST_TIMEOUT_SECONDS,
)
diff --git a/products/notebooks/backend/sql_v2_callback.py b/products/notebooks/backend/sql_v2_callback.py
index 62f39f6bd992..73090de888ee 100644
--- a/products/notebooks/backend/sql_v2_callback.py
+++ b/products/notebooks/backend/sql_v2_callback.py
@@ -19,6 +19,11 @@ from products.notebooks.backend.sql_v2_serializers import NotebookSQLV2CallbackR
logger = structlog.get_logger(__name__)
+# The envelope lands whole in a Postgres row. The kernel already caps streams, media, and
+# preview cells well below this; anything bigger is a misbehaving (or hostile) sandbox, so
+# reject rather than store. Sized above the kernel's worst case (~4 MB media + streams).
+MAX_ENVELOPE_BYTES = 8_000_000
+
@extend_schema(
tags=["notebooks"],
@@ -55,6 +60,10 @@ def notebook_sql_v2_callback(request, run_id: str) -> JsonResponse:
if token_run_id != run_id:
return JsonResponse({"error": "Token does not match run"}, status=403)
+ if len(request.body) > MAX_ENVELOPE_BYTES:
+ logger.warning("sql_v2_callback_envelope_too_large", run_id=run_id, size=len(request.body))
+ return JsonResponse({"error": "Envelope too large"}, status=400)
+
try:
body = json.loads(request.body)
except (json.JSONDecodeError, ValueError):
diff --git a/products/notebooks/backend/sql_v2_frame_store.md b/products/notebooks/backend/sql_v2_frame_store.md
new file mode 100644
index 000000000000..1bfcfe8f46c7
--- /dev/null
+++ b/products/notebooks/backend/sql_v2_frame_store.md
@@ -0,0 +1,221 @@
+# SQLV2 frame materialization via object storage
+
+Design notes for moving python-node frame materialization off the Redis JSON transport and onto an object-storage handoff.
+Status: **proposal** — not started; materialization is deliberately clamped at 50k rows until phase 1 lands.
+
+## Problem
+
+When a python node reads an upstream SQLV2 frame, the sandbox kernel fetches the whole frame through the data plane
+(`sql_v2_data_plane.py`), which rides the generic async query manager:
+
+1. A Celery worker executes the HogQL and holds the full result as Python tuples.
+2. The worker JSON-renders the entire result into **one Redis string value** (`QueryStatusManager.store_query_status`).
+3. On poll, a web worker reads the blob back, parses the JSON, and re-encodes it as an Arrow stream for the sandbox.
+
+The frame is fully copied ~5 times, and the middle copy sits in Redis — the shared cache for the whole deployment.
+This transport is implicitly sized by the 50k row ceiling (`MAX_SELECT_RETURNED_ROWS` under the async limit context),
+so materialized frames are silently clipped at 50k rows today.
+A `LimitContext.NOTEBOOK_MATERIALIZE` context raising the ceiling to 2M (`_MATERIALIZE_ROW_CAP`) was built and then
+**deliberately reverted**: without a better payload transport, wide multi-hundred-thousand-row frames stress Redis
+(single-threaded, 512MB per-value hard cap, eviction pressure) and the workers that render/parse the JSON.
+The clamp is pinned by `test_materialization_request_is_accepted_and_clipped_at_the_row_ceiling` and comes off as
+part of phase 1, when the transport can carry what the limit allows.
+
+## Decision sketch: durable object handoff, not live push
+
+Two async candidates were compared (web-tier streaming is ruled out — no design may pin a web worker on bulk bytes):
+
+- **A — worker/CH writes Arrow to object storage; sandbox pulls a presigned URL.**
+- **B — worker pushes the Arrow stream directly into the sandbox's kernel server.**
+
+A wins on every axis that matters here except single-transfer latency:
+
+- **Lifetime decoupling.** Push needs producer and consumer alive simultaneously; the sandbox is the most ephemeral
+ component we have (Modal cold starts, idle teardown, kernel restarts wipe local disk). An object survives all of that:
+ any sandbox instance — including one restarted mid-run — can fetch, resume with Range requests, and retry per leg.
+- **ClickHouse resource-hold.** A `SELECT` counts as running until the client drains the last block.
+ Draining into S3 happens at datacenter speed, so CH resources are held for ~pure execution time.
+ Draining into a Modal container is paced by public-internet throughput and the kernel's ingest —
+ backpressure propagates into CH (memory pinned, query slot held, execution-time clock ticking).
+- **Reuse.** Frames are keyed by `query_hash`; an object serves retries, kernel restarts, and unchanged upstream
+ queries without re-executing CH. Push has no reuse story — every delivery is a fresh execution.
+- **Attack surface.** Pull keeps the sandbox ingress-free; push requires a new streamed-upload endpoint on the
+ kernel server, exposed to the internet, plus a request/callback correlation protocol.
+
+Making the sandbox "S3-shaped" is easy at the protocol level (accept a chunked PUT) but cannot provide S3's
+semantics — durability, resume, producer/consumer decoupling — because the sandbox is ephemeral by design.
+The hard part isn't accepting bytes; it's being a reliable place for bytes to live.
+
+## Prior art in the repo
+
+Every building block already runs in production. Inventory (per deep-dive, 2026-07):
+
+### ClickHouse writes S3 directly (`INSERT INTO FUNCTION s3(...)`)
+
+| Flow | User-facing? | What it teaches us |
+| ----------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| **Batch exports internal stage** — `products/batch_exports/backend/pipeline/internal_stage.py:237`, `temporal/sql.py:8` | Yes, indirectly: users configure recurring batch exports (Data pipelines → Destinations); every run of every destination stages through this first | The core recipe: `INSERT INTO FUNCTION s3(...'ArrowStream') PARTITION BY rand() % N`, keyless IAM in cloud (CH instance role), partition sizing (~250k rows/file), 64MiB insert blocks, delete-prefix-before-write cleanup, bucket-lifecycle retention |
+| File-download batch export — `destinations/file_download_batch_export.py:236` | Yes: user requests an export file, downloads when ready | STS `assume_role` scoped to a single bucket prefix, 1h expiry — the tightest credential pattern in the repo |
+| Query-log exports (Dagster ×2) — `posthog/dags/export_query_logs_to_s3.py:98` | No: internal ops, daily schedule | `s3_truncate_on_insert=1` for idempotent re-runs; per-host fan-out |
+| Duckling backfill — `posthog/dags/events_backfill_to_duckling.py:1420` | No: operator-run migration tooling | Dynamic fan-out sizing (target rows/file), bounded CH writer memory via Parquet row-group settings |
+| Identity matching — `products/growth/dags/identity_matching.py:485` | No: internal experiment | CH staging its own intermediate datasets in S3 and reading them back via `FROM s3(...)` |
+| Web analytics Native export — `posthog/models/web_preaggregated/sql.py:835` | No (write side appears dormant) | Native format preserves AggregateFunction states across the S3 round-trip |
+
+### Python/Temporal worker streams CH results and uploads
+
+| Flow | User-facing? | What it teaches us |
+| ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| **Data-modeling materialization** — `posthog/temporal/data_modeling/activities/materialize_view.py:346-598` | Yes: user creates a saved query / materialized view (Data warehouse), runs it manually or on schedule | HogQL → `astream_query_as_arrow` in bounded ~100MB batches → Delta/Parquet on S3 via delta-rs; **CH reads the result back** through `s3()`/`s3Cluster()`/`deltaLake()` table functions — proof that CH→S3→query round-trips are production reality |
+| CSV/XLSX exports — `products/exports/backend/tasks/csv_exporter.py:480,641`, `models/exported_asset.py:315` | Yes: user clicks "Export" on an insight/table, gets notified, downloads | `LimitContext.EXPORT` + 10k-row pagination, single PUT to `OBJECT_STORAGE_BUCKET`, **7-day TTL with lazy expiry**, download via **presigned URL** — the asset-lifecycle pattern to copy |
+| Usage reports v2 — `posthog/temporal/usage_report/activities.py:105` | No: automated billing | Staging many small CH results as S3 objects with explicit best-effort cleanup |
+
+### Relevant negative
+
+There is **no generic S3-backed query-result cache** — `query_cache_factory.py` only returns the Redis manager.
+That cache exists to reuse identical insight queries within a TTL; the notebook flow already gets its reuse from
+`query_hash`-keyed frames, so we are not duplicating (or blocked on) any platform facility.
+
+## Security model for sandbox reads
+
+Trust model today: the sandbox holds a signed, notebook+team-bound data-plane token and pulls from
+`/internal/notebooks/data_plane/` over HTTPS. The frame store keeps that shape — the control plane stays
+token-authed; only the bulk-bytes leg moves to object storage.
+
+- **How the sandbox reads without AWS credentials.** The sandbox never assumes a role and never holds AWS
+ credentials of any kind. The backend — which does hold the role — signs a GET for one specific object with an
+ expiry and embeds that signature in the URL (a presigned URL); S3 verifies the signature server-side, so the
+ fetch is a plain HTTPS GET with no SDK. This is the same position a user's browser is in when it downloads a
+ CSV export (`ExportedAsset.get_content_response`) — an external reader given a narrow expiring capability, not
+ an identity. STS temp credentials (file-download-export pattern) were considered and rejected for the read
+ side: they would hand real, if scoped, AWS credentials to a container that executes arbitrary user code,
+ where a presign is one object, one verb, minutes. Note a presign is only valid while the credentials that
+ signed it are — fine for minutes-scale expiry, and the reason day-long URLs can't be minted from
+ instance-role session credentials.
+- **Bucket posture.** Private bucket (or dedicated prefix), public access blocked, SSE at rest.
+ Per the repo's storage direction: SeaweedFS locally, S3 in cloud, standard S3 client, no hardcoded endpoints.
+- **Tenant isolation lives at mint time, not in the URL.** Object keys are namespaced
+ `notebooks/frames/team_{team_id}/{notebook_short_id}/{query_hash}.arrow`.
+ The status endpoint verifies the data-plane token (which binds notebook + team) **before** presigning,
+ and only ever presigns objects under that team's prefix. A sandbox can never request another team's key
+ because it never names keys at all — it polls a query_id it was issued.
+- **Presigned GET discipline.** Short expiry (minutes — long enough for a resume-with-Range retry loop, no more),
+ HTTPS-only, never logged. A presigned URL is a bearer secret of the same class as the existing command tokens;
+ its blast radius is one object for a few minutes.
+- **Write-side auth.** CH writes via its instance role (keyless, batch-exports pattern), write-scoped to the
+ notebooks prefix. If tighter isolation is wanted later: STS prefix-scoped credentials per run
+ (file-download-export pattern).
+- **Egress.** The sandbox already makes outbound HTTPS calls to the PostHog API; fetching a presigned S3 URL adds
+ one more allowed destination. If Modal egress policy must stay single-destination, the fallback is proxying the
+ object through the data-plane endpoint as a bounded stream — bytes transit Django once, but never Redis and
+ never as JSON. Keep this as a config switch, not the default.
+- **Data at rest is a conscious change.** Query results currently live ≤20 min in Redis; parking them in object
+ storage for hours is a retention-policy decision. Bound it with a bucket lifecycle TTL (e.g. 24h) plus
+ delete-prefix-on-supersede, and document it.
+
+## Resource governance — not hammering ClickHouse
+
+Materialization is **user-facing** — someone is waiting on their cell — so it belongs on the ONLINE pool with
+interactive queries (OFFLINE is where batch exports, usage reports, and cohort calculations run, with
+explicitly accepted latency variance and failure rates; a user-waiting query must not queue behind those).
+The risk is different: a single materialization can be far more expensive than an insight query, an
+**uncapped whale in a pool tuned for bounded queries**. The governance goal is therefore not relocation but
+making the whale impossible. Note the cap that matters is not the row count — an insight query with
+`LIMIT 50000` can still scan billions of rows; cost is bounded by execution time, bytes read, memory,
+and threads.
+
+Layered levers:
+
+- **Per-query SETTINGS (batch-exports recipe).** The staging query carries hard caps, as `internal_stage.py`
+ does: `max_execution_time` (modestly above the insight ceiling — frame pulls are legitimately heavier),
+ `max_bytes_to_read` (refuse oversized scans up front), `max_memory_usage`,
+ `max_bytes_before_external_sort/group_by` (spill to disk), `max_threads`, `min_insert_block_size_bytes`
+ (64MiB there). `max_network_bandwidth` can throttle the S3 write rate if needed.
+- **Scheduler priority, not pool exile.** CH's `priority` setting lets materialization run ONLINE while
+ yielding CPU to interactive queries under genuine contention — dashboards get right-of-way without
+ sending notebooks to a worse pool.
+- **Tiered row ceiling.** Don't jump 50k → 2M in one step: raise to ~500k with the phase-1 transport,
+ watch the footprint, then raise toward `_MATERIALIZE_ROW_CAP`.
+- **Admission control above CH.** One operation per notebook is already enforced by the operations logic;
+ add a per-team concurrency cap (one concurrent materialization per team initially) and a small dedicated
+ Celery queue so global concurrency equals worker count. The refs resolver already minimizes demand —
+ only frames the code actually reads are materialized.
+- **Dedicated ClickHouse user as the backstop.** The repo already splits traffic across CH users
+ (`ClickHouseUser.APP` / `API`), each governed by a server-side settings profile. A materialization user gets
+ profile limits, QUOTAs, and `max_concurrent_queries_for_user` — a hard server-enforced ceiling no
+ application bug can exceed.
+- **Demand elimination.** Phase 3's `query_hash` reuse means an unchanged upstream query never re-executes;
+ long-term this is the strongest lever.
+- **Escalation path.** If notebooks' share of online capacity becomes meaningful, the router already supports
+ product-specific pools (`Workload.ENDPOINTS` is precedent) — a dedicated notebooks pool with online-grade
+ latency is the growth answer, decided with data rather than up front.
+
+The flow is already measurable: the data plane tags queries with `Product.NOTEBOOKS`, and the Dagster
+query-log exports make its CH footprint analyzable, so the knobs can be tightened with data.
+
+## Phased plan — start basic, improve later
+
+**Phase 0 (current state).** Materialization runs over the existing Redis transport, clipped at 50k rows.
+Fine for the current flag-gated audience and frames up to low hundreds of thousands of rows.
+
+**Phase 1 — swap the payload path, minimal moving parts.**
+Reintroduce `LimitContext.NOTEBOOK_MATERIALIZE` together with the new transport (tiered ceiling — see
+resource governance — landing eventually at `_MATERIALIZE_ROW_CAP`).
+When the data-plane task runs under it, the worker streams the CH result
+(`output_format="ArrowStream"`, bounded batches — data-modeling pattern) into one object,
+stores the **object key** in `QueryStatus` instead of rows, and the status endpoint answers the poll with a
+**302 redirect to a presigned URL**.
+The kernel's `requests` client follows redirects by default and drops the `Authorization` header on cross-host
+redirects, so the existing executor works nearly unchanged and the presigned URL needs no auth.
+Keep the Redis path as fallback when object storage is unconfigured (dev parity, degraded mode).
+
+Two decisions locked in for this phase:
+
+- **Format: one plain Arrow IPC stream object per frame — not Delta, not Parquet.** Delta earns its machinery
+ when ClickHouse re-reads a versioned, overwritten _table_ (data modeling's case). A frame is an immutable
+ write-once blob keyed by `query_hash`, read by pandas — an "update" is a different hash, i.e. a different
+ key. The executor already consumes ArrowStream from the data plane, so the sandbox-side change is just
+ "read the same bytes from a different host". If size matters, Arrow IPC supports LZ4/ZSTD buffer
+ compression without a format change; multi-file partitioning waits for phase 2, if ever.
+- **The queue is the throttle.** Under worker streaming, one active task = one running CH query = one upload,
+ so the dedicated queue's concurrency directly bounds CH concurrency, worker memory (~100MB × concurrency),
+ and S3 parallelism with a single knob — no dedicated CH user needed for v1 (that stays as hardening).
+ Throttling moves load in time (backlog), never above the cap; the real amplification risk is impatient
+ re-runs, and the async manager's existing `cache_key` dedup (`get_running_query_by_cache_key`) closes it:
+ enqueue with `cache_key = query_hash` and duplicate in-flight materializations join the running query
+ instead of stacking new ones.
+
+**Phase 2 — let ClickHouse do the writing (only if the data says so).**
+Replace the worker-streamed upload with `INSERT INTO FUNCTION s3(...'ArrowStream')` (batch-exports recipe):
+the worker's job shrinks to issuing one statement; zero result bytes transit PostHog Python.
+Add partitioned files + a manifest for very large frames, and Range-based resume in the executor.
+
+Why phase 1 streams from the worker instead of starting here:
+
+- **Security path.** Phase 1 keeps the whole HogQL runner path (team scoping, property access controls applied
+ at print time) untouched — new code only handles the result. The CH-side write must print the guarded SQL
+ and splice it into a raw `INSERT ... SELECT` executed outside the runner; batch exports does this safely,
+ but over its own known tables, not arbitrary user HogQL. That seam deserves its own review, not a ride-along.
+- **Credentials.** Workers already hold object-storage credentials; the CH-side write needs the cluster's IAM
+ role extended to the notebooks prefix (see open questions) and local CH → SeaweedFS config.
+- **Load placement.** Worker streaming actually puts _less_ work on ClickHouse — CH only executes and streams
+ blocks, while Arrow encoding and S3 PUTs burn worker CPU/NIC instead of CH-node resources. The worker's
+ drain pace is set by an in-region worker→S3 leg, so CH's result-hold time is near-identical either way.
+- **What A buys.** Worker economics at scale (a slot held seconds instead of the stream duration) and no
+ double transfer for very large frames. With per-team concurrency ~1 and frames in the tens-to-hundreds of
+ MB, neither matters yet — escalate on query-log evidence, and phase 2 may never be needed.
+
+**Phase 3 — reuse and convergence.**
+Serve repeat materializations of an unchanged upstream query straight from the existing object
+(`query_hash` in the key makes this a HEAD check), tighten lifecycle (delete on supersede),
+and align the format with the local-DuckDB engine direction so materialized frames double as DuckDB-readable
+tables without re-encoding.
+
+## Open questions
+
+- Bucket choice: reuse `OBJECT_STORAGE_BUCKET` under a `notebooks/` prefix vs a dedicated bucket
+ (dedicated is cleaner for lifecycle rules and IAM scoping; more infra to provision).
+- Does cloud CH's instance role already permit writes to the chosen bucket, or does that need infra work
+ (batch exports suggests the pattern is established)?
+- Presign from SeaweedFS in local dev: verify the presigned host is reachable from the locally-run kernel.
+- Whether phase 1 should also carry SQLV2 (hogql-node) first pages, or stay materialization-only
+ (recommendation: materialization-only — envelopes are small and the current path serves them well).
diff --git a/products/notebooks/backend/sql_v2_references.py b/products/notebooks/backend/sql_v2_references.py
index 9b4016260a31..9017889d380d 100644
--- a/products/notebooks/backend/sql_v2_references.py
+++ b/products/notebooks/backend/sql_v2_references.py
@@ -13,6 +13,9 @@ own ``WITH`` is left alone. Broken definitions that nothing references are never
so an unrelated malformed node can't fail a run.
"""
+import hashlib
+from typing import Any
+
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.errors import ExposedHogQLError
@@ -20,6 +23,8 @@ from posthog.hogql.parser import parse_select
from posthog.hogql.printer import print_prepared_ast
from posthog.hogql.visitor import TraversingVisitor
+from products.notebooks.backend.python_analysis import analyze_python_globals
+
class SQLV2ReferenceError(Exception):
"""A reference could not be resolved (cycle, or a referenced definition won't parse). User-facing."""
@@ -124,3 +129,32 @@ def resolve_sql_v2_references(code: str, refs: dict[str, str | None]) -> str:
root.ctes = ctes
return print_prepared_ast(root, context=HogQLContext(team_id=None), dialect="hogql")
+
+
+def resolve_python_node_inputs(code: str, refs: dict[str, str | None]) -> list[dict[str, Any]]:
+ """Return the materialization specs for the upstream frames a Python node reads.
+
+ `refs` maps each named upstream node's dataframe name to its **last-run** HogQL (or None
+ if it has never completed a run). A Python node references frames as plain variables, so
+ we materialize only the names its code actually reads — each becomes a HogQL input the
+ executor fetches to a local Arrow file, keyed by `query_hash` so an unchanged upstream
+ query reuses its frame.
+
+ Raises SQLV2ReferenceError if the code reads a known node that has not been run yet.
+ """
+ used = set(analyze_python_globals(code).used)
+ inputs: list[dict[str, Any]] = []
+ for name, last_run_code in refs.items():
+ if not name or name not in used:
+ continue
+ if last_run_code is None or not last_run_code.strip():
+ raise SQLV2ReferenceError(f"Referenced node '{name}' has not been run yet — run it first.")
+ inputs.append(
+ {
+ "name": name,
+ "kind": "hogql",
+ "query": last_run_code,
+ "query_hash": hashlib.sha256(last_run_code.encode()).hexdigest(),
+ }
+ )
+ return inputs
diff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.py
index 80183991dbb4..2e56e7b79bca 100644
--- a/products/notebooks/backend/sql_v2_serializers.py
+++ b/products/notebooks/backend/sql_v2_serializers.py
@@ -3,8 +3,33 @@ from rest_framework import serializers
class NotebookSQLV2RunRequestSerializer(serializers.Serializer):
node_id = serializers.CharField(help_text="ProseMirror node id of the SQLV2 node being run.")
+ node_type = serializers.ChoiceField(
+ choices=["hogql", "python"],
+ required=False,
+ default="hogql",
+ help_text=(
+ "Execution kind. 'hogql' pushes the query to ClickHouse; 'python' runs the code in the "
+ "sandbox kernel, materializing referenced upstream nodes as pandas frames first."
+ ),
+ )
code = serializers.CharField(
- help_text="The HogQL the node contains; the sandbox runs it through the data plane. Must not be blank.",
+ help_text="The node's source — HogQL for a hogql node, Python for a python node. Must not be blank.",
+ )
+ output_name = serializers.CharField(
+ required=False,
+ default="",
+ allow_blank=True,
+ help_text="Python node only: the dataframe variable to preview as the result (falls back to the last expression).",
+ )
+ refs = serializers.DictField(
+ child=serializers.CharField(),
+ required=False,
+ default=dict,
+ help_text=(
+ "Available upstream nodes, mapping each named node's dataframe name to its ProseMirror "
+ "node id, resolved to each node's last-run query. A hogql node inlines the referenced ones "
+ "as CTEs; a python node materializes the ones its code reads as pandas frames."
+ ),
)
refs = serializers.DictField(
child=serializers.CharField(),
@@ -40,8 +65,10 @@ class NotebookSQLV2DataPlaneRequestSerializer(serializers.Serializer):
required=False,
default=50,
min_value=1,
- max_value=1000,
- help_text="Maximum number of rows to return (applied as an outer LIMIT).",
+ # Must admit the kernel executor's full-frame materialize cap (_MATERIALIZE_ROW_CAP);
+ # the HogQL printer clamps explicit LIMITs to MAX_SELECT_RETURNED_ROWS regardless.
+ max_value=2_000_000,
+ help_text="Maximum number of rows to return (applied as an outer LIMIT, clamped by HogQL's row ceiling).",
)
offset = serializers.IntegerField(
required=False,
@@ -51,8 +78,33 @@ class NotebookSQLV2DataPlaneRequestSerializer(serializers.Serializer):
)
+class NotebookSQLV2MediaSerializer(serializers.Serializer):
+ mime_type = serializers.CharField(help_text="MIME type of the media, e.g. 'image/png' for a matplotlib figure.")
+ # The kernel sends this key as `data`; the field name collides with DRF's `.data` property at
+ # the type level only (fields live in a dict at runtime), so the ignore is safe.
+ data = serializers.CharField(help_text="Base64-encoded media bytes.") # type: ignore[assignment]
+
+
class NotebookSQLV2EnvelopeSerializer(serializers.Serializer):
status = serializers.CharField(help_text="Run outcome: 'ok' or 'error'.")
+ stdout = serializers.CharField(
+ required=False,
+ default="",
+ allow_blank=True,
+ help_text="Captured stdout from a Python node run.",
+ )
+ stderr = serializers.CharField(
+ required=False,
+ default="",
+ allow_blank=True,
+ help_text="Captured stderr (including tracebacks) from a Python node run.",
+ )
+ media = NotebookSQLV2MediaSerializer(
+ many=True,
+ required=False,
+ default=list,
+ help_text="Rich outputs from a Python node run, e.g. matplotlib figures as PNGs.",
+ )
columns = serializers.ListField(
child=serializers.CharField(),
required=False,
diff --git a/products/notebooks/backend/temporal/sql_v2.py b/products/notebooks/backend/temporal/sql_v2.py
index e21e4ba32f81..6d3f4d25b8b7 100644
--- a/products/notebooks/backend/temporal/sql_v2.py
+++ b/products/notebooks/backend/temporal/sql_v2.py
@@ -6,8 +6,9 @@ never on a web worker. Instance lifecycle is owned by the Kernel info panel
(kernel/start); dispatch lazily ensures the SQLV2 server on the running kernel.
"""
-from dataclasses import dataclass
+from dataclasses import dataclass, field
from datetime import timedelta
+from typing import Any
from temporalio import activity, common, workflow
@@ -25,6 +26,10 @@ class SQLV2RunInput:
team_id: int
user_id: int | None = None
code: str = ""
+ node_type: str = "hogql"
+ output_name: str = ""
+ # For a python node: [{name, kind, query, query_hash}] frames to materialize before running.
+ inputs: list[dict[str, Any]] = field(default_factory=list)
def _load_notebook_and_user(team_id: int, notebook_short_id: str, user_id: int | None) -> tuple[Notebook, User | None]:
@@ -38,7 +43,15 @@ def dispatch_sql_v2_run_activity(input: SQLV2RunInput) -> None:
notebook, user = _load_notebook_and_user(input.team_id, input.notebook_short_id, input.user_id)
run = NotebookNodeRun.objects.for_team(input.team_id).get(id=input.run_id)
try:
- dispatch_sql_v2_run(notebook, user, run, input.code)
+ dispatch_sql_v2_run(
+ notebook,
+ user,
+ run,
+ input.code,
+ node_type=input.node_type,
+ output_name=input.output_name,
+ inputs=input.inputs,
+ )
except SQLV2KernelNotRunning:
# Terminal — retrying won't start the kernel. Mark failed; the SSE stream surfaces it.
run.status = NotebookNodeRun.Status.FAILED
diff --git a/products/notebooks/backend/test/test_kernel_bootstrap.py b/products/notebooks/backend/test/test_kernel_bootstrap.py
new file mode 100644
index 000000000000..351830524e0b
--- /dev/null
+++ b/products/notebooks/backend/test/test_kernel_bootstrap.py
@@ -0,0 +1,101 @@
+import os
+import tempfile
+
+from django.test import SimpleTestCase
+
+import pyarrow as pa
+
+from products.notebooks.backend.sandbox.kernel.bootstrap import _MEDIA_MAX_FIGURES, KernelSession
+
+
+class TestKernelSessionRunNode(SimpleTestCase):
+ def setUp(self):
+ self._dir = tempfile.TemporaryDirectory()
+ self.addCleanup(self._dir.cleanup)
+ self.session = KernelSession(data_dir=self._dir.name)
+
+ def _write_frame(self, name: str, table: pa.Table) -> str:
+ path = os.path.join(self._dir.name, "frames", f"{name}.arrow")
+ with pa.OSFile(path, "wb") as sink:
+ with pa.ipc.new_file(sink, table.schema) as writer:
+ writer.write_table(table)
+ return path
+
+ def _run(self, code: str, inputs=None, output_name=None) -> dict:
+ return self.session.run_node(
+ {"node": {"type": "python", "code": code, "output_name": output_name}, "inputs": inputs or []}
+ )
+
+ def test_dataframe_last_expression_is_previewed(self):
+ envelope = self._run("import pandas as pd\npd.DataFrame({'a': [1, 2], 'b': [3, 4]})")
+ self.assertEqual(envelope["status"], "ok")
+ self.assertEqual(envelope["columns"], ["a", "b"])
+ self.assertEqual(envelope["first_page"], [[1, 3], [2, 4]])
+ self.assertEqual(envelope["row_count"], 2)
+
+ def test_output_name_frame_is_previewed_over_last_expression(self):
+ envelope = self._run("import pandas as pd\nresult = pd.DataFrame({'x': [9]})\n1 + 1", output_name="result")
+ self.assertEqual(envelope["columns"], ["x"])
+ self.assertEqual(envelope["first_page"], [[9]])
+
+ def test_row_count_and_has_more_reflect_the_full_frame(self):
+ envelope = self.session.run_node(
+ {"node": {"code": "import pandas as pd\npd.DataFrame({'n': range(120)})"}, "page_limit": 50}
+ )
+ self.assertEqual(envelope["row_count"], 120)
+ self.assertEqual(len(envelope["first_page"]), 50)
+ self.assertTrue(envelope["has_more"])
+
+ def test_stdout_is_captured(self):
+ envelope = self._run("print('hello from the kernel')")
+ self.assertIn("hello from the kernel", envelope["stdout"])
+ self.assertEqual(envelope["columns"], [])
+
+ def test_matplotlib_figure_is_captured_as_png(self):
+ envelope = self._run("import matplotlib.pyplot as plt\nplt.plot([1, 2, 3])")
+ self.assertEqual(len(envelope["media"]), 1)
+ self.assertEqual(envelope["media"][0]["mime_type"], "image/png")
+ self.assertTrue(envelope["media"][0]["data"])
+
+ def test_exception_surfaces_as_error_envelope(self):
+ envelope = self._run("raise ValueError('boom')")
+ self.assertEqual(envelope["status"], "error")
+ self.assertIn("ValueError: boom", envelope["error"])
+
+ def test_hogql_input_is_bound_as_a_pandas_frame(self):
+ # The server streams a CH result to a local Arrow file; the kernel must expose it as
+ # a pandas frame the node code can filter — this is the Journey 4 materialization step.
+ self._write_frame("df1", pa.table({"id": [1, 2, 3], "v": [10, 20, 30]}))
+ path = os.path.join(self._dir.name, "frames", "df1.arrow")
+ envelope = self._run("df1[df1.id > 1]", inputs=[{"name": "df1", "kind": "hogql", "path": path}])
+ self.assertEqual(envelope["status"], "ok")
+ self.assertEqual(envelope["columns"], ["id", "v"])
+ self.assertEqual(envelope["first_page"], [[2, 20], [3, 30]])
+
+ def test_missing_local_input_produces_a_clear_error(self):
+ envelope = self._run("1 + 1", inputs=[{"name": "never_made", "kind": "local"}])
+ self.assertEqual(envelope["status"], "error")
+ self.assertIn("never_made", envelope["error"])
+
+ def test_oversized_stdout_is_truncated(self):
+ envelope = self._run("print('x' * 100_000)")
+ self.assertLess(len(envelope["stdout"]), 33_000)
+ self.assertIn("[output truncated", envelope["stdout"])
+
+ def test_oversized_preview_cells_are_clipped(self):
+ envelope = self._run("import pandas as pd\npd.DataFrame({'s': ['y' * 50_000]})")
+ cell = envelope["first_page"][0][0]
+ self.assertLessEqual(len(cell), 10_001)
+ self.assertTrue(cell.endswith("…"))
+ self.assertEqual(envelope["row_count"], 1)
+
+ def test_figures_beyond_the_media_cap_are_omitted(self):
+ envelope = self._run(
+ "import matplotlib.pyplot as plt\n"
+ f"for i in range({_MEDIA_MAX_FIGURES + 1}):\n"
+ " plt.figure()\n"
+ " plt.plot([1, i])\n"
+ )
+ self.assertEqual(envelope["status"], "ok")
+ self.assertEqual(len(envelope["media"]), _MEDIA_MAX_FIGURES)
+ self.assertIn("1 figure(s) omitted", envelope["stderr"])
diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.py
index 82850b455701..bdcdc02471ca 100644
--- a/products/notebooks/backend/test/test_sql_v2.py
+++ b/products/notebooks/backend/test/test_sql_v2.py
@@ -45,6 +45,7 @@ from products.notebooks.backend.sql_v2 import (
sql_v2_page_lock_key,
verify_data_plane_token,
)
+from products.notebooks.backend.sql_v2_callback import MAX_ENVELOPE_BYTES
from products.notebooks.backend.sql_v2_data_plane import _rows_to_arrow_bytes
from products.notebooks.backend.temporal.sql_v2 import (
SQLV2RunInput,
@@ -144,6 +145,12 @@ class TestSQLV2Callback(APIBaseTest):
self.assertEqual(response.status_code, 403)
self.assertEqual(self._reload_run().status, NotebookNodeRun.Status.RUNNING)
+ def test_oversized_envelope_is_rejected(self):
+ token = mint_callback_token(str(self.node_run.id), self.team.id)
+ response = self._post(token, envelope={**self.envelope, "stdout": "x" * (MAX_ENVELOPE_BYTES + 1)})
+ self.assertEqual(response.status_code, 400)
+ self.assertEqual(self._reload_run().status, NotebookNodeRun.Status.RUNNING)
+
def test_unknown_run_returns_404(self):
other_id = "00000000-0000-0000-0000-000000000000"
token = mint_callback_token(other_id, self.team.id)
@@ -256,6 +263,42 @@ class TestSQLV2Run(APIBaseTest):
self.assertEqual(NotebookNodeRun.objects.for_team(self.team.id).filter(node_id="c").count(), 0)
mock_start.assert_not_called()
+ @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_python_node_dispatches_with_materialization_inputs(self, _mock_enabled, mock_start):
+ # A python node keeps its code verbatim and ships the frames it reads as materialization inputs.
+ self._record_done_run("node-df1", "select id from events")
+ response = self.client.post(
+ self.run_url,
+ data={
+ "node_id": "py",
+ "node_type": "python",
+ "code": "df1.head()",
+ "output_name": "result",
+ "refs": {"df1": "node-df1"},
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, 200)
+ run = NotebookNodeRun.objects.for_team(self.team.id).get(id=response.json()["run_id"])
+ self.assertEqual(run.code, "df1.head()") # python code stored as-is, not CTE-resolved
+ dispatched = mock_start.call_args.args[0]
+ self.assertEqual(dispatched.node_type, "python")
+ self.assertEqual(dispatched.output_name, "result")
+ self.assertEqual([i["name"] for i in dispatched.inputs], ["df1"])
+ self.assertEqual(dispatched.inputs[0]["query"], "select id from events")
+
+ @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_python_node_referencing_a_never_run_node_is_rejected(self, _mock_enabled, mock_start):
+ response = self.client.post(
+ self.run_url,
+ data={"node_id": "py", "node_type": "python", "code": "df1.head()", "refs": {"df1": "node-df1"}},
+ format="json",
+ )
+ self.assertEqual(response.status_code, 400)
+ mock_start.assert_not_called()
+
@patch(
"products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow",
side_effect=RuntimeError("temporal unavailable"),
@@ -731,6 +774,18 @@ class TestSQLV2DataPlaneEndpoint(APIBaseTest):
_columns, rows, _types = decode_arrow_stream(response.content)
self.assertEqual(rows, [(2,), (3,), (4,)])
+ def test_materialization_request_is_accepted_and_clipped_at_the_row_ceiling(self):
+ # The kernel executor fetches whole frames with limit=_MATERIALIZE_ROW_CAP (2M, not
+ # importable here: the executor module needs jupyter_client). The serializer must
+ # accept that limit (it once capped at 1000, 400-ing every materialization), and the
+ # async limit context then clips the frame at MAX_SELECT_RETURNED_ROWS (50k) — a
+ # deliberate bound until the object-storage frame store (sql_v2_frame_store.md)
+ # gives big frames a transport that doesn't round-trip through Redis.
+ response = self._run_to_completion({"query": "select number from numbers(50001)", "limit": 2_000_000})
+ self.assertEqual(response.status_code, 200, response.content)
+ _columns, rows, _types = decode_arrow_stream(response.content)
+ self.assertEqual(len(rows), 50_000)
+
def test_execution_error_surfaces_through_status(self):
# Valid syntax but fails at execution — the error must reach the sandbox via the poll.
response = self._run_to_completion({"query": "select nonexistent_column from events"})
@@ -1070,3 +1125,79 @@ class TestSQLV2KernelPackage(SimpleTestCase):
self.assertIn("nb_kernel/server.py", names)
self.assertIn("nb_kernel/__init__.py", names)
self.assertEqual(len(version), 16)
+
+
+class TestSQLV2PythonNodeRun(SimpleTestCase):
+ def test_materialize_query_writes_a_readable_arrow_file(self):
+ # Journey 4 materialization: the server streams a CH result to a local Arrow *file* the
+ # kernel later mmaps. It must be an IPC file (open_file), and the temp must be renamed away.
+ import os
+ import tempfile
+
+ import pyarrow as pa
+
+ from products.notebooks.backend.sandbox.kernel import data_plane as kernel_data_plane
+
+ arrow_bytes = _rows_to_arrow_bytes(["id", "v"], [(1, 10), (2, 20)], [["id", "Int64"], ["v", "Int64"]])
+
+ class _FakeResponse(io.BytesIO):
+ def __init__(self, body: bytes):
+ super().__init__(body)
+ self.headers = {"Content-Type": "application/vnd.apache.arrow.stream"}
+
+ def __exit__(self, *args):
+ return False
+
+ with tempfile.TemporaryDirectory() as directory:
+ dest = os.path.join(directory, "df.arrow")
+ with patch.object(
+ kernel_data_plane.urllib.request,
+ "urlopen",
+ side_effect=lambda request, timeout=None: _FakeResponse(arrow_bytes),
+ ):
+ rows = kernel_data_plane.materialize_query_to_file(
+ "http://backend/dp", "t", "select 1", dest, limit=1000
+ )
+ self.assertEqual(rows, 2)
+ table = pa.ipc.open_file(pa.memory_map(dest)).read_all()
+ self.assertEqual(table.num_rows, 2)
+ self.assertEqual(table.column_names, ["id", "v"])
+ self.assertFalse(os.path.exists(dest + ".partial"))
+
+ def test_execute_run_routes_python_nodes_to_the_executor(self):
+ result_envelope = {"status": "ok", "columns": ["a"]}
+ delivered: dict = {}
+ payload = {
+ "run_id": "r-py",
+ "node": {"type": "python", "code": "1 + 1"},
+ "callback_url": "http://backend/cb",
+ "callback_token": "t",
+ }
+ with (
+ patch.object(kernel_runner, "_run_python_node", return_value=result_envelope) as run_python,
+ patch.object(kernel_runner, "_post_callback", side_effect=lambda url, token, env: delivered.update(env)),
+ ):
+ kernel_runner.execute_run(payload)
+ run_python.assert_called_once()
+ self.assertEqual(delivered["status"], "ok")
+
+ def test_execute_run_keeps_hogql_nodes_off_the_kernel(self):
+ # A pure-HogQL node must stay on the capped data-plane fetch — never spin up the kernel.
+ payload = {
+ "run_id": "r-hogql",
+ "code": "select 1",
+ "callback_url": "http://backend/cb",
+ "callback_token": "t",
+ "data_plane_url": "u",
+ "data_plane_token": "t",
+ }
+ with (
+ patch.object(kernel_runner, "_run_python_node") as run_python,
+ patch.object(kernel_runner, "_post_callback"),
+ patch(
+ "products.notebooks.backend.sandbox.kernel.data_plane.fetch_query_page",
+ return_value=(["n"], [(1,)], [["n", "Int64"]]),
+ ),
+ ):
+ kernel_runner.execute_run(payload)
+ run_python.assert_not_called()
diff --git a/products/notebooks/backend/test/test_sql_v2_references.py b/products/notebooks/backend/test/test_sql_v2_references.py
index 11cd4e832b6e..6e6dfff031ef 100644
--- a/products/notebooks/backend/test/test_sql_v2_references.py
+++ b/products/notebooks/backend/test/test_sql_v2_references.py
@@ -1,6 +1,34 @@
from django.test import SimpleTestCase
-from products.notebooks.backend.sql_v2_references import SQLV2ReferenceError, resolve_sql_v2_references
+from products.notebooks.backend.sql_v2_references import (
+ SQLV2ReferenceError,
+ resolve_python_node_inputs,
+ resolve_sql_v2_references,
+)
+
+
+class TestResolvePythonNodeInputs(SimpleTestCase):
+ def test_only_referenced_frames_are_materialized(self):
+ # A python node reads frames as variables; materialize only the ones its code uses.
+ inputs = resolve_python_node_inputs("df1.head()", {"df1": "select id from events", "df2": "select 1"})
+ self.assertEqual(len(inputs), 1)
+ self.assertEqual(inputs[0]["name"], "df1")
+ self.assertEqual(inputs[0]["kind"], "hogql")
+ self.assertEqual(inputs[0]["query"], "select id from events")
+ self.assertTrue(inputs[0]["query_hash"])
+
+ def test_unused_refs_are_ignored(self):
+ self.assertEqual(resolve_python_node_inputs("import pandas as pd\npd.DataFrame()", {"df1": "select 1"}), [])
+
+ def test_query_hash_is_stable_for_the_same_query(self):
+ # The executor reuses a frame file keyed by hash, so identical queries must hash identically.
+ a = resolve_python_node_inputs("df1", {"df1": "select 1"})[0]["query_hash"]
+ b = resolve_python_node_inputs("df1", {"df1": "select 1"})[0]["query_hash"]
+ self.assertEqual(a, b)
+
+ def test_referencing_a_never_run_node_raises(self):
+ with self.assertRaises(SQLV2ReferenceError):
+ resolve_python_node_inputs("df1.head()", {"df1": None})
class TestResolveSQLV2References(SimpleTestCase):