: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 result paging via the sandbox kernel for NotebooksV2 (#68280)
Sinan Kucukkoselerb329e68d0096
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex bd8f8f6c093d..e550d603f684 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -4940,11 +4940,28 @@ const api = {types?: [string, string][]row_count?: numberfirst_page?: (string | number | null)[][]+ has_more?: boolean} | nullerror: string | null}> {return await new ApiRequest().notebook(notebookId).withAction(`sql_v2/runs/${runId}`).get()},+ async sqlV2RunPage(+ notebookId: NotebookType['short_id'],+ runId: string,+ params: { offset: number; limit: number }+ ): Promise<{+ columns: string[]+ types: [string, string][]+ rows: (string | number | null)[][]+ has_more: boolean+ }> {+ return await new ApiRequest()+ .notebook(notebookId)+ .withAction(`sql_v2/runs/${runId}/page`)+ .withQueryString(params)+ .get()+ },async markdownSave(notebookId: NotebookType['short_id'],data: {diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsxindex 2dd5d58009cd..059171ea9ace 100644--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx@@ -37,6 +37,7 @@ import { LineGraph } from './Components/Charts/LineGraph'import { PieChart } from './Components/Charts/PieChart'import { TwoDimensionalHeatmap } from './Components/Heatmap/TwoDimensionalHeatmap'import { seriesBreakdownLogic } from './Components/seriesBreakdownLogic'+import { SideBar } from './Components/SideBar'import { Table } from './Components/Table'import { TableDisplay } from './Components/TableDisplay'import { AddVariableButton } from './Components/Variables/AddVariableButton'@@ -364,6 +365,14 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX{!props.embedded && <VariablesForInsight />}<div className="flex flex-1 flex-row gap-4">+ {/* The gear above toggles this panel (Series/Display tabs) — same layout the+ SQL editor's OutputPane builds around its own visualization fork. */}+ {!readOnly && showResultControls && isChartSettingsPanelOpen && (+ <>+ <SideBar />+ <LemonDivider vertical className="h-full" />+ </>+ )}<div className="w-full h-full flex-1 overflow-auto">{component}</div></div></div>diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsxindex 15fccfefe6f2..1a4e61de7d3f 100644--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx@@ -13,7 +13,7 @@ import { NotebookNodeAttributeProperties, NotebookNodeProps, NotebookNodeType }import { NotebookDataframeTable } from './components/NotebookDataframeTable'import { NotebookCodeSQLEditorSettings } from './components/NotebookSQLEditor'import { notebookNodeLogic } from './notebookNodeLogic'-import { notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'+import { SQL_V2_DEFAULT_PAGE_SIZE, notebookNodeSQLV2Logic } from './notebookNodeSQLV2Logic'import { NotebookDataframeResult } from './pythonExecution'export type NotebookNodeSQLV2Result = {@@ -21,6 +21,7 @@ export type NotebookNodeSQLV2Result = {types?: [string, string][]row_count: numberfirst_page: (string | number | null)[][]+ has_more?: boolean}export type NotebookNodeSQLV2Attributes = {@@ -31,7 +32,8 @@ export type NotebookNodeSQLV2Attributes = {vizQuery?: DataVisualizationNode | null}-const VIZ_MIN_HEIGHT = 420+// Matches the SQL editor output pane's default so charts land at v1-node size.+const VIZ_MIN_HEIGHT = 350const toDataframeResult = (result: NotebookNodeSQLV2Result): NotebookDataframeResult => {const columns = result.columns ?? []@@ -73,10 +75,24 @@ const Component = ({runId: attributes.runId ?? null,hasResult: !!attributes.result,})- const { isRunning, runError } = useValues(dataLogic)+ const { isRunning, runError, page, pageSize, pageResult, pageLoading, operationBlockReason } = useValues(dataLogic)+ const { setPage, setPageSize } = useActions(dataLogic)const result = attributes.result ?? null- const dataframeResult = useMemo(() => (result ? toDataframeResult(result) : null), [result])+ // Page 1 at the default size comes straight from the envelope; other pages re-query CH.+ const dataframeResult = useMemo(() => {+ if (pageResult) {+ return toDataframeResult({+ columns: pageResult.columns,+ row_count: pageResult.rows.length,+ first_page: pageResult.rows,+ })+ }+ return result ? toDataframeResult(result) : null+ }, [pageResult, result])+ const hasMorePages = pageResult+ ? pageResult.has_more+ : (result?.has_more ?? (result?.first_page ?? []).length >= SQL_V2_DEFAULT_PAGE_SIZE)const cachedResults = useMemo(() => (result ? toCachedResults(result) : null), [result])const activeTab = attributes.outputTab === OutputTab.Visualization ? OutputTab.Visualization : OutputTab.Results@@ -96,9 +112,9 @@ const Component = ({}return (- <div data-attr="notebook-node-sql-v2" className="flex h-full flex-col">+ <div data-attr="notebook-node-sql-v2" className="flex h-full min-h-0 flex-col"><div- className="space-y-3"+ className="flex min-h-0 flex-1 flex-col gap-2"onMouseDown={(event) => event.stopPropagation()}onDragStart={(event) => event.stopPropagation()}>@@ -106,7 +122,7 @@ const Component = ({<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()}>+ <div className="shrink-0 px-2 pt-1" onClick={(event) => event.stopPropagation()}><LemonTabssize="small"activeKey={activeTab}@@ -127,23 +143,38 @@ const Component = ({/></div>{activeTab === OutputTab.Results ? (- <NotebookDataframeTable- result={dataframeResult}- loading={isRunning}- page={1}- pageSize={Math.max(dataframeResult.rows.length, 1)}- onNextPage={() => {}}- onPreviousPage={() => {}}- onPageSizeChange={() => {}}- />+ <div className="min-h-0 flex-1 overflow-y-auto">+ <NotebookDataframeTable+ result={dataframeResult}+ loading={isRunning || pageLoading}+ page={page}+ pageSize={pageSize}+ hasMore={hasMorePages}+ // Serialize page fetches: no new page while one is in flight, a run+ // is replacing this result, or another cell's operation is running.+ paginationDisabledReason={+ pageLoading+ ? 'Fetching page…'+ : isRunning+ ? 'Query is running'+ : (operationBlockReason ?? undefined)+ }+ onNextPage={() => setPage(page + 1)}+ onPreviousPage={() => setPage(page - 1)}+ onPageSizeChange={setPageSize}+ />+ </div>) : (<div- className="px-2 pb-2 flex min-h-0 flex-1 flex-col"+ className="px-2 pb-2 flex min-h-0 flex-1 flex-col overflow-hidden"onClick={(event) => event.stopPropagation()}><Query// Keyed per run so a fresh envelope re-seeds the cached response.- uniqueKey={`${nodeId}-viz-${attributes.runId ?? 'initial'}`}+ // The SQLEditor prefix opts into container-governed chart sizing+ // (dataVisualizationLogic.presetChartHeight) — without it charts+ // render at 60vh, dwarfing the node.+ uniqueKey={`SQLEditor-notebook-sqlv2-${nodeId}-${attributes.runId ?? 'initial'}`}query={vizQuery}setQuery={(query) => {// DataVisualization pushes default settings during its render;@@ -161,7 +192,7 @@ const Component = ({<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">+ <div className="shrink-0 px-2 pb-2 text-[10px] uppercase tracking-wide text-muted select-text">run_id: {attributes.runId}</div>) : null}@@ -185,7 +216,7 @@ const Settings = ({runId: attributes.runId ?? null,hasResult: !!attributes.result,})- const { isRunning } = useValues(dataLogic)+ const { isRunning, operationBlockReason } = useValues(dataLogic)const { runQuery } = useActions(dataLogic)return (@@ -195,6 +226,7 @@ const Settings = ({tabIdSuffix="datav2"onRunQuery={(code) => runQuery(code)}runQueryLoading={isRunning}+ runQueryDisabledReason={operationBlockReason ?? undefined}runQueryTooltip="Run SQL (v2) query"/>)diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookDataframeTable.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookDataframeTable.tsxindex 2322a09907b3..850a005ed197 100644--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookDataframeTable.tsx+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookDataframeTable.tsx@@ -11,6 +11,11 @@ type NotebookDataframeTableProps = {loading: booleanpage: numberpageSize: number+ /** Unknown-total mode: when set, Next is driven by this flag and no total is shown+ * (push-to-CH paging can't know the full count without an extra query). */+ hasMore?: boolean+ /** Disables all pagination controls, e.g. while a page fetch is already in flight. */+ paginationDisabledReason?: stringonNextPage: () => voidonPreviousPage: () => voidonPageSizeChange: (pageSize: number) => void@@ -40,6 +45,8 @@ export const NotebookDataframeTable = ({loading,page,pageSize,+ hasMore,+ paginationDisabledReason,onNextPage,onPreviousPage,onPageSizeChange,@@ -65,11 +72,19 @@ export const NotebookDataframeTable = ({)}, [page, pageSize, result?.rows])+ const isUnknownTotal = hasMore !== undefinedconst rowCount = result?.rowCount ?? 0- const startIndex = rowCount > 0 ? (page - 1) * pageSize + 1 : 0- const endIndex = rowCount > 0 ? Math.min(page * pageSize, rowCount) : 0+ const rowsShown = result?.rows.length ?? 0+ const startIndex = rowsShown > 0 ? (page - 1) * pageSize + 1 : 0+ const endIndex = isUnknownTotal+ ? rowsShown > 0+ ? startIndex + rowsShown - 1+ : 0+ : rowCount > 0+ ? Math.min(page * pageSize, rowCount)+ : 0const hasPrevious = page > 1- const hasNext = endIndex < rowCount+ const hasNext = isUnknownTotal ? !!hasMore : endIndex < rowCountconst isInitialLoading = loading && rowCount === 0const emptyState = isInitialLoading ? (<div className="flex items-center justify-center gap-2 py-6 text-xs text-muted">@@ -101,6 +116,7 @@ export const NotebookDataframeTable = ({size="small"value={pageSize}onChange={(value) => onPageSizeChange(value ?? pageSize)}+ disabledReason={paginationDisabledReason}options={PAGE_SIZE_OPTIONS.map((option) => ({label: option.toString(),value: option,@@ -108,18 +124,26 @@ export const NotebookDataframeTable = ({/></div><div className="flex items-center gap-2 pr-2">- <span>{rowCount === 0 ? 'No rows' : `${startIndex}-${endIndex} of ${rowCount}`}</span>+ <span>+ {isUnknownTotal+ ? rowsShown === 0+ ? 'No rows'+ : `${startIndex}-${endIndex}`+ : rowCount === 0+ ? 'No rows'+ : `${startIndex}-${endIndex} of ${rowCount}`}+ </span><LemonButtonsize="small"onClick={onPreviousPage}- disabledReason={hasPrevious ? undefined : 'No previous page'}+ disabledReason={paginationDisabledReason ?? (hasPrevious ? undefined : 'No previous page')}>Prev</LemonButton><LemonButtonsize="small"onClick={onNextPage}- disabledReason={hasNext ? undefined : 'No next page'}+ disabledReason={paginationDisabledReason ?? (hasNext ? undefined : 'No next page')}>Next</LemonButton>diff --git a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsxindex e01983f21fc8..33e01d10cbb0 100644--- a/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx+++ b/frontend/src/scenes/notebooks/Nodes/components/NotebookSQLEditor.tsx@@ -411,7 +411,8 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string }>({[attributes.nodeId, tabIdSuffix])useNotebookCodeSQLEditorSync({ attributes, updateAttributes, tabId })- const { queryInput } = useValues(sqlEditorLogic({ tabId, mode: SQLEditorMode.Embedded }))+ const editorLogic = sqlEditorLogic({ tabId, mode: SQLEditorMode.Embedded })+ const { queryInput } = useValues(editorLogic)// 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@@ -436,7 +437,18 @@ export function NotebookCodeSQLEditorSettings<T extends { code: string }>({panel={SQLEditorPanel.Query}defaultShowDatabaseTree={false}autoFocusQueryPane={autoFocusQueryPane}- onRunQuery={onRunQuery ? () => onRunQuery(liveCode) : undefined}+ // Read the editor's current text imperatively at run time. The Cmd+Enter keybinding+ // fires a stale closure (and Monaco's keybinding value can come through empty), so a+ // captured `liveCode` would run the previous query. The mounted logic's `queryInput`+ // is the same source the Run button uses; fall back to `liveCode` before first sync.+ onRunQuery={+ onRunQuery+ ? () => {+ const current = editorLogic.values.queryInput+ onRunQuery(typeof current === 'string' && current.trim() ? current : 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.tsindex 79165d294c01..9812e0bb3169 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts@@ -53,13 +53,13 @@ describe('notebookNodeSQLV2Logic', () => {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 },+ result: { columns: ['a'], first_page: [[1]], row_count: 1, has_more: false },error: null,})mount({ runId: 'r1', hasResult: false })await expectLogic(logic).toFinishAllListeners()expect(updateAttributes).toHaveBeenCalledWith({- result: { columns: ['a'], types: [], row_count: 1, first_page: [[1]] },+ result: { columns: ['a'], types: [], row_count: 1, first_page: [[1]], has_more: false },})expect(logic.values.isRunning).toBe(false)})@@ -90,4 +90,120 @@ describe('notebookNodeSQLV2Logic', () => {await expectLogic(logic).toFinishAllListeners()expect(resultSpy).not.toHaveBeenCalled()})++ it('a second sequential run replaces the first run result', async () => {+ resultSpy.mockImplementation((_s: string, runId: string) =>+ Promise.resolve(+ runId === 'r1'+ ? { status: 'done', result: { columns: ['a'], first_page: [[1]], row_count: 1 }, error: null }+ : { status: 'done', result: { columns: ['b'], first_page: [[2]], row_count: 1 }, error: null }+ )+ )+ mount()+ logic.actions.runQuery('select 1')+ await expectLogic(logic).toFinishAllListeners()+ runSpy.mockResolvedValueOnce({ run_id: 'r2' })+ logic.actions.runQuery('select 2')+ await expectLogic(logic).toFinishAllListeners()+ const resultWrites = updateAttributes.mock.calls.map((c) => c[0]).filter((a) => a.result)+ expect(resultWrites.at(-1).result).toEqual(expect.objectContaining({ columns: ['b'], first_page: [[2]] }))+ })++ it('ignores a stale poll from a previous run', async () => {+ // r1's poll stays in flight until we resolve it — after r2 has become the active run.+ let resolveR1: (value: unknown) => void = () => {}+ const r1Poll = new Promise((resolve) => {+ resolveR1 = resolve+ })+ resultSpy.mockImplementation((_shortId: string, runId: string) =>+ runId === 'r1' ? r1Poll : Promise.resolve({ status: 'running', result: null, error: null })+ )+ runSpy.mockResolvedValue({ run_id: 'r2' })++ // afterMount starts polling r1; wait until its poll is actually in flight.+ mount({ runId: 'r1', hasResult: false })+ await expectLogic(logic).toDispatchActions(['startPolling', 'pollResult'])++ // Start a new run while r1's poll is still pending — r2 becomes the active run.+ logic.actions.runQuery('select 2')+ await expectLogic(logic).toDispatchActions(['runQuery', 'startPolling'])++ // r1's stale poll now resolves with the OLD query's result.+ resolveR1({+ status: 'done',+ result: { columns: ['old'], first_page: [[1]], row_count: 1, has_more: false },+ error: null,+ })+ await expectLogic(logic).toFinishAllListeners()++ // The stale result must not overwrite the node, and r2's run must keep polling (not stopped).+ expect(updateAttributes).not.toHaveBeenCalledWith(+ expect.objectContaining({ result: expect.objectContaining({ columns: ['old'] }) })+ )+ expect(logic.values.isRunning).toBe(true)+ })++ it('blocks a second node while another node has a run in flight', async () => {+ // Default resultSpy keeps r1 'running', so the notebook stays busy after n1 dispatches.+ mount()+ const other = notebookNodeSQLV2Logic({ nodeId: 'n2', notebookShortId: 'nb1', updateAttributes })+ other.mount()+ logic.actions.runQuery('select 1')+ await expectLogic(logic).toFinishAllListeners()+ other.actions.runQuery('select 2')+ await expectLogic(other).toFinishAllListeners()+ expect(runSpy).toHaveBeenCalledTimes(1)+ expect(other.values.isRunning).toBe(false)+ expect(other.values.operationBlockReason).toBeTruthy()+ other.unmount()+ })++ it('blocks page fetches while another node is busy', async () => {+ const pageSpy = jest.spyOn(api.notebooks, 'sqlV2RunPage')+ mount()+ logic.actions.runQuery('select 1')+ await expectLogic(logic).toFinishAllListeners()+ const other = notebookNodeSQLV2Logic({+ nodeId: 'n2',+ notebookShortId: 'nb1',+ updateAttributes,+ runId: 'r9',+ hasResult: true,+ })+ other.mount()+ other.actions.setPage(2)+ await expectLogic(other).toFinishAllListeners()+ expect(pageSpy).not.toHaveBeenCalled()+ other.unmount()+ })++ it('releases the notebook when a run finishes so the next run can proceed', async () => {+ resultSpy.mockResolvedValue({+ status: 'done',+ result: { columns: ['a'], first_page: [[1]], row_count: 1 },+ error: null,+ })+ mount()+ const other = notebookNodeSQLV2Logic({ nodeId: 'n2', notebookShortId: 'nb1', updateAttributes })+ other.mount()+ logic.actions.runQuery('select 1')+ await expectLogic(logic).toFinishAllListeners()+ other.actions.runQuery('select 2')+ await expectLogic(other).toFinishAllListeners()+ expect(runSpy).toHaveBeenCalledTimes(2)+ other.unmount()+ })++ it('unmounting a busy node releases the notebook', async () => {+ mount()+ logic.actions.runQuery('select 1')+ await expectLogic(logic).toFinishAllListeners()+ logic.unmount()+ const other = notebookNodeSQLV2Logic({ nodeId: 'n2', notebookShortId: 'nb1', updateAttributes })+ other.mount()+ logic = other // afterEach unmounts this one; n1 is already unmounted+ other.actions.runQuery('select 2')+ await expectLogic(other).toFinishAllListeners()+ expect(runSpy).toHaveBeenCalledTimes(2)+ })})diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.tsindex 81e3a91202a3..0c745b18cf9d 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts@@ -1,13 +1,24 @@-import { actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'+import { actions, afterMount, beforeUnmount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import api from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { NotebookOperation, notebookOperationsLogic } from '../Notebook/notebookOperationsLogic'import { NotebookNodeSQLV2Result } from './NotebookNodeSQLV2'import type { notebookNodeSQLV2LogicType } from './notebookNodeSQLV2LogicType'const POLL_INTERVAL_MS = 1000const MAX_POLL_ATTEMPTS = 150 // ~2.5 minutes at 1s+export const SQL_V2_DEFAULT_PAGE_SIZE = 50++export type NotebookNodeSQLV2Page = {+ columns: string[]+ types: [string, string][]+ rows: (string | number | null)[][]+ has_more: boolean+}+export interface NotebookNodeSQLV2LogicProps {nodeId: stringnotebookShortId: string@@ -21,6 +32,13 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([path((key) => ['scenes', 'notebooks', 'Nodes', 'notebookNodeSQLV2Logic', key]),props({} as NotebookNodeSQLV2LogicProps),key((props) => props.nodeId),+ connect((props: NotebookNodeSQLV2LogicProps) => ({+ values: [notebookOperationsLogic({ shortId: props.notebookShortId }), ['activeOperation', 'isBusy']],+ actions: [+ notebookOperationsLogic({ shortId: props.notebookShortId }),+ ['startOperation', 'finishOperation', 'finishNodeOperations'],+ ],+ })),actions({runQuery: (code: string) => ({ code }),startPolling: (runId: string) => ({ runId }),@@ -28,6 +46,11 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([stopPolling: true,setIsRunning: (isRunning: boolean) => ({ isRunning }),setRunError: (runError: string | null) => ({ runError }),+ setPage: (page: number) => ({ page }),+ setPageSize: (pageSize: number) => ({ pageSize }),+ setPageResult: (pageResult: NotebookNodeSQLV2Page | null) => ({ pageResult }),+ setPageLoading: (pageLoading: boolean) => ({ pageLoading }),+ resetPaging: true,}),reducers({// Tracks the run being in progress; driven by the run's status, not a socket lifecycle.@@ -47,76 +70,204 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([setRunError: (_, { runError }) => runError,},],+ page: [+ 1,+ {+ setPage: (_, { page }) => Math.max(1, page),+ setPageSize: () => 1,+ resetPaging: () => 1,+ runQuery: () => 1,+ },+ ],+ pageSize: [+ SQL_V2_DEFAULT_PAGE_SIZE as number,+ {+ setPageSize: (_, { pageSize }) => pageSize,+ resetPaging: () => SQL_V2_DEFAULT_PAGE_SIZE,+ },+ ],+ // Rows fetched for the current page; null means "show the envelope's first page".+ pageResult: [+ null as NotebookNodeSQLV2Page | null,+ {+ setPageResult: (_, { pageResult }) => pageResult,+ resetPaging: () => null,+ runQuery: () => null,+ },+ ],+ pageLoading: [+ false,+ {+ setPageLoading: (_, { pageLoading }) => pageLoading,+ resetPaging: () => false,+ },+ ],}),- listeners(({ props, actions, cache }) => ({- runQuery: async ({ code }) => {- if (!code.trim()) {- actions.setRunError('Query is empty — type some HogQL first.')- actions.setIsRunning(false)+ listeners(({ props, actions, cache, values }) => {+ // One operation at a time across the whole notebook (see notebookOperationsLogic);+ // ids are per node + kind so re-registering our own operation stays idempotent.+ const runOperation: NotebookOperation = { id: `${props.nodeId}:run`, nodeId: props.nodeId, kind: 'run' }+ const pageOperation: NotebookOperation = { id: `${props.nodeId}:page`, nodeId: props.nodeId, kind: 'page' }++ const loadCurrentPage = async (): Promise<void> => {+ const { page, pageSize } = values+ const runId = props.runId+ if (!runId) {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) {+ if (page === 1 && pageSize === SQL_V2_DEFAULT_PAGE_SIZE) {+ // The envelope already carries this page — no round trip.+ actions.setPageResult(null)return}- cache.pollAttempts = (cache.pollAttempts ?? 0) + 1- if (cache.pollAttempts > MAX_POLL_ATTEMPTS) {- actions.setRunError('Timed out waiting for result')- actions.stopPolling()+ // The pagination UI is disabled while the notebook is busy; this guards the+ // programmatic path. A same-node re-page supersedes (stale response discarded below).+ if (values.isBusy && values.activeOperation?.id !== pageOperation.id) {+ lemonToast.info('Another operation is running in this notebook — wait for it to finish.')+ actions.resetPaging()return}- cache.pollInFlight = true+ actions.startOperation(pageOperation)+ const fetchId = (cache.pageFetchId = (cache.pageFetchId ?? 0) + 1)+ actions.setPageLoading(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,+ const pageResult = await api.notebooks.sqlV2RunPage(props.notebookShortId, runId, {+ offset: (page - 1) * pageSize,+ limit: pageSize,+ })+ if (cache.pageFetchId === fetchId) {+ actions.setPageResult(pageResult)+ }+ } catch (error: any) {+ if (cache.pageFetchId !== fetchId) {+ return+ }+ if (error?.status === 409) {+ lemonToast.info('This result was replaced by a newer run — showing the latest first page.')+ } else {+ lemonToast.error(error?.detail || error?.message || 'Failed to fetch page')+ }+ // Either way the requested page never arrived — fall back to the envelope's+ // first page rather than showing old rows under a new page number.+ actions.resetPaging()+ } finally {+ // A superseding fetch re-registered the same operation id — leave the release to it.+ if (cache.pageFetchId === fetchId) {+ actions.setPageLoading(false)+ actions.finishOperation(pageOperation.id)+ }+ }+ }++ return {+ setPage: loadCurrentPage,+ setPageSize: loadCurrentPage,+ runQuery: async ({ code }) => {+ if (!code.trim()) {+ actions.setRunError('Query is empty — type some HogQL first.')+ actions.setIsRunning(false)+ return+ }+ // The run button is disabled while the notebook is busy; this guards Cmd+Enter+ // and programmatic dispatch. Re-running our own node supersedes as before.+ if (values.isBusy && values.activeOperation?.nodeId !== props.nodeId) {+ lemonToast.info('Another operation is running in this notebook — wait for it to finish.')+ actions.setIsRunning(false)+ return+ }+ actions.startOperation(runOperation)+ try {+ const { run_id } = await api.notebooks.sqlV2Run(props.notebookShortId, {+ node_id: props.nodeId,+ code,})+ // Mark this as the active run so a still-in-flight poll from a previous run+ // can't overwrite this result or stop this run's poller once it resolves.+ cache.activeRunId = run_id+ 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)+ actions.finishOperation(runOperation.id)+ }+ },+ startPolling: ({ runId }) => {+ // Idempotent re-register: also covers a remount resuming a persisted in-flight run.+ actions.startOperation(runOperation)+ cache.activeRunId = 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()- } else if (status === 'failed') {- actions.setRunError(error ?? 'Run failed')+ return+ }+ cache.pollInFlight = true+ try {+ const { status, result, error } = await api.notebooks.sqlV2RunResult(props.notebookShortId, runId)+ // A newer run started while this poll was in flight — its result and poller+ // must win, so drop this stale response instead of overwriting/stopping it.+ if (runId !== cache.activeRunId) {+ return+ }+ if (status === 'done') {+ props.updateAttributes({+ result: result+ ? {+ columns: result.columns ?? [],+ types: result.types ?? [],+ row_count: result.row_count ?? 0,+ first_page: result.first_page ?? [],+ has_more: result.has_more ?? false,+ }+ : null,+ })+ // A fresh envelope replaces whatever page the user had drilled into.+ actions.resetPaging()+ actions.stopPolling()+ } else if (status === 'failed') {+ actions.setRunError(error ?? 'Run failed')+ actions.stopPolling()+ }+ // 'running' → keep polling+ } catch (error) {+ if (runId !== cache.activeRunId) {+ return+ }+ actions.setRunError(error instanceof Error ? error.message : 'Failed to fetch result')actions.stopPolling()+ } finally {+ cache.pollInFlight = false}- // '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)- },+ },+ stopPolling: () => {+ cache.disposables.dispose('pollResult')+ actions.setIsRunning(false)+ actions.finishOperation(runOperation.id)+ },+ }+ }),+ selectors(({ props }) => ({+ // Set while another node's operation is in flight — wire into disabledReason props.+ operationBlockReason: [+ (s) => [s.activeOperation],+ (activeOperation): string | null =>+ activeOperation && activeOperation.nodeId !== props.nodeId+ ? 'Another operation is running in this notebook'+ : null,+ ],})),afterMount(({ props, actions }) => {// Recover after a reload/remount: a persisted runId with no result means the run may still be@@ -125,4 +276,8 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([actions.startPolling(props.runId)}}),+ beforeUnmount(({ props, actions }) => {+ // A deleted or unmounted cell must never leave the notebook wedged as busy.+ actions.finishNodeOperations(props.nodeId)+ }),])diff --git a/frontend/src/scenes/notebooks/Notebook/notebookOperationsLogic.ts b/frontend/src/scenes/notebooks/Notebook/notebookOperationsLogic.tsnew file mode 100644index 000000000000..284d4592f48d--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/notebookOperationsLogic.ts@@ -0,0 +1,60 @@+import { actions, kea, key, path, props, reducers, selectors } from 'kea'++import type { notebookOperationsLogicType } from './notebookOperationsLogicType'++export interface NotebookOperationsLogicProps {+ shortId: string+}++export type NotebookOperation = {+ /** Unique per operation, e.g. `${nodeId}:run` — re-registering the same id is idempotent. */+ id: string+ nodeId: string+ kind: 'run' | 'page'+}++/**+ * Notebook-wide registry of in-flight data operations (query runs, page fetches).+ *+ * One operation at a time per notebook: node logics register on start and release on every+ * terminal path, and gate their own actions on `isBusy` so a user can't stack operations+ * across cells. Client-local UX only — collaborators and other tabs are not serialized;+ * server-side guards remain the real enforcement.+ */+export const notebookOperationsLogic = kea<notebookOperationsLogicType>([+ path((key) => ['scenes', 'notebooks', 'Notebook', 'notebookOperationsLogic', key]),+ props({} as NotebookOperationsLogicProps),+ key((props) => props.shortId),+ actions({+ startOperation: (operation: NotebookOperation) => ({ operation }),+ finishOperation: (id: string) => ({ id }),+ // Sweep for unmount/delete of a node: a removed cell must never wedge the notebook.+ finishNodeOperations: (nodeId: string) => ({ nodeId }),+ }),+ reducers({+ operations: [+ {} as Record<string, NotebookOperation>,+ {+ startOperation: (state, { operation }) => ({ ...state, [operation.id]: operation }),+ finishOperation: (state, { id }) => {+ if (!(id in state)) {+ return state+ }+ const next = { ...state }+ delete next[id]+ return next+ },+ finishNodeOperations: (state, { nodeId }) =>+ Object.fromEntries(Object.entries(state).filter(([, operation]) => operation.nodeId !== nodeId)),+ },+ ],+ }),+ selectors({+ activeOperation: [+ (s) => [s.operations],+ (operations: Record<string, NotebookOperation>): NotebookOperation | null =>+ Object.values(operations)[0] ?? null,+ ],+ isBusy: [(s) => [s.operations], (operations): boolean => Object.keys(operations).length > 0],+ }),+])diff --git a/posthog/urls.py b/posthog/urls.pyindex 115b13f4ec9e..41f2504051da 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -52,7 +52,11 @@ 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_plane+from products.notebooks.backend.facade.sql_v2 import (+ notebook_sql_v2_callback,+ notebook_sql_v2_data_plane,+ notebook_sql_v2_data_plane_status,+)from 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@@ -463,6 +467,10 @@ urlpatterns = ["internal/notebooks/data_plane/query/",csrf_exempt(notebook_sql_v2_data_plane),),+ path(+ "internal/notebooks/data_plane/query/<str:query_id>/",+ csrf_exempt(notebook_sql_v2_data_plane_status),+ ),# 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.pyindex d58550bcdc06..678658d0d286 100644--- a/products/notebooks/backend/facade/sql_v2.py+++ b/products/notebooks/backend/facade/sql_v2.py@@ -7,4 +7,7 @@ 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_plane+from ..sql_v2_data_plane import (+ notebook_sql_v2_data_plane as notebook_sql_v2_data_plane,+ notebook_sql_v2_data_plane_status as notebook_sql_v2_data_plane_status,+)diff --git a/products/notebooks/backend/migrations/0009_notebooknoderun_code.py b/products/notebooks/backend/migrations/0009_notebooknoderun_code.pynew file mode 100644index 000000000000..b3266597763a--- /dev/null+++ b/products/notebooks/backend/migrations/0009_notebooknoderun_code.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-07-03 13:35++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notebooks", "0008_kernelruntime_server_connect_token_and_more"),+ ]++ operations = [+ migrations.AddField(+ model_name="notebooknoderun",+ name="code",+ field=models.TextField(blank=True, default=""),+ ),+ ]diff --git a/products/notebooks/backend/migrations/max_migration.txt b/products/notebooks/backend/migrations/max_migration.txtindex df39697e3bba..a346e0e0095f 100644--- a/products/notebooks/backend/migrations/max_migration.txt+++ b/products/notebooks/backend/migrations/max_migration.txt@@ -1 +1 @@-0008_kernelruntime_server_connect_token_and_more+0009_notebooknoderun_codediff --git a/products/notebooks/backend/models.py b/products/notebooks/backend/models.pyindex 48af7af7b9c7..ed6decba3f95 100644--- a/products/notebooks/backend/models.py+++ b/products/notebooks/backend/models.py@@ -196,6 +196,9 @@ class NotebookNodeRun(TeamScopedRootMixin, UUIDModel):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)+ # The node's code at run time — paging must re-query what produced the result,+ # not whatever the editor holds now.+ code = models.TextField(blank=True, default="")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)diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.pyindex c278464f701b..0e1692424637 100644--- a/products/notebooks/backend/presentation/views/notebook.py+++ b/products/notebooks/backend/presentation/views/notebook.py@@ -4,6 +4,7 @@ from datetime import timedeltafrom typing import Any, castfrom django.conf import settings+from django.core.cache import cachefrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db import transactionfrom django.db.models import Q, QuerySet@@ -52,8 +53,18 @@ from products.notebooks.backend.kernel_runtime import build_notebook_sandbox_confrom 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.sql_v2 import (+ PAGE_LOCK_TTL_SECONDS,+ SQLV2KernelNotRunning,+ SQLV2PageError,+ fetch_sql_v2_page,+ is_sql_v2_enabled,+ sql_v2_page_lock_key,+)+from products.notebooks.backend.sql_v2_serializers import (+ NotebookSQLV2PageRequestSerializer,+ NotebookSQLV2RunRequestSerializer,+)from products.notebooks.backend.temporal.client import start_sql_v2_run_workflowfrom products.notebooks.backend.temporal.sql_v2 import SQLV2RunInputfrom products.tasks.backend.facade.exceptions import SandboxProvisionError@@ -912,6 +923,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDteam_id=self.team_id,notebook=notebook,node_id=serializer.validated_data["node_id"],+ code=serializer.validated_data["code"],status=NotebookNodeRun.Status.RUNNING,)@@ -969,6 +981,86 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD})+ @extend_schema(exclude=True)+ @action(+ methods=["GET"],+ url_path="sql_v2/runs/(?P<run_id>[^/.]+)/page",+ detail=True,+ required_scopes=["notebook:read", "query:read"],+ )+ def sql_v2_run_page(self, request: Request, run_id: str | None = None, **kwargs):+ # A page fetch is not a run (see sql_v2_result_delivery.md): a bounded synchronous+ # re-query of the run's code with LIMIT/OFFSET, proxied through the running kernel.+ user = self._current_user()+ if not (settings.DEBUG or is_sql_v2_enabled(user)) or run_id is None:+ raise Http404()++ serializer = NotebookSQLV2PageRequestSerializer(data=request.query_params)+ serializer.is_valid(raise_exception=True)+ notebook = self._get_notebook_for_kernel()+ # Paging re-queries ClickHouse and returns analytics rows, so gate it on query access+ # too — a notebook editor whose query access is denied must not read rows through it.+ 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()+ if run.status != NotebookNodeRun.Status.DONE:+ return Response({"detail": "Run has no result to page."}, status=400)++ # Stale run: the node produced a newer result since — the client must reload from+ # the new envelope rather than mix pages from two executions.+ is_stale = (+ NotebookNodeRun.objects.for_team(self.team_id)+ .filter(+ notebook=notebook,+ node_id=run.node_id,+ status=NotebookNodeRun.Status.DONE,+ created_at__gt=run.created_at,+ )+ .exists()+ )+ if is_stale:+ return Response({"detail": "stale"}, status=409)++ # Runs recorded before the code column existed (default "") have no query to page.+ # Send that to the kernel and it round-trips into an opaque "page fetch failed"; catch+ # it here with guidance instead.+ if not run.code.strip():+ return Response(+ {"detail": "This result predates page support — re-run the query to page through it."},+ status=400,+ )++ # An out-of-cache page holds this worker synchronously for up to the kernel timeout,+ # so cap each user at one in-flight page fetch — otherwise parallel paging requests+ # could occupy many web workers at once.+ lock_key = sql_v2_page_lock_key(self.team_id, user.id if isinstance(user, User) else None)+ if not cache.add(lock_key, True, timeout=PAGE_LOCK_TTL_SECONDS):+ return Response({"detail": "Another page fetch is already in progress — try again shortly."}, status=429)+ try:+ page = fetch_sql_v2_page(+ notebook,+ user if isinstance(user, User) else None,+ run,+ offset=serializer.validated_data["offset"],+ limit=serializer.validated_data["limit"],+ )+ except SQLV2KernelNotRunning:+ return Response({"detail": "Kernel is not running. Re-run the query first."}, status=503)+ except SQLV2PageError as e:+ return Response({"detail": str(e)}, status=400)+ except Exception:+ logger.exception("notebook_sql_v2_page_failed", notebook_short_id=notebook.short_id)+ return Response({"detail": "Failed to fetch page."}, status=503)+ finally:+ cache.delete(lock_key)++ return Response(page)+@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/data_plane.py b/products/notebooks/backend/sandbox/kernel/data_plane.pyindex 5082f99b5192..eb6443e6ca31 100644--- a/products/notebooks/backend/sandbox/kernel/data_plane.py+++ b/products/notebooks/backend/sandbox/kernel/data_plane.py@@ -1,18 +1,26 @@"""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).+run-scoped data-plane token), which enqueues it on the backend's async query+manager and returns a query_id; this client then polls the status endpoint until+the rows come back as an Arrow stream. No backend web worker waits on ClickHouse+— and this thread is the kernel's own, invisible to the user. Uses urllib so the+only third-party dependency is pyarrow (present in the sandbox image)."""import json+import timeimport urllib.errorimport urllib.requestfrom typing import Anyimport pyarrow as pa-_REQUEST_TIMEOUT_SECONDS = 120+_REQUEST_TIMEOUT_SECONDS = 30+# Total budget for one query: enqueue + Celery pickup + ClickHouse execution.+_POLL_DEADLINE_SECONDS = 180+_POLL_INITIAL_INTERVAL_SECONDS = 0.3+_POLL_MAX_INTERVAL_SECONDS = 2.0class DataPlaneError(Exception):@@ -33,7 +41,10 @@ def fetch_query_page(# 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-detectedwith urllib.request.urlopen(request, timeout=_REQUEST_TIMEOUT_SECONDS) as response:- return decode_arrow_stream(response)+ if _is_arrow(response):+ # A pre-async-manager backend answers the POST with the rows directly.+ return decode_arrow_stream(response)+ body = json.loads(response.read() or b"{}")except urllib.error.HTTPError as exc:raise DataPlaneError(_error_detail(exc)) from excexcept urllib.error.URLError as exc:@@ -41,6 +52,38 @@ def fetch_query_page(except pa.ArrowInvalid as exc:raise DataPlaneError(f"Invalid Arrow response from the data plane: {exc}") from exc+ query_id = body.get("query_id")+ if not query_id:+ raise DataPlaneError("Data plane did not accept the query")+ return _poll_for_result(f"{url.rstrip('/')}/{query_id}/", token)+++def _poll_for_result(status_url: str, token: str) -> tuple[list[str], list[tuple[Any, ...]], list[list[str]]]:+ request = urllib.request.Request(status_url, headers={"Authorization": f"Bearer {token}"}, method="GET")+ deadline = time.monotonic() + _POLL_DEADLINE_SECONDS+ interval = _POLL_INITIAL_INTERVAL_SECONDS+ while time.monotonic() < deadline:+ try:+ # status_url is the backend's own data-plane endpoint from the signed run payload, not user input.+ # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected+ with urllib.request.urlopen(request, timeout=_REQUEST_TIMEOUT_SECONDS) as response:+ if _is_arrow(response):+ return decode_arrow_stream(response)+ # 202 — still running.+ 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+ time.sleep(interval)+ interval = min(interval * 1.5, _POLL_MAX_INTERVAL_SECONDS)+ raise DataPlaneError("Timed out waiting for the query to finish")+++def _is_arrow(response: Any) -> bool:+ return "arrow" in (response.headers.get("Content-Type") or "")+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).diff --git a/products/notebooks/backend/sandbox/kernel/envelope.py b/products/notebooks/backend/sandbox/kernel/envelope.pyindex f8b87106aa4b..7d3c09240df7 100644--- a/products/notebooks/backend/sandbox/kernel/envelope.py+++ b/products/notebooks/backend/sandbox/kernel/envelope.py@@ -28,15 +28,23 @@ def _json_cell(value: Any) -> Any:return str(value)+def json_safe_rows(rows: list[tuple[Any, ...]]) -> list[list[Any]]:+ return [[_json_cell(cell) for cell in row] for row in rows]++def from_columns_and_rows(- columns: list[str], rows: list[tuple[Any, ...]], types: list[list[str]] | None = None+ columns: list[str],+ rows: list[tuple[Any, ...]],+ types: list[list[str]] | None = None,+ has_more: bool = False,) -> 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],+ "first_page": json_safe_rows(rows),+ "has_more": has_more,"result_id": str(uuid.uuid4()),}diff --git a/products/notebooks/backend/sandbox/kernel/runner.py b/products/notebooks/backend/sandbox/kernel/runner.pyindex 25131b665998..2ab3bda5e822 100644--- a/products/notebooks/backend/sandbox/kernel/runner.py+++ b/products/notebooks/backend/sandbox/kernel/runner.py@@ -1,14 +1,23 @@"""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+For the current Journey 1/2 scope every node is a pure-HogQL display node, so a+run is a capped fetch through the data plane — the ipykernel is not involved(see sql_v2_kernel_architecture.md, "division of labor").++A run fetches up to `cache_limit` rows in one ClickHouse query and keeps them in+an in-memory per-run cache; `/page` requests within the cache are local slices+(no ClickHouse work, no held backend workers). Only paging beyond the cache — or+after a kernel restart emptied it — re-queries the data plane with LIMIT/OFFSET.+This is the capped, memory-resident precursor of the file-backed result store in+sql_v2_kernel_architecture.md."""import jsonimport logging+import threadingimport urllib.errorimport urllib.request+from collections import OrderedDictfrom typing import Anyfrom . import envelope@@ -17,6 +26,13 @@ logger = logging.getLogger(__name__)_CALLBACK_TIMEOUT_SECONDS = 15_DEFAULT_PAGE_LIMIT = 50+_DEFAULT_CACHE_LIMIT = 300+_MAX_CACHED_RESULTS = 20++# run_id -> {columns, types, rows (json-safe), complete}; complete means the cache+# holds the query's entire result, not just the first cache_limit rows.+_result_cache: OrderedDict[str, dict[str, Any]] = OrderedDict()+_result_cache_lock = threading.Lock()def execute_run(payload: dict[str, Any]) -> None:@@ -25,25 +41,97 @@ def execute_run(payload: dict[str, Any]) -> None:_post_callback(payload["callback_url"], payload["callback_token"], result)-def _build_envelope(payload: dict[str, Any]) -> dict[str, Any]:+def _fetch_capped_page(payload: dict[str, Any], limit: int, offset: int) -> dict[str, Any]:+ """Fetch limit+1 rows through the data plane; the extra row only signals has_more."""# Deferred so a broken pyarrow install degrades to a per-run error envelope# instead of preventing the server from starting.from . import data_plane # noqa: PLC0415+ columns, rows, types = data_plane.fetch_query_page(+ payload["data_plane_url"],+ payload["data_plane_token"],+ payload["code"],+ limit=limit + 1,+ offset=offset,+ )+ has_more = len(rows) > limit+ return {"columns": columns, "rows": rows[:limit], "types": types, "has_more": has_more}+++def _cache_result(+ run_id: str, columns: list[str], types: list[list[str]], rows: list[list[Any]], complete: bool+) -> None:+ with _result_cache_lock:+ _result_cache[run_id] = {"columns": columns, "types": types, "rows": rows, "complete": complete}+ _result_cache.move_to_end(run_id)+ while len(_result_cache) > _MAX_CACHED_RESULTS:+ _result_cache.popitem(last=False)+++def _cached_page(run_id: str, offset: int, limit: int) -> dict[str, Any] | None:+ """Slice a page out of the cached result, or None if the cache can't serve it."""+ with _result_cache_lock:+ entry = _result_cache.get(run_id)+ if entry is None:+ return None+ _result_cache.move_to_end(run_id)+ rows = entry["rows"]+ end = offset + limit+ # A page that runs past an incomplete cache needs rows we don't have — re-query.+ if not entry["complete"] and end > len(rows):+ return None+ return {+ "columns": entry["columns"],+ "types": entry["types"],+ "rows": rows[offset:end],+ "has_more": end < len(rows) or not entry["complete"],+ }+++def _build_envelope(payload: dict[str, Any]) -> dict[str, Any]:+ from . import data_plane # noqa: PLC0415 — see _fetch_capped_page++ page_limit = int(payload.get("page_limit") or _DEFAULT_PAGE_LIMIT)+ cache_limit = max(int(payload.get("cache_limit") or _DEFAULT_CACHE_LIMIT), page_limit)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),+ result = _fetch_capped_page(payload, limit=cache_limit, offset=0)+ rows = envelope.json_safe_rows(result["rows"])+ run_id = str(payload.get("run_id") or "")+ if run_id:+ _cache_result(run_id, result["columns"], result["types"], rows, complete=not result["has_more"])+ return envelope.from_columns_and_rows(+ result["columns"],+ result["rows"][:page_limit],+ result["types"],+ has_more=result["has_more"] or len(rows) > 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 callbackreturn envelope.from_error(f"Run failed in the sandbox: {exc}")+def fetch_page(payload: dict[str, Any]) -> dict[str, Any]:+ """Serve a /page request: a cached local slice, or a bounded synchronous re-query.++ Raises DataPlaneError for user-facing query errors; the server maps it to a 400.+ """+ offset = int(payload.get("offset") or 0)+ limit = int(payload.get("limit") or _DEFAULT_PAGE_LIMIT)++ cached = _cached_page(str(payload.get("run_id") or ""), offset, limit)+ if cached is not None:+ return cached++ page = _fetch_capped_page(payload, limit=limit, offset=offset)+ return {+ "columns": page["columns"],+ "types": page["types"],+ "rows": envelope.json_safe_rows(page["rows"]),+ "has_more": page["has_more"],+ }++def _post_callback(callback_url: str, callback_token: str, result: dict[str, Any]) -> None:request = urllib.request.Request(callback_url,diff --git a/products/notebooks/backend/sandbox/kernel/server.py b/products/notebooks/backend/sandbox/kernel/server.pyindex bb33e10bcbf7..abea5e122842 100644--- a/products/notebooks/backend/sandbox/kernel/server.py+++ b/products/notebooks/backend/sandbox/kernel/server.py@@ -7,6 +7,9 @@ Launched inside the sandbox as `python -m nb_kernel.server --port … --secret-fcontent hash the backend deployed, used for the redeploy handshake.- POST /run → verifies the HMAC command token, returns 202, executes the run anddelivers the result callback on a background thread.+- POST /page → verifies the HMAC command token, synchronously re-queries the data+ plane with the request's LIMIT/OFFSET and returns the rows in the 200 response.+ A page fetch is bounded, so it is plain request/response — no callback."""import json@@ -17,7 +20,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom typing import Anyfrom .auth import verify_command_token-from .runner import execute_run+from .runner import execute_run, fetch_pageDEFAULT_PORT = 47821@@ -32,7 +35,7 @@ class KernelServerHandler(BaseHTTPRequestHandler):self._respond(404, {"error": "Not found"})def do_POST(self) -> None:- if self.path != "/run":+ if self.path not in ("/run", "/page"):self._respond(404, {"error": "Not found"})returntry:@@ -41,13 +44,34 @@ class KernelServerHandler(BaseHTTPRequestHandler):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()):+ if not verify_command_token(_config["secret"], payload.get("run_id", ""), self._command_token()):self._respond(401, {"error": "Invalid command token"})return- threading.Thread(target=execute_run, args=(payload,), daemon=True).start()- self._respond(202, {"accepted": True})+ if self.path == "/run":+ threading.Thread(target=execute_run, args=(payload,), daemon=True).start()+ self._respond(202, {"accepted": True})+ return+ self._handle_page(payload)++ def _handle_page(self, payload: dict[str, Any]) -> None:+ from . import data_plane # noqa: PLC0415 — keep pyarrow off the server startup path- def _bearer_token(self) -> str:+ try:+ self._respond(200, fetch_page(payload))+ except data_plane.DataPlaneError as exc:+ self._respond(400, {"error": str(exc)})+ except Exception: # noqa: BLE001 — a page failure must not kill the request thread silently+ logging.getLogger(__name__).exception("nb_kernel page fetch failed")+ self._respond(500, {"error": "Page fetch failed in the sandbox"})++ def _command_token(self) -> str:+ # The command token rides its own header: Authorization carries the Modal connect+ # token (tunnel auth), which must stay out of the URL to stay out of access logs.+ # Fall back to a bearer Authorization for a backend that still sends the pre-split+ # layout (mixed versions during a rolling deploy).+ token = (self.headers.get("X-Command-Token") or "").strip()+ if token:+ return tokenauthorization = self.headers.get("Authorization", "")return authorization[len("Bearer ") :].strip() if authorization.startswith("Bearer ") else ""diff --git a/products/notebooks/backend/sql_v2.py b/products/notebooks/backend/sql_v2.pyindex ea0a70f46a48..cc2a76412cb2 100644--- a/products/notebooks/backend/sql_v2.py+++ b/products/notebooks/backend/sql_v2.py@@ -37,9 +37,11 @@ _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).+# Rows in the display page the run envelope carries to the UI.DISPLAY_PAGE_LIMIT = 50+# Rows the kernel fetches and caches per run. Pages within the cache are local slices+# (no ClickHouse re-query); paging beyond it falls back to a LIMIT/OFFSET re-query.+RESULT_CACHE_ROWS = 300# The container port the sandbox already exposes (mapped to a host port at create# time). Mirrors docker_sandbox.AGENT_SERVER_PORT (47821) and@@ -55,13 +57,27 @@ _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+# A page fetch holds a web worker for the whole kernel -> data plane -> CH round trip.+_PAGE_POST_TIMEOUT_SECONDS = 60+# Safety-net TTL for the per-user page-fetch lock: sized just past the POST timeout so a+# worker killed before its finally-release can't wedge the user's paging for long.+PAGE_LOCK_TTL_SECONDS = _PAGE_POST_TIMEOUT_SECONDS + 10_COMMAND_TOKEN_TTL_SECONDS = 300+def sql_v2_page_lock_key(team_id: int, user_id: int | None) -> str:+ """One in-flight page fetch per user: each holds a web worker for up to the POST timeout."""+ return f"sqlv2_page_inflight:{team_id}:{user_id if user_id is not None else 'anon'}"++class SQLV2KernelNotRunning(Exception):"""Raised when a run is dispatched but the notebook has no running sandbox."""+class SQLV2PageError(Exception):+ """A page fetch the kernel rejected or failed; message is user-facing."""++def is_sql_v2_enabled(user: User | None) -> bool:if user is None or not user.distinct_id:return False@@ -152,15 +168,32 @@ def _find_running_runtime(notebook: Notebook, user: User | None) -> KernelRuntimreturn 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+_COMMAND_TOKEN_HEADER = "X-Command-Token"+++def _sandbox_auth_headers(connect_token: str | None, command_token: str | None = None) -> dict[str, str]:+ """Auth headers for a request into the sandbox.++ The Modal connect token rides `Authorization: Bearer` — Modal's edge accepts it there+ as well as in the query string, and headers stay out of proxy/access logs while URLs+ do not. With that slot taken, the kernel's command token travels in its own header.+ """+ headers: dict[str, str] = {}+ if connect_token:+ headers["Authorization"] = f"Bearer {connect_token}"+ if command_token:+ headers[_COMMAND_TOKEN_HEADER] = command_token+ return headersdef _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)+ response = requests.get(+ f"{server_url.rstrip('/')}/health",+ headers=_sandbox_auth_headers(connect_token),+ timeout=2,+ )if response.status_code != 200:return Nonereturn str(response.json().get("version") or "")@@ -246,7 +279,7 @@ def dispatch_sql_v2_run(notebook: Notebook, user: User | None, run: NotebookNodecommand_token = mint_command_token(kernel_server_secret(str(runtime.id)), str(run.id))user_id = user.id if isinstance(user, User) else Noneresponse = requests.post(- _with_connect_token(f"{runtime.server_url.rstrip('/')}/run", runtime.server_connect_token),+ f"{runtime.server_url.rstrip('/')}/run",json={"run_id": str(run.id),"code": code,@@ -255,8 +288,61 @@ def dispatch_sql_v2_run(notebook: Notebook, user: User | None, run: NotebookNode"data_plane_url": build_data_plane_url(),"data_plane_token": mint_data_plane_token(notebook.short_id, notebook.team_id, user_id),"page_limit": DISPLAY_PAGE_LIMIT,+ "cache_limit": RESULT_CACHE_ROWS,},- headers={"Authorization": f"Bearer {command_token}"},+ headers=_sandbox_auth_headers(runtime.server_connect_token, command_token),timeout=_RUN_POST_TIMEOUT_SECONDS,)response.raise_for_status()+++def fetch_sql_v2_page(notebook: Notebook, user: User | None, run: NotebookNodeRun, offset: int, limit: int) -> dict:+ """Fetch one result page through the kernel — a bounded synchronous re-query.++ Unlike a run this never bootstraps the server (no control plane from a web+ worker); a missing or unreachable server means the user has to re-run.+ """+ runtime = _find_running_runtime(notebook, user)+ if runtime is None or not runtime.server_url:+ raise SQLV2KernelNotRunning()++ command_token = mint_command_token(kernel_server_secret(str(runtime.id)), str(run.id))+ user_id = user.id if isinstance(user, User) else None+ try:+ response = requests.post(+ f"{runtime.server_url.rstrip('/')}/page",+ json={+ "run_id": str(run.id),+ "code": run.code,+ "offset": offset,+ "limit": limit,+ "data_plane_url": build_data_plane_url(),+ "data_plane_token": mint_data_plane_token(notebook.short_id, notebook.team_id, user_id),+ },+ headers=_sandbox_auth_headers(runtime.server_connect_token, command_token),+ timeout=_PAGE_POST_TIMEOUT_SECONDS,+ )+ except requests.RequestException as exc:+ raise SQLV2KernelNotRunning() from exc++ if response.status_code in (404, 401, 403):+ # 404 → kernel-server predates the /page route; 401/403 → the command token expired or+ # the kernel was redeployed with a new secret. All are session-level, not query errors —+ # a re-run redeploys/reissues, so surface them as "re-run" (503), not a page failure.+ raise SQLV2KernelNotRunning()+ if response.status_code == 400:+ raise SQLV2PageError(_kernel_error_detail(response))+ if response.status_code != 200:+ # Any other non-200 (e.g. a kernel 500) is an infrastructure problem, not a bad query.+ raise SQLV2KernelNotRunning()+ return response.json()+++def _kernel_error_detail(response: requests.Response) -> str:+ try:+ detail = response.json().get("error")+ if isinstance(detail, str) and detail:+ return detail+ except ValueError:+ pass+ return "Page fetch failed in the sandbox."diff --git a/products/notebooks/backend/sql_v2_data_plane.py b/products/notebooks/backend/sql_v2_data_plane.pyindex 5aef309c232b..caa2ec8f7a71 100644--- a/products/notebooks/backend/sql_v2_data_plane.py+++ b/products/notebooks/backend/sql_v2_data_plane.py@@ -1,15 +1,25 @@"""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.+Token-authed sandbox -> backend endpoints (like the result callback, plain+function views, no session). The sandbox never parses HogQL — it sends the query+text here; parsing, access control, and execution all stay backend-side.++Queries run through the async query manager (the same Celery-backed path insights+and the SQL editor use), so no web worker ever waits on ClickHouse:++- `POST .../data_plane/query/` validates and enqueues, returning 202 {query_id}.+- `GET .../data_plane/query/<query_id>/` returns 202 while the Celery worker is+ still executing, and the rows as an Arrow stream once complete. The kernel's+ background thread polls this — invisible to the user, who already waits on the+ run callback or the page response.+Wired in posthog/urls.py at internal/notebooks/data_plane/query/."""import jsonfrom typing import Any+from django.conf import settingsfrom django.core import signingfrom django.http import HttpRequest, HttpResponse, JsonResponse@@ -18,8 +28,8 @@ from drf_spectacular.utils import OpenApiResponse, extend_schemafrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.parser import parse_select-from posthog.hogql.query import execute_hogql_query+from posthog.clickhouse.client.execute_async import QueryNotFoundError, enqueue_process_query_task, get_query_statusfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models import Team, User@@ -58,35 +68,42 @@ def _rows_to_arrow_bytes(return sink.getvalue().to_pybytes()+def _verify_request_token(request: HttpRequest) -> tuple[str, int, int | None] | JsonResponse:+ 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:+ return verify_data_plane_token(token)+ except signing.BadSignature:+ return JsonResponse({"error": "Invalid data-plane token"}, status=401)++@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"),+ 202: OpenApiResponse(description="Query accepted; poll the status endpoint with the returned query_id"),+ 400: OpenApiResponse(description="Invalid request body or HogQL syntax 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."+ "data-plane token minted at run dispatch (no session). Validates and enqueues the query "+ "for the notebook's team via the async query manager — HogQL access controls apply — "+ "and returns a query_id for the sandbox to poll."),)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)+ claims = _verify_request_token(request)+ if isinstance(claims, JsonResponse):+ return claims+ notebook_short_id, team_id, user_id = claimstry:body = json.loads(request.body)@@ -108,24 +125,72 @@ def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:user = User.objects.filter(id=user_id).first() if user_id else Nonetry:- # 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)+ # Validate the user's HogQL up front so syntax errors fail here with a clear+ # message instead of surfacing through the async status.+ parse_select(data["query"])except ExposedHogQLError as exc:return JsonResponse({"error": str(exc)}, status=400)++ # Wrap rather than mutate the user's query: the outer LIMIT/OFFSET caps the page+ # regardless of the query's own shape (set queries, its own LIMIT, etc.).+ # The inner query is validated HogQL (parsed above) and the wrapper is re-parsed as HogQL+ # downstream, so there is no raw-SQL injection; limit/offset are int()-cast.+ # nosemgrep: semgrep.rules.security.hogql-fstring-audit+ wrapped = f"select * from ({data['query']}) limit {int(data['limit'])} offset {int(data['offset'])}"++ try:+ with tags_context(product=Product.NOTEBOOKS, feature=Feature.QUERY, team_id=team.id):+ status = enqueue_process_query_task(+ team=team,+ user_id=user.id if user else None,+ query_json={"kind": "HogQLQuery", "query": wrapped},+ # Dispatch normally rides transaction.on_commit, which never fires inside+ # a test transaction — run inline there, like the manager's own tests do.+ _test_only_bypass_celery=settings.TEST,+ )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)+ logger.exception("notebook_sql_v2_data_plane_enqueue_failed", notebook_short_id=notebook_short_id)+ return JsonResponse({"error": "Query could not be scheduled."}, 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 JsonResponse({"query_id": status.id}, status=202)+++@extend_schema(+ tags=["notebooks"],+ responses={+ (200, ARROW_STREAM_CONTENT_TYPE): OpenApiResponse(description="Query result as an Arrow IPC stream"),+ 202: OpenApiResponse(description="Query is still running"),+ 400: OpenApiResponse(description="Query failed"),+ 401: OpenApiResponse(description="Missing or invalid data-plane token"),+ 404: OpenApiResponse(description="Query not found or expired"),+ },+ summary="SQLV2 data-plane query status",+ description=(+ "Internal endpoint the notebook sandbox polls for an enqueued data-plane query. "+ "Returns 202 while the query runs and the rows as an Arrow IPC stream once complete."+ ),+)+def notebook_sql_v2_data_plane_status(request: HttpRequest, query_id: str) -> HttpResponse:+ if request.method != "GET":+ return JsonResponse({"error": "Method not allowed"}, status=405)++ claims = _verify_request_token(request)+ if isinstance(claims, JsonResponse):+ return claims+ _notebook_short_id, team_id, _user_id = claims++ try:+ status = get_query_status(team_id=team_id, query_id=query_id)+ except QueryNotFoundError:+ return JsonResponse({"error": "Query not found or expired"}, status=404)++ if not status.complete:+ return JsonResponse({"status": "running"}, status=202)+ if status.error:+ return JsonResponse({"error": status.error_message or "Query execution failed."}, status=400)++ results: dict[str, Any] = status.results or {}+ columns = [str(column) for column in (results.get("columns") or [])]+ types = [[str(name), str(type_name)] for name, type_name in (results.get("types") or [])]+ payload = _rows_to_arrow_bytes(columns, results.get("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.mdindex 9dc5a349c2a1..66b2bec0b598 100644--- a/products/notebooks/backend/sql_v2_kernel_architecture.md+++ b/products/notebooks/backend/sql_v2_kernel_architecture.md@@ -43,14 +43,14 @@ Sandbox (Modal / Docker container)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 |+| 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 | one result page — bounded, no callback. Today (pure-HogQL nodes) it re-queries the data plane with the run’s code + LIMIT/OFFSET; materialized results will slice from `/data/results` once the result store exists |+| `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}`.@@ -78,14 +78,13 @@ Runs execute **one at a time** in arrival order (a kernel has one namespace; conNew 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)+POST /internal/notebooks/data_plane/query/ → 202 { "query_id" } (validate + enqueue)+GET /internal/notebooks/data_plane/query/<id>/ → 202 while running,+Authorization: Bearer <data-plane token> 200 Arrow IPC stream when complete```- **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.+- **Execution**: the endpoint validates the HogQL, then enqueues it on the **async query manager** — the same Celery-backed path insights and the SQL editor use — so no web worker ever waits on ClickHouse. The kernel polls the status route; the Celery query worker runs the HogQL layer (access controls apply) against ClickHouse — or DuckLake for warehouse sources (Journey 6) — and the completed result returns as Arrow on the poll. Large materializations that outgrow the manager's Redis-resident results will need a streaming variant of this endpoint (direct execution, record batches into the response) — that's a later, additive change.- **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:diff --git a/products/notebooks/backend/sql_v2_result_delivery.md b/products/notebooks/backend/sql_v2_result_delivery.mdindex dab860ad5271..cccfcc3e6d21 100644--- a/products/notebooks/backend/sql_v2_result_delivery.md+++ b/products/notebooks/backend/sql_v2_result_delivery.md@@ -109,9 +109,12 @@ reads stay stateless.## 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.+**Now: a capped in-memory cache in the kernel-server.** A run fetches up to+`RESULT_CACHE_ROWS` (300) rows in one ClickHouse query; the kernel-server keeps+them per run (LRU over the last 20 runs). `/page` requests within the cache are+local slices — no ClickHouse work, no held backend workers. Paging beyond the+cache, or after a kernel restart emptied it, falls back to a LIMIT/OFFSET+re-query through the data plane.**Later: durable store** (object storage / Parquet / a results table). Thesandbox materializes the full result at run time; `result_id` is the storage key.diff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.pyindex 662a117d82e4..7b6b8c567fa6 100644--- a/products/notebooks/backend/sql_v2_serializers.py+++ b/products/notebooks/backend/sql_v2_serializers.py@@ -8,6 +8,22 @@ class NotebookSQLV2RunRequestSerializer(serializers.Serializer):)+class NotebookSQLV2PageRequestSerializer(serializers.Serializer):+ offset = serializers.IntegerField(+ required=False,+ default=0,+ min_value=0,+ help_text="Number of rows to skip; pages re-query ClickHouse with LIMIT/OFFSET.",+ )+ limit = serializers.IntegerField(+ required=False,+ default=50,+ min_value=1,+ max_value=500,+ help_text="Rows per page.",+ )++class NotebookSQLV2DataPlaneRequestSerializer(serializers.Serializer):query = serializers.CharField(help_text="HogQL SELECT to execute against the notebook team's data.")limit = serializers.IntegerField(@@ -40,6 +56,11 @@ class NotebookSQLV2EnvelopeSerializer(serializers.Serializer):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.")+ has_more = serializers.BooleanField(+ required=False,+ default=False,+ help_text="Whether ClickHouse has more rows beyond first_page (detected by fetching limit+1).",+ )first_page = serializers.ListField(child=serializers.ListField(help_text="A single result row as a list of cell values."),required=False,diff --git a/products/notebooks/backend/temporal/sql_v2.py b/products/notebooks/backend/temporal/sql_v2.pyindex 5ae7e21400c4..e21e4ba32f81 100644--- a/products/notebooks/backend/temporal/sql_v2.py+++ b/products/notebooks/backend/temporal/sql_v2.py@@ -69,7 +69,8 @@ class NotebookSQLV2RunWorkflow(PostHogWorkflow):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.+ # All workflow related errors are caught and re-tried within 'await'.+ # This catch clause means dispatch exhausted its retries — let's make sure the run reaches a terminal state.await workflow.execute_activity(mark_sql_v2_run_failed_activity,input,diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.pyindex 7f9012bd2e62..3a2a06b9bd76 100644--- a/products/notebooks/backend/test/test_sql_v2.py+++ b/products/notebooks/backend/test/test_sql_v2.py@@ -33,11 +33,15 @@ from products.notebooks.backend.sandbox.kernel import (from products.notebooks.backend.sandbox.kernel.data_plane import DataPlaneError, decode_arrow_streamfrom products.notebooks.backend.sql_v2 import (SQLV2KernelNotRunning,+ SQLV2PageError,+ dispatch_sql_v2_run,ensure_sql_v2_server,+ fetch_sql_v2_page,kernel_server_secret,mint_callback_token,mint_command_token,mint_data_plane_token,+ sql_v2_page_lock_key,verify_data_plane_token,)from products.notebooks.backend.sql_v2_data_plane import _rows_to_arrow_bytes@@ -165,6 +169,8 @@ class TestSQLV2Run(APIBaseTest):run_id = response.json()["run_id"]run = NotebookNodeRun.objects.for_team(self.team.id).get(id=run_id)self.assertEqual(run.status, NotebookNodeRun.Status.RUNNING)+ # Paging re-queries the run's stored code, so losing it here breaks every page fetch.+ self.assertEqual(run.code, "select 1")mock_start.assert_called_once()self.assertEqual(str(mock_start.call_args.args[0].run_id), run_id)@@ -253,7 +259,7 @@ class TestSQLV2EnsureServer(APIBaseTest):self.assertEqual(self.sandbox.files, {})def test_stale_server_is_redeployed(self):- # Missing this redeploy strands sandboxes on old kernel code.+ # Missing this redeploy strands sandboxes on old kernel code (e.g. no /page route).runtime = self._create_runtime(server_url="http://localhost:1")result = self._ensure(reported_version="some-old-version")package, _version = kernel_package_bytes_and_hash()@@ -282,6 +288,173 @@ class TestSQLV2EnsureServer(APIBaseTest):self._ensure(reported_version=None)+class TestSQLV2RunPage(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbpage1")++ def _create_run(self, status=NotebookNodeRun.Status.DONE, node_id="n1", code="select 1") -> NotebookNodeRun:+ with team_scope(self.team.id):+ return NotebookNodeRun.objects.create(+ team=self.team, notebook=self.notebook, node_id=node_id, status=status, code=code+ )++ def _get(self, run_id: str, offset=50, limit=50):+ return self.client.get(+ f"/api/projects/{self.team.id}/notebooks/{self.notebook.short_id}/sql_v2/runs/{run_id}/page/",+ {"offset": offset, "limit": limit},+ )++ @patch("products.notebooks.backend.presentation.views.notebook.fetch_sql_v2_page")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_returns_page_from_kernel(self, _mock_enabled, mock_fetch):+ mock_fetch.return_value = {"columns": ["a"], "types": [["a", "Int64"]], "rows": [[51]], "has_more": False}+ run = self._create_run()+ response = self._get(str(run.id))+ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json()["rows"], [[51]])+ self.assertEqual(mock_fetch.call_args.kwargs["offset"], 50)+ self.assertEqual(mock_fetch.call_args.kwargs["limit"], 50)++ @patch("products.notebooks.backend.presentation.views.notebook.fetch_sql_v2_page")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_stale_run_is_rejected(self, _mock_enabled, mock_fetch):+ # A newer completed run supersedes this result — paging it would mix two executions.+ old_run = self._create_run()+ self._create_run() # newer DONE run for the same node+ response = self._get(str(old_run.id))+ self.assertEqual(response.status_code, 409)+ self.assertEqual(response.json()["detail"], "stale")+ mock_fetch.assert_not_called()++ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_kernel_not_running_returns_503(self, _mock_enabled):+ # No KernelRuntime exists, so the real fetch path raises SQLV2KernelNotRunning.+ run = self._create_run()+ response = self._get(str(run.id))+ self.assertEqual(response.status_code, 503)++ @patch("products.notebooks.backend.presentation.views.notebook.fetch_sql_v2_page")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_empty_code_run_is_rejected_before_reaching_the_kernel(self, _mock_enabled, mock_fetch):+ # Pre-migration runs stored code="" — paging must fail clearly, not round-trip to an opaque error.+ run = self._create_run(code="")+ response = self._get(str(run.id))+ self.assertEqual(response.status_code, 400)+ self.assertIn("re-run", response.json()["detail"])+ mock_fetch.assert_not_called()++ @parameterized.expand(+ [+ ("running_run", NotebookNodeRun.Status.RUNNING, 400),+ ("failed_run", NotebookNodeRun.Status.FAILED, 400),+ ]+ )+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_non_done_run_is_rejected(self, _name, status, expected, _mock_enabled):+ run = self._create_run(status=status)+ self.assertEqual(self._get(str(run.id)).status_code, expected)++ @patch("products.notebooks.backend.presentation.views.notebook.fetch_sql_v2_page")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_query_restricted_member_cannot_page(self, _mock_enabled, mock_fetch):+ # Paging returns analytics rows, so a query-denied notebook reader must not fetch pages.+ run = self._create_run()+ _restrict_query_access(self)+ self.assertEqual(self._get(str(run.id)).status_code, 403)+ mock_fetch.assert_not_called()++ @patch("products.notebooks.backend.presentation.views.notebook.fetch_sql_v2_page")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_one_in_flight_page_fetch_per_user(self, _mock_enabled, mock_fetch):+ # Each out-of-cache page fetch holds a web worker for up to the kernel timeout, so a+ # user with a fetch already in flight must be rejected instead of stacking workers.+ mock_fetch.return_value = {"columns": [], "types": [], "rows": [], "has_more": False}+ run = self._create_run()+ lock_key = sql_v2_page_lock_key(self.team.id, self.user.id)+ cache.add(lock_key, True, timeout=10)+ try:+ response = self._get(str(run.id))+ self.assertEqual(response.status_code, 429)+ mock_fetch.assert_not_called()+ finally:+ cache.delete(lock_key)+ # A finished fetch releases the lock, so back-to-back sequential pages keep working.+ self.assertEqual(self._get(str(run.id)).status_code, 200)+ self.assertEqual(self._get(str(run.id)).status_code, 200)+++class TestSQLV2PageDispatch(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.notebook = Notebook.objects.create(team=self.team, short_id="nbpgd01")+ with team_scope(self.team.id):+ self.node_run = NotebookNodeRun.objects.create(+ team=self.team,+ notebook=self.notebook,+ node_id="n1",+ status=NotebookNodeRun.Status.DONE,+ code="select event from events",+ )++ def _create_runtime(self) -> 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="http://localhost:12345",+ server_connect_token="connect-tok",+ )++ def test_raises_without_running_kernel(self):+ with self.assertRaises(SQLV2KernelNotRunning):+ fetch_sql_v2_page(self.notebook, self.user, self.node_run, offset=50, limit=50)++ @patch("products.notebooks.backend.sql_v2.requests.post")+ def test_posts_run_code_and_paging_to_kernel(self, mock_post):+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {"columns": [], "types": [], "rows": [], "has_more": False}+ runtime = self._create_runtime()+ fetch_sql_v2_page(self.notebook, self.user, self.node_run, offset=100, limit=25)+ self.assertIn("/page", mock_post.call_args.args[0])+ # Credentials ride headers, never the URL — a query-string token lands in access logs.+ self.assertNotIn("?", mock_post.call_args.args[0])+ headers = mock_post.call_args.kwargs["headers"]+ self.assertEqual(headers["Authorization"], "Bearer connect-tok")+ self.assertTrue(+ kernel_auth.verify_command_token(+ kernel_server_secret(str(runtime.id)), str(self.node_run.id), headers["X-Command-Token"]+ )+ )+ payload = mock_post.call_args.kwargs["json"]+ # The kernel must page the code that produced the result, not whatever the editor holds now.+ self.assertEqual(payload["code"], "select event from events")+ self.assertEqual((payload["offset"], payload["limit"]), (100, 25))++ @parameterized.expand(+ [+ ("outdated_kernel_404", 404, None, SQLV2KernelNotRunning),+ # Token expiry / kernel redeploy — a re-run reissues the token, so it's "re-run" (503), not a query error.+ ("stale_token_401", 401, None, SQLV2KernelNotRunning),+ ("forbidden_403", 403, None, SQLV2KernelNotRunning),+ ("query_error_400", 400, {"error": "no such column"}, SQLV2PageError),+ # Any other non-200 is infrastructure, not a bad query.+ ("kernel_error_500", 500, None, SQLV2KernelNotRunning),+ ]+ )+ @patch("products.notebooks.backend.sql_v2.requests.post")+ def test_kernel_error_statuses_map_to_exceptions(self, _name, status_code, body, expected_exception, mock_post):+ mock_post.return_value.status_code = status_code+ mock_post.return_value.json.return_value = body+ self._create_runtime()+ with self.assertRaises(expected_exception):+ fetch_sql_v2_page(self.notebook, self.user, self.node_run, offset=0, limit=50)++class TestSQLV2RunResult(APIBaseTest):def setUp(self):super().setUp()@@ -371,7 +544,7 @@ class TestSQLV2Activities(APIBaseTest):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 versionrun = self._create_run()- KernelRuntime.objects.create(+ runtime = KernelRuntime.objects.create(team=self.team,notebook=self.notebook,notebook_short_id=self.notebook.short_id,@@ -380,12 +553,24 @@ class TestSQLV2Activities(APIBaseTest):backend=KernelRuntime.Backend.DOCKER,sandbox_id="sbx-1",server_url="http://localhost:12345",+ server_connect_token="connect-tok",)dispatch_sql_v2_run_activity(self._run_input(run))mock_post.assert_called_once()self.assertIn("/run", mock_post.call_args.args[0])+ # Credentials ride headers, never the URL — a query-string token lands in access logs.+ self.assertNotIn("?", mock_post.call_args.args[0])+ headers = mock_post.call_args.kwargs["headers"]+ self.assertEqual(headers["Authorization"], "Bearer connect-tok")+ self.assertTrue(+ kernel_auth.verify_command_token(+ kernel_server_secret(str(runtime.id)), str(run.id), headers["X-Command-Token"]+ )+ )payload = mock_post.call_args.kwargs["json"]self.assertEqual(payload["code"], "select 1")+ # Dropping cache_limit silently degrades every page fetch into a ClickHouse re-query.+ self.assertGreater(payload["cache_limit"], payload["page_limit"])# 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))@@ -452,8 +637,22 @@ class TestSQLV2DataPlaneEndpoint(APIBaseTest):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 _get_status(self, query_id: str, token: str | None = None):+ return self.client.get(+ f"{self.URL}{query_id}/",+ HTTP_AUTHORIZATION=f"Bearer {token or self._token()}",+ )++ def _run_to_completion(self, body: dict):+ # Celery is eager in tests, so the enqueue executes inline and the first+ # status poll is already terminal — the same protocol the kernel follows.+ response = self._post(body, token=self._token())+ self.assertEqual(response.status_code, 202, response.content)+ query_id = response.json()["query_id"]+ return self._get_status(query_id)+def test_runs_query_and_returns_arrow(self):- response = self._post({"query": "select 1 as answer"}, token=self._token())+ response = self._run_to_completion({"query": "select 1 as answer"})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)@@ -464,11 +663,28 @@ class TestSQLV2DataPlaneEndpoint(APIBaseTest):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())+ response = self._run_to_completion({"query": "select number from numbers(10)", "limit": 3, "offset": 2})self.assertEqual(response.status_code, 200, response.content)_columns, rows, _types = decode_arrow_stream(response.content)self.assertEqual(rows, [(2,), (3,), (4,)])+ def test_execution_error_surfaces_through_status(self):+ # Valid syntax but fails at execution — the error must reach the sandbox via the poll.+ response = self._run_to_completion({"query": "select nonexistent_column from events"})+ self.assertEqual(response.status_code, 400, response.content)+ self.assertTrue(response.json()["error"])++ def test_status_rejects_bad_auth_and_unknown_query(self):+ self.assertEqual(self.client.get(f"{self.URL}deadbeef/").status_code, 401)+ self.assertEqual(self._get_status("deadbeef").status_code, 404)++ def test_status_is_team_scoped(self):+ # A leaked query_id plus a token for another team must not read the result.+ response = self._post({"query": "select 1"}, token=self._token())+ query_id = response.json()["query_id"]+ other_team_token = mint_data_plane_token(self.notebook.short_id, self.team.id + 999, None)+ self.assertEqual(self._get_status(query_id, token=other_team_token).status_code, 404)+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)@@ -488,10 +704,90 @@ class TestSQLV2DataPlaneEndpoint(APIBaseTest):response = self._post({"query": "select 1"}, token=self._token(short_id="nope999"))self.assertEqual(response.status_code, 404)+ @parameterized.expand(+ [+ # The wrapper nests the user's query as a subquery; these are the shapes+ # that break naive wrapping (inner LIMIT interacting with the outer one,+ # and set queries that must stay parenthesized).+ ("inner_limit_caps_before_outer", "select number from numbers(10) limit 4", 3, 2, [(2,), (3,)]),+ ("union_set_query", "select 1 as n union all select 2 as n", 10, 0, [(1,), (2,)]),+ ]+ )+ def test_query_shapes_survive_the_wrapper(self, _name, query, limit, offset, expected_rows):+ response = self._run_to_completion({"query": query, "limit": limit, "offset": offset})+ self.assertEqual(response.status_code, 200, response.content)+ _columns, rows, _types = decode_arrow_stream(response.content)+ self.assertEqual(sorted(rows), expected_rows)+++class TestSQLV2RunContract(APIBaseTest):+ def test_dispatch_payload_drives_the_kernel_and_its_callback_round_trips(self):+ # Closes the seams the unit tests can't see: the dispatch payload's keys must+ # match what the kernel runner reads, the runner's envelope must satisfy the+ # callback serializer, and the callback token/URL minted at dispatch must be+ # accepted by the callback endpoint. A renamed payload or envelope key passes+ # every per-component test and breaks only here.+ notebook = Notebook.objects.create(team=self.team, short_id="nbctr01")+ with team_scope(self.team.id):+ run = NotebookNodeRun.objects.create(+ team=self.team,+ notebook=notebook,+ node_id="n1",+ status=NotebookNodeRun.Status.RUNNING,+ code="select 1",+ )+ KernelRuntime.objects.create(+ team=self.team,+ notebook=notebook,+ notebook_short_id=notebook.short_id,+ user=self.user,+ status=KernelRuntime.Status.RUNNING,+ backend=KernelRuntime.Backend.DOCKER,+ sandbox_id="sbx-1",+ server_url="http://localhost:1",+ )++ with (+ patch(+ "products.notebooks.backend.sql_v2._server_version",+ return_value=kernel_package_bytes_and_hash()[1],+ ),+ patch("products.notebooks.backend.sql_v2.requests.post") as mock_post,+ ):+ dispatch_sql_v2_run(notebook, self.user, run, "select 1")+ payload = mock_post.call_args.kwargs["json"]++ delivered: dict = {}+ with (+ patch(+ "products.notebooks.backend.sandbox.kernel.data_plane.fetch_query_page",+ return_value=(["a"], [(1,)], [["a", "Int64"]]),+ ),+ patch.object(+ kernel_runner,+ "_post_callback",+ side_effect=lambda url, token, env: delivered.update({"url": url, "envelope": env}),+ ),+ ):+ kernel_runner.execute_run(payload)++ self.assertTrue(delivered["url"].endswith(f"/internal/notebooks/runs/{run.id}/result/"))+ response = self.client.post(+ f"/internal/notebooks/runs/{run.id}/result/",+ data=json.dumps({"envelope": delivered["envelope"]}),+ content_type="application/json",+ HTTP_AUTHORIZATION=f"Bearer {payload['callback_token']}",+ )+ self.assertEqual(response.status_code, 200, response.content)+ stored = NotebookNodeRun.objects.for_team(self.team.id).get(id=run.id)+ self.assertEqual(stored.status, NotebookNodeRun.Status.DONE)+ self.assertEqual(stored.envelope["first_page"], [[1]])+ self.assertEqual(stored.envelope["types"], [["a", "Int64"]])+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.+ # The kernel HTTP layer (routing, auth wiring, async-run vs sync-page split) 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@@ -501,11 +797,14 @@ class TestSQLV2KernelServerHTTP(SimpleTestCase):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):+ def post(path: str, token: str, token_header: str = "X-Command-Token"):+ # X-Command-Token is the primary transport; Authorization stays a fallback for+ # backends that predate the split (Authorization now carries Modal tunnel auth).+ token_value = f"Bearer {token}" if token_header == "Authorization" else tokenrequest = urllib.request.Request(f"{base}{path}",data=json.dumps({"run_id": "run-1"}).encode(),- headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},+ headers={token_header: token_value, "Content-Type": "application/json"},method="POST",)return urllib.request.urlopen(request, timeout=5)@@ -525,6 +824,20 @@ class TestSQLV2KernelServerHTTP(SimpleTestCase):self.assertEqual(response.status, 202)self.assertTrue(ran.wait(5)) # the run must execute off the request thread+ # An older backend sends the command token as a bearer Authorization — the+ # fallback must keep verifying it while mixed versions roll out.+ ran.clear()+ with patch.object(kernel_server, "execute_run", side_effect=lambda _p: ran.set()):+ with post("/run", token=token, token_header="Authorization") as response:+ self.assertEqual(response.status, 202)+ self.assertTrue(ran.wait(5))++ page = {"columns": ["a"], "types": [], "rows": [[1]], "has_more": False}+ with patch.object(kernel_server, "fetch_page", return_value=page):+ with post("/page", token=token) as response:+ self.assertEqual(response.status, 200) # pages are synchronous+ self.assertEqual(json.loads(response.read())["rows"], [[1]])+with self.assertRaises(urllib.error.HTTPError) as unknown:post("/nope", token=token)self.assertEqual(unknown.exception.code, 404)@@ -584,6 +897,109 @@ class TestSQLV2KernelPackage(SimpleTestCase):self.assertEqual(delivered["status"], "error")self.assertEqual(delivered["error"], "no such table")+ def _run_and_cache(self, run_id: str, rows_returned: int, cache_limit: int = 300):+ payload = {+ "run_id": run_id,+ "code": "select 1",+ "callback_url": "http://backend/cb",+ "callback_token": "t",+ "data_plane_url": "u",+ "data_plane_token": "t",+ "page_limit": 50,+ "cache_limit": cache_limit,+ }+ mock_fetch = patch(+ "products.notebooks.backend.sandbox.kernel.data_plane.fetch_query_page",+ return_value=(["n"], [(i,) for i in range(rows_returned)], [["n", "Int64"]]),+ )+ with mock_fetch as fetch:+ result = kernel_runner._build_envelope(payload)+ return payload, result, fetch++ def test_pages_within_the_cache_never_requery(self):+ # The whole point of the cache: paging must not re-run the query on ClickHouse.+ payload, result, _ = self._run_and_cache("r-cache-1", rows_returned=301)+ self.assertEqual(len(result["first_page"]), 50)+ self.assertTrue(result["has_more"])+ with patch("products.notebooks.backend.sandbox.kernel.data_plane.fetch_query_page") as fetch:+ page = kernel_runner.fetch_page({**payload, "offset": 250, "limit": 50})+ fetch.assert_not_called()+ self.assertEqual(page["rows"][0], [250])+ self.assertEqual(len(page["rows"]), 50)+ self.assertTrue(page["has_more"]) # cache is incomplete — more rows exist beyond it++ def test_page_beyond_incomplete_cache_falls_back_to_requery(self):+ payload, _result, _ = self._run_and_cache("r-cache-2", rows_returned=301)+ with patch(+ "products.notebooks.backend.sandbox.kernel.data_plane.fetch_query_page",+ return_value=(["n"], [(i,) for i in range(10)], [["n", "Int64"]]),+ ) as fetch:+ kernel_runner.fetch_page({**payload, "offset": 290, "limit": 50})+ self.assertEqual(fetch.call_args.kwargs["offset"], 290)++ def test_complete_cache_reports_no_more_rows(self):+ payload, result, _ = self._run_and_cache("r-cache-3", rows_returned=120)+ self.assertTrue(result["has_more"]) # 120 rows > the 50-row first page+ with patch("products.notebooks.backend.sandbox.kernel.data_plane.fetch_query_page") as fetch:+ page = kernel_runner.fetch_page({**payload, "offset": 100, "limit": 50})+ fetch.assert_not_called()+ self.assertEqual(len(page["rows"]), 20)+ self.assertFalse(page["has_more"])++ @parameterized.expand(+ [+ ("more_rows_exist", 6, True, 5), # limit+1 rows came back → has_more, trimmed to limit+ ("exact_page", 5, False, 5),+ ("short_page", 2, False, 2),+ ]+ )+ def test_fetch_page_has_more_via_limit_plus_one(self, _name, rows_returned, expected_has_more, expected_rows):+ payload = {"code": "select 1", "data_plane_url": "u", "data_plane_token": "t", "offset": 10, "limit": 5}+ with patch(+ "products.notebooks.backend.sandbox.kernel.data_plane.fetch_query_page",+ return_value=(["n"], [(i,) for i in range(rows_returned)], [["n", "Int64"]]),+ ) as mock_fetch:+ page = kernel_runner.fetch_page(payload)+ self.assertEqual(mock_fetch.call_args.kwargs["limit"], 6) # fetches limit+1+ self.assertEqual(mock_fetch.call_args.kwargs["offset"], 10)+ self.assertEqual(page["has_more"], expected_has_more)+ self.assertEqual(len(page["rows"]), expected_rows)++ def test_kernel_polls_until_the_arrow_result_arrives(self):+ # The kernel must follow the enqueue → poll protocol: accept the 202 query_id,+ # keep polling through "running" responses, and decode the eventual Arrow 200.+ from products.notebooks.backend.sandbox.kernel import data_plane as kernel_data_plane++ class _FakeResponse(io.BytesIO):+ def __init__(self, content_type: str, body: bytes):+ super().__init__(body)+ self.headers = {"Content-Type": content_type}++ def __exit__(self, *args):+ return False # keep readable after the with-block, like a drained HTTP response++ arrow_bytes = _rows_to_arrow_bytes(["n"], [(7,)], [["n", "Int64"]])+ responses = iter(+ [+ _FakeResponse("application/json", b'{"query_id": "q1"}'),+ _FakeResponse("application/json", b'{"status": "running"}'),+ _FakeResponse("application/vnd.apache.arrow.stream", arrow_bytes),+ ]+ )+ polled_urls: list[str] = []++ def fake_urlopen(request, timeout=None):+ polled_urls.append(request.full_url)+ return next(responses)++ with (+ patch.object(kernel_data_plane.urllib.request, "urlopen", side_effect=fake_urlopen),+ patch.object(kernel_data_plane.time, "sleep"),+ ):+ columns, rows, _types = kernel_data_plane.fetch_query_page("http://backend/dp", "t", "select 1", limit=5)+ self.assertEqual((columns, rows), (["n"], [(7,)]))+ self.assertEqual(polled_urls[1:], ["http://backend/dp/q1/", "http://backend/dp/q1/"])+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: