:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(notebooks): add new SQL query node for revamped markdown notebooksV2 (#67733)
Sinan Kucukkoselerdc71e89738da
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 308bc1ac7eef..60eca9671425 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -198,6 +198,7 @@ rules:|Node|NotificationEvent|Notebook+ |NotebookNodeRun|ObjectMediaPreview|ParserRecipe|PendingSourceCredential@@ -472,6 +473,7 @@ rules:|Node|NotificationEvent|Notebook+ |NotebookNodeRun|ObjectMediaPreview|ParserRecipe|PendingSourceCredentialdiff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 5271b3bcbe51..5e67227516b1 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -4924,6 +4924,27 @@ const api = {async kernelStatus(notebookId: NotebookType['short_id']): Promise<Record<string, any>> {return await new ApiRequest().notebook(notebookId).withAction('kernel/status').get()},+ async sqlV2Run(+ notebookId: NotebookType['short_id'],+ data: { node_id: string; code: string }+ ): Promise<{ run_id: string }> {+ return await new ApiRequest().notebook(notebookId).withAction('sql_v2/run').create({ data })+ },+ async sqlV2RunResult(+ notebookId: NotebookType['short_id'],+ runId: string+ ): Promise<{+ status: 'running' | 'done' | 'failed'+ result: {+ columns?: string[]+ types?: [string, string][]+ row_count?: number+ first_page?: (string | number | null)[][]+ } | null+ error: string | null+ }> {+ return await new ApiRequest().notebook(notebookId).withAction(`sql_v2/runs/${runId}`).get()+ },async markdownSave(notebookId: NotebookType['short_id'],data: {diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 741b6964f991..762463421850 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -460,6 +460,7 @@ export const FEATURE_FLAGS = {REPLAY_VIDEO_BASED_SUMMARIZATION: 'replay-video-based-summarization', // owner: #team-replayREPLAY_VISION: 'replay-vision', // owner: #team-replayREPLAY_VISION_ACTIONS: 'replay-vision-actions', // owner: #team-replay+ REVAMPED_PY_NOTEBOOKS: 'revamped-py-notebooks', // owner: #team-data-toolsREVENUE_ANALYTICS: 'revenue-analytics', // owner: @rafaeelaudibert #team-customer-analyticsREVENUE_FIELDS_IN_POWER_USERS_TABLE: 'revenue-fields-in-power-users-table', // owner: @arthurdedeus #team-customer-analyticsSCENE_MENU_BAR: 'scene-menu-bar', // owner: @adamleithp #team-platform-ux, gates the per-scene MenuBar above SceneTitleSectiondiff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsxnew file mode 100644index 000000000000..15fccfefe6f2--- /dev/null+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx@@ -0,0 +1,231 @@+import { useActions, useMountedLogic, useValues } from 'kea'+import { useMemo } from 'react'++import { LemonTabs } from 'lib/lemon-ui/LemonTabs'+import { OutputTab } from 'scenes/data-warehouse/editor/outputPaneLogic'+import { createPostHogWidgetNode } from 'scenes/notebooks/Nodes/NodeWrapper'++import { Query } from '~/queries/Query/Query'+import { DataVisualizationNode, HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'+import { ChartDisplayType } from '~/types'++import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType } from '../types'+import { NotebookDataframeTable } from './components/NotebookDataframeTable'+import { NotebookCodeSQLEditorSettings } from './components/NotebookSQLEditor'+import { notebookNodeLogic } from './notebookNodeLogic'+import { notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'+import { NotebookDataframeResult } from './pythonExecution'++export type NotebookNodeSQLV2Result = {+ columns: string[]+ types?: [string, string][]+ row_count: number+ first_page: (string | number | null)[][]+}++export type NotebookNodeSQLV2Attributes = {+ code: string+ runId?: string | null+ result?: NotebookNodeSQLV2Result | null+ outputTab?: OutputTab | null+ vizQuery?: DataVisualizationNode | null+}++const VIZ_MIN_HEIGHT = 420++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]))),+ // Page over what we actually have; the envelope only carries the first page.+ rowCount: firstPage.length,+ }+}++// Results from before the envelope carried types (or a kernel that omitted them):+// approximate from the first non-null cell so numeric axes still work in charts.+const inferTypes = (result: NotebookNodeSQLV2Result): [string, string][] =>+ (result.columns ?? []).map((column, index) => {+ const sample = (result.first_page ?? []).map((row) => row[index]).find((cell) => cell !== null)+ return [column, typeof sample === 'number' ? 'Float64' : 'String']+ })++const toCachedResults = (result: NotebookNodeSQLV2Result): HogQLQueryResponse => ({+ results: result.first_page ?? [],+ columns: result.columns ?? [],+ types: result.types?.length ? result.types : inferTypes(result),+})++const Component = ({+ attributes,+ updateAttributes,+}: NotebookNodeProps<NotebookNodeSQLV2Attributes>): 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 } = useValues(dataLogic)++ const result = attributes.result ?? null+ const dataframeResult = useMemo(() => (result ? toDataframeResult(result) : null), [result])+ const cachedResults = useMemo(() => (result ? toCachedResults(result) : null), [result])+ const activeTab = attributes.outputTab === OutputTab.Visualization ? OutputTab.Visualization : OutputTab.Results++ // The stored viz config wins, but the source always tracks the node's current code.+ const vizQuery = useMemo(+ (): DataVisualizationNode => ({+ kind: NodeKind.DataVisualizationNode,+ display: ChartDisplayType.ActionsLineGraph,+ ...attributes.vizQuery,+ source: { kind: NodeKind.HogQLQuery, query: attributes.code },+ }),+ [attributes.vizQuery, attributes.code]+ )++ if (!expanded) {+ return null+ }++ return (+ <div data-attr="notebook-node-sql-v2" className="flex h-full flex-col">+ <div+ className="space-y-3"+ onMouseDown={(event) => event.stopPropagation()}+ onDragStart={(event) => event.stopPropagation()}+ >+ {runError ? (+ <div className="p-2 text-xs font-mono text-danger whitespace-pre-wrap">{runError}</div>+ ) : dataframeResult && cachedResults ? (+ <>+ <div className="px-2 pt-1" onClick={(event) => event.stopPropagation()}>+ <LemonTabs+ size="small"+ activeKey={activeTab}+ onChange={(tab) => {+ // Charts need vertical room; the default node height only fits a few table rows.+ const height =+ tab === OutputTab.Visualization &&+ (typeof attributes.height !== 'number' || attributes.height < VIZ_MIN_HEIGHT)+ ? VIZ_MIN_HEIGHT+ : attributes.height+ updateAttributes({ outputTab: tab, height })+ }}+ barClassName="mb-0"+ tabs={[+ { key: OutputTab.Results, label: 'Results' },+ { key: OutputTab.Visualization, label: 'Visualization' },+ ]}+ />+ </div>+ {activeTab === OutputTab.Results ? (+ <NotebookDataframeTable+ result={dataframeResult}+ loading={isRunning}+ page={1}+ pageSize={Math.max(dataframeResult.rows.length, 1)}+ onNextPage={() => {}}+ onPreviousPage={() => {}}+ onPageSizeChange={() => {}}+ />+ ) : (+ <div+ className="px-2 pb-2 flex min-h-0 flex-1 flex-col"+ onClick={(event) => event.stopPropagation()}+ >+ <Query+ // Keyed per run so a fresh envelope re-seeds the cached response.+ uniqueKey={`${nodeId}-viz-${attributes.runId ?? 'initial'}`}+ query={vizQuery}+ setQuery={(query) => {+ // DataVisualization pushes default settings during its render;+ // defer the doc write so we don't update Tiptap mid-render.+ const vizQuery = query as DataVisualizationNode+ setTimeout(() => updateAttributes({ vizQuery }), 0)+ }}+ cachedResults={cachedResults}+ attachTo={notebookLogic}+ />+ </div>+ )}+ </>+ ) : (+ <div className="text-xs text-muted font-mono p-2">Run the query to see execution results.</div>+ )}+ {attributes.runId ? (+ <div className="px-2 pb-2 text-[10px] uppercase tracking-wide text-muted select-text">+ run_id: {attributes.runId}+ </div>+ ) : null}+ </div>+ </div>+ )+}++const Settings = ({+ attributes,+ updateAttributes,+}: NotebookNodeAttributeProperties<NotebookNodeSQLV2Attributes>): 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 } = useValues(dataLogic)+ const { runQuery } = useActions(dataLogic)++ return (+ <NotebookCodeSQLEditorSettings+ attributes={attributes}+ updateAttributes={updateAttributes}+ tabIdSuffix="datav2"+ onRunQuery={(code) => runQuery(code)}+ runQueryLoading={isRunning}+ runQueryTooltip="Run SQL (v2) query"+ />+ )+}++export const NotebookNodeSQLV2 = createPostHogWidgetNode<NotebookNodeSQLV2Attributes>({+ nodeType: NotebookNodeType.SQLV2,+ titlePlaceholder: 'SQL (v2)',+ Component,+ heightEstimate: 120,+ minHeight: 80,+ resizeable: true,+ startExpanded: true,+ attributes: {+ code: {+ default: '',+ },+ runId: {+ default: null,+ },+ result: {+ default: null,+ },+ outputTab: {+ default: OutputTab.Results,+ },+ vizQuery: {+ default: null,+ },+ },+ Settings,+ settingsPlacement: 'inline',+ serializedText: (attrs) => attrs.code,+})diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsxindex dc21f197726e..e01983f21fc8 100644--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx@@ -400,7 +400,8 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string }>({runQueryTooltip,}: NotebookNodeAttributeProperties<T> & {tabIdSuffix: string- onRunQuery?: () => void+ /** Called with the live editor text — `attributes.code` can lag it by a Tiptap round-trip. */+ onRunQuery?: (code: string) => voidrunQueryLoading?: booleanrunQueryDisabledReason?: stringrunQueryTooltip?: string@@ -410,6 +411,9 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string }>({[attributes.nodeId, tabIdSuffix])useNotebookCodeSQLEditorSync({ attributes, updateAttributes, tabId })+ const { queryInput } = useValues(sqlEditorLogic({ tabId, mode: SQLEditorMode.Embedded }))+ // Prefer what the user sees in the editor; fall back to the attribute before the first sync.+ const liveCode = queryInput ?? (typeof attributes.code === 'string' ? attributes.code : '')// Focus the editor only when this user just inserted the node - a node mounting on// notebook load or after a structural re-render must never steal the caret.const [autoFocusQueryPane] = useState(() => wasNotebookNodeJustInserted(attributes.nodeId))@@ -432,7 +436,7 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string }>({panel={SQLEditorPanel.Query}defaultShowDatabaseTree={false}autoFocusQueryPane={autoFocusQueryPane}- onRunQuery={onRunQuery}+ onRunQuery={onRunQuery ? () => onRunQuery(liveCode) : undefined}runQueryLoading={runQueryLoading}runQueryDisabledReason={runQueryDisabledReason}runQueryTooltip={runQueryTooltip}diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.tsnew file mode 100644index 000000000000..79165d294c01--- /dev/null+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts@@ -0,0 +1,93 @@+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'++import { initKeaTests } from '~/test/init'++import { notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'++describe('notebookNodeSQLV2Logic', () => {+ let logic: ReturnType<typeof notebookNodeSQLV2Logic.build>+ let updateAttributes: jest.Mock+ let runSpy: jest.SpyInstance+ let resultSpy: jest.SpyInstance++ const mount = (props: Record<string, unknown> = {}): void => {+ logic = notebookNodeSQLV2Logic({ nodeId: 'n1', notebookShortId: 'nb1', updateAttributes, ...props })+ logic.mount()+ }++ beforeEach(() => {+ initKeaTests()+ updateAttributes = jest.fn()+ runSpy = jest.spyOn(api.notebooks, 'sqlV2Run').mockResolvedValue({ run_id: 'r1' })+ // Default: the run is still executing, so polling continues without resolving.+ resultSpy = jest+ .spyOn(api.notebooks, 'sqlV2RunResult')+ .mockResolvedValue({ status: 'running', result: null, error: null })+ })++ afterEach(() => {+ logic?.unmount()+ jest.restoreAllMocks()+ })++ it('rejects blank code before dispatching a run', async () => {+ mount()+ logic.actions.runQuery(' ')+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({ runError: 'Query is empty — type some HogQL first.', isRunning: false })+ expect(runSpy).not.toHaveBeenCalled()+ })++ it('dispatches the run, persists the run id, and starts polling', async () => {+ mount()+ logic.actions.runQuery('select 1')+ await expectLogic(logic).toDispatchActions(['runQuery', 'startPolling', 'pollResult'])+ expect(runSpy).toHaveBeenCalledWith('nb1', { node_id: 'n1', code: 'select 1' })+ // The run id is persisted so a reload/remount can recover the in-flight run.+ expect(updateAttributes).toHaveBeenCalledWith({ runId: 'r1', result: null })+ })++ it('maps a done envelope into the node result and stops the spinner', async () => {+ resultSpy.mockResolvedValue({+ status: 'done',+ result: { columns: ['a'], first_page: [[1]], row_count: 1 },+ error: null,+ })+ mount({ runId: 'r1', hasResult: false })+ await expectLogic(logic).toFinishAllListeners()+ expect(updateAttributes).toHaveBeenCalledWith({+ result: { columns: ['a'], types: [], row_count: 1, first_page: [[1]] },+ })+ expect(logic.values.isRunning).toBe(false)+ })++ it('surfaces a failed run as an error', async () => {+ resultSpy.mockResolvedValue({ status: 'failed', result: null, error: 'no such table' })+ mount({ runId: 'r1', hasResult: false })+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.runError).toBe('no such table')+ expect(logic.values.isRunning).toBe(false)+ })++ it('surfaces a run dispatch failure as an error', async () => {+ runSpy.mockRejectedValue(new Error('network down'))+ mount()+ logic.actions.runQuery('select 1')+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ runError: 'network down', isRunning: false })+ })++ it('resumes polling a persisted un-finished run on mount', async () => {+ mount({ runId: 'r1', hasResult: false })+ await expectLogic(logic).toDispatchActions(['startPolling', 'pollResult'])+ expect(resultSpy).toHaveBeenCalledWith('nb1', 'r1')+ })++ it('does not poll a persisted run that already has a result', async () => {+ mount({ runId: 'r1', hasResult: true })+ await expectLogic(logic).toFinishAllListeners()+ expect(resultSpy).not.toHaveBeenCalled()+ })+})diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.tsnew file mode 100644index 000000000000..81e3a91202a3--- /dev/null+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts@@ -0,0 +1,128 @@+import { actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'++import api from 'lib/api'++import { NotebookNodeSQLV2Result } from './NotebookNodeSQLV2'+import type { notebookNodeSQLV2LogicType } from './notebookNodeSQLV2LogicType'++const POLL_INTERVAL_MS = 1000+const MAX_POLL_ATTEMPTS = 150 // ~2.5 minutes at 1s++export interface NotebookNodeSQLV2LogicProps {+ nodeId: string+ notebookShortId: string+ // Current node attributes, so a fresh mount can recover an in-flight/finished run by its runId.+ runId?: string | null+ hasResult?: boolean+ updateAttributes: (attrs: { runId?: string | null; result?: NotebookNodeSQLV2Result | null }) => void+}++export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([+ path((key) => ['scenes', 'notebooks', 'Nodes', 'notebookNodeSQLV2Logic', key]),+ props({} as NotebookNodeSQLV2LogicProps),+ key((props) => props.nodeId),+ actions({+ runQuery: (code: string) => ({ code }),+ startPolling: (runId: string) => ({ runId }),+ pollResult: (runId: string) => ({ runId }),+ stopPolling: true,+ setIsRunning: (isRunning: boolean) => ({ isRunning }),+ setRunError: (runError: string | null) => ({ runError }),+ }),+ reducers({+ // Tracks the run being in progress; driven by the run's status, not a socket lifecycle.+ isRunning: [+ false,+ {+ runQuery: () => true,+ startPolling: () => true,+ setIsRunning: (_, { isRunning }) => isRunning,+ },+ ],+ runError: [+ null as string | null,+ {+ runQuery: () => null,+ startPolling: () => null,+ setRunError: (_, { runError }) => runError,+ },+ ],+ }),+ listeners(({ props, actions, cache }) => ({+ runQuery: async ({ code }) => {+ if (!code.trim()) {+ actions.setRunError('Query is empty — type some HogQL first.')+ actions.setIsRunning(false)+ return+ }+ try {+ const { run_id } = await api.notebooks.sqlV2Run(props.notebookShortId, {+ node_id: props.nodeId,+ code,+ })+ props.updateAttributes({ runId: run_id, result: null })+ actions.startPolling(run_id)+ } catch (error) {+ actions.setRunError(error instanceof Error ? error.message : 'Failed to run query')+ actions.setIsRunning(false)+ }+ },+ startPolling: ({ runId }) => {+ cache.pollAttempts = 0+ actions.pollResult(runId)+ // Same key auto-disposes any previous poller; disposables clean up on unmount and pause on hidden tab.+ cache.disposables.add(() => {+ const intervalId = window.setInterval(() => actions.pollResult(runId), POLL_INTERVAL_MS)+ return () => clearInterval(intervalId)+ }, 'pollResult')+ },+ pollResult: async ({ runId }) => {+ if (cache.pollInFlight) {+ return+ }+ cache.pollAttempts = (cache.pollAttempts ?? 0) + 1+ if (cache.pollAttempts > MAX_POLL_ATTEMPTS) {+ actions.setRunError('Timed out waiting for result')+ actions.stopPolling()+ return+ }+ cache.pollInFlight = true+ try {+ const { status, result, error } = await api.notebooks.sqlV2RunResult(props.notebookShortId, runId)+ if (status === 'done') {+ props.updateAttributes({+ result: result+ ? {+ columns: result.columns ?? [],+ types: result.types ?? [],+ row_count: result.row_count ?? 0,+ first_page: result.first_page ?? [],+ }+ : null,+ })+ actions.stopPolling()+ } else if (status === 'failed') {+ actions.setRunError(error ?? 'Run failed')+ actions.stopPolling()+ }+ // 'running' → keep polling+ } catch (error) {+ actions.setRunError(error instanceof Error ? error.message : 'Failed to fetch result')+ actions.stopPolling()+ } finally {+ cache.pollInFlight = false+ }+ },+ stopPolling: () => {+ cache.disposables.dispose('pollResult')+ actions.setIsRunning(false)+ },+ })),+ afterMount(({ props, actions }) => {+ // Recover after a reload/remount: a persisted runId with no result means the run may still be+ // in flight or already finished — poll to catch up rather than lose the result.+ if (props.runId && !props.hasResult) {+ actions.startPolling(props.runId)+ }+ }),+])diff --git a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsxindex 694c2ad1f8ec..27b641935d9d 100644--- a/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx+++ b/frontend/src/scenes/notebooks/Notebook/MarkdownNotebookV2Renderer.tsx@@ -18,13 +18,14 @@ import {import type { MarkdownNotebookCaretPosition, RemoteNotebookCaret } from 'lib/components/MarkdownNotebook/remoteCarets'import type { NotebookBlockNode } from 'lib/components/MarkdownNotebook/types'import { getInlineText } from 'lib/components/MarkdownNotebook/utils'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { uuid } from 'lib/utils/dom'import type { NotebookArtifactContent } from '~/queries/schema/schema-assistant-messages'import { MarkdownNotebookExperimentPicker } from './MarkdownNotebookExperimentPicker'import { InlineAIAssistantMessage, InlineAICompletion, InlineNotebookAIRunner } from './MarkdownNotebookInlineAI'-import { NOTEBOOK_MARKDOWN_REGISTRY } from './markdownNotebookRegistry'+import { getMarkdownRegistryForFeatureFlags } from './markdownNotebookRegistry'import {InlineNotebookAIRequest,MarkdownNotebookRuntimeContext,@@ -55,6 +56,8 @@ type MarkdownNotebookV2Props = {export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotebookV2Props): JSX.Element {const { isEditable, notebook, markdownEditorValue, markdownEditorInteractionActive, markdownRemoteCarets } =useValues(notebookLogic)+ const { featureFlags } = useValues(featureFlagLogic)+ const markdownRegistry = useMemo(() => getMarkdownRegistryForFeatureFlags(featureFlags), [featureFlags])const {handleMarkdownEditorChange,setMarkdownEditorInteractionActive,@@ -576,7 +579,7 @@ export function MarkdownNotebookV2({ debugOpen, onDebugOpenChange }: MarkdownNotremoteValue={remoteMarkdown}remoteVersion={notebook?.version}mode={isEditable ? 'edit' : 'view'}- registry={NOTEBOOK_MARKDOWN_REGISTRY}+ registry={markdownRegistry}extraInsertCommands={isEditable ? buildExtraInsertCommands : undefined}onChange={isEditable ? handleMarkdownNotebookChange : undefined}onConflict={reportMarkdownMergeConflicts}diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsxindex e916f25e1c68..94fba5279c46 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookRegistry.tsx@@ -1,6 +1,7 @@import '../Nodes/NotebookNodeBacklink'import '../Nodes/NotebookNodeCohort'import '../Nodes/NotebookNodeCustomerJourney/NotebookNodeCustomerJourney'+import '../Nodes/NotebookNodeSQLV2'import '../Nodes/NotebookNodeDuckSQL'import '../Nodes/NotebookNodeEarlyAccessFeature'import '../Nodes/NotebookNodeEmbed'@@ -49,6 +50,8 @@ import {NotebookPropValue,} from 'lib/components/MarkdownNotebook/types'import { isNotebookPropValue, toSerializablePropValue } from 'lib/components/MarkdownNotebook/utils'+import { FEATURE_FLAGS } from 'lib/constants'+import { type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'import { NODE_ICONS } from '../nodeIcons'import { NotebookNodeContext } from '../Nodes/NotebookNodeContext'@@ -104,6 +107,7 @@ export const MARKDOWN_TAG_TO_NOTEBOOK_NODE_TYPE: Partial<Record<string, NotebookPython: NotebookNodeType.Python,DuckSQL: NotebookNodeType.DuckSQL,HogQLSQL: NotebookNodeType.HogQLSQL,+ SQLV2: NotebookNodeType.SQLV2,Recording: NotebookNodeType.Recording,RecordingPlaylist: NotebookNodeType.RecordingPlaylist,FeatureFlag: NotebookNodeType.FeatureFlag,@@ -145,6 +149,9 @@ export const MARKDOWN_NODE_DEFINITIONS: {{ tagName: 'Python', category: 'Code' },{ 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+ // getMarkdownRegistryForFeatureFlags strips it when revamped-py-notebooks is off.+ { tagName: 'SQLV2', category: 'SQL', label: 'SQL (v2)', insertCommand: { aliases: ['data', 'sql'] } },{ tagName: 'RecordingPlaylist', category: 'Data', label: 'Session recordings' },{ tagName: 'Experiment', category: 'Experiment' },{ tagName: 'Image', category: 'Media', EditComponent: ImageEdit },@@ -222,6 +229,30 @@ export const NOTEBOOK_MARKDOWN_REGISTRY: NotebookComponentRegistry = createMarkd},])+// Node tags that only appear in the markdown insert menu when their feature flag is on.+// Only insertion is gated — rendering of already-inserted nodes is never gated.+export function getMarkdownRegistryForFeatureFlags(featureFlags: FeatureFlagsSet): NotebookComponentRegistry {+ const hiddenTags: string[] = []+ if (!featureFlags[FEATURE_FLAGS.REVAMPED_PY_NOTEBOOKS]) {+ hiddenTags.push('SQLV2')+ }++ if (hiddenTags.length === 0) {+ return NOTEBOOK_MARKDOWN_REGISTRY+ }++ // Dropping insertCommand hides the node from the insert menu (it filters falsy+ // insertCommand), while the ViewComponent stays so existing nodes still render.+ const components = { ...NOTEBOOK_MARKDOWN_REGISTRY.components }+ for (const tagName of hiddenTags) {+ const definition = components[tagName]+ if (definition) {+ components[tagName] = { ...definition, insertCommand: undefined }+ }+ }+ return { components }+}+export function getMarkdownNotebookNodeTitle(node: NotebookComponentBlockNode,nodeType: NotebookNodeType | undefined,diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.tsindex 88858eb7d63b..a541db202c92 100644--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts@@ -40,6 +40,7 @@ export const NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG: Partial<Record<NotebookNodeType[NotebookNodeType.Python]: 'Python',[NotebookNodeType.DuckSQL]: 'DuckSQL',[NotebookNodeType.HogQLSQL]: 'HogQLSQL',+ [NotebookNodeType.SQLV2]: 'SQLV2',[NotebookNodeType.Recording]: 'Recording',[NotebookNodeType.RecordingPlaylist]: 'RecordingPlaylist',[NotebookNodeType.FeatureFlag]: 'FeatureFlag',diff --git a/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx b/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsxindex 8cc6d18fdfe7..291ef688a551 100644--- a/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx+++ b/frontend/src/scenes/notebooks/NotebooksTable/ContainsTypeFilter.tsx@@ -28,6 +28,7 @@ export const fromNodeTypeToLabel: Omit<[NotebookNodeType.Python]: 'Python',[NotebookNodeType.DuckSQL]: 'SQL (DuckDB)',[NotebookNodeType.HogQLSQL]: 'SQL (HogQL)',+ [NotebookNodeType.SQLV2]: 'SQL (v2)',[NotebookNodeType.Recording]: 'Session recordings',[NotebookNodeType.RecordingPlaylist]: 'Session replay playlists',[NotebookNodeType.ReplayTimestamp]: 'Session recording comments',diff --git a/frontend/src/scenes/notebooks/nodeIcons.tsx b/frontend/src/scenes/notebooks/nodeIcons.tsxindex 72992a2b819e..261a83e3ce1c 100644--- a/frontend/src/scenes/notebooks/nodeIcons.tsx+++ b/frontend/src/scenes/notebooks/nodeIcons.tsx@@ -31,6 +31,7 @@ export const NODE_ICONS: Partial<Record<NotebookNodeType, JSX.Element>> = {[NotebookNodeType.Query]: <IconGraph />,[NotebookNodeType.HogQLSQL]: <IconHogQL />,[NotebookNodeType.DuckSQL]: <IconHogQL />,+ [NotebookNodeType.SQLV2]: <IconHogQL />,[NotebookNodeType.Python]: <IconPython />,[NotebookNodeType.Latex]: <IconSquareRoot />,[NotebookNodeType.Recording]: <IconRewindPlay />,diff --git a/frontend/src/scenes/notebooks/types.ts b/frontend/src/scenes/notebooks/types.tsindex ca7422957a08..ad2f52befa48 100644--- a/frontend/src/scenes/notebooks/types.ts+++ b/frontend/src/scenes/notebooks/types.ts@@ -50,6 +50,7 @@ export enum NotebookNodeType {Python = 'ph-python',DuckSQL = 'ph-duck-sql',HogQLSQL = 'ph-hogql-sql',+ SQLV2 = 'ph-sql-v2',Recording = 'ph-recording',RecordingPlaylist = 'ph-recording-playlist',FeatureFlag = 'ph-feature-flag',diff --git a/frontend/src/scenes/notebooks/utils.ts b/frontend/src/scenes/notebooks/utils.tsindex abe2b5019d8f..4b249e68cdb4 100644--- a/frontend/src/scenes/notebooks/utils.ts+++ b/frontend/src/scenes/notebooks/utils.ts@@ -51,6 +51,7 @@ export const textContent = (node: RichContentNode): string => {[NotebookNodeType.Python]: customOrTitleSerializer,[NotebookNodeType.DuckSQL]: customOrTitleSerializer,[NotebookNodeType.HogQLSQL]: customOrTitleSerializer,+ [NotebookNodeType.SQLV2]: customOrTitleSerializer,[NotebookNodeType.Recording]: customOrTitleSerializer,[NotebookNodeType.LLMTrace]: customOrTitleSerializer,[NotebookNodeType.Issues]: customOrTitleSerializer,diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.pyindex 4b8638d47290..e00434b65349 100644--- a/posthog/clickhouse/query_tagging.py+++ b/posthog/clickhouse/query_tagging.py@@ -69,6 +69,7 @@ class Product(StrEnum):MCP_ANALYTICS = "mcp_analytics" # queries from the MCP analytics product (insights, dashboards, sessions)MESSAGING = "messaging"MOBILE_REPLAY = "mobile_replay"+ NOTEBOOKS = "notebooks"PIPELINE_DESTINATIONS = "pipeline_destinations"PLATFORM_AND_SUPPORT = "platform_and_support"POSTHOG_CODE = "posthog_code"diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 3c6dc8229cf9..399c39144373 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -198,6 +198,10 @@ from products.logs.backend.facade.temporal import (ACTIVITIES as LOGS_ALERTING_ACTIVITIES,WORKFLOWS as LOGS_ALERTING_WORKFLOWS,)+from products.notebooks.backend.facade.temporal import (+ ACTIVITIES as NOTEBOOKS_ACTIVITIES,+ WORKFLOWS as NOTEBOOKS_WORKFLOWS,+)from products.replay_vision.backend.temporal import (ACTIVITIES as REPLAY_VISION_ACTIVITIES,WORKFLOWS as REPLAY_VISION_WORKFLOWS,@@ -276,7 +280,8 @@ _task_queue_specs = [+ INGESTION_ACCEPTANCE_TEST_WORKFLOWS+ WAREHOUSE_SOURCES_QUEUE_PARTITION_WORKFLOWS+ SYNC_EVENTS_RETENTION_WORKFLOWS- + JOB_LOGS_WORKFLOWS,+ + JOB_LOGS_WORKFLOWS+ + NOTEBOOKS_WORKFLOWS,PROXY_SERVICE_ACTIVITIES+ DELETE_PERSONS_ACTIVITIES+ DELETE_TEAMS_ACTIVITIES@@ -293,7 +298,8 @@ _task_queue_specs = [+ INGESTION_ACCEPTANCE_TEST_ACTIVITIES+ WAREHOUSE_SOURCES_QUEUE_PARTITION_ACTIVITIES+ SYNC_EVENTS_RETENTION_ACTIVITIES- + JOB_LOGS_ACTIVITIES,+ + JOB_LOGS_ACTIVITIES+ + NOTEBOOKS_ACTIVITIES,),(settings.EXPERIMENTS_RECALCULATION_TASK_QUEUE,diff --git a/posthog/urls.py b/posthog/urls.pyindex 6a192f0f85bb..115b13f4ec9e 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -52,6 +52,7 @@ from products.demo.backend.facade.api import demo_routefrom products.early_access_features.backend.api import early_access_featuresfrom products.legal_documents.backend.presentation.webhook import legal_document_pandadoc_webhookfrom products.messaging.backend.api.customerio_webhook import CustomerIOWebhookView+from products.notebooks.backend.facade.sql_v2 import notebook_sql_v2_callback, notebook_sql_v2_data_planefrom products.product_tours.backend.api import product_toursfrom products.signals.backend import views as signals_viewsfrom products.signals.backend.views import SignalUserAutonomyConfigView as signals_user_autonomy_view@@ -452,6 +453,16 @@ urlpatterns = ["internal/tasks/runs/<str:run_id>/agent-proxy-callback/",csrf_exempt(agent_proxy_callback),),+ # Internal SQLV2 run result callback (auth: signed callback token)+ path(+ "internal/notebooks/runs/<str:run_id>/result/",+ csrf_exempt(notebook_sql_v2_callback),+ ),+ # Internal SQLV2 data plane — the sandbox's HogQL read path (auth: signed data-plane token)+ path(+ "internal/notebooks/data_plane/query/",+ csrf_exempt(notebook_sql_v2_data_plane),+ ),# Internal service-to-service endpoints (authenticated with POSTHOG_INTERNAL_SERVICE_TOKEN)path("api/projects/<str:team_id>/internal/hog_flows/user_blast_radius",diff --git a/products/notebooks/backend/facade/sql_v2.py b/products/notebooks/backend/facade/sql_v2.pynew file mode 100644index 000000000000..d58550bcdc06--- /dev/null+++ b/products/notebooks/backend/facade/sql_v2.py@@ -0,0 +1,10 @@+"""+Facade re-exports for the SQLV2 sandbox-facing endpoints.++Core (`posthog/urls.py`) wires the internal sandbox -> backend endpoints — the+run result callback and the data plane — through these re-exports rather than+importing the view modules directly.+"""++from ..sql_v2_callback import notebook_sql_v2_callback as notebook_sql_v2_callback+from ..sql_v2_data_plane import notebook_sql_v2_data_plane as notebook_sql_v2_data_planediff --git a/products/notebooks/backend/facade/temporal.py b/products/notebooks/backend/facade/temporal.pynew file mode 100644index 000000000000..e38ab33d67f9--- /dev/null+++ b/products/notebooks/backend/facade/temporal.py@@ -0,0 +1,12 @@+"""+Facade re-exports for Temporal wiring.++The worker bootstrap (`start_temporal_worker`) registers notebook workflows and+activities through these re-exports rather than importing ``backend.temporal``+directly.+"""++from ..temporal import (+ ACTIVITIES as ACTIVITIES,+ WORKFLOWS as WORKFLOWS,+)diff --git a/products/notebooks/backend/kernel_package.py b/products/notebooks/backend/kernel_package.pynew file mode 100644index 000000000000..f927580458ca--- /dev/null+++ b/products/notebooks/backend/kernel_package.py@@ -0,0 +1,42 @@+"""Builds the deployable tarball of the in-sandbox kernel package.++The `kernel/` package ships into the sandbox as `nb_kernel/`: `ensure_sql_v2_server`+writes the tarball, extracts it, and launches `python -m nb_kernel.server`. The+content hash doubles as the server version — /health reports it, and a mismatch+with the running server triggers a redeploy (the dev loop needs no image rebuild).+"""++import io+import hashlib+import tarfile+from functools import lru_cache+from pathlib import Path++SANDBOX_PACKAGE_NAME = "nb_kernel"++_KERNEL_DIR = Path(__file__).parent / "sandbox" / "kernel"+++def _kernel_files() -> list[Path]:+ return sorted(_KERNEL_DIR.glob("*.py"))+++@lru_cache(maxsize=1)+def kernel_package_bytes_and_hash() -> tuple[bytes, str]:+ """Return (tar.gz bytes, content hash) of the kernel package, deterministically."""+ digest = hashlib.sha256()+ buffer = io.BytesIO()+ with tarfile.open(fileobj=buffer, mode="w:gz") as tar:+ for path in _kernel_files():+ content = path.read_bytes()+ digest.update(path.name.encode())+ digest.update(content)+ info = tarfile.TarInfo(name=f"{SANDBOX_PACKAGE_NAME}/{path.name}")+ info.size = len(content)+ info.mtime = 0 # keep the archive byte-stable for a given content hash+ tar.addfile(info, io.BytesIO(content))+ return buffer.getvalue(), digest.hexdigest()[:16]+++def kernel_package_hash() -> str:+ return kernel_package_bytes_and_hash()[1]diff --git a/products/notebooks/backend/kernel_runtime.py b/products/notebooks/backend/kernel_runtime.pyindex a970ae36029c..87f8cc60d358 100644--- a/products/notebooks/backend/kernel_runtime.py+++ b/products/notebooks/backend/kernel_runtime.py@@ -773,7 +773,12 @@ class KernelRuntimeService:kernel_id = f"kernel-{runtime.id}"sandbox_config = build_notebook_sandbox_config(notebook)sandbox_class = self._get_sandbox_class(backend)- sandbox = sandbox_class.create(sandbox_config)+ try:+ sandbox = sandbox_class.create(sandbox_config)+ except Exception as err:+ detail = getattr(err, "context", None) or str(err)+ self._mark_runtime_error(runtime, f"Failed to provision sandbox: {detail}")+ raisetry:kernel_pid = self._start_kernel_process(sandbox, connection_file)diff --git a/products/notebooks/backend/migrations/0007_notebooknoderun.py b/products/notebooks/backend/migrations/0007_notebooknoderun.pynew file mode 100644index 000000000000..095a2ddbab6d--- /dev/null+++ b/products/notebooks/backend/migrations/0007_notebooknoderun.py@@ -0,0 +1,70 @@+# Generated by Django 5.2.14 on 2026-07-01 11:04++import django.db.models.deletion+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("notebooks", "0006_resourcenotebook_account_unique_constraint"),+ ("posthog", "1245_duckgres_sink_schema_state"),+ ]++ operations = [+ migrations.CreateModel(+ name="NotebookNodeRun",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("node_id", models.CharField(max_length=128)),+ (+ "status",+ models.CharField(+ choices=[+ ("running", "running"),+ ("done", "done"),+ ("failed", "failed"),+ ],+ default="running",+ max_length=20,+ ),+ ),+ ("envelope", models.JSONField(blank=True, default=None, null=True)),+ ("result_id", models.UUIDField(blank=True, null=True)),+ ("error", models.TextField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "notebook",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ to="notebooks.notebook",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False, on_delete=django.db.models.deletion.CASCADE, to="posthog.team"+ ),+ ),+ ],+ options={+ "db_table": "posthog_notebooknoderun",+ "indexes": [+ models.Index(+ fields=["team", "notebook", "node_id"],+ name="posthog_not_team_id_764c87_idx",+ )+ ],+ },+ ),+ ]diff --git a/products/notebooks/backend/migrations/0008_kernelruntime_server_connect_token_and_more.py b/products/notebooks/backend/migrations/0008_kernelruntime_server_connect_token_and_more.pynew file mode 100644index 000000000000..bb4f2191d27c--- /dev/null+++ b/products/notebooks/backend/migrations/0008_kernelruntime_server_connect_token_and_more.py@@ -0,0 +1,22 @@+# Generated by Django 5.2.14 on 2026-07-01 13:35++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notebooks", "0007_notebooknoderun"),+ ]++ operations = [+ migrations.AddField(+ model_name="kernelruntime",+ name="server_connect_token",+ field=models.TextField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="kernelruntime",+ name="server_url",+ field=models.TextField(blank=True, null=True),+ ),+ ]diff --git a/products/notebooks/backend/migrations/max_migration.txt b/products/notebooks/backend/migrations/max_migration.txtindex b068a5676249..df39697e3bba 100644--- a/products/notebooks/backend/migrations/max_migration.txt+++ b/products/notebooks/backend/migrations/max_migration.txt@@ -1 +1 @@-0006_resourcenotebook_account_unique_constraint+0008_kernelruntime_server_connect_token_and_morediff --git a/products/notebooks/backend/models.py b/products/notebooks/backend/models.pyindex dc1d8f7656c9..48af7af7b9c7 100644--- a/products/notebooks/backend/models.py+++ b/products/notebooks/backend/models.py@@ -6,9 +6,11 @@ from django.utils import timezonefrom posthog.models.file_system.constants import DEFAULT_SURFACEfrom posthog.models.file_system.file_system_mixin import FileSystemSyncMixinfrom posthog.models.file_system.file_system_representation import FileSystemRepresentation+from posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.team import Teamfrom posthog.models.utils import (RootTeamMixin,+ UUIDModel,UUIDTModel,build_partial_uniqueness_constraint,build_unique_relationship_check,@@ -169,9 +171,40 @@ class KernelRuntime(UUIDTModel):connection_file = models.TextField(null=True, blank=True)sandbox_id = models.CharField(max_length=128, null=True, blank=True)last_error = models.TextField(null=True, blank=True)+ server_url = models.TextField(null=True, blank=True)+ server_connect_token = models.TextField(null=True, blank=True)class Meta:db_table = "posthog_kernelruntime"indexes = [models.Index(fields=["team", "notebook_short_id", "user", "status"]),]+++class NotebookNodeRun(TeamScopedRootMixin, UUIDModel):+ """A single execution of a revamped-notebooks (SQLV2) node.+ The primary key is the run_id referenced by the run/callback/stream endpoints.+ """++ class Status(models.TextChoices):+ RUNNING = "running", "running"+ DONE = "done", "done"+ FAILED = "failed", "failed"++ # db_constraint=False: creating a real FK to the hot posthog_team table locks it on deploy.+ # Tenant isolation is still enforced by the fail-closed TeamScopedRootMixin manager.+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ notebook = models.ForeignKey("notebooks.Notebook", on_delete=models.CASCADE)+ node_id = models.CharField(max_length=128)+ status = models.CharField(choices=Status, default=Status.RUNNING, max_length=20)+ envelope: JSONField = JSONField(default=None, null=True, blank=True)+ result_id = models.UUIDField(null=True, blank=True)+ error = models.TextField(null=True, blank=True)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ db_table = "posthog_notebooknoderun"+ indexes = [+ models.Index(fields=["team", "notebook", "node_id"]),+ ]diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.pyindex 6a8774089795..c278464f701b 100644--- a/products/notebooks/backend/presentation/views/notebook.py+++ b/products/notebooks/backend/presentation/views/notebook.py@@ -3,9 +3,11 @@ import hashlibfrom datetime import timedeltafrom typing import Any, cast+from django.conf import settings+from django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db import transactionfrom django.db.models import Q, QuerySet-from django.http import JsonResponse+from django.http import Http404, JsonResponsefrom django.utils.timezone import nowimport structlog@@ -19,6 +21,7 @@ from drf_spectacular.utils import (extend_schema_view,)from rest_framework import serializers, viewsets+from rest_framework.exceptions import PermissionDeniedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.serializers import BaseSerializer@@ -46,9 +49,13 @@ from products.notebooks.backend import collab_stream, markdown_collab, presencefrom products.notebooks.backend.activity_logging import log_notebook_activityfrom products.notebooks.backend.collab import submit_stepsfrom products.notebooks.backend.kernel_runtime import build_notebook_sandbox_config, get_kernel_runtime-from products.notebooks.backend.models import KernelRuntime, Notebook+from products.notebooks.backend.models import KernelRuntime, Notebook, NotebookNodeRunfrom products.notebooks.backend.python_analysis import analyze_python_globals, annotate_python_nodesfrom products.notebooks.backend.query_validation import InvalidNotebookQueryError, normalize_notebook_query_nodes+from products.notebooks.backend.sql_v2 import is_sql_v2_enabled+from products.notebooks.backend.sql_v2_serializers import NotebookSQLV2RunRequestSerializer+from products.notebooks.backend.temporal.client import start_sql_v2_run_workflow+from products.notebooks.backend.temporal.sql_v2 import SQLV2RunInputfrom products.tasks.backend.facade.exceptions import SandboxProvisionErrorfrom products.tasks.backend.facade.sandbox import SandboxStatus@@ -519,6 +526,14 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDreturn self.get_object()+ def _require_query_access(self) -> None:+ # SQLV2 runs arbitrary HogQL and returns analytics rows, so notebook access alone is not+ # enough — a notebook editor whose query access is denied must not read data through it.+ # Mirrors ee/api/subscription.py: the query:read scope gates tokens, this gates sessions+ # (which carry no scopes) and enforces real RBAC for tokens too.+ if not self.user_access_control.check_access_level_for_resource("query", "viewer"):+ raise PermissionDenied("You need query access to run SQL in a notebook.")+def _current_user(self) -> User | None:return self.request.user if isinstance(self.request.user, User) else None@@ -879,6 +894,81 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDreturn Response(data)+ # Experimental, flag-gated slice — kept out of the public OpenAPI schema (no generated FE/MCP types yet).+ @extend_schema(exclude=True)+ @action(methods=["POST"], url_path="sql_v2/run", detail=True, required_scopes=["notebook:write", "query:read"])+ def sql_v2_run(self, request: Request, **kwargs):+ user = self._current_user()+ # Server-side gate is permissive in local dev (frontend still gates the UI); prod is flag-gated.+ if not (settings.DEBUG or is_sql_v2_enabled(user)):+ raise Http404()++ serializer = NotebookSQLV2RunRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ notebook = self._get_notebook_for_kernel()+ self._require_query_access()++ run = NotebookNodeRun.objects.create(+ team_id=self.team_id,+ notebook=notebook,+ node_id=serializer.validated_data["node_id"],+ status=NotebookNodeRun.Status.RUNNING,+ )++ try:+ start_sql_v2_run_workflow(+ SQLV2RunInput(+ run_id=str(run.id),+ notebook_short_id=notebook.short_id,+ team_id=self.team_id,+ user_id=user.id if isinstance(user, User) else None,+ code=serializer.validated_data["code"],+ )+ )+ except Exception:+ logger.exception("notebook_sql_v2_run_start_failed", notebook_short_id=notebook.short_id)+ run.status = NotebookNodeRun.Status.FAILED+ run.error = "Failed to start run."+ run.save(update_fields=["status", "error", "updated_at"])+ return Response({"detail": "Failed to start run."}, status=503)++ return Response({"run_id": str(run.id)})++ @extend_schema(exclude=True)+ @action(+ methods=["GET"],+ url_path="sql_v2/runs/(?P<run_id>[^/.]+)",+ detail=True,+ required_scopes=["notebook:read", "query:read"],+ )+ def sql_v2_run_result(self, request: Request, run_id: str | None = None, **kwargs):+ # The node short-polls this durable read to learn when its run finishes. One indexed+ # query, no held connection — resilient to reloads/remounts (see sql_v2_result_delivery.md).+ user = self._current_user()+ if not (settings.DEBUG or is_sql_v2_enabled(user)) or run_id is None:+ raise Http404()++ # Scope to the notebook (via get_object → per-notebook access control), not just the+ # team: a team-only lookup lets a user read a run from a notebook they can't access.+ notebook = self._get_notebook_for_kernel()+ # The result envelope is analytics rows, so gate reads on query access too — a+ # notebook-reader whose query access is denied must not read the rows back.+ self._require_query_access()+ try:+ run = NotebookNodeRun.objects.for_team(self.team_id).filter(id=run_id, notebook=notebook).first()+ except DjangoValidationError: # malformed run_id (not a UUID)+ raise Http404()+ if run is None:+ raise Http404()++ return Response(+ {+ "status": run.status,+ "result": run.envelope if run.status == NotebookNodeRun.Status.DONE else None,+ "error": run.error or None,+ }+ )+@extend_schema(request=NotebookCollabSaveSerializer)@action(methods=["POST"], url_path="collab/save", detail=True, required_scopes=["notebook:write"])def collab_save(self, request: Request, **kwargs):diff --git a/products/notebooks/backend/sandbox/kernel/__init__.py b/products/notebooks/backend/sandbox/kernel/__init__.pynew file mode 100644index 000000000000..5f07164ae41a--- /dev/null+++ b/products/notebooks/backend/sandbox/kernel/__init__.py@@ -0,0 +1,13 @@+"""The in-sandbox SQLV2 kernel-server, as a real package.++Nothing here may import Django or posthog — this code is tarred up by+`kernel_package.py`, written into the notebook sandbox, extracted as the+`nb_kernel` package, and launched there (`python -m nb_kernel.server`). It may+only use the stdlib plus the libraries baked into the notebook sandbox image+(`Dockerfile.sandbox-notebook`): pyarrow, duckdb, pandas, jupyter_client.++Intra-package imports must stay relative so the code works under both names+(`products.notebooks.backend.kernel` in tests, `nb_kernel` in the sandbox).++See `products/notebooks/backend/sql_v2_kernel_architecture.md` for the design.+"""diff --git a/products/notebooks/backend/sandbox/kernel/auth.py b/products/notebooks/backend/sandbox/kernel/auth.pynew file mode 100644index 000000000000..ae55e4be06d8--- /dev/null+++ b/products/notebooks/backend/sandbox/kernel/auth.py@@ -0,0 +1,23 @@+"""Command-token verification — the sandbox side of `sql_v2.mint_command_token`.++Must stay in sync with the HMAC scheme in `products/notebooks/backend/sql_v2.py`;+the mint↔verify round-trip is unit-tested in `test_sql_v2.py`.+"""++import hmac+import time+import hashlib+++def verify_command_token(secret: str, run_id: str, token: str) -> bool:+ if not secret or not token:+ return False+ try:+ token_run_id, exp_str, signature = token.rsplit(".", 2)+ exp = int(exp_str)+ except (ValueError, AttributeError):+ return False+ if token_run_id != run_id or exp < int(time.time()):+ return False+ expected = hmac.new(secret.encode(), f"{token_run_id}.{exp_str}".encode(), hashlib.sha256).hexdigest()+ return hmac.compare_digest(expected, signature)diff --git a/products/notebooks/backend/sandbox/kernel/data_plane.py b/products/notebooks/backend/sandbox/kernel/data_plane.pynew file mode 100644index 000000000000..5082f99b5192--- /dev/null+++ b/products/notebooks/backend/sandbox/kernel/data_plane.py@@ -0,0 +1,95 @@+"""Client for the backend data plane — the sandbox's only read path to PostHog data.++POSTs a HogQL query to the backend's data-plane endpoint (authed with the+run-scoped data-plane token) and decodes the Arrow stream response. Uses urllib+so the only third-party dependency is pyarrow (present in the sandbox image).+"""++import json+import urllib.error+import urllib.request+from typing import Any++import pyarrow as pa++_REQUEST_TIMEOUT_SECONDS = 120+++class DataPlaneError(Exception):+ """A query the data plane rejected or failed to run; message is user-facing."""+++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."""+ request = urllib.request.Request(+ url,+ data=json.dumps({"query": query, "limit": limit, "offset": offset}).encode(),+ headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},+ method="POST",+ )+ try:+ # url is the backend's own data-plane endpoint from the signed run payload, never user-controlled.+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected+ with urllib.request.urlopen(request, timeout=_REQUEST_TIMEOUT_SECONDS) as response:+ return decode_arrow_stream(response)+ except urllib.error.HTTPError as exc:+ raise DataPlaneError(_error_detail(exc)) from exc+ except urllib.error.URLError as exc:+ raise DataPlaneError(f"Could not reach the data plane: {exc.reason}") from exc+ except pa.ArrowInvalid as exc:+ raise DataPlaneError(f"Invalid Arrow response from the data plane: {exc}") from exc+++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).++ 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)]+ rows = list(zip(*column_values)) if column_values else []++ metadata = table.schema.metadata or {}+ raw_types = metadata.get(b"hogql_types")+ if raw_types:+ try:+ types = [[str(name), str(type_name)] for name, type_name in json.loads(raw_types)]+ except (json.JSONDecodeError, ValueError, TypeError):+ types = _types_from_arrow_schema(table.schema)+ else:+ types = _types_from_arrow_schema(table.schema)+ return columns, rows, types+++def _types_from_arrow_schema(schema: Any) -> list[list[str]]:+ def type_name(arrow_type: Any) -> str:+ if pa.types.is_boolean(arrow_type):+ return "Bool"+ if pa.types.is_integer(arrow_type):+ return "Int64"+ if pa.types.is_floating(arrow_type) or pa.types.is_decimal(arrow_type):+ return "Float64"+ if pa.types.is_timestamp(arrow_type):+ return "DateTime"+ if pa.types.is_date(arrow_type):+ return "Date"+ return "String"++ return [[field.name, type_name(field.type)] for field in schema]+++def _error_detail(exc: urllib.error.HTTPError) -> str:+ try:+ body = json.loads(exc.read().decode("utf-8", "replace"))+ detail = body.get("error")+ if isinstance(detail, str) and detail:+ return detail+ except (json.JSONDecodeError, ValueError, OSError):+ pass+ return f"Data plane request failed with HTTP {exc.code}"diff --git a/products/notebooks/backend/sandbox/kernel/envelope.py b/products/notebooks/backend/sandbox/kernel/envelope.pynew file mode 100644index 000000000000..f8b87106aa4b--- /dev/null+++ b/products/notebooks/backend/sandbox/kernel/envelope.py@@ -0,0 +1,45 @@+"""Result-envelope construction.++The envelope is the small JSON the sandbox POSTs to the backend callback:+`{status, columns, row_count, first_page, result_id, error?}`. It carries a+bounded preview only — never the full result (see sql_v2_result_delivery.md).+"""++import math+import uuid+import datetime+from typing import Any+++def _json_cell(value: Any) -> Any:+ """Coerce an Arrow-produced cell into a JSON-safe value."""+ if value is None or isinstance(value, bool | int | str):+ return value+ if isinstance(value, float):+ return value if math.isfinite(value) else None+ if isinstance(value, datetime.datetime | datetime.date | datetime.time):+ return value.isoformat()+ if isinstance(value, bytes | bytearray):+ return value.decode("utf-8", "replace")+ if isinstance(value, list | tuple):+ return [_json_cell(item) for item in value]+ if isinstance(value, dict):+ return {str(key): _json_cell(item) for key, item in value.items()}+ return str(value)+++def from_columns_and_rows(+ columns: list[str], rows: list[tuple[Any, ...]], types: list[list[str]] | None = None+) -> dict[str, Any]:+ return {+ "status": "ok",+ "columns": columns,+ "types": types or [],+ "row_count": len(rows),+ "first_page": [[_json_cell(cell) for cell in row] for row in rows],+ "result_id": str(uuid.uuid4()),+ }+++def from_error(message: str) -> dict[str, Any]:+ return {"status": "error", "error": message}diff --git a/products/notebooks/backend/sandbox/kernel/runner.py b/products/notebooks/backend/sandbox/kernel/runner.pynew file mode 100644index 000000000000..25131b665998--- /dev/null+++ b/products/notebooks/backend/sandbox/kernel/runner.py@@ -0,0 +1,59 @@+"""Per-run execution: fetch the data, build the envelope, deliver the callback.++For the current Journey 1 scope every node is a pure-HogQL display node, so a run+is a capped-page fetch through the data plane — the ipykernel is not involved+(see sql_v2_kernel_architecture.md, "division of labor").+"""++import json+import logging+import urllib.error+import urllib.request+from typing import Any++from . import envelope++logger = logging.getLogger(__name__)++_CALLBACK_TIMEOUT_SECONDS = 15+_DEFAULT_PAGE_LIMIT = 50+++def execute_run(payload: dict[str, Any]) -> None:+ """Entry point for a /run request, invoked on a background thread."""+ result = _build_envelope(payload)+ _post_callback(payload["callback_url"], payload["callback_token"], result)+++def _build_envelope(payload: dict[str, Any]) -> dict[str, Any]:+ # Deferred so a broken pyarrow install degrades to a per-run error envelope+ # instead of preventing the server from starting.+ from . import data_plane # noqa: PLC0415++ try:+ columns, rows, types = data_plane.fetch_query_page(+ payload["data_plane_url"],+ payload["data_plane_token"],+ payload["code"],+ limit=int(payload.get("page_limit") or _DEFAULT_PAGE_LIMIT),+ )+ return envelope.from_columns_and_rows(columns, rows, types)+ except data_plane.DataPlaneError as exc:+ return envelope.from_error(str(exc))+ except Exception as exc: # noqa: BLE001 — any failure must still produce a callback+ return envelope.from_error(f"Run failed in the sandbox: {exc}")+++def _post_callback(callback_url: str, callback_token: str, result: dict[str, Any]) -> None:+ request = urllib.request.Request(+ callback_url,+ data=json.dumps({"envelope": result}).encode(),+ headers={"Authorization": f"Bearer {callback_token}", "Content-Type": "application/json"},+ method="POST",+ )+ try:+ # url is the backend's own callback endpoint from the signed run payload, never user-controlled.+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected+ urllib.request.urlopen(request, timeout=_CALLBACK_TIMEOUT_SECONDS)+ except Exception: # noqa: BLE001 — best-effort; the backend watchdog covers a lost callback+ logger.exception("nb_kernel callback delivery failed")diff --git a/products/notebooks/backend/sandbox/kernel/server.py b/products/notebooks/backend/sandbox/kernel/server.pynew file mode 100644index 000000000000..bb33e10bcbf7--- /dev/null+++ b/products/notebooks/backend/sandbox/kernel/server.py@@ -0,0 +1,82 @@+"""The kernel-server HTTP entry point.++Launched inside the sandbox as `python -m nb_kernel.server --port … --secret-file …+--version …`. Routes:++- GET /health → {"status": "ok", "version": …} — the version is the package+ content hash the backend deployed, used for the redeploy handshake.+- POST /run → verifies the HMAC command token, returns 202, executes the run and+ delivers the result callback on a background thread.+"""++import json+import logging+import argparse+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from typing import Any++from .auth import verify_command_token+from .runner import execute_run++DEFAULT_PORT = 47821++_config: dict[str, str] = {"secret": "", "version": "unknown"}+++class KernelServerHandler(BaseHTTPRequestHandler):+ def do_GET(self) -> None:+ if self.path == "/health":+ self._respond(200, {"status": "ok", "version": _config["version"]})+ else:+ self._respond(404, {"error": "Not found"})++ def do_POST(self) -> None:+ if self.path != "/run":+ self._respond(404, {"error": "Not found"})+ return+ try:+ length = int(self.headers.get("Content-Length", 0))+ payload = json.loads(self.rfile.read(length) or b"{}")+ except (json.JSONDecodeError, ValueError):+ self._respond(400, {"error": "Invalid JSON body"})+ return+ if not verify_command_token(_config["secret"], payload.get("run_id", ""), self._bearer_token()):+ self._respond(401, {"error": "Invalid command token"})+ return+ threading.Thread(target=execute_run, args=(payload,), daemon=True).start()+ self._respond(202, {"accepted": True})++ def _bearer_token(self) -> str:+ authorization = self.headers.get("Authorization", "")+ return authorization[len("Bearer ") :].strip() if authorization.startswith("Bearer ") else ""++ def _respond(self, status: int, body: dict[str, Any]) -> None:+ payload = json.dumps(body).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++ def log_message(self, *args: Any) -> None:+ pass+++def main() -> None:+ logging.basicConfig(level=logging.INFO) # stdout/stderr land in the server log file+ parser = argparse.ArgumentParser()+ parser.add_argument("--port", type=int, default=DEFAULT_PORT)+ parser.add_argument("--secret-file", required=True)+ parser.add_argument("--version", default="unknown")+ args = parser.parse_args()++ with open(args.secret_file) as secret_file:+ _config["secret"] = secret_file.read().strip()+ _config["version"] = args.version++ ThreadingHTTPServer(("0.0.0.0", args.port), KernelServerHandler).serve_forever()+++if __name__ == "__main__":+ main()diff --git a/products/notebooks/backend/sql_v2.py b/products/notebooks/backend/sql_v2.pynew file mode 100644index 000000000000..ea0a70f46a48--- /dev/null+++ b/products/notebooks/backend/sql_v2.py@@ -0,0 +1,262 @@+"""Helpers for the revamped-notebooks SQLV2 run flow (Journey 1).++The backend dispatches a run to the in-sandbox kernel-server with a single HTTP+POST (mirroring PostHog Code's agent-server). The kernel-server fetches the+node's capped result page from the data-plane endpoint (real ClickHouse data via+HogQL) and POSTs the envelope back to the token-authed callback endpoint. The+control plane (write_file / execute) is used only to deploy and launch the+kernel-server package — never per run.++The callback and data-plane tokens are stateless signed tokens for the slice;+hardening swaps them for the RS256 sandbox event-ingest JWTs used by PostHog Code.+"""++import hmac+import time+import hashlib++from django.conf import settings+from django.core import signing++import requests+import structlog+import posthoganalytics++from posthog.models.user import User++from products.notebooks.backend.kernel_package import SANDBOX_PACKAGE_NAME, kernel_package_bytes_and_hash+from products.notebooks.backend.models import KernelRuntime, Notebook, NotebookNodeRun+from products.tasks.backend.facade.sandbox import SandboxBase, get_sandbox_class_for_backend++logger = structlog.get_logger(__name__)++REVAMPED_PY_NOTEBOOKS_FLAG = "revamped-py-notebooks"++_CALLBACK_TOKEN_SALT = "notebooks.sql_v2.callback"+_CALLBACK_TOKEN_MAX_AGE_SECONDS = 3600+_DATA_PLANE_TOKEN_SALT = "notebooks.sql_v2.data_plane"+_DATA_PLANE_TOKEN_MAX_AGE_SECONDS = 3600++# Rows in the display page the kernel fetches for a run. Paging beyond it re-queries+# ClickHouse (push-to-CH: a displayed HogQL node is never fully materialized).+DISPLAY_PAGE_LIMIT = 50++# The container port the sandbox already exposes (mapped to a host port at create+# time). Mirrors docker_sandbox.AGENT_SERVER_PORT (47821) and+# modal_sandbox.AGENT_SERVER_PORT (8080) — the kernel-server binds it inside the sandbox.+_CONTAINER_PORT_BY_BACKEND: dict[str, int] = {+ KernelRuntime.Backend.DOCKER: 47821,+ KernelRuntime.Backend.MODAL: 8080,+}+_PACKAGE_ROOT = "/tmp/nb_kernel_pkg"+_TARBALL_PATH = "/tmp/nb_kernel.tar.gz"+_SECRET_PATH = "/tmp/nb_sql_v2_secret"+_SERVER_LOG_PATH = "/tmp/nb_kernel_server.log"+_SERVER_PID_PATH = "/tmp/nb_kernel_server.pid"+_SERVER_READY_TIMEOUT_SECONDS = 15+_RUN_POST_TIMEOUT_SECONDS = 10+_COMMAND_TOKEN_TTL_SECONDS = 300+++class SQLV2KernelNotRunning(Exception):+ """Raised when a run is dispatched but the notebook has no running sandbox."""+++def is_sql_v2_enabled(user: User | None) -> bool:+ if user is None or not user.distinct_id:+ return False+ kwargs: dict = {"only_evaluate_locally": False, "send_feature_flag_events": False}+ org = getattr(user, "organization", None)+ if org is not None:+ org_id = str(org.id)+ kwargs["groups"] = {"organization": org_id}+ kwargs["group_properties"] = {"organization": {"id": org_id}}+ return bool(posthoganalytics.feature_enabled(REVAMPED_PY_NOTEBOOKS_FLAG, user.distinct_id, **kwargs))+++def mint_callback_token(run_id: str, team_id: int) -> str:+ return signing.dumps({"run_id": run_id, "team_id": team_id}, salt=_CALLBACK_TOKEN_SALT)+++def verify_callback_token(token: str) -> tuple[str, int]:+ """Return (run_id, team_id) from a valid token, else raise signing.BadSignature."""+ data = signing.loads(token, salt=_CALLBACK_TOKEN_SALT, max_age=_CALLBACK_TOKEN_MAX_AGE_SECONDS)+ return str(data["run_id"]), int(data["team_id"])+++def kernel_server_secret(runtime_id: str) -> str:+ """Per-kernel command-auth secret, derived from Django's signing key.++ Only the backend can derive it (holds SECRET_KEY); a copy is written into the+ sandbox at bootstrap so the kernel-server can verify command tokens. Nothing to+ persist. This is the HMAC analogue of Code's RS256 connection-JWT keypair;+ hardening to RS256 would let the sandbox hold only a public key.+ """+ return hmac.new(+ settings.SECRET_KEY.encode(),+ f"nb-sql-v2-kernel:{runtime_id}".encode(),+ hashlib.sha256,+ ).hexdigest()+++def mint_command_token(secret: str, run_id: str, ttl_seconds: int = _COMMAND_TOKEN_TTL_SECONDS) -> str:+ """Sign a short-lived, run-scoped command token; `kernel.auth` verifies it in the sandbox."""+ exp = int(time.time()) + ttl_seconds+ signature = hmac.new(secret.encode(), f"{run_id}.{exp}".encode(), hashlib.sha256).hexdigest()+ return f"{run_id}.{exp}.{signature}"+++def _backend_base_url() -> str:+ # The sandbox reaches the host backend here. Docker maps localhost -> host.docker.internal,+ # so default to that for local dev; SANDBOX_API_URL overrides (e.g. ngrok for Modal).+ base = getattr(settings, "SANDBOX_API_URL", None) or "http://host.docker.internal:8000"+ return base.rstrip("/")+++def build_callback_url(run_id: str) -> str:+ return f"{_backend_base_url()}/internal/notebooks/runs/{run_id}/result/"+++def build_data_plane_url() -> str:+ return f"{_backend_base_url()}/internal/notebooks/data_plane/query/"+++def mint_data_plane_token(notebook_short_id: str, team_id: int, user_id: int | None) -> str:+ return signing.dumps(+ {"notebook_short_id": notebook_short_id, "team_id": team_id, "user_id": user_id},+ salt=_DATA_PLANE_TOKEN_SALT,+ )+++def verify_data_plane_token(token: str) -> tuple[str, int, int | None]:+ """Return (notebook_short_id, team_id, user_id) from a valid token, else raise signing.BadSignature."""+ data = signing.loads(token, salt=_DATA_PLANE_TOKEN_SALT, max_age=_DATA_PLANE_TOKEN_MAX_AGE_SECONDS)+ user_id = data.get("user_id")+ return str(data["notebook_short_id"]), int(data["team_id"]), int(user_id) if user_id is not None else None+++def _find_running_runtime(notebook: Notebook, user: User | None) -> KernelRuntime | None:+ runtime = (+ KernelRuntime.objects.filter(+ team_id=notebook.team_id,+ notebook_short_id=notebook.short_id,+ user=user if isinstance(user, User) else None,+ )+ .order_by("-last_used_at")+ .first()+ )+ if runtime is None or not runtime.sandbox_id:+ return None+ if runtime.status not in (KernelRuntime.Status.RUNNING, KernelRuntime.Status.STARTING):+ return None+ return runtime+++def _with_connect_token(url: str, connect_token: str | None) -> str:+ return f"{url}?_modal_connect_token={connect_token}" if connect_token else url+++def _server_version(server_url: str, connect_token: str | None) -> str | None:+ """The deployed package hash the running server reports, or None if unreachable."""+ health_url = _with_connect_token(f"{server_url.rstrip('/')}/health", connect_token)+ try:+ response = requests.get(health_url, timeout=2)+ if response.status_code != 200:+ return None+ return str(response.json().get("version") or "")+ except (requests.RequestException, ValueError):+ return None+++def _wait_for_server_ready(server_url: str, connect_token: str | None, expected_version: str) -> None:+ deadline = time.monotonic() + _SERVER_READY_TIMEOUT_SECONDS+ while time.monotonic() < deadline:+ if _server_version(server_url, connect_token) == expected_version:+ return+ time.sleep(0.3)+ raise RuntimeError("SQLV2 kernel-server did not become ready")+++def _deploy_kernel_server(sandbox: SandboxBase, runtime: KernelRuntime, package: bytes, version: str) -> None:+ """Write the kernel package + secret into the sandbox and (re)launch the server.++ This is the only place the control plane (write_file/execute) is used, exactly+ as Code bootstraps its agent-server. Per-run dispatch is a plain authed POST.+ """+ port = _CONTAINER_PORT_BY_BACKEND.get(runtime.backend, 47821)+ sandbox.write_file(_SECRET_PATH, kernel_server_secret(str(runtime.id)).encode())+ sandbox.write_file(_TARBALL_PATH, package)+ # Stop a previous server via its PID file — never pkill by our own name: the+ # pattern would match this very launch command's shell and kill it mid-deploy.+ # The pkill lines only clear pre-package servers (distinct names, safe to+ # match) from sandboxes that predate the PID file; drop them once those age out.+ # `< /dev/null` detaches the server from the exec's pipes so `execute` returns.+ # The backgrounded launch must stay a single simple command (PYTHONPATH= prefix,+ # no `cd X && …`) — a compound list backgrounds a wrapper subshell, so `$!`+ # would record the wrapper's PID and the next redeploy would kill nothing.+ # Prefer the notebook venv python (has pyarrow).+ launch = (+ f"kill $(cat {_SERVER_PID_PATH} 2>/dev/null) 2>/dev/null || true; "+ "pkill -f '[n]b_sql_v2_kernel_server' 2>/dev/null; pkill -f '[n]b_data_v2_kernel_server' 2>/dev/null; "+ f"rm -rf {_PACKAGE_ROOT} && mkdir -p {_PACKAGE_ROOT} && tar -xzf {_TARBALL_PATH} -C {_PACKAGE_ROOT} && "+ 'PY=/opt/notebook-venv/bin/python3; [ -x "$PY" ] || PY=python3; '+ f'PYTHONPATH={_PACKAGE_ROOT} nohup "$PY" -m {SANDBOX_PACKAGE_NAME}.server '+ f"--port {port} --secret-file {_SECRET_PATH} --version {version} "+ f"> {_SERVER_LOG_PATH} 2>&1 < /dev/null & echo $! > {_SERVER_PID_PATH}"+ )+ sandbox.execute(launch, timeout_seconds=30)+++def ensure_sql_v2_server(notebook: Notebook, user: User | None) -> KernelRuntime:+ """Ensure the in-sandbox kernel-server is running the current package version.++ Idempotent — a healthy server at the expected version is reused as-is; a stale+ or unreachable one is redeployed from the freshly built tarball (this is the+ dev loop: edit `kernel/`, next run redeploys, no image rebuild).+ """+ runtime = _find_running_runtime(notebook, user)+ if runtime is None:+ raise SQLV2KernelNotRunning()++ package, version = kernel_package_bytes_and_hash()+ if runtime.server_url and _server_version(runtime.server_url, runtime.server_connect_token) == version:+ return runtime++ sandbox_class = get_sandbox_class_for_backend(runtime.backend)+ assert runtime.sandbox_id # _find_running_runtime only returns runtimes with a sandbox+ sandbox = sandbox_class.get_by_id(runtime.sandbox_id)+ _deploy_kernel_server(sandbox, runtime, package, version)++ credentials = sandbox.get_connect_credentials()+ _wait_for_server_ready(credentials.url, credentials.token, version)++ runtime.server_url = credentials.url+ runtime.server_connect_token = credentials.token+ runtime.save(update_fields=["server_url", "server_connect_token"])+ return runtime+++def dispatch_sql_v2_run(notebook: Notebook, user: User | None, run: NotebookNodeRun, code: str) -> 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.+ """+ 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+ response = requests.post(+ _with_connect_token(f"{runtime.server_url.rstrip('/')}/run", runtime.server_connect_token),+ 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,+ },+ headers={"Authorization": f"Bearer {command_token}"},+ timeout=_RUN_POST_TIMEOUT_SECONDS,+ )+ response.raise_for_status()diff --git a/products/notebooks/backend/sql_v2_callback.py b/products/notebooks/backend/sql_v2_callback.pynew file mode 100644index 000000000000..62f39f6bd992--- /dev/null+++ b/products/notebooks/backend/sql_v2_callback.py@@ -0,0 +1,83 @@+"""Token-authed sandbox -> backend callback for SQLV2 runs (Journey 1 slice).++Mirrors PostHog Code's agent-proxy callback: a plain function view (no team+scoping, no session), authed by a Bearer token the run endpoint minted. Wired in+posthog/urls.py at internal/notebooks/runs/<run_id>/result/.+"""++import json++from django.core import signing+from django.http import JsonResponse++import structlog+from drf_spectacular.utils import OpenApiResponse, extend_schema++from products.notebooks.backend.models import NotebookNodeRun+from products.notebooks.backend.sql_v2 import verify_callback_token+from products.notebooks.backend.sql_v2_serializers import NotebookSQLV2CallbackRequestSerializer++logger = structlog.get_logger(__name__)+++@extend_schema(+ tags=["notebooks"],+ request=NotebookSQLV2CallbackRequestSerializer,+ responses={+ 200: OpenApiResponse(description="Result stored"),+ 401: OpenApiResponse(description="Missing or invalid callback token"),+ 403: OpenApiResponse(description="Token does not match the run"),+ 404: OpenApiResponse(description="Run not found"),+ },+ summary="SQLV2 run result callback",+ description=(+ "Internal endpoint the notebook sandbox POSTs its result envelope to after a SQLV2 run. "+ "Authenticated with the signed callback token minted by the run endpoint (no session). "+ "Idempotent: re-delivery of the same run_id upserts the same row."+ ),+)+def notebook_sql_v2_callback(request, run_id: str) -> JsonResponse:+ if request.method != "POST":+ return JsonResponse({"error": "Method not allowed"}, status=405)++ authorization = request.headers.get("Authorization", "")+ if not authorization.startswith("Bearer "):+ return JsonResponse({"error": "Missing authorization bearer token"}, status=401)+ token = authorization[len("Bearer ") :].strip()+ if not token:+ return JsonResponse({"error": "Missing authorization bearer token"}, status=401)++ try:+ token_run_id, team_id = verify_callback_token(token)+ except signing.BadSignature:+ return JsonResponse({"error": "Invalid callback token"}, status=401)++ if token_run_id != run_id:+ return JsonResponse({"error": "Token does not match run"}, status=403)++ try:+ body = json.loads(request.body)+ except (json.JSONDecodeError, ValueError):+ return JsonResponse({"error": "Invalid JSON body"}, status=400)++ serializer = NotebookSQLV2CallbackRequestSerializer(data=body)+ if not serializer.is_valid():+ return JsonResponse({"error": "Invalid request body", "detail": serializer.errors}, status=400)++ # Store the raw JSON envelope (JSON-native types) — the serializer's validated_data+ # would coerce result_id to a uuid.UUID, which the JSONField can't serialize.+ envelope = body["envelope"]++ try:+ run = NotebookNodeRun.objects.for_team(team_id).get(id=run_id)+ except NotebookNodeRun.DoesNotExist:+ return JsonResponse({"error": "Run not found"}, status=404)++ is_ok = envelope.get("status") == "ok"+ run.status = NotebookNodeRun.Status.DONE if is_ok else NotebookNodeRun.Status.FAILED+ run.envelope = envelope+ run.result_id = envelope.get("result_id")+ run.error = envelope.get("error")+ run.save(update_fields=["status", "envelope", "result_id", "error", "updated_at"])++ return JsonResponse({"ok": True})diff --git a/products/notebooks/backend/sql_v2_data_plane.py b/products/notebooks/backend/sql_v2_data_plane.pynew file mode 100644index 000000000000..5aef309c232b--- /dev/null+++ b/products/notebooks/backend/sql_v2_data_plane.py@@ -0,0 +1,131 @@+"""The SQLV2 data plane: the sandbox's read path to PostHog data.++Token-authed sandbox -> backend endpoint (like the result callback, a plain+function view, no session) that runs a HogQL query for the notebook's team and+streams the result back as Arrow. The sandbox never parses HogQL — it sends the+query text here; parsing, access control, and execution all stay backend-side.+Wired in posthog/urls.py at internal/notebooks/data_plane/query/.+"""++import json+from typing import Any++from django.core import signing+from django.http import HttpRequest, HttpResponse, JsonResponse++import structlog+from drf_spectacular.utils import OpenApiResponse, extend_schema++from posthog.hogql.errors import ExposedHogQLError+from posthog.hogql.parser import parse_select+from posthog.hogql.query import execute_hogql_query++from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.models import Team, User++from products.notebooks.backend.models import Notebook+from products.notebooks.backend.sql_v2 import verify_data_plane_token+from products.notebooks.backend.sql_v2_serializers import NotebookSQLV2DataPlaneRequestSerializer++logger = structlog.get_logger(__name__)++ARROW_STREAM_CONTENT_TYPE = "application/vnd.apache.arrow.stream"+++def _rows_to_arrow_bytes(+ columns: list[str], rows: list[tuple[Any, ...]], types: list[list[str]] | None = None+) -> bytes:+ import pyarrow as pa # noqa: PLC0415 — keeps the heavy dep off the urls.py import path++ # Column-by-column with a per-column string fallback: HogQL results can contain+ # values Arrow can't infer (UUIDs, mixed types, tuples) and one odd column must+ # not fail the whole response.+ arrays = []+ for index in range(len(columns)):+ values = [row[index] for row in rows]+ try:+ arrays.append(pa.array(values))+ except (pa.ArrowInvalid, pa.ArrowTypeError, pa.ArrowNotImplementedError):+ arrays.append(pa.array([None if value is None else str(value) for value in values], type=pa.string()))+ table = pa.Table.from_arrays(arrays, names=columns)+ # Carry the HogQL/ClickHouse type names alongside the Arrow schema — the FE viz+ # layer needs them (numeric/date axis detection) and Arrow types are lossier.+ if types:+ table = table.replace_schema_metadata({"hogql_types": json.dumps(types)})+ sink = pa.BufferOutputStream()+ with pa.ipc.new_stream(sink, table.schema) as writer:+ writer.write_table(table)+ return sink.getvalue().to_pybytes()+++@extend_schema(+ tags=["notebooks"],+ request=NotebookSQLV2DataPlaneRequestSerializer,+ responses={+ (200, ARROW_STREAM_CONTENT_TYPE): OpenApiResponse(description="Query result as an Arrow IPC stream"),+ 400: OpenApiResponse(description="Invalid request body or HogQL error"),+ 401: OpenApiResponse(description="Missing or invalid data-plane token"),+ 404: OpenApiResponse(description="Notebook not found"),+ },+ summary="SQLV2 data-plane query",+ description=(+ "Internal endpoint the notebook sandbox POSTs HogQL to. Authenticated with the signed "+ "data-plane token minted at run dispatch (no session). Runs the query for the notebook's "+ "team — HogQL access controls apply — and returns the rows as an Arrow IPC stream."+ ),+)+def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:+ if request.method != "POST":+ return JsonResponse({"error": "Method not allowed"}, status=405)++ authorization = request.headers.get("Authorization", "")+ token = authorization[len("Bearer ") :].strip() if authorization.startswith("Bearer ") else ""+ if not token:+ return JsonResponse({"error": "Missing authorization bearer token"}, status=401)++ try:+ notebook_short_id, team_id, user_id = verify_data_plane_token(token)+ except signing.BadSignature:+ return JsonResponse({"error": "Invalid data-plane token"}, status=401)++ try:+ body = json.loads(request.body)+ except (json.JSONDecodeError, ValueError):+ return JsonResponse({"error": "Invalid JSON body"}, status=400)++ serializer = NotebookSQLV2DataPlaneRequestSerializer(data=body)+ if not serializer.is_valid():+ # The error string is what the kernel surfaces to the user, so make it say which field failed.+ detail = "; ".join(+ f"{field}: {' '.join(str(error) for error in errors)}" for field, errors in serializer.errors.items()+ )+ return JsonResponse({"error": f"Invalid request body — {detail}", "detail": serializer.errors}, status=400)+ data = serializer.validated_data++ if not Notebook.objects.filter(team_id=team_id, short_id=notebook_short_id).exists():+ return JsonResponse({"error": "Notebook not found"}, status=404)+ team = Team.objects.get(id=team_id)+ user = User.objects.filter(id=user_id).first() if user_id else None++ try:+ # Wrap rather than mutate the user's query: the outer LIMIT/OFFSET caps the page+ # regardless of the query's own shape (set queries, its own LIMIT, etc.).+ inner = parse_select(data["query"])+ # limit/offset are int()-coerced so no injection is possible; the user query enters via placeholder.+ # nosemgrep: hogql-fstring-audit+ wrapped = parse_select(+ f"select * from {{__sqlv2_inner__}} limit {int(data['limit'])} offset {int(data['offset'])}",+ placeholders={"__sqlv2_inner__": inner},+ )+ with tags_context(product=Product.NOTEBOOKS, feature=Feature.QUERY, team_id=team.id):+ response = execute_hogql_query(query=wrapped, team=team, query_type="SQLV2DataPlaneQuery", user=user)+ except ExposedHogQLError as exc:+ return JsonResponse({"error": str(exc)}, status=400)+ except Exception:+ logger.exception("notebook_sql_v2_data_plane_query_failed", notebook_short_id=notebook_short_id)+ return JsonResponse({"error": "Query execution failed."}, status=500)++ columns = [str(column) for column in (response.columns or [])]+ types = [[str(name), str(type_name)] for name, type_name in (response.types or [])]+ payload = _rows_to_arrow_bytes(columns, response.results or [], types)+ return HttpResponse(payload, content_type=ARROW_STREAM_CONTENT_TYPE)diff --git a/products/notebooks/backend/sql_v2_kernel_architecture.md b/products/notebooks/backend/sql_v2_kernel_architecture.mdnew file mode 100644index 000000000000..9dc5a349c2a1--- /dev/null+++ b/products/notebooks/backend/sql_v2_kernel_architecture.md@@ -0,0 +1,169 @@+# SQLV2 sandbox kernel architecture++How the in-sandbox runtime is structured so it can:++1. accept HTTP requests to run commands (as it does today),+2. make HTTP requests to the PostHog backend to fetch ClickHouse data (the data plane),+3. load SQL responses as Python dataframes from locally stored files,+4. run DuckDB locally against those files and against kernel-made dataframes.++This extends the Journey 1 slice (`sql_v2.py`, the `kernel/` package) toward the full walkthrough design: push compute to CH, stream Arrow to local files, sandbox drives execution, results return via callback.++## Two processes, one owner++The sandbox runs **two cooperating processes**, both owned by the notebook runtime:++```text+Sandbox (Modal / Docker container)+├── kernel-server ← long-lived HTTP server (today's exposed port)+│ ├── HTTP API: /health /run /page /interrupt /state+│ ├── run queue → executor (jupyter_client, one run at a time)+│ ├── data-plane client (streams Arrow from backend → local files)+│ └── result-store reader (pyarrow mmap / read-only DuckDB, serves /page)+├── ipykernel ← child process, spawned and owned by kernel-server+│ └── user namespace + `_ph` bootstrap module+│ (persistent DuckDB connection, frame registry, node runner)+└── /data+ ├── frames/<query_hash>.arrow materialized CH inputs (Arrow IPC files)+ ├── results/<result_id>.arrow node outputs, for paging+ └── duck/ DuckDB db file + temp spill directory+```++**Why not one process (exec user code inside the server)?** Interrupt requires SIGINT semantics (`KernelManager.interrupt_kernel()`), a segfaulting C extension must not take down the HTTP endpoint, and ipykernel gives stdout/stderr/`display_data` (matplotlib PNG) capture for free. All of that is already in the image.++**Why not keep the backend driving a bare ipykernel (V1)?** That is the stdout bridge we are replacing: every execution round-trips the docker/Modal control plane with a generated script. Here the control plane is used exactly once — to launch the kernel-server — and everything after is plain authed HTTP. The kernel-server becomes the single owner of the kernel process (spawn, health, interrupt, restart); the backend never touches the kernel directly.++### Division of labor (the important rule)++- **The kernel-server does all network I/O.** It receives commands, calls the data plane, sends the result callback. Credentials (command secret, callback token, data-plane token) live only in the server process.+- **The ipykernel does all compute and holds all data.** User Python, DuckDB queries, pandas frames, the persistent DuckDB connection.+- **They share data through files** (`/data`), never through sockets: the server streams Arrow onto disk; the kernel maps those files into DuckDB/pandas. This keeps backend credentials out of the process that runs user code — user code can read anything in its own process, so the less that process holds, the better. (Everything in the sandbox is scoped to this one notebook/team regardless; this is defense in depth, not the boundary.)++## The HTTP API (capability 1)++Same server, same port, same HMAC command-token auth as today (`sql_v2.mint_command_token` / `_verify_command_token`), extended:++| Route | Sync? | Purpose |+| ---------------------- | ----- | ------------------------------------------------------------------------------------- |+| `GET /health` | sync | liveness + `{version, kernel_alive}` — version drives the redeploy handshake |+| `POST /run` | 202 | enqueue a node run; result arrives via callback |+| `POST /interrupt` | sync | `KernelManager.interrupt_kernel()` (SIGINT) for the active run |+| `POST /page` | sync | slice rows out of a stored result (`result_id`, offset, limit) — bounded, no callback |+| `GET /state` | sync | list materialized frames, kernel variables, DuckDB tables (Journey 7) |+| `POST /kernel/restart` | sync | recycle the ipykernel child; frames on disk survive, namespace does not |++The command token grows a **scope** claim: `run:<run_id>` (authorizes `/run`, `/interrupt` for that run) or `kernel:<runtime_id>` (authorizes `/page`, `/state`, `/kernel/restart`). Same HMAC scheme, signed payload becomes `{scope}.{exp}`.++`POST /run` body (superset of today's):++```json+{+ "run_id": "…",+ "node": { "type": "hogql | duckdb | python", "code": "…", "output_name": "df3" },+ "inputs": [+ { "name": "df1", "kind": "hogql", "query": "<CTE-resolved HogQL>", "query_hash": "sha256…" },+ { "name": "df2", "kind": "local" }+ ],+ "callback": { "url": "…", "token": "…" },+ "data_plane": { "url": "…", "token": "…" }+}+```++The backend resolves upstream HogQL references into `inputs` before dispatch (it owns the notebook document); the sandbox never parses HogQL. `kind: local` asserts the frame already exists in the kernel (made by an earlier Python/DuckDB node); the server fails the run cleanly if it doesn't.++Runs execute **one at a time** in arrival order (a kernel has one namespace; concurrent mutation is meaningless). The server keeps a small FIFO queue and per-run state so `/run` returns 202 immediately, and the watchdog/callback bookkeeping has one source of truth. `/page` and `/state` are served concurrently off the server's own read-only view of `/data` — they never wait behind a long run.++## The data plane (capability 2)++New backend endpoint, the counterpart of the callback:++```text+POST /internal/notebooks/<short_id>/data_plane/query+Authorization: Bearer <data-plane token>+{ "query": "<HogQL>", "limit"?, "offset"? }+→ 200, Content-Type: application/vnd.apache.arrow.stream (RecordBatch stream)+```++- **Auth**: a signed data-plane token, same `django.core.signing` pattern as the callback token, scoped `(notebook, team)`, minted per run and delivered inside the `/run` payload. TTL must exceed the run watchdog. Hardening later swaps both for RS256 JWTs (Code's `sandbox_event_ingest` pattern), unchanged wire shape.+- **Execution**: the endpoint runs the HogQL through the normal HogQL layer (access controls apply), against ClickHouse — or DuckLake for warehouse sources (Journey 6) — and writes Arrow record batches into the streaming HTTP response as they arrive. No object storage, no buffering the full result server-side.+- **Client side**: the kernel-server issues the request with `requests(..., stream=True)` and feeds `response.raw` into `pyarrow.ipc.open_stream`, writing batches straight into an Arrow IPC **file** under `/data/frames/<query_hash>.arrow`. Peak memory is one record batch, regardless of result size.++Two uses of the same endpoint:++1. **Display page for a pure-HogQL node** — the server requests the query with `LIMIT/OFFSET` for the capped page, builds the envelope from the small Arrow payload, and **never involves the kernel**. Paging/sorting a displayed HogQL node is a fresh CH query every time (accepted trade-off from the walkthrough).+2. **Materialization** — when a Python/DuckDB node needs a CH-resident input, the server fetches the **full** result to a frame file first, then hands the run to the kernel.++Frame files are keyed by `query_hash` (sha256 of the canonical resolved query): re-running a Python node whose inputs didn't change reuses the file; an edited upstream query changes the hash, so staleness falls out naturally (the UI's stale-flag flow, Journey 10, decides _when_ to re-run; the hash decides _whether_ a fetch is needed).++## Loading frames into Python (capability 3)++The kernel is bootstrapped once (at kernel start, by the kernel-server) with a small module, `_ph`, which holds:++- a **persistent DuckDB connection** (`duckdb.connect("/data/duck/duck.db")` with `temp_directory` set, so big operations spill to disk),+- a **frame registry**: `name → {query_hash, path, registered_view}`,+- the **node runner** the server invokes per run.++For each run, the server sends the kernel a single execute request — `_ph.run_node(<payload>)` — where the payload lists the node code and the (already fetched) input file paths. `run_node`:++1. **Registers inputs.** For each `hogql` input: `pyarrow.ipc.open_file(path)` (memory-mapped, zero-copy) and `duckdb.register(name, arrow_object)` — the frame is queryable in DuckDB without ever fully loading into RAM. For a **Python** node it additionally binds `name = <arrow>.to_pandas()` into the user namespace — this is the one step that materializes in RAM, matching the accepted trade-off ("pandas may need to materialize all in memory"); heavy reduction should happen in HogQL/DuckDB first.+2. **Runs the node** (below).+3. **Builds the envelope** — `{status, stdout, stderr, error?, result_id, columns, dtypes, row_count, first_page, media}` — and returns it as the execute result. The kernel-server, not the kernel, POSTs it to the callback URL.+4. **Writes the result frame** (if the node produced one) to `/data/results/<result_id>.arrow`, so `/page` can slice it later without touching the kernel.++Python node execution uses `get_ipython().run_cell(code)` inside a capture context: full IPython semantics (last-expression value, tracebacks), stdout/stderr capture, and matplotlib figures arrive as `display_data` PNG — straight into `envelope.media`.++## Local DuckDB (capability 4)++**DuckDB nodes always execute inside the kernel process.** This is forced by DuckDB's replacement scans: `duckdb.sql("select * from my_pandas_df")` only resolves `my_pandas_df` if the frame lives in the same process. Since DuckDB nodes exist precisely to query local frames (decision 3), they run where the frames are.++A DuckDB node is then just: register any not-yet-registered file-backed inputs, `_ph.duck.sql(code)`, bind the result relation to `output_name` (as a registered DuckDB view + lazily-materializable frame), envelope with a capped preview. The result stays lazy in DuckDB until a downstream Python node calls for pandas.++The routing rule the server applies per run (from the walkthrough, now concrete):++- `node.type == hogql` and **all** inputs are `hogql` → push to CH: data-plane page fetch only, kernel untouched.+- anything else (Python node, DuckDB node, or a HogQL node would go here if we ever allow HogQL over local frames — we don't; that's what DuckDB syntax is for) → materialize `hogql` inputs to frame files, run in the kernel.++## Result store and paging++`/page` reads `/data/results/<result_id>.arrow` in the **server** process (pyarrow mmap slice, or a read-only DuckDB connection for sorted/filtered pages). Consequences:++- paging a materialized result is sub-ms and never queues behind a running cell,+- `result_id` stays valid across a **kernel** restart (files survive; only the namespace dies) but not across a **sandbox** death — consistent with the documented alive-only trade-off in `sql_v2_result_delivery.md`,+- results above a size cap are written truncated with a `truncated: true` marker in the envelope; the UI offers re-run-with-filters rather than paging into a 10 GB frame.++## Packaging: from embedded string to a real package++`KERNEL_SERVER_SOURCE` (a stdlib-only string in Django) cannot carry this. Replace it with a real, dependency-using package that never imports Django:++```text+products/notebooks/kernel/ # or backend/kernel_src/ — sandbox-side code, no Django+├── server.py # HTTP server (stdlib ThreadingHTTPServer stays fine — 202s and bounded reads)+├── auth.py # command-token verification (mirror of sql_v2 HMAC, round-trip unit-tested)+├── executor.py # run queue, jupyter_client KernelManager ownership, watchdog, callback POST+├── data_plane.py # Arrow streaming fetch → /data/frames+├── result_store.py # /page + /state reads+├── bootstrap.py # the `_ph` module injected into the kernel (duck conn, frame registry, run_node)+└── envelope.py # envelope construction shared by executor/bootstrap+```++Dependencies (`jupyter_client`, `pyarrow`, `duckdb`, `pandas`, `requests`) are already in `Dockerfile.sandbox-notebook`; no new image deps needed. Delivery:++- **Prod**: bake the package into the sandbox image (like Code's agent-server), launched as `python -m …kernel.server --port … --secret-file …`.+- **Dev / iteration**: keep the `write_file` bootstrap in `ensure_sql_v2_server`, but upload a tarball of the package keyed by content hash; `/health` reports the hash, and a mismatch triggers re-upload + restart. Editing kernel code then needs no image rebuild.++Because the package is plain Python with no Django imports, it gets normal unit tests in CI (auth round-trip, envelope building, run_node against a real in-process DuckDB, data-plane client against a stub Arrow server).++## Failure handling++- **Kernel dies mid-run** (OOM, segfault): the server's executor notices (execute reply timeout / `km.is_alive()` false), POSTs a `{status: "failed", error: "kernel_died"}` envelope to the callback, and can restart the kernel on the next run. The backend-side watchdog stays as the outer net for the case where the whole _sandbox_ dies and no callback can ever arrive.+- **Data-plane fetch fails** mid-stream: partial frame files are written to a temp name and renamed only on success, so the registry never sees a torn file; the run fails with the fetch error in the envelope.+- **Sandbox dies**: everything under `/data` is gone; recovery is the walkthrough's re-provision + mark-all-stale + re-run flow. Nothing here changes that.++## Build order++1. **Package extraction (pure refactor).** Move the current fabricated-result server into the package + tarball bootstrap + version handshake. E2E slice stays green; `KERNEL_SERVER_SOURCE` is deleted.+2. **Server owns an ipykernel.** `executor.py` spawns the kernel via `KernelManager`, injects `_ph`; `/run` with `node.type: python` executes real code and returns a real envelope (stdout, tracebacks, matplotlib media). `/interrupt` works.+3. **Backend data-plane endpoint** (HogQL → Arrow stream) + server-side fetch. Pure-HogQL display nodes return real ClickHouse data — Journey 1 is real end to end, Journey 2 paging via re-query.+4. **Materialization.** `inputs` in the run payload, frame files, `_ph` registration + pandas binding — Journeys 4/5.+5. **DuckDB node type** — Journey 3-alt/5/6 local joins.+6. **Result store `/page` + `/state`** — Journey 2 (materialized paging) and Journey 7.diff --git a/products/notebooks/backend/sql_v2_result_delivery.md b/products/notebooks/backend/sql_v2_result_delivery.mdnew file mode 100644index 000000000000..dab860ad5271--- /dev/null+++ b/products/notebooks/backend/sql_v2_result_delivery.md@@ -0,0 +1,168 @@+# SQLV2 result delivery++How a SQLV2 node learns that its run finished and gets the result envelope.++## Current approach: FE short-poll (implemented)++The run result is written durably to `NotebookNodeRun` (Postgres) by the sandbox+callback. The frontend node polls a cheap read endpoint until the run reaches a+terminal state.++- **Backend:** `GET .../sql_v2/runs/<run_id>` returns `{status, result, error}`+ by reading the `NotebookNodeRun` row (one indexed query). No held connection,+ no busy-loop.+- **Frontend:** the node polls that endpoint (~1s) while it has a `runId` and the+ run is `running`; stops on `done`/`failed`. In-progress state is derived from+ the run status, so it survives remounts and reloads. The poll timer lives in+ `cache.disposables` (auto-cleanup + pause on hidden tab).++Chosen because the result is a **single terminal value**, not a live event stream.+Polling a durable row is simpler than SSE and inherently resilient to connection+death, reloads, and node remounts (the failure modes we hit). Cost is a handful of+1-query reads per run.++## Future approach: Redis pub/sub push (implement when we want lower latency)++Keep the durable Postgres write as the source of truth; add a Redis pub/sub+channel so the result is pushed the instant the callback lands, instead of waiting+for the next poll tick. This is worth doing if/when poll latency (~1s) becomes+noticeable, or when many concurrent runs make polling wasteful. It is **pub/sub,+not a Redis Stream** — we deliver one terminal result, so we don't need replay.++### Backend++1. **Callback handler** (`sql_v2_callback.py`)+ - Keep the DB write (envelope → `NotebookNodeRun`) as the authoritative source.+ - After the write, best-effort `PUBLISH notebook:sql_v2:run:<run_id>` with a+ tiny signal (e.g. `{"status": "done"}`). Payload stays small — the SSE handler+ re-reads the authoritative envelope from Postgres. A failed publish never loses+ data; the connect-time read (below) covers it.++2. **SSE stream handler** — replace the busy-poll with **subscribe-then-check**:+ 1. **Subscribe first** to `notebook:sql_v2:run:<run_id>` (before the DB read —+ this closes the race where the callback fires between read and subscribe).+ 2. **Read the run once.** If already `done`/`failed` → emit result/error,+ unsubscribe, return. (Covers "finished before I connected.")+ 3. Else **block on the subscription** with a bounded timeout + periodic SSE+ heartbeat. On message → re-read the run → emit → return. On timeout → error.+ - No polling loop, no `time.sleep`.++3. **Redis + async**+ - Use the existing async Redis client; the handler must be **async** so a held+ SSE connection is an idle coroutine, not a worker thread.++### Frontend++4. Node logic keeps its durable-run recovery (fetch/poll by persisted `runId` on+ mount when `result` is missing) as the fallback path — the SSE push is the+ fast path, the DB read on connect is the safety net.++### Edge cases++- **Subscribe-before-read ordering** — the one race that matters.+- **Postgres is authoritative**, pub/sub is only a wake-up; a missed message falls+ back to the connect-time read, never data loss.+- **Timeout + heartbeat** so connections don't hang and proxies don't kill idle+ streams.+- **Unsubscribe/cleanup** on every exit path (result, error, timeout, disconnect).++### Why not a Redis Stream (like PostHog Code)++PostHog Code streams many incremental agent events and needs replay on reconnect+(`Last-Event-ID` cursor over a trimmed stream). SQLV2 delivers one terminal+result, so pub/sub + a durable row is sufficient and much simpler. Revisit the+Stream approach only if SQLV2 starts streaming incremental output (stdout,+rows-as-they-arrive, progress).++---++# Result storage & paging (design, not yet implemented)++## Three layers — don't conflate them++| Layer | Where it lives | Size |+| --------------------------- | ---------------------------------------------------- | ------------------------------------------------ |+| `NotebookNodeRun.envelope` | Postgres JSONField on the run | small — metadata + `first_page` **preview** only |+| Full result (all pages) | a **result store** the sandbox populates at run time | can be large |+| `NotebookNodeRun.result_id` | Postgres (UUID column, from the envelope) | tiny — a **handle** into the store |++The envelope carries `{columns, row_count, first_page, result_id}` — a bounded+preview plus a pointer. **It never holds more than the first page.** The full+dataset lives in the result store, referenced by `result_id`. This is the+"pass large data by reference, not by value" rule (same reason Temporal payloads+are capped) — a multi-MB dataframe must never land in the JSONField or the+callback body.++## One run = one row (not one row per page)++`NotebookNodeRun` is one row per **execution** (per Run click). It produces one+`result_id` and one stored result set. **A page fetch is not a run** — it's a+read of an already-materialized result, so it creates **no new `NotebookNodeRun`,+no Temporal workflow, no DB write**. Runs stay the audit/history record; page+reads stay stateless.++```text+1 Run click → 1 NotebookNodeRun → 1 result_id → 1 stored result set+ ↑+ page 1, 2, 3, "download all" ──read-only────┘ (0 new runs)+```++## Where the full result lives++**Now: kernel-resident.** The full dataframe stays as a variable in the live+kernel (mirrors the existing DuckSQL/HogQL nodes, which page via+`api.notebooks.kernelDataframe`). `result_id` identifies that resident frame.++**Later: durable store** (object storage / Parquet / a results table). The+sandbox materializes the full result at run time; `result_id` is the storage key.+Removes the alive-only limitation below. Switch to this when results must survive+kernel teardown/reloads.++## Page fetch with a kernel-resident store++The data is _in_ the sandbox, so a page fetch **must round-trip to the sandbox** —+but it must **not** use the run's async callback. The callback exists because a+run has unbounded latency; slicing rows out of an in-memory frame is fast and+bounded, so paging is a plain **synchronous request/response**:++```text+Run (unbounded): FE → POST /sql_v2/run → Temporal → kernel-server POST /run → 202+ (later) → POST /callback → DB → FE polls+Page (bounded): FE → GET /sql_v2/results/<result_id>?page=2&page_size=100+ → backend finds the running kernel+ → HTTP POST kernel-server /page {result_id, page, page_size}+ → kernel-server slices resident frame, returns rows in the 200 response+ → backend returns rows to FE+```++- **No docker control plane needed.** The run goes through Temporal partly because+ `ensure_sql_v2_server` bootstraps the server via `write_file`/`execute` (docker+ socket). By page-fetch time the kernel-server is already up, so paging is just a+ **network HTTP call** to it — allowed even under the dev Seatbelt sandbox (only+ the docker _socket_ is denied, not network egress). Hence a synchronous+ web→kernel-server call is fine and low-latency.+- **To build:** add a synchronous `/page` route to the kernel-server+ (`kernel/server.py`) + a thin backend read endpoint that proxies to it.++## Kernel-resident tradeoff: alive-only++The `result_id` slice exists only while that kernel is up. If the kernel+idle-times-out, is restarted, or the notebook reloads onto a fresh kernel,+`result_id` is stale → `/page` returns not-found → the UI must **re-run** to get a+fresh `result_id`. Durable storage is what removes this later.++## Related model notes++- **`KernelRuntime.server_url` / `server_connect_token`** are stored **plaintext**+ (`TextField`). This matches PostHog Code, which keeps `sandbox_url` /+ `sandbox_connect_token` plaintext in `TaskRun.state` (a plain JSONField). The+ connect token is an ephemeral Modal tunnel token, not a durable account secret+ (those, e.g. env vars, tasks _does_ encrypt via `EncryptedJSONStringField`). If+ we ever want defense-in-depth, an encrypted field is the established pattern.+- **`NotebookNodeRun` has no FK to `KernelRuntime`** and doesn't need one: dispatch+ targets the currently-running kernel and the result returns by `run_id`; a later+ run just creates a new row against whatever kernel is up then. If we want+ run→sandbox traceability for debugging, prefer storing the **`sandbox_id` string**+ on the run over a hard FK — `KernelRuntime` rows are transient+ (starting/stopped/discarded/error), so a FK would couple run history to a churny+ row.diff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.pynew file mode 100644index 000000000000..662a117d82e4--- /dev/null+++ b/products/notebooks/backend/sql_v2_serializers.py@@ -0,0 +1,63 @@+from rest_framework import serializers+++class NotebookSQLV2RunRequestSerializer(serializers.Serializer):+ node_id = serializers.CharField(help_text="ProseMirror node id of the SQLV2 node being run.")+ code = serializers.CharField(+ help_text="The HogQL the node contains; the sandbox runs it through the data plane. Must not be blank.",+ )+++class NotebookSQLV2DataPlaneRequestSerializer(serializers.Serializer):+ query = serializers.CharField(help_text="HogQL SELECT to execute against the notebook team's data.")+ limit = serializers.IntegerField(+ required=False,+ default=50,+ min_value=1,+ max_value=1000,+ help_text="Maximum number of rows to return (applied as an outer LIMIT).",+ )+ offset = serializers.IntegerField(+ required=False,+ default=0,+ min_value=0,+ help_text="Number of rows to skip (applied as an outer OFFSET), for paging.",+ )+++class NotebookSQLV2EnvelopeSerializer(serializers.Serializer):+ status = serializers.CharField(help_text="Run outcome: 'ok' or 'error'.")+ columns = serializers.ListField(+ child=serializers.CharField(),+ required=False,+ default=list,+ help_text="Result column names.",+ )+ types = serializers.ListField(+ child=serializers.ListField(child=serializers.CharField(), help_text="A [column name, ClickHouse type] pair."),+ required=False,+ default=list,+ help_text="ClickHouse type per column, as [name, type] pairs; used by the visualization tab.",+ )+ row_count = serializers.IntegerField(required=False, default=0, help_text="Number of rows in the result.")+ first_page = serializers.ListField(+ child=serializers.ListField(help_text="A single result row as a list of cell values."),+ required=False,+ default=list,+ help_text="First page of result rows for display; each row is a list of cell values.",+ )+ result_id = serializers.UUIDField(+ required=False,+ allow_null=True,+ help_text="Identifier of the materialized result, used as the paging key.",+ )+ error = serializers.CharField(+ required=False,+ allow_null=True,+ allow_blank=True,+ help_text="Error message when status is 'error'.",+ )+++class NotebookSQLV2CallbackRequestSerializer(serializers.Serializer):+ envelope = NotebookSQLV2EnvelopeSerializer(help_text="The result envelope produced by the sandbox run.")diff --git a/products/notebooks/backend/temporal/__init__.py b/products/notebooks/backend/temporal/__init__.pynew file mode 100644index 000000000000..4bef916a4f94--- /dev/null+++ b/products/notebooks/backend/temporal/__init__.py@@ -0,0 +1,14 @@+from products.notebooks.backend.temporal.sql_v2 import (+ NotebookSQLV2RunWorkflow,+ dispatch_sql_v2_run_activity,+ mark_sql_v2_run_failed_activity,+)++WORKFLOWS = [+ NotebookSQLV2RunWorkflow,+]++ACTIVITIES = [+ dispatch_sql_v2_run_activity,+ mark_sql_v2_run_failed_activity,+]diff --git a/products/notebooks/backend/temporal/client.py b/products/notebooks/backend/temporal/client.pynew file mode 100644index 000000000000..dcbb89bfc349--- /dev/null+++ b/products/notebooks/backend/temporal/client.py@@ -0,0 +1,29 @@+"""Fire-and-forget starter for the SQLV2 run workflow, callable from sync DRF views."""++from django.conf import settings++from asgiref.sync import async_to_sync+from temporalio.client import Client++from posthog.temporal.common.client import sync_connect++from products.notebooks.backend.temporal.sql_v2 import SQLV2RunInput+++@async_to_sync+async def _start_workflow(temporal: Client, name: str, workflow_id: str, inputs: object) -> None:+ await temporal.start_workflow(+ name,+ inputs,+ id=workflow_id,+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,+ )+++def start_sql_v2_run_workflow(inputs: SQLV2RunInput) -> None:+ _start_workflow(+ sync_connect(),+ "notebook-sandbox-cmd-run",+ f"notebook-sandbox-cmd-run-{inputs.run_id}",+ inputs,+ )diff --git a/products/notebooks/backend/temporal/sql_v2.py b/products/notebooks/backend/temporal/sql_v2.pynew file mode 100644index 000000000000..5ae7e21400c4--- /dev/null+++ b/products/notebooks/backend/temporal/sql_v2.py@@ -0,0 +1,79 @@+"""Temporal workflow/activities for the SQLV2 run dispatch.++The run endpoint kicks this off fire-and-forget so the sandbox I/O (kernel-server+bootstrap on first run, the /run POST) runs on a Temporal worker with retries —+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 datetime import timedelta++from temporalio import activity, common, workflow++from posthog.models.user import User+from posthog.temporal.common.base import PostHogWorkflow++from products.notebooks.backend.models import Notebook, NotebookNodeRun+from products.notebooks.backend.sql_v2 import SQLV2KernelNotRunning, dispatch_sql_v2_run+++@dataclass+class SQLV2RunInput:+ run_id: str+ notebook_short_id: str+ team_id: int+ user_id: int | None = None+ code: str = ""+++def _load_notebook_and_user(team_id: int, notebook_short_id: str, user_id: int | None) -> tuple[Notebook, User | None]:+ notebook = Notebook.objects.get(team_id=team_id, short_id=notebook_short_id)+ user = User.objects.filter(id=user_id).first() if user_id else None+ return notebook, user++[email protected](name="notebook-sandbox-cmd-dispatch")+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)+ except SQLV2KernelNotRunning:+ # Terminal — retrying won't start the kernel. Mark failed; the SSE stream surfaces it.+ run.status = NotebookNodeRun.Status.FAILED+ run.error = "Kernel is not running. Start the instance first."+ run.save(update_fields=["status", "error", "updated_at"])++[email protected](name="notebook-sandbox-cmd-mark-failed")+def mark_sql_v2_run_failed_activity(input: SQLV2RunInput) -> None:+ run = NotebookNodeRun.objects.for_team(input.team_id).filter(id=input.run_id).first()+ if run is not None and run.status == NotebookNodeRun.Status.RUNNING:+ run.status = NotebookNodeRun.Status.FAILED+ run.error = "Run failed to dispatch to the kernel."+ run.save(update_fields=["status", "error", "updated_at"])++[email protected](name="notebook-sandbox-cmd-run")+class NotebookSQLV2RunWorkflow(PostHogWorkflow):+ inputs_cls = SQLV2RunInput++ @workflow.run+ async def run(self, input: SQLV2RunInput) -> None:+ try:+ await workflow.execute_activity(+ dispatch_sql_v2_run_activity,+ input,+ start_to_close_timeout=timedelta(seconds=60),+ retry_policy=common.RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=2)),+ )+ except Exception:+ # Dispatch exhausted its retries — make sure the run reaches a terminal state.+ await workflow.execute_activity(+ mark_sql_v2_run_failed_activity,+ input,+ start_to_close_timeout=timedelta(seconds=30),+ retry_policy=common.RetryPolicy(maximum_attempts=3),+ )+ raisediff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.pynew file mode 100644index 000000000000..7f9012bd2e62--- /dev/null+++ b/products/notebooks/backend/test/test_sql_v2.py@@ -0,0 +1,593 @@+import io+import json+import math+import tarfile+import datetime+import threading+import urllib.error+import urllib.request+from http.server import ThreadingHTTPServer+from types import SimpleNamespace+from typing import Any++from posthog.test.base import APIBaseTest+from unittest.mock import patch++from django.core import signing+from django.core.cache import cache+from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.constants import AvailableFeature+from posthog.models.organization import OrganizationMembership+from posthog.models.scoping import team_scope++from products.notebooks.backend.kernel_package import kernel_package_bytes_and_hash+from products.notebooks.backend.models import KernelRuntime, Notebook, NotebookNodeRun+from products.notebooks.backend.sandbox.kernel import (+ auth as kernel_auth,+ envelope as kernel_envelope,+ runner as kernel_runner,+)+from products.notebooks.backend.sandbox.kernel.data_plane import DataPlaneError, decode_arrow_stream+from products.notebooks.backend.sql_v2 import (+ SQLV2KernelNotRunning,+ ensure_sql_v2_server,+ kernel_server_secret,+ mint_callback_token,+ mint_command_token,+ mint_data_plane_token,+ verify_data_plane_token,+)+from products.notebooks.backend.sql_v2_data_plane import _rows_to_arrow_bytes+from products.notebooks.backend.temporal.sql_v2 import (+ SQLV2RunInput,+ dispatch_sql_v2_run_activity,+ mark_sql_v2_run_failed_activity,+)++from ee.models.rbac.access_control import AccessControl+++def _restrict_query_access(test: APIBaseTest) -> None:+ # Demote from owner (owner bypasses access control) to member, turn on the ACCESS_CONTROL+ # feature, and write an explicit query "none" row so the user falls below query-read.+ test.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ test.organization.save(update_fields=["available_product_features"])+ test.organization_membership.level = OrganizationMembership.Level.MEMBER+ test.organization_membership.save(update_fields=["level"])+ AccessControl.objects.create(+ team=test.team,+ resource="query",+ resource_id=None,+ organization_member=test.organization_membership,+ access_level="none",+ )+ cache.clear()+++class TestSQLV2Callback(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbcb123")+ with team_scope(self.team.id):+ self.node_run = NotebookNodeRun.objects.create(+ team=self.team,+ notebook=self.notebook,+ node_id="node-1",+ status=NotebookNodeRun.Status.RUNNING,+ )+ self.url = f"/internal/notebooks/runs/{self.node_run.id}/result/"+ self.envelope = {+ "status": "ok",+ "columns": ["count"],+ "row_count": 1,+ "first_page": [[42]],+ "result_id": str(self.node_run.id),+ }++ def _post(self, token: str, envelope=None):+ return self.client.post(+ self.url,+ data=json.dumps({"envelope": envelope if envelope is not None else self.envelope}),+ content_type="application/json",+ HTTP_AUTHORIZATION=f"Bearer {token}",+ )++ def _reload_run(self) -> NotebookNodeRun:+ return NotebookNodeRun.objects.for_team(self.team.id).get(id=self.node_run.id)++ def test_valid_token_stores_result(self):+ token = mint_callback_token(str(self.node_run.id), self.team.id)+ response = self._post(token)+ self.assertEqual(response.status_code, 200)+ run = self._reload_run()+ self.assertEqual(run.status, NotebookNodeRun.Status.DONE)+ self.assertEqual(run.envelope["first_page"], [[42]])+ self.assertEqual(str(run.result_id), str(self.node_run.id))++ def test_redelivery_is_idempotent(self):+ token = mint_callback_token(str(self.node_run.id), self.team.id)+ self._post(token)+ self._post(token)+ count = NotebookNodeRun.objects.for_team(self.team.id).filter(id=self.node_run.id).count()+ self.assertEqual(count, 1)+ self.assertEqual(self._reload_run().status, NotebookNodeRun.Status.DONE)++ @parameterized.expand(+ [+ ("missing_token", None, 401),+ ("garbage_token", "not-a-real-token", 401),+ ]+ )+ def test_rejects_bad_auth(self, _name, token, expected_status):+ if token is None:+ response = self.client.post(+ self.url, data=json.dumps({"envelope": self.envelope}), content_type="application/json"+ )+ else:+ response = self._post(token)+ self.assertEqual(response.status_code, expected_status)+ self.assertEqual(self._reload_run().status, NotebookNodeRun.Status.RUNNING)++ def test_token_for_other_run_is_forbidden(self):+ token = mint_callback_token("00000000-0000-0000-0000-0000000000ff", self.team.id)+ response = self._post(token)+ self.assertEqual(response.status_code, 403)+ 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)+ response = self.client.post(+ f"/internal/notebooks/runs/{other_id}/result/",+ data=json.dumps({"envelope": self.envelope}),+ content_type="application/json",+ HTTP_AUTHORIZATION=f"Bearer {token}",+ )+ self.assertEqual(response.status_code, 404)+++class TestSQLV2Run(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbrun01")+ self.run_url = f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/run/"++ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_run_creates_row_and_starts_workflow(self, _mock_enabled, mock_start):+ response = self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1"}, format="json")+ self.assertEqual(response.status_code, 200)+ run_id = response.json()["run_id"]+ run = NotebookNodeRun.objects.for_team(self.team.id).get(id=run_id)+ self.assertEqual(run.status, NotebookNodeRun.Status.RUNNING)+ mock_start.assert_called_once()+ self.assertEqual(str(mock_start.call_args.args[0].run_id), run_id)++ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_query_restricted_member_cannot_run(self, _mock_enabled, mock_start):+ # A notebook editor whose query access is denied must not execute HogQL through the node.+ _restrict_query_access(self)+ response = self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1"}, format="json")+ self.assertEqual(response.status_code, 403)+ mock_start.assert_not_called()+ self.assertFalse(NotebookNodeRun.objects.for_team(self.team.id).exists())++ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_blank_code_is_rejected_before_dispatch(self, _mock_enabled, mock_start):+ # A stale-attribute FE bug once sent empty code all the way into the sandbox; fail fast here instead.+ response = self.client.post(self.run_url, data={"node_id": "n1", "code": ""}, format="json")+ self.assertEqual(response.status_code, 400)+ self.assertEqual(NotebookNodeRun.objects.for_team(self.team.id).filter(notebook=self.notebook).count(), 0)+ mock_start.assert_not_called()++ @patch(+ "products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow",+ side_effect=RuntimeError("temporal unavailable"),+ )+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_run_marks_failed_when_workflow_start_fails(self, _mock_enabled, _mock_start):+ response = self.client.post(self.run_url, data={"node_id": "n1", "code": "select 1"}, format="json")+ self.assertEqual(response.status_code, 503)+ run = NotebookNodeRun.objects.for_team(self.team.id).filter(notebook=self.notebook).first()+ assert run is not None+ self.assertEqual(run.status, NotebookNodeRun.Status.FAILED)+++class _RecordingSandbox:+ """Stands in for the docker/Modal sandbox: records control-plane calls."""++ def __init__(self):+ self.files: dict[str, bytes] = {}+ self.commands: list[str] = []++ def write_file(self, path: str, payload: bytes) -> None:+ self.files[path] = payload++ def execute(self, command: str, timeout_seconds: int | None = None) -> None:+ self.commands.append(command)++ def get_connect_credentials(self):+ return SimpleNamespace(url="http://localhost:45678", token="connect-tok")+++class TestSQLV2EnsureServer(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbens01")+ self.sandbox = _RecordingSandbox()++ def _create_runtime(self, server_url: str | None = None) -> KernelRuntime:+ return KernelRuntime.objects.create(+ team=self.team,+ notebook=self.notebook,+ notebook_short_id=self.notebook.short_id,+ user=self.user,+ status=KernelRuntime.Status.RUNNING,+ backend=KernelRuntime.Backend.DOCKER,+ sandbox_id="sbx-1",+ server_url=server_url or "",+ )++ def _ensure(self, reported_version: str | None):+ sandbox_class = SimpleNamespace(get_by_id=lambda _id: self.sandbox)+ with (+ patch("products.notebooks.backend.sql_v2._server_version", return_value=reported_version),+ patch("products.notebooks.backend.sql_v2.get_sandbox_class_for_backend", return_value=sandbox_class),+ patch("products.notebooks.backend.sql_v2._wait_for_server_ready"),+ ):+ return ensure_sql_v2_server(self.notebook, self.user)++ def test_current_server_is_reused_without_control_plane_calls(self):+ # A redeploy on every run would restart the server and wipe the result cache.+ runtime = self._create_runtime(server_url="http://localhost:1")+ result = self._ensure(reported_version=kernel_package_bytes_and_hash()[1])+ self.assertEqual(result.id, runtime.id)+ self.assertEqual(self.sandbox.commands, [])+ self.assertEqual(self.sandbox.files, {})++ def test_stale_server_is_redeployed(self):+ # Missing this redeploy strands sandboxes on old kernel code.+ runtime = self._create_runtime(server_url="http://localhost:1")+ result = self._ensure(reported_version="some-old-version")+ package, _version = kernel_package_bytes_and_hash()+ self.assertEqual(self.sandbox.files["/tmp/nb_kernel.tar.gz"], package)+ self.assertEqual(self.sandbox.files["/tmp/nb_sql_v2_secret"], kernel_server_secret(str(runtime.id)).encode())+ self.assertEqual(len(self.sandbox.commands), 1)+ self.assertEqual(result.server_url, "http://localhost:45678")+ self.assertEqual(result.server_connect_token, "connect-tok")++ def test_launch_command_shape_regressions(self):+ # Two bugs shipped from this one string: pkill -f of our own module name matches+ # the launch command's shell and kills the deploy; and backgrounding a compound+ # command records a wrapper subshell PID so later redeploys kill nothing.+ self._create_runtime(server_url="http://localhost:1")+ self._ensure(reported_version="some-old-version")+ launch = self.sandbox.commands[0]+ self.assertNotRegex(launch, r"pkill[^;&]*[^\[]nb_kernel")+ self.assertIn("echo $! > /tmp/nb_kernel_server.pid", launch)+ # The backgrounded segment must be a single simple command (no cd &&-chain).+ backgrounded = launch.rsplit(";", 1)[-1].split("&")[0]+ self.assertNotIn("&&", backgrounded)+ self.assertIn("nb_kernel.server", backgrounded)++ def test_no_running_runtime_raises(self):+ with self.assertRaises(SQLV2KernelNotRunning):+ self._ensure(reported_version=None)+++class TestSQLV2RunResult(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbres01")++ def _url(self, run_id: str) -> str:+ return f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/runs/{run_id}/"++ def _create_run(self, status, envelope=None, error="") -> NotebookNodeRun:+ with team_scope(self.team.id):+ return NotebookNodeRun.objects.create(+ team=self.team, notebook=self.notebook, node_id="n1", status=status, envelope=envelope, error=error+ )++ @parameterized.expand(+ [+ (NotebookNodeRun.Status.RUNNING, None, "", None, None),+ (NotebookNodeRun.Status.DONE, {"first_page": [[42]]}, "", {"first_page": [[42]]}, None),+ (NotebookNodeRun.Status.FAILED, None, "boom", None, "boom"),+ ]+ )+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_result_shape_by_status(self, status, envelope, error, expected_result, expected_error, _mock_enabled):+ run = self._create_run(status, envelope=envelope, error=error)+ response = self.client.get(self._url(str(run.id)))+ self.assertEqual(response.status_code, 200)+ body = response.json()+ self.assertEqual(body["status"], status)+ # result is only surfaced when done; error only when failed+ self.assertEqual(body["result"], expected_result)+ self.assertEqual(body["error"], expected_error)++ @parameterized.expand([("00000000-0000-0000-0000-000000000000",), ("not-a-uuid",)])+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_missing_or_malformed_run_returns_404(self, run_id, _mock_enabled):+ self.assertEqual(self.client.get(self._url(run_id)).status_code, 404)++ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_run_from_another_notebook_is_not_readable(self, _mock_enabled):+ # IDOR guard: a run belonging to a different notebook in the same team must not be+ # fetchable through this notebook's endpoint, even with a valid run_id.+ other_notebook = Notebook.objects.create(team=self.team, short_id="nbres02")+ with team_scope(self.team.id):+ other_run = NotebookNodeRun.objects.create(+ team=self.team, notebook=other_notebook, node_id="n1", status=NotebookNodeRun.Status.DONE+ )+ self.assertEqual(self.client.get(self._url(str(other_run.id))).status_code, 404)++ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_query_restricted_member_cannot_read_result(self, _mock_enabled):+ # The result envelope is analytics rows, so a query-denied notebook reader must not read them back.+ run = self._create_run(NotebookNodeRun.Status.DONE, envelope={"first_page": [[42]]})+ _restrict_query_access(self)+ self.assertEqual(self.client.get(self._url(str(run.id))).status_code, 403)+++class TestSQLV2Activities(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbact01")++ def _create_run(self) -> NotebookNodeRun:+ with team_scope(self.team.id):+ return NotebookNodeRun.objects.create(+ team=self.team, notebook=self.notebook, node_id="n1", status=NotebookNodeRun.Status.RUNNING+ )++ def _run_input(self, run: NotebookNodeRun) -> SQLV2RunInput:+ return SQLV2RunInput(+ run_id=str(run.id),+ notebook_short_id=self.notebook.short_id,+ team_id=self.team.id,+ user_id=self.user.id,+ code="select 1",+ )++ def _reload(self, run: NotebookNodeRun) -> NotebookNodeRun:+ return NotebookNodeRun.objects.for_team(self.team.id).get(id=run.id)++ def test_dispatch_activity_marks_failed_without_kernel(self):+ run = self._create_run()+ dispatch_sql_v2_run_activity(self._run_input(run))+ self.assertEqual(self._reload(run).status, NotebookNodeRun.Status.FAILED)++ @patch("products.notebooks.backend.sql_v2._server_version")+ @patch("products.notebooks.backend.sql_v2.requests.post")+ def test_dispatch_activity_posts_to_ready_server(self, mock_post, mock_version):+ mock_version.return_value = kernel_package_bytes_and_hash()[1] # server already at the deployed version+ run = self._create_run()+ KernelRuntime.objects.create(+ team=self.team,+ notebook=self.notebook,+ notebook_short_id=self.notebook.short_id,+ user=self.user,+ status=KernelRuntime.Status.RUNNING,+ backend=KernelRuntime.Backend.DOCKER,+ sandbox_id="sbx-1",+ server_url="http://localhost:12345",+ )+ dispatch_sql_v2_run_activity(self._run_input(run))+ mock_post.assert_called_once()+ self.assertIn("/run", mock_post.call_args.args[0])+ payload = mock_post.call_args.kwargs["json"]+ self.assertEqual(payload["code"], "select 1")+ # The kernel needs both legs to complete a run: the data plane to fetch, the callback to report.+ short_id, team_id, _user_id = verify_data_plane_token(payload["data_plane_token"])+ self.assertEqual((short_id, team_id), (self.notebook.short_id, self.team.id))+ self.assertIn("/internal/notebooks/data_plane/query/", payload["data_plane_url"])+ self.assertEqual(self._reload(run).status, NotebookNodeRun.Status.RUNNING)++ def test_mark_failed_activity(self):+ run = self._create_run()+ mark_sql_v2_run_failed_activity(self._run_input(run))+ self.assertEqual(self._reload(run).status, NotebookNodeRun.Status.FAILED)+++class TestSQLV2CommandToken(SimpleTestCase):+ # Backend mints (sql_v2), the in-sandbox kernel verifies (kernel.auth) — this+ # round-trip is the contract that keeps the two HMAC implementations in sync.+ def test_valid_token_verifies(self):+ secret = kernel_server_secret("rt-1")+ self.assertTrue(kernel_auth.verify_command_token(secret, "run-1", mint_command_token(secret, "run-1")))++ @parameterized.expand(+ [+ ("wrong_run_id", lambda s: (s, "run-2", mint_command_token(s, "run-1"))),+ ("wrong_secret", lambda s: (kernel_server_secret("rt-2"), "run-1", mint_command_token(s, "run-1"))),+ ("tampered_signature", lambda s: (s, "run-1", mint_command_token(s, "run-1")[:-1] + "x")),+ ("expired", lambda s: (s, "run-1", mint_command_token(s, "run-1", ttl_seconds=-1))),+ ("garbage", lambda s: (s, "run-1", "not-a-token")),+ ]+ )+ def test_invalid_tokens_rejected(self, _name, make_case):+ verify_secret, run_id, token = make_case(kernel_server_secret("rt-1"))+ self.assertFalse(kernel_auth.verify_command_token(verify_secret, run_id, token))+++class TestSQLV2DataPlaneToken(SimpleTestCase):+ def test_round_trip(self):+ token = mint_data_plane_token("nb123", 7, 42)+ self.assertEqual(verify_data_plane_token(token), ("nb123", 7, 42))++ @parameterized.expand(+ [+ ("tampered", lambda: mint_data_plane_token("nb123", 7, 42)[:-2] + "xx"),+ ("wrong_salt", lambda: mint_callback_token("run-1", 7)),+ ("garbage", lambda: "not-a-token"),+ ]+ )+ def test_invalid_tokens_rejected(self, _name, make_token):+ with self.assertRaises(signing.BadSignature):+ verify_data_plane_token(make_token())+++class TestSQLV2DataPlaneEndpoint(APIBaseTest):+ URL = "/internal/notebooks/data_plane/query/"++ def setUp(self):+ super().setUp()+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbdp001")++ def _post(self, body: dict, token: str | None = None):+ kwargs: dict[str, Any] = {"data": json.dumps(body), "content_type": "application/json"}+ if token is not None:+ kwargs["HTTP_AUTHORIZATION"] = f"Bearer {token}"+ return self.client.post(self.URL, **kwargs)++ def _token(self, short_id: str | None = None) -> str:+ return mint_data_plane_token(short_id or self.notebook.short_id, self.team.id, self.user.id)++ def test_runs_query_and_returns_arrow(self):+ response = self._post({"query": "select 1 as answer"}, token=self._token())+ self.assertEqual(response.status_code, 200, response.content)+ self.assertEqual(response["Content-Type"], "application/vnd.apache.arrow.stream")+ columns, rows, types = decode_arrow_stream(response.content)+ self.assertEqual(columns, ["answer"])+ self.assertEqual(rows, [(1,)])+ # The real ClickHouse type must survive the Arrow round-trip (schema metadata).+ self.assertEqual(types[0][0], "answer")+ self.assertIn("Int", types[0][1])++ def test_outer_limit_and_offset_cap_the_page(self):+ response = self._post({"query": "select number from numbers(10)", "limit": 3, "offset": 2}, token=self._token())+ self.assertEqual(response.status_code, 200, response.content)+ _columns, rows, _types = decode_arrow_stream(response.content)+ self.assertEqual(rows, [(2,), (3,), (4,)])++ def test_hogql_error_is_surfaced(self):+ response = self._post({"query": "select ceci n'est pas une query"}, token=self._token())+ self.assertEqual(response.status_code, 400)+ self.assertTrue(response.json()["error"])++ @parameterized.expand(+ [+ ("missing_token", None, 401),+ ("garbage_token", "not-a-token", 401),+ ]+ )+ def test_rejects_bad_auth(self, _name, token, expected_status):+ response = self._post({"query": "select 1"}, token=token)+ self.assertEqual(response.status_code, expected_status)++ def test_unknown_notebook_returns_404(self):+ response = self._post({"query": "select 1"}, token=self._token(short_id="nope999"))+ self.assertEqual(response.status_code, 404)+++class TestSQLV2KernelServerHTTP(SimpleTestCase):+ # The kernel HTTP layer (routing + command-token auth) has no other CI coverage —+ # it only runs inside the sandbox. Loopback-only, stubbed runner.+ def test_routes_auth_and_dispatch(self):+ from products.notebooks.backend.sandbox.kernel import server as kernel_server++ original_config = dict(kernel_server._config)+ kernel_server._config.update({"secret": "test-secret", "version": "vtest"})+ httpd = ThreadingHTTPServer(("127.0.0.1", 0), kernel_server.KernelServerHandler)+ threading.Thread(target=httpd.serve_forever, daemon=True).start()+ base = f"http://127.0.0.1:{httpd.server_address[1]}"++ def post(path: str, token: str):+ request = urllib.request.Request(+ f"{base}{path}",+ data=json.dumps({"run_id": "run-1"}).encode(),+ headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},+ method="POST",+ )+ return urllib.request.urlopen(request, timeout=5)++ token = mint_command_token("test-secret", "run-1")+ try:+ with urllib.request.urlopen(f"{base}/health", timeout=5) as response:+ self.assertEqual(json.loads(response.read())["version"], "vtest")++ with self.assertRaises(urllib.error.HTTPError) as forged:+ post("/run", token="forged")+ self.assertEqual(forged.exception.code, 401)++ ran = threading.Event()+ with patch.object(kernel_server, "execute_run", side_effect=lambda _p: ran.set()):+ with post("/run", token=token) as response:+ self.assertEqual(response.status, 202)+ self.assertTrue(ran.wait(5)) # the run must execute off the request thread++ with self.assertRaises(urllib.error.HTTPError) as unknown:+ post("/nope", token=token)+ self.assertEqual(unknown.exception.code, 404)+ finally:+ httpd.shutdown()+ httpd.server_close()+ kernel_server._config.clear()+ kernel_server._config.update(original_config)+++class TestSQLV2KernelPackage(SimpleTestCase):+ def test_arrow_contract_round_trip(self):+ # Where backend encoding and kernel decoding actually meet: duplicate column+ # names must survive, a mixed-type column falls back to strings, and the+ # declared HogQL types ride through as schema metadata.+ columns = ["value", "value", "mixed"]+ rows = [(1, "a", 1), (2, "b", "two")]+ types = [["value", "Int64"], ["value", "String"], ["mixed", "String"]]+ decoded_columns, decoded_rows, decoded_types = decode_arrow_stream(_rows_to_arrow_bytes(columns, rows, types))+ self.assertEqual(decoded_columns, columns)+ self.assertEqual(decoded_rows, [(1, "a", "1"), (2, "b", "two")])+ self.assertEqual(decoded_types, types)++ def test_types_fall_back_to_arrow_schema_without_metadata(self):+ columns, rows = ["n", "s"], [(1, "a")]+ _cols, _rows, types = decode_arrow_stream(_rows_to_arrow_bytes(columns, rows))+ self.assertEqual(types, [["n", "Int64"], ["s", "String"]])++ def test_envelope_cells_are_json_safe(self):+ result = kernel_envelope.from_columns_and_rows(+ ["ts", "nan", "blob"],+ [(datetime.datetime(2026, 7, 3, 12, 0), math.nan, b"bytes")],+ )+ json.dumps(result) # a NaN or datetime here would make the callback body unparseable+ self.assertEqual(result["first_page"], [["2026-07-03T12:00:00", None, "bytes"]])+ self.assertEqual(result["row_count"], 1)++ def test_runner_delivers_error_callback_when_fetch_fails(self):+ # A failed fetch must still produce a callback — otherwise the run hangs until the watchdog.+ payload = {+ "run_id": "r1",+ "code": "select 1",+ "callback_url": "http://backend/cb",+ "callback_token": "cbt",+ "data_plane_url": "http://backend/dp",+ "data_plane_token": "dpt",+ }+ delivered = {}+ with (+ patch.object(kernel_runner, "_post_callback", side_effect=lambda url, token, env: delivered.update(env)),+ patch(+ "products.notebooks.backend.sandbox.kernel.data_plane.fetch_query_page",+ side_effect=DataPlaneError("no such table"),+ ),+ ):+ kernel_runner.execute_run(payload)+ self.assertEqual(delivered["status"], "error")+ self.assertEqual(delivered["error"], "no such table")++ def test_tarball_contains_the_package(self):+ package, version = kernel_package_bytes_and_hash()+ with tarfile.open(fileobj=io.BytesIO(package), mode="r:gz") as tar:+ names = tar.getnames()+ self.assertIn("nb_kernel/server.py", names)+ self.assertIn("nb_kernel/__init__.py", names)+ self.assertEqual(len(version), 16)diff --git a/pyproject.toml b/pyproject.tomlindex 1ded7d4aa6a1..e516751b2624 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -576,6 +576,10 @@ ignore_imports = ["products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.presence","products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.python_analysis","products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.query_validation",+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2",+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.sql_v2_serializers",+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.temporal.client",+ "products.notebooks.backend.presentation.views.notebook -> products.notebooks.backend.temporal.sql_v2",# TODO: data_warehouse presentation wave — the structural move landed the viewsets under# presentation/views/ but they still reach in-product internals and sibling products# (warehouse_sources, data_modeling, data_tools, cdp, revenue_analytics, batch_exports)