:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(notebooks): run SQL joins over Python frames in local DuckDB (#69032)
Sinan Kucukkoseler92e4b814ecc3
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 7caf08a70d56..ba2c587e740a 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -4897,7 +4897,7 @@ const api = {data: {node_id: stringcode: string- refs?: Record<string, string>+ refs?: Record<string, { node_id: string; kind: 'hogql' | 'local' }>node_type?: 'hogql' | 'python'output_name?: string}diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.tsindex 1dea80c8101c..592c1e54076f 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeContent.ts@@ -284,19 +284,19 @@ export const getUniqueSqlV2ReturnVariable = (}// Markdown notebooks hold their cells as component tags inside a single markdown attribute,-// so walking the tiptap JSON alone never finds them. Expand `<SQLV2 …>` tags into+// so walking the tiptap JSON alone never finds them. Expand the given cell tag into// tiptap-shaped nodes so the collectors and the dependency graph see the same cells in both-// notebook formats. Scoped to SQLV2: expanding the other node types here would change their-// (currently markdown-blind) summaries and disambiguated naming.-const expandMarkdownNotebookSqlV2Nodes = (node: any): JSONContent[] => {+// notebook formats. Scoped to the revamped-notebook cell types (SQLV2 + kernel Python):+// expanding the other node types would change their (markdown-blind) summaries and naming.+const expandMarkdownNotebookNodesOfType = (node: any, nodeType: NotebookNodeType): JSONContent[] => {if (typeof node?.attrs?.markdown !== 'string') {return []}return parseMarkdownNotebook(node.attrs.markdown).nodes.flatMap((block) =>- block.type === 'component' && block.tagName === NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG[NotebookNodeType.SQLV2]+ block.type === 'component' && block.tagName === NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG[nodeType]? [{- type: NotebookNodeType.SQLV2,+ type: nodeType,attrs: {...block.props,// Prefer the persisted nodeId prop: the parsed block id is a content@@ -313,6 +313,9 @@ const expandMarkdownNotebookSqlV2Nodes = (node: any): JSONContent[] => {)}+const expandMarkdownNotebookSqlV2Nodes = (node: any): JSONContent[] =>+ expandMarkdownNotebookNodesOfType(node, NotebookNodeType.SQLV2)+export const collectSqlV2Nodes = (content?: JSONContent | null): SqlV2NodeSummary[] => {if (!content || typeof content !== 'object') {return []@@ -384,6 +387,47 @@ export const collectPythonNodes = (content?: JSONContent | null): PythonNodeSummreturn nodes}+export type PythonKernelNodeSummary = {+ nodeId: string+ returnVariable: string+}++// Kernel-run Python cells (revamped notebooks): each binds its result to `returnVariable` in+// the kernel namespace. Unlike the SQL collectors the names are NOT disambiguated — they are+// exactly the kernel variables, so a duplicated returnVariable means last-run-wins, matching+// kernel semantics. Markdown-aware (unlike the legacy collectPythonNodes) because revamped+// markdown notebooks store their cells as `<PythonV2 …/>` component tags.+export const collectPythonKernelNodes = (content?: JSONContent | null): PythonKernelNodeSummary[] => {+ if (!content || typeof content !== 'object') {+ return []+ }++ const nodes: PythonKernelNodeSummary[] = []++ const walk = (node: any): void => {+ if (!node || typeof node !== 'object') {+ return+ }+ if (node.type === NotebookNodeType.PythonV2) {+ const attrs = node.attrs ?? {}+ const returnVariable =+ typeof attrs.returnVariable === 'string' && attrs.returnVariable.trim()+ ? attrs.returnVariable.trim()+ : 'df'+ nodes.push({ nodeId: attrs.nodeId ?? '', returnVariable })+ }+ if (node.type === NotebookNodeType.MarkdownNotebook) {+ expandMarkdownNotebookNodesOfType(node, NotebookNodeType.PythonV2).forEach(walk)+ }+ if (Array.isArray(node.content)) {+ node.content.forEach(walk)+ }+ }++ walk(content)+ return nodes+}+export const collectHogqlSqlNodes = (content?: JSONContent | null): HogqlSqlNodeSummary[] => {if (!content || typeof content !== 'object') {return []diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.tsindex 53f870a80624..d612da2f5815 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.test.ts@@ -41,32 +41,58 @@ describe('notebookNodeSQLV2Logic', () => {attrs: { nodeId, returnVariable },})+ const pythonNode = (nodeId: string, returnVariable?: string): JSONContent => ({+ type: NotebookNodeType.PythonV2,+ attrs: { nodeId, returnVariable },+ })+const doc = (...children: JSONContent[]): JSONContent => ({type: 'doc',content: children,})+ const hogql = (node_id: string): { node_id: string; kind: 'hogql' } => ({ node_id, kind: 'hogql' })+ const local = (node_id: string): { node_id: string; kind: 'local' } => ({ node_id, kind: 'local' })+it('maps each named sibling to its node id, excluding the running node itself', () => {// Including self would inline the node as a CTE of its own name — a cycle the backend rejects.const document = doc(sqlNode('a', 'df1'), sqlNode('self', 'df2'), sqlNode('c', 'df3'))- expect(collectSqlV2Refs(document, 'self')).toEqual({ df1: 'a', df3: 'c' })+ expect(collectSqlV2Refs(document, 'self')).toEqual({ df1: hogql('a'), df3: hogql('c') })})it('disambiguates duplicate names the way the dependency graph does', () => {// Raw attributes would let node b shadow node a under the shared name —// the join would silently run against the wrong node's data.const document = doc(sqlNode('a', 'sql_df'), sqlNode('b', 'sql_df'), sqlNode('self', 'sql_df'))- expect(collectSqlV2Refs(document, 'self')).toEqual({ sql_df: 'a', sql_df_2: 'b' })+ expect(collectSqlV2Refs(document, 'self')).toEqual({ sql_df: hogql('a'), sql_df_2: hogql('b') })})it('resolves blank names to the default the dependency graph shows', () => {const document = doc(sqlNode('a', ''), sqlNode('b', ' '))- expect(collectSqlV2Refs(document, 'self')).toEqual({ sql_df: 'a', sql_df_2: 'b' })+ expect(collectSqlV2Refs(document, 'self')).toEqual({ sql_df: hogql('a'), sql_df_2: hogql('b') })})it('finds SQLV2 nodes nested inside other content', () => {const document = doc({ type: 'column', content: [sqlNode('a', 'df1')] })- expect(collectSqlV2Refs(document, 'self')).toEqual({ df1: 'a' })+ expect(collectSqlV2Refs(document, 'self')).toEqual({ df1: hogql('a') })+ })++ it('collects python cells as local refs under their kernel variable name', () => {+ // Journey 5: a SQL node referencing new_events must reroute to DuckDB, which only+ // happens if the python cell's returnVariable reaches the backend as a local ref.+ const document = doc(sqlNode('a', 'df1'), pythonNode('py', 'new_events'), pythonNode('py2'))+ expect(collectSqlV2Refs(document, 'self')).toEqual({+ df1: hogql('a'),+ new_events: local('py'),+ df: local('py2'), // returnVariable defaults to 'df', matching the python cell UI+ })+ })++ it('a sql ref wins a name collision with a python cell', () => {+ // SQL names are disambiguated in the UI; kernel variables are not — renaming the+ // local ref would break its correspondence with the kernel namespace, so it drops.+ const document = doc(sqlNode('a', 'df1'), pythonNode('py', 'df1'))+ expect(collectSqlV2Refs(document, 'self')).toEqual({ df1: hogql('a') })})it('collects refs from markdown notebook cells, preferring their persisted nodeId', () => {@@ -78,12 +104,18 @@ describe('notebookNodeSQLV2Logic', () => {serializeMarkdownNotebookComponent('SQLV2', { nodeId: 'a', returnVariable: 'df1', code: 'select 1' }),serializeMarkdownNotebookComponent('SQLV2', { nodeId: 'self', returnVariable: 'df2', code: '' }),serializeMarkdownNotebookComponent('SQLV2', { returnVariable: 'df3', code: 'select 3' }),+ serializeMarkdownNotebookComponent('PythonV2', {+ nodeId: 'py',+ returnVariable: 'new_events',+ code: 'x = 1',+ }),].join('\n\n')const refs = collectSqlV2Refs(buildMarkdownNotebookContent(markdown), 'self')- expect(refs.df1).toEqual('a')+ expect(refs.df1).toEqual(hogql('a'))expect(refs.df2).toBeUndefined()// Without a persisted nodeId the cell falls back to its parsed fingerprint id.- expect(refs.df3).toMatch(/^mdn-/)+ expect(refs.df3?.node_id).toMatch(/^mdn-/)+ expect(refs.new_events).toEqual(local('py'))})})@@ -108,12 +140,16 @@ describe('notebookNodeSQLV2Logic', () => {it('dispatches a python run with its node type and output name', async () => {mount()- logic.actions.runQuery('df.head()', { sql_df: 'other' }, { nodeType: 'python', outputName: 'df' })+ logic.actions.runQuery(+ 'df.head()',+ { sql_df: { node_id: 'other', kind: 'hogql' } },+ { nodeType: 'python', outputName: 'df' }+ )await expectLogic(logic).toDispatchActions(['runQuery', 'startPolling'])expect(runSpy).toHaveBeenCalledWith('nb1', {node_id: 'n1',code: 'df.head()',- refs: { sql_df: 'other' },+ refs: { sql_df: { node_id: 'other', kind: 'hogql' } },node_type: 'python',output_name: 'df',})diff --git a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.tsindex 7d9aaa9eaf0f..71731d33f9a8 100644--- a/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts+++ b/frontend/src/scenes/notebooks/Nodes/notebookNodeSQLV2Logic.ts@@ -5,27 +5,45 @@ import { JSONContent } from 'lib/components/RichContentEditor/types'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { NotebookOperation, notebookOperationsLogic } from '../Notebook/notebookOperationsLogic'-import { collectSqlV2Nodes } from './notebookNodeContent'+import { collectPythonKernelNodes, collectSqlV2Nodes } from './notebookNodeContent'import { NotebookNodeSQLV2Result } from './NotebookNodeSQLV2'import type { notebookNodeSQLV2LogicType } from './notebookNodeSQLV2LogicType'-// Map every SQLV2 sibling's dataframe name -> node id, excluding the running node itself.-// Delegates to collectSqlV2Nodes so duplicate names get the same disambiguated form the-// dependency graph shows (sql_df, sql_df_2, …) — raw attributes would let a later duplicate-// silently shadow the node the user actually referenced. The backend resolves each referenced-// node to its last-run query and inlines it as a CTE — the frontend only supplies the wiring.-export function collectSqlV2Refs(doc: JSONContent | null | undefined, selfNodeId: string): Record<string, string> {- const refs: Record<string, string> = {}+export type SqlV2RunRef = {+ node_id: string+ // 'hogql' is a SQL node's query definition; 'local' is a dataframe a Python cell bound in+ // the kernel namespace. The backend routes a SQL run to ClickHouse or the sandbox's DuckDB+ // based on which kinds the query actually references.+ kind: 'hogql' | 'local'+}++// Map every sibling cell's dataframe name -> {node id, kind}, excluding the running node itself.+// SQLV2 siblings delegate to collectSqlV2Nodes so duplicate names get the same disambiguated+// form the dependency graph shows (sql_df, sql_df_2, …) — raw attributes would let a later+// duplicate silently shadow the node the user actually referenced. Python siblings contribute+// their returnVariable verbatim (it IS the kernel variable); on a name collision the SQL ref+// wins, since SQL names are already disambiguated in the UI and kernel variables are not.+// The backend resolves each referenced hogql node to its last-run query — the frontend only+// supplies the wiring.+export function collectSqlV2Refs(doc: JSONContent | null | undefined, selfNodeId: string): Record<string, SqlV2RunRef> {+ const refs: Record<string, SqlV2RunRef> = {}for (const node of collectSqlV2Nodes(doc)) {if (node.nodeId && node.nodeId !== selfNodeId) {- refs[node.returnVariable] = node.nodeId+ refs[node.returnVariable] = { node_id: node.nodeId, kind: 'hogql' }+ }+ }+ for (const node of collectPythonKernelNodes(doc)) {+ if (node.nodeId && node.nodeId !== selfNodeId && !(node.returnVariable in refs)) {+ refs[node.returnVariable] = { node_id: node.nodeId, kind: 'local' }}}return refs}const POLL_INTERVAL_MS = 1000-const MAX_POLL_ATTEMPTS = 150 // ~2.5 minutes at 1s+// Must outlast the backend's own run budgets (180s data-plane poll deadline, 300s kernel+// execute timeout) plus slack, or a slow-but-successful run gets reported as timed out.+const MAX_POLL_ATTEMPTS = 330 // ~5.5 minutes at 1sexport const SQL_V2_DEFAULT_PAGE_SIZE = 50@@ -66,10 +84,11 @@ export const notebookNodeSQLV2Logic = kea<notebookNodeSQLV2LogicType>([],})),actions({- // refs maps each named sibling node's dataframe name to its node id. A hogql node- // inlines the referenced ones as CTEs (Journey 3); a python node materializes the- // ones its code reads as pandas frames (Journey 4).- runQuery: (code: string, refs: Record<string, string> = {}, opts: RunQueryOptions = {}) => ({+ // refs maps each named sibling cell's dataframe name to {node id, kind}. A SQL node+ // inlines referenced hogql refs as CTEs (Journey 3) — or runs locally in DuckDB when+ // it references a local frame (Journey 5); a python node materializes the hogql refs+ // its code reads as pandas frames (Journey 4).+ runQuery: (code: string, refs: Record<string, SqlV2RunRef> = {}, opts: RunQueryOptions = {}) => ({code,refs,opts,diff --git a/products/notebooks/backend/migrations/0010_notebooknoderun_node_type.py b/products/notebooks/backend/migrations/0010_notebooknoderun_node_type.pynew file mode 100644index 000000000000..ea3ce3aac806--- /dev/null+++ b/products/notebooks/backend/migrations/0010_notebooknoderun_node_type.py@@ -0,0 +1,25 @@+# Generated by Django 5.2.14 on 2026-07-07 17:37++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("notebooks", "0009_notebooknoderun_code"),+ ]++ operations = [+ migrations.AddField(+ model_name="notebooknoderun",+ name="node_type",+ field=models.CharField(+ choices=[+ ("hogql", "hogql"),+ ("python", "python"),+ ("duckdb", "duckdb"),+ ],+ default="hogql",+ max_length=20,+ ),+ ),+ ]diff --git a/products/notebooks/backend/migrations/max_migration.txt b/products/notebooks/backend/migrations/max_migration.txtindex a346e0e0095f..be3b4447a6c4 100644--- a/products/notebooks/backend/migrations/max_migration.txt+++ b/products/notebooks/backend/migrations/max_migration.txt@@ -1 +1 @@-0009_notebooknoderun_code+0010_notebooknoderun_node_typediff --git a/products/notebooks/backend/models.py b/products/notebooks/backend/models.pyindex ed6decba3f95..89fb50ccdccb 100644--- a/products/notebooks/backend/models.py+++ b/products/notebooks/backend/models.py@@ -191,11 +191,19 @@ class NotebookNodeRun(TeamScopedRootMixin, UUIDModel):DONE = "done", "done"FAILED = "failed", "failed"+ class NodeType(models.TextChoices):+ HOGQL = "hogql", "hogql"+ PYTHON = "python", "python"+ DUCKDB = "duckdb", "duckdb"+# db_constraint=False: creating a real FK to the hot posthog_team table locks it on deploy.# Tenant isolation is still enforced by the fail-closed TeamScopedRootMixin manager.team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)notebook = models.ForeignKey("notebooks.Notebook", on_delete=models.CASCADE)node_id = models.CharField(max_length=128)+ # How the run executed: hogql pushed to ClickHouse (pages re-query by `code`); python and+ # duckdb ran in the sandbox kernel (pages slice the on-sandbox result frame by `result_id`).+ node_type = models.CharField(choices=NodeType, default=NodeType.HOGQL, max_length=20)# 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="")diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.pyindex 0c3c60d945f5..359c55261b4b 100644--- a/products/notebooks/backend/presentation/views/notebook.py+++ b/products/notebooks/backend/presentation/views/notebook.py@@ -27,6 +27,7 @@ from rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.serializers import BaseSerializer+from posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.query import execute_hogql_queryfrom posthog.api.forbid_destroy_model import ForbidDestroyModel@@ -69,10 +70,10 @@ from products.notebooks.backend.sql_v2 import (sql_v2_page_lock_key,)from products.notebooks.backend.sql_v2_references import (- PythonNodeRef,+ SQLV2Ref,SQLV2ReferenceError,resolve_python_node_inputs,- resolve_sql_v2_references,+ resolve_sql_node_run,)from products.notebooks.backend.sql_v2_serializers import (NotebookSQLV2PageRequestSerializer,@@ -980,43 +981,57 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDnotebook = self._get_notebook_for_kernel()self._require_query_access()- # Resolve each referenced node to its last-run query (not its live editor text), so a- # join recomputes against the definitions that produced the results on screen. Inlining- # happens once here, so the run stores a self-contained query and paging re-queries it- # without re-resolving refs.- ref_node_ids: dict[str, str] = serializer.validated_data.get("refs") or {}+ # Resolve each referenced hogql node to its last-run query (not its live editor text),+ # so a join recomputes against the definitions that produced the results on screen.+ # Inlining happens once here, so the run stores a self-contained query and paging+ # re-queries it without re-resolving refs. Local refs (Python-made frames) carry no+ # query — they live in the kernel namespace.+ ref_specs: dict[str, dict] = serializer.validated_data.get("refs") or {}+ hogql_node_ids = {spec["node_id"] for spec in ref_specs.values() if spec["kind"] == "hogql"}# One DISTINCT ON query fetches the latest DONE run (id + code) for every referenced node.+ latest_runs = (+ NotebookNodeRun.objects.for_team(self.team_id)+ .filter(notebook=notebook, node_id__in=hogql_node_ids, status=NotebookNodeRun.Status.DONE)+ .order_by("node_id", "-created_at")+ .distinct("node_id")+ .values_list("node_id", "id", "code", "node_type")+ )+ # A SQL node's runs can alternate between hogql and duckdb (Journey 5 rerouting), so a+ # kind=hogql ref is only trustworthy when the node's LATEST result really is hogql —+ # a duckdb run's code is raw, non-self-contained SQL naming kernel frames, and inlining+ # it as a CTE would ship it to ClickHouse. Treat that node as not-run instead.latest_by_node: dict[str, tuple[str, str]] = {node_id: (str(run_id), code)- for node_id, run_id, code in (- NotebookNodeRun.objects.for_team(self.team_id)- .filter(notebook=notebook, node_id__in=set(ref_node_ids.values()), status=NotebookNodeRun.Status.DONE)- .order_by("node_id", "-created_at")- .distinct("node_id")- .values_list("node_id", "id", "code")- )+ for node_id, run_id, code, run_type in latest_runs+ if run_type == NotebookNodeRun.NodeType.HOGQL}+ refs: dict[str, SQLV2Ref] = {}+ for name, spec in ref_specs.items():+ if spec["kind"] == "local":+ refs[name] = SQLV2Ref(kind="local")+ else:+ latest = latest_by_node.get(spec["node_id"])+ refs[name] = SQLV2Ref(+ kind="hogql",+ node_id=spec["node_id"],+ run_id=latest[0] if latest else None,+ last_run_code=latest[1] if latest else None,+ )node_type = serializer.validated_data["node_type"]code = serializer.validated_data["code"]output_name = serializer.validated_data["output_name"]try:if node_type == "python":- # A python node stores its code as-is; referenced frames become materialization inputs,+ # A python node stores its code as-is; referenced frames become kernel inputs,# keyed by the upstream run_id so a re-run yields a fresh (not stale) frame.- python_refs: dict[str, PythonNodeRef | None] = {- name: (PythonNodeRef(node_id, *latest_by_node[node_id]) if node_id in latest_by_node else None)- for name, node_id in ref_node_ids.items()- }- run_code, inputs = code, resolve_python_node_inputs(code, python_refs)+ run_code, inputs = code, resolve_python_node_inputs(code, refs)else:- # A join recomputes against each ref's last-run query (not its live editor text), so- # inlining happens once here and paging re-queries the stored self-contained query.- last_run_code: dict[str, str | None] = {- name: (latest_by_node[node_id][1] if node_id in latest_by_node else None)- for name, node_id in ref_node_ids.items()- }- run_code, inputs = resolve_sql_v2_references(code, last_run_code), []- except SQLV2ReferenceError as e:+ # A SQL node pushes to ClickHouse — unless it references a local frame, which+ # reroutes it to the sandbox's DuckDB (Journey 5).+ node_type, run_code, inputs = resolve_sql_node_run(code, refs)+ # ExposedHogQLError: with refs present the user's own code is parsed at dispatch, so a+ # plain typo raises here — it's a bad query (400 with the parse message), not a 500.+ except (SQLV2ReferenceError, ExposedHogQLError) as e:return Response({"detail": str(e)}, status=400)run = NotebookNodeRun.objects.create(@@ -1024,6 +1039,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDnotebook=notebook,node_id=serializer.validated_data["node_id"],code=run_code,+ node_type=node_type,status=NotebookNodeRun.Status.RUNNING,)@@ -1129,14 +1145,19 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDif 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,- )+ if run.node_type == NotebookNodeRun.NodeType.HOGQL:+ # Runs recorded before the code column existed (default "") have no query to page.+ # Send that to the kernel and it round-trips into an opaque "page fetch failed"; catch+ # it here with guidance instead.+ if not run.code.strip():+ return Response(+ {"detail": "This result predates page support — re-run the query to page through it."},+ status=400,+ )+ # A kernel run (python/duckdb) pages by slicing its result frame in the sandbox, so it+ # needs the result_id its envelope advertised — no frame written means nothing to page.+ elif not run.result_id:+ return Response({"detail": "This result has no pageable frame — re-run the node."}, status=400)# An out-of-cache page holds this worker synchronously for up to the kernel timeout,# so cap each user at one in-flight page fetch — otherwise parallel paging requestsdiff --git a/products/notebooks/backend/sandbox/kernel/bootstrap.py b/products/notebooks/backend/sandbox/kernel/bootstrap.pyindex f87c7cc08ade..f1422b18c575 100644--- a/products/notebooks/backend/sandbox/kernel/bootstrap.py+++ b/products/notebooks/backend/sandbox/kernel/bootstrap.py@@ -1,4 +1,4 @@-"""The `_ph` kernel session injected into the ipykernel namespace (Journey 4).+"""The `_ph` kernel session injected into the ipykernel namespace (Journeys 4/5).(Not to be confused with the legacy stdout "notebook bridge" in kernel_runtime.py thatthis whole path replaces — nothing here smuggles RPCs over stdout. `run_node` reads@@ -16,6 +16,12 @@ kernel-server hands it a single call, `_ph.run_node(payload)`, per run.3. returns the result envelope (the kernel-server, not the kernel, POSTs it back);4. writes the produced frame to a local Arrow file so `/page` can slice it later.+A DuckDB node (Journey 5 — SQL over local frames, which can't push to ClickHouse) shares+steps 1/3/4 but runs its SQL on the session's persistent DuckDB connection instead of+IPython, with local pandas frames registered so the query can join them against the+mmapped HogQL inputs; the result binds back into the user namespace under `output_name`+for downstream nodes.+Heavy deps (duckdb/pandas/pyarrow/IPython) are imported at module load — this module onlyever runs inside the kernel, where they are present, never on the kernel-server startuppath (which stays stdlib + pyarrow). matplotlib loads eagerly at session construction so@@ -90,14 +96,21 @@ class KernelSession:def run_node(self, payload: dict[str, Any]) -> dict[str, Any]:node = payload.get("node") or {}+ node_type = str(node.get("type") or "python")preview_rows = int(payload.get("page_limit") or _DEFAULT_PREVIEW_ROWS)try:- self._register_inputs(payload.get("inputs") or [])+ self._register_inputs(payload.get("inputs") or [], node_type=node_type)except Exception as exc: # noqa: BLE001 — a bad input must still produce an envelopereturn envelope.from_python_execution(status="error", error=f"Input registration failed: {exc}")+ if node_type == "duckdb":+ return self._run_duckdb_node(node, preview_rows)+self._plt.close("all") # start from a clean figure state so we only capture this run's plots- with capture_output() as captured:+ # display=False: only stdout/stderr are consumed (figures come from matplotlib+ # directly). Capturing display would also swap the ZMQ shell's display machinery,+ # which silently drops run_cell's last-expression result inside an ipykernel.+ with capture_output(display=False) as captured:execution = self.shell.run_cell(node.get("code") or "", store_history=False)media, omitted_figures = self._collect_media()@@ -105,16 +118,31 @@ class KernelSession:stderr = _truncate_stream(captured.stderr)if omitted_figures:stderr += f"\n[{omitted_figures} figure(s) omitted: over the media size cap]"- if execution.error_in_exec is not None:+ # error_before_exec covers syntax/compile errors — run_cell reports those without+ # setting error_in_exec, and they must not masquerade as a successful empty run.+ error = execution.error_in_exec or execution.error_before_exec+ if error is not None:return envelope.from_python_execution(status="error",stdout=stdout,stderr=stderr,- error=f"{type(execution.error_in_exec).__name__}: {execution.error_in_exec}",+ error=f"{type(error).__name__}: {error}",media=media,)- result_df = self._result_frame(node.get("output_name"), execution.result)+ output_name = str(node.get("output_name") or "")+ result_df = self._result_frame(output_name, execution.result)+ if output_name:+ if result_df is not None:+ # Bind for downstream nodes: pandas in the namespace (Python) and a DuckDB+ # entry (SQL) — the same contract as a DuckDB node's output_name.+ self.shell.user_ns[output_name] = result_df+ self._register_duck(output_name, result_df)+ else:+ # No frame this run: drop any stale DuckDB registration so SQL can't keep+ # reading a previous run's rows. The namespace is left to the user's code —+ # it may hold a deliberate non-frame value under this name.+ self._unregister_duck(output_name)columns, types, rows, row_count, has_more = self._preview(result_df, preview_rows)# result_id keys the on-disk frame for paging — only advertise one that actually exists.result_id = self._write_result_frame(result_df) if result_df is not None else None@@ -131,34 +159,97 @@ class KernelSession:result_id=result_id,)- def _register_inputs(self, inputs: list[dict[str, Any]]) -> None:+ def _register_inputs(self, inputs: list[dict[str, Any]], node_type: str) -> None:+ bind_pandas = node_type == "python"for spec in inputs:name = spec["name"]kind = spec.get("kind")if kind == "hogql":- # mmap the server-streamed frame; register zero-copy in DuckDB and bind pandas- # for Python code (the one step that materializes in RAM).- table = pa.ipc.open_file(spec["path"]).read_all()- self.duck.register(name, table)- self._registered.add(name)- self.shell.user_ns[name] = table.to_pandas()+ # mmap the server-streamed frame and register it zero-copy in DuckDB (the+ # buffers keep referencing the map after the handle closes); for a Python+ # node additionally bind pandas (the one step that materializes in RAM).+ with pa.memory_map(spec["path"]) as source:+ table = pa.ipc.open_file(source).read_all()+ self._register_duck(name, table)+ if bind_pandas:+ self.shell.user_ns[name] = table.to_pandas()elif kind == "local":- # Made by an earlier node in this kernel; it must already be present.- if name not in self.shell.user_ns and name not in self._registered:- raise KeyError(f"local frame '{name}' is not in the kernel")+ # Made by an earlier node in this kernel; it must currently be present.+ if name in self.shell.user_ns:+ frame = self.shell.user_ns[name]+ if isinstance(frame, pd.DataFrame):+ # Re-register every run so SQL sees the frame's current value.+ self._register_duck(name, frame)+ else:+ # Rebound to a non-frame since it was registered: drop the stale DuckDB+ # entry so SQL can't silently read old data. Python code can still use+ # the object as-is; SQL over it is a clear error instead of wrong rows.+ self._unregister_duck(name)+ if node_type == "duckdb":+ raise TypeError(f"'{name}' is not a dataframe in the kernel (it is {type(frame).__name__})")+ else:+ # Never made — or deleted since it was registered, in which case the stale+ # registration must go so SQL can't keep reading the old frame.+ self._unregister_duck(name)+ raise KeyError(f"local frame '{name}' is not in the kernel — run the node that creates it first")else:raise ValueError(f"unknown input kind '{kind}' for '{name}'")- def _result_frame(self, output_name: str | None, last_expression: Any) -> "pd.DataFrame | None":- # Prefer the explicitly named output; fall back to the cell's last-expression value.+ def _register_duck(self, name: str, frame: Any) -> None:+ self._unregister_duck(name) # replace cleanly when a frame was registered before+ self.duck.register(name, frame)+ self._registered.add(name)++ def _unregister_duck(self, name: str) -> None:+ try:+ self.duck.unregister(name)+ except Exception: # noqa: BLE001 — nothing registered under this name yet+ pass+ self._registered.discard(name)++ def _run_duckdb_node(self, node: dict[str, Any], preview_rows: int) -> dict[str, Any]:+ output_name = node.get("output_name") or ""+ try:+ relation = self.duck.sql(node.get("code") or "")+ # Non-SELECT statements (DDL etc.) yield no relation — a valid, frameless run.+ result_df = relation.df() if relation is not None else None+ except Exception as exc: # noqa: BLE001 — any DuckDB failure must still produce an envelope+ return envelope.from_python_execution(status="error", error=f"{type(exc).__name__}: {exc}")if output_name:- candidate = self.shell.user_ns.get(output_name)- if isinstance(candidate, pd.DataFrame):- return candidate+ if result_df is not None:+ # Bind for downstream nodes: pandas in the namespace (Python) and a DuckDB entry (SQL).+ self.shell.user_ns[output_name] = result_df+ self._register_duck(output_name, result_df)+ else:+ # A frameless run (DDL etc.) invalidates any previous binding under this name —+ # downstream nodes must not silently keep reading the previous run's frame.+ self.shell.user_ns.pop(output_name, None)+ self._unregister_duck(output_name)+ columns, types, rows, row_count, has_more = self._preview(result_df, preview_rows)+ result_id = self._write_result_frame(result_df) if result_df is not None else None+ return envelope.from_python_execution(+ status="ok",+ columns=columns,+ types=types,+ rows=rows,+ row_count=row_count,+ has_more=has_more,+ result_id=result_id,+ )++ def _result_frame(self, output_name: str | None, last_expression: Any) -> "pd.DataFrame | None":+ # Prefer this run's last-expression value; the named output in the namespace is only+ # a fallback (it covers cells whose last line is an assignment, which yields no+ # expression value). Namespace-first would resurface the frame a previous run bound+ # under output_name instead of this run's fresh result.if isinstance(last_expression, pd.DataFrame):return last_expressionif isinstance(last_expression, pd.Series):return last_expression.to_frame()+ if output_name:+ candidate = self.shell.user_ns.get(output_name)+ if isinstance(candidate, pd.DataFrame):+ return candidatereturn Nonedef _preview(diff --git a/products/notebooks/backend/sandbox/kernel/executor.py b/products/notebooks/backend/sandbox/kernel/executor.pyindex aa9c8ef62a62..d78849da90bf 100644--- a/products/notebooks/backend/sandbox/kernel/executor.py+++ b/products/notebooks/backend/sandbox/kernel/executor.py@@ -1,4 +1,4 @@-"""Owns the ipykernel child and runs Python nodes through it (Journey 4, arch build step 2).+"""Owns the ipykernel child and runs kernel nodes through it (Journeys 4/5, arch build steps 2+5).Sandbox-only: this is the one module that imports `jupyter_client` and drives a livekernel, both of which exist only in the notebook sandbox image — so it is exercised there,@@ -7,7 +7,7 @@ in test_kernel_bootstrap). Everything network/credential-bearing stays in this pkernel receives only local file paths and node code, never a token (division of labor insql_v2_kernel_architecture.md).-Flow for a Python node:+Flow for a kernel node (python or duckdb — the kernel branches on node.type):1. materialize each HogQL input — the server streams the full CH result to a local Arrowfile keyed by query_hash (reused when the upstream query is unchanged);2. hand the kernel `_ph.run_node(payload)` (paths only) and read back the envelope it writes;@@ -49,7 +49,7 @@ class KernelExecutor:self._kc: Any = Noneself._lock = threading.Lock()- def run_python_node(self, payload: dict[str, Any]) -> dict[str, Any]:+ def run_kernel_node(self, payload: dict[str, Any]) -> dict[str, Any]:with self._lock: # a kernel has one namespace — concurrent runs are meaninglesstry:self._ensure_kernel()diff --git a/products/notebooks/backend/sandbox/kernel/result_store.py b/products/notebooks/backend/sandbox/kernel/result_store.pynew file mode 100644index 000000000000..f74eb8c9f09f--- /dev/null+++ b/products/notebooks/backend/sandbox/kernel/result_store.py@@ -0,0 +1,48 @@+"""Read-only page slices of on-sandbox result frames (arch doc: the result-store reader).++A kernel node (python/duckdb) writes its result to `/data/results/<result_id>.arrow`;+`/page` requests for it are served here, in the **server** process — a memory-mapped+pyarrow slice that never queues behind a running cell and never touches the data plane+(the node's code is not a HogQL query, so there is nothing to re-query).++Frames live only on the sandbox disk: after a sandbox death the file is gone and the+node has to be re-run — the documented alive-only trade-off in sql_v2_result_delivery.md.+"""++import os+import uuid+from typing import Any++import pyarrow as pa++from . import envelope+from .data_plane import _table_to_rows_and_types++_RESULTS_DIR = "/data/results"+++class ResultStoreError(Exception):+ """A page request the result store can't serve; message is user-facing."""+++def read_page(result_id: str, offset: int, limit: int, results_dir: str = _RESULTS_DIR) -> dict[str, Any]:+ """Slice one page out of a stored result frame; raises ResultStoreError when it can't."""+ try:+ frame_id = str(uuid.UUID(result_id)) # also confines the path join to a UUID filename+ except (TypeError, ValueError):+ raise ResultStoreError("Invalid result id.")+ path = os.path.join(results_dir, f"{frame_id}.arrow")+ if not os.path.exists(path):+ raise ResultStoreError("This result is no longer in the sandbox — re-run the node.")+ try:+ with pa.memory_map(path) as source:+ table = pa.ipc.open_file(source).read_all()+ except pa.ArrowInvalid as exc:+ raise ResultStoreError(f"Stored result frame is unreadable: {exc}")+ columns, rows, types = _table_to_rows_and_types(table.slice(offset, limit))+ return {+ "columns": columns,+ "types": types,+ "rows": envelope.json_safe_rows(rows),+ "has_more": offset + limit < table.num_rows,+ }diff --git a/products/notebooks/backend/sandbox/kernel/runner.py b/products/notebooks/backend/sandbox/kernel/runner.pyindex 660f3ce102ea..bb491fed4424 100644--- a/products/notebooks/backend/sandbox/kernel/runner.py+++ b/products/notebooks/backend/sandbox/kernel/runner.py@@ -38,27 +38,27 @@ _result_cache_lock = threading.Lock()def execute_run(payload: dict[str, Any]) -> None:"""Entry point for a /run request, invoked on a background thread.- Routing rule (sql_v2_kernel_architecture.md): a Python node runs in the ipykernel- (materialize inputs, run code); a pure-HogQL display node stays a capped data-plane- fetch and never touches the kernel.+ Routing rule (sql_v2_kernel_architecture.md): a kernel node — python or duckdb —+ runs in the ipykernel (materialize inputs, run code); a pure-HogQL display node+ stays a capped data-plane fetch and never touches the kernel."""node = payload.get("node") or {}- if node.get("type") == "python":- result = _run_python_node(payload)+ if node.get("type") in ("python", "duckdb"):+ result = _run_kernel_node(payload)else:result = _build_envelope(payload)_post_callback(payload["callback_url"], payload["callback_token"], result)-def _run_python_node(payload: dict[str, Any]) -> dict[str, Any]:+def _run_kernel_node(payload: dict[str, Any]) -> dict[str, Any]:# Deferred so the server startup path never imports jupyter_client (heavy, sandbox-only).from . import executor # noqa: PLC0415 — keeps jupyter_client off the server import pathtry:- return executor.get_executor().run_python_node(payload)+ return executor.get_executor().run_kernel_node(payload)except Exception as exc: # noqa: BLE001 — a run must always produce a callback envelope- logger.exception("nb_kernel python node run failed")- return envelope.from_error(f"Python node failed in the sandbox: {exc}")+ logger.exception("nb_kernel kernel node run failed")+ return envelope.from_error(f"Node failed in the sandbox: {exc}")def _fetch_capped_page(payload: dict[str, Any], limit: int, offset: int) -> dict[str, Any]:@@ -132,13 +132,22 @@ def _build_envelope(payload: dict[str, Any]) -> dict[str, Any]:def fetch_page(payload: dict[str, Any]) -> dict[str, Any]:- """Serve a /page request: a cached local slice, or a bounded synchronous re-query.+ """Serve a /page request: a result-frame slice, a cached local slice, or a bounded re-query.- Raises DataPlaneError for user-facing query errors; the server maps it to a 400.+ A payload carrying `result_id` is a kernel-node result — it pages exclusively from the+ on-disk result frame (its code is not a HogQL query, so there is no data-plane fallback).+ Raises DataPlaneError/ResultStoreError for user-facing errors; the server maps them to 400."""offset = int(payload.get("offset") or 0)limit = int(payload.get("limit") or _DEFAULT_PAGE_LIMIT)+ result_id = payload.get("result_id")+ if result_id:+ # Deferred so a broken pyarrow install degrades per-request, not at server startup.+ from . import result_store # noqa: PLC0415++ return result_store.read_page(str(result_id), offset, limit)+cached = _cached_page(str(payload.get("run_id") or ""), offset, limit)if cached is not None:return cacheddiff --git a/products/notebooks/backend/sandbox/kernel/server.py b/products/notebooks/backend/sandbox/kernel/server.pyindex 0e70c5886600..854172c46999 100644--- a/products/notebooks/backend/sandbox/kernel/server.py+++ b/products/notebooks/backend/sandbox/kernel/server.py@@ -64,11 +64,11 @@ class KernelServerHandler(BaseHTTPRequestHandler):self._respond(200, {"interrupted": True})def _handle_page(self, payload: dict[str, Any]) -> None:- from . import data_plane # noqa: PLC0415 — keep pyarrow off the server startup path+ from . import data_plane, result_store # noqa: PLC0415 — keep pyarrow off the server startup pathtry:self._respond(200, fetch_page(payload))- except data_plane.DataPlaneError as exc:+ except (data_plane.DataPlaneError, result_store.ResultStoreError) as exc:self._respond(400, {"error": str(exc)})except Exception: # noqa: BLE001 — a page failure must not kill the request thread silentlylogging.getLogger(__name__).exception("nb_kernel page fetch failed")diff --git a/products/notebooks/backend/sql_v2.py b/products/notebooks/backend/sql_v2.pyindex a0da0271c137..52abe98586fd 100644--- a/products/notebooks/backend/sql_v2.py+++ b/products/notebooks/backend/sql_v2.py@@ -281,8 +281,8 @@ def dispatch_sql_v2_run("""Dispatch a run to the in-sandbox kernel-server with a single authed HTTP POST.Returns as soon as the server accepts (202); the result arrives via the callback. A- python node carries the `node`/`inputs` shape the executor consumes; a hogql node keeps- the flat `code` the capped-fetch path reads — the two paths stay additive.+ kernel node (python or duckdb) carries the `node`/`inputs` shape the executor consumes;+ a hogql node keeps the flat `code` the capped-fetch path reads — the paths stay additive."""runtime = ensure_sql_v2_server(notebook, user)assert runtime.server_url # ensure_sql_v2_server always returns a runtime with a live server_url@@ -297,8 +297,8 @@ def dispatch_sql_v2_run("page_limit": DISPLAY_PAGE_LIMIT,"cache_limit": RESULT_CACHE_ROWS,}- if node_type == "python":- payload["node"] = {"type": "python", "code": code, "output_name": output_name}+ if node_type in ("python", "duckdb"):+ payload["node"] = {"type": node_type, "code": code, "output_name": output_name}payload["inputs"] = inputs or []else:payload["code"] = code@@ -312,10 +312,13 @@ def dispatch_sql_v2_run(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.+ """Fetch one result page through the kernel — a bounded synchronous read.- 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.+ A hogql run pages by re-querying its stored code through the data plane with+ LIMIT/OFFSET; a kernel run (python/duckdb) pages by slicing its on-sandbox result+ frame, keyed by `result_id` — its code is not a HogQL query, so no data-plane+ fallback exists for it. 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:@@ -323,17 +326,21 @@ def fetch_sql_v2_page(notebook: Notebook, user: User | None, run: NotebookNodeRucommand_token = mint_command_token(kernel_server_secret(str(runtime.id)), str(run.id))user_id = user.id if isinstance(user, User) else None+ payload: dict = {+ "run_id": str(run.id),+ "offset": offset,+ "limit": limit,+ }+ if run.node_type == NotebookNodeRun.NodeType.HOGQL:+ payload["code"] = run.code+ payload["data_plane_url"] = build_data_plane_url()+ payload["data_plane_token"] = mint_data_plane_token(notebook.short_id, notebook.team_id, user_id)+ else:+ payload["result_id"] = str(run.result_id)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),- },+ json=payload,headers=_sandbox_auth_headers(runtime.server_connect_token, command_token),timeout=_PAGE_POST_TIMEOUT_SECONDS,)diff --git a/products/notebooks/backend/sql_v2_data_plane.py b/products/notebooks/backend/sql_v2_data_plane.pyindex caa2ec8f7a71..d1fb3e991e27 100644--- a/products/notebooks/backend/sql_v2_data_plane.py+++ b/products/notebooks/backend/sql_v2_data_plane.py@@ -135,8 +135,10 @@ def notebook_sql_v2_data_plane(request: HttpRequest) -> HttpResponse:# regardless of the query's own shape (set queries, its own LIMIT, etc.).# The inner query is validated HogQL (parsed above) and the wrapper is re-parsed as HogQL# downstream, so there is no raw-SQL injection; limit/offset are int()-cast.+ # The newline before the closing paren keeps a trailing line comment (`-- …`) in the+ # user's query from swallowing the wrapper.# nosemgrep: semgrep.rules.security.hogql-fstring-audit- wrapped = f"select * from ({data['query']}) limit {int(data['limit'])} offset {int(data['offset'])}"+ wrapped = f"select * from ({data['query']}\n) limit {int(data['limit'])} offset {int(data['offset'])}"try:with tags_context(product=Product.NOTEBOOKS, feature=Feature.QUERY, team_id=team.id):diff --git a/products/notebooks/backend/sql_v2_kernel_architecture.md b/products/notebooks/backend/sql_v2_kernel_architecture.mdindex 66b2bec0b598..60ccae4c6c2f 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 | 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 |+| 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. A hogql run re-queries the data plane with the run’s code + LIMIT/OFFSET; a kernel run (python/duckdb) sends `result_id` and slices its `/data/results/<result_id>.arrow` frame in the server process |+| `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}`.diff --git a/products/notebooks/backend/sql_v2_references.py b/products/notebooks/backend/sql_v2_references.pyindex c9d4903a7d02..138b4282bb01 100644--- a/products/notebooks/backend/sql_v2_references.py+++ b/products/notebooks/backend/sql_v2_references.py@@ -1,4 +1,4 @@-"""Resolve SQLV2 node references by inlining upstream node queries as CTEs (Journey 3).+"""Resolve SQLV2 node references and route each run to its engine (Journeys 3–5).A SQLV2 node is a HogQL *query definition*, not a materialized frame. When one nodereferences another by its dataframe name — ``select … from df1 join df2`` — the whole@@ -11,8 +11,14 @@ Only names the query actually reaches are inlined, transitively and in dependenc(a CTE must be printed before the CTEs that use it). A name the query shadows with itsown ``WITH`` is left alone. Broken definitions that nothing references are never parsed,so an unrelated malformed node can't fail a run.++Journey 5 adds **local** refs — frames a Python node bound in the kernel namespace. A+local frame cannot be pushed to ClickHouse, so a SQL node that references one runs in+the sandbox's DuckDB instead (`resolve_sql_node_run` decides per run), materializing+whatever HogQL refs it also reads — the same input shape Python nodes use."""+import refrom dataclasses import dataclassfrom typing import Any@@ -25,11 +31,33 @@ from posthog.hogql.visitor import TraversingVisitorfrom products.notebooks.backend.python_analysis import analyze_python_globals+# String literals ('' or backslash escapes) and comments, for the routing fallback to blank+# out before scanning: a frame name mentioned in a literal or comment must not trigger DuckDB+# routing. Double-quoted tokens are kept — in DuckDB those are quoted identifiers, i.e. real+# table references. An unbalanced literal simply doesn't match, degrading to the raw scan.+_SQL_LITERALS_AND_COMMENTS = re.compile(r"'(?:[^'\\]|\\.|'')*'|--[^\n]*|/\*.*?\*/", re.DOTALL)+class SQLV2ReferenceError(Exception):"""A reference could not be resolved (cycle, or a referenced definition won't parse). User-facing."""+@dataclass(frozen=True)+class SQLV2Ref:+ """One upstream node available to a run, keyed by its dataframe name.++ kind "hogql" is a query definition — node_id names the upstream node, and run_id /+ last_run_code identify its latest completed run (both None if it has never completed+ one); kind "local" is a frame a Python node bound in the kernel namespace — it has+ no query, only a name.+ """++ kind: str # "hogql" | "local"+ node_id: str | None = None+ run_id: str | None = None+ last_run_code: str | None = None++class _TableReferenceCollector(TraversingVisitor):"""Collect the FROM/JOIN targets of a query that name one of `candidates`.@@ -118,8 +146,10 @@ def resolve_sql_v2_references(code: str, refs: dict[str, str | None]) -> str:# The merged WITH hangs off a SelectQuery; wrap a top-level UNION so it can carry one.# The f-string embeds only `code`, already validated as HogQL by parse_select above; the# wrap is re-parsed here and printed via the AST printer, so no raw SQL reaches ClickHouse.+ # The newline before the closing paren keeps a trailing line comment (`-- …`) in the+ # user's query from swallowing the wrapper.# nosemgrep: semgrep.rules.security.hogql-fstring-audit- root = main if isinstance(main, ast.SelectQuery) else parse_select(f"select * from ({code})")+ root = main if isinstance(main, ast.SelectQuery) else parse_select(f"select * from ({code}\n)")if not isinstance(root, ast.SelectQuery): # narrow for the type checker; the wrap is always a SelectQueryreturn codectes: dict[str, ast.CTE] = dict(root.ctes or {})@@ -131,41 +161,86 @@ def resolve_sql_v2_references(code: str, refs: dict[str, str | None]) -> str:return print_prepared_ast(root, context=HogQLContext(team_id=None), dialect="hogql")-@dataclass(frozen=True)-class PythonNodeRef:- """The latest completed run of an upstream node a Python frame can materialize from."""-- node_id: str- run_id: str- query: str---def resolve_python_node_inputs(code: str, refs: dict[str, PythonNodeRef | None]) -> list[dict[str, Any]]:- """Return the materialization specs for the upstream frames a Python node reads.-- `refs` maps each named upstream node's dataframe name to its **latest completed run**- (or None if it has never completed a run). A Python node references frames as plain- variables, so we materialize only the names its code actually reads — each becomes a- HogQL input the executor fetches to a local Arrow file, keyed by the upstream `run_id`- so a re-run of that node yields a fresh frame (not stale data) and the executor can- evict the node's superseded frames.-- Raises SQLV2ReferenceError if the code reads a known node that has not been run yet.+def _hogql_input(name: str, ref: SQLV2Ref) -> dict[str, Any]:+ """The materialization spec for one HogQL ref: the executor fetches its last-run query to a+ local Arrow file keyed by the upstream run_id, so the same run reuses its frame while a+ re-run materializes fresh data and the node's superseded frames get evicted."""+ if ref.run_id is None or ref.last_run_code is None or not ref.last_run_code.strip():+ raise SQLV2ReferenceError(f"Referenced node '{name}' has not been run yet — run it first.")+ return {+ "name": name,+ "kind": "hogql",+ "node_id": ref.node_id,+ "run_id": ref.run_id,+ "query": ref.last_run_code,+ }+++def resolve_python_node_inputs(code: str, refs: dict[str, SQLV2Ref]) -> list[dict[str, Any]]:+ """Return the input specs for the upstream frames a Python node reads.++ A Python node references frames as plain variables, so only the names its code actually+ reads become inputs: a HogQL ref becomes a materialization spec keyed by the upstream+ run_id (see `_hogql_input`), so a re-run of the upstream node yields a fresh frame (not+ stale data); a local ref becomes a presence assertion — the frame already lives in the+ kernel namespace (bound by the upstream Python node), so the kernel just fails cleanly+ when it doesn't.++ Raises SQLV2ReferenceError if the code reads a HogQL node that has not been run yet."""used = set(analyze_python_globals(code).used)inputs: list[dict[str, Any]] = []for name, ref in refs.items():if not name or name not in used:continue- if ref is None or not ref.query.strip():- raise SQLV2ReferenceError(f"Referenced node '{name}' has not been run yet — run it first.")- inputs.append(- {- "name": name,- "kind": "hogql",- "node_id": ref.node_id,- "run_id": ref.run_id,- "query": ref.query,- }- )+ if ref.kind == "local":+ inputs.append({"name": name, "kind": "local"})+ else:+ inputs.append(_hogql_input(name, ref))return inputs+++def resolve_sql_node_run(code: str, refs: dict[str, SQLV2Ref]) -> tuple[str, str, list[dict[str, Any]]]:+ """Route a SQL node run to its engine; return (node_type, run_code, inputs).++ The routing rule from the journey walkthroughs (decision 1): a query whose referenced+ inputs are all HogQL definitions pushes to ClickHouse with the refs inlined as CTEs —+ `("hogql", inlined_code, [])`. A query that references any **local** frame (made by a+ Python node) cannot run in ClickHouse, so it runs in the sandbox's DuckDB instead —+ `("duckdb", code_as_written, inputs)`, where inputs materialize the HogQL refs it also+ reads (Journey 5: the join forces `df2` into the sandbox) and assert the local ones.++ Raises SQLV2ReferenceError for unrunnable refs, and lets the HogQL parser's own error+ surface for a malformed query that doesn't touch any local frame.+ """+ local_names = {name for name, ref in refs.items() if name and ref.kind == "local"}+ hogql_refs = {name: ref for name, ref in refs.items() if name and ref.kind == "hogql"}+ hogql_codes = {name: ref.last_run_code for name, ref in hogql_refs.items()}+ referenced_locals: set[str] = set()+ referenced_hogql: set[str] = set()+ if local_names:+ candidates = local_names | set(hogql_refs)+ try:+ found = _references(parse_select(code), candidates)+ except ExposedHogQLError:+ # DuckDB-only syntax can't parse as HogQL. If it names a local frame+ # (word-boundary match outside string literals and comments), route it to+ # DuckDB and let DuckDB report its own errors; otherwise fall through so+ # the HogQL path surfaces the parse error.+ searchable = _SQL_LITERALS_AND_COMMENTS.sub(" ", code)+ found = {name for name in candidates if re.search(rf"\b{re.escape(name)}\b", searchable)}+ if not found & local_names:+ found = set()+ referenced_locals = found & local_names+ referenced_hogql = found - local_names++ if not referenced_locals:+ return "hogql", resolve_sql_v2_references(code, hogql_codes), []++ inputs: list[dict[str, Any]] = []+ for name in sorted(referenced_locals | referenced_hogql):+ if name in local_names:+ inputs.append({"name": name, "kind": "local"})+ else:+ inputs.append(_hogql_input(name, hogql_refs[name]))+ return "duckdb", code, inputsdiff --git a/products/notebooks/backend/sql_v2_result_delivery.md b/products/notebooks/backend/sql_v2_result_delivery.mdindex cccfcc3e6d21..2e6ba1abc21b 100644--- a/products/notebooks/backend/sql_v2_result_delivery.md+++ b/products/notebooks/backend/sql_v2_result_delivery.md@@ -109,13 +109,19 @@ reads stay stateless.## Where the full result lives-**Now: a capped in-memory cache in the kernel-server.** A run fetches up to+**Now: a capped in-memory cache in the kernel-server (hogql runs).** A run fetches up to`RESULT_CACHE_ROWS` (300) rows in one ClickHouse query; the kernel-server keepsthem per run (LRU over the last 20 runs). `/page` requests within the cache arelocal slices — no ClickHouse work, no held backend workers. Paging beyond thecache, or after a kernel restart emptied it, falls back to a LIMIT/OFFSETre-query through the data plane.+**Kernel runs (python/duckdb) page from the on-sandbox result store.** The kernel+writes each produced frame to `/data/results/<result_id>.arrow`; `/page` requests+carrying a `result_id` slice that file in the server process (`kernel/result_store.py`,+pyarrow mmap). There is no data-plane fallback — the run's code is not a HogQL query —+so a lost frame (sandbox death) means re-run, per the alive-only trade-off below.+**Later: durable store** (object storage / Parquet / a results table). Thesandbox materializes the full result at run time; `result_id` is the storage key.Removes the alive-only limitation below. Switch to this when results must survivediff --git a/products/notebooks/backend/sql_v2_serializers.py b/products/notebooks/backend/sql_v2_serializers.pyindex 2e56e7b79bca..b57e5410d4b4 100644--- a/products/notebooks/backend/sql_v2_serializers.py+++ b/products/notebooks/backend/sql_v2_serializers.py@@ -1,6 +1,21 @@from rest_framework import serializers+class NotebookSQLV2RefSerializer(serializers.Serializer):+ node_id = serializers.CharField(help_text="ProseMirror node id of the upstream node this name points at.")+ # Named `kind` on purpose (matches the kernel input spec); avoids the `type`/`format`+ # enum-collision trap, and the endpoint is schema-excluded anyway.+ kind = serializers.ChoiceField(+ choices=["hogql", "local"],+ required=False,+ default="hogql",+ help_text=(+ "What the name resolves to: 'hogql' is a SQL node's query definition (resolved to its "+ "last-run HogQL); 'local' is a dataframe a Python node bound in the kernel namespace."+ ),+ )++class NotebookSQLV2RunRequestSerializer(serializers.Serializer):node_id = serializers.CharField(help_text="ProseMirror node id of the SQLV2 node being run.")node_type = serializers.ChoiceField(@@ -8,37 +23,31 @@ class NotebookSQLV2RunRequestSerializer(serializers.Serializer):required=False,default="hogql",help_text=(- "Execution kind. 'hogql' pushes the query to ClickHouse; 'python' runs the code in the "- "sandbox kernel, materializing referenced upstream nodes as pandas frames first."+ "Execution kind. 'hogql' is a SQL node — pushed to ClickHouse, or rerouted to the sandbox's "+ "DuckDB when it references a local frame; 'python' runs the code in the sandbox kernel, "+ "materializing referenced upstream nodes as pandas frames first."),)code = serializers.CharField(- help_text="The node's source — HogQL for a hogql node, Python for a python node. Must not be blank.",+ help_text="The node's source — SQL for a hogql node, Python for a python node. Must not be blank.",)output_name = serializers.CharField(required=False,default="",allow_blank=True,- help_text="Python node only: the dataframe variable to preview as the result (falls back to the last expression).",- )- refs = serializers.DictField(- child=serializers.CharField(),- required=False,- default=dict,help_text=(- "Available upstream nodes, mapping each named node's dataframe name to its ProseMirror "- "node id, resolved to each node's last-run query. A hogql node inlines the referenced ones "- "as CTEs; a python node materializes the ones its code reads as pandas frames."+ "Kernel nodes only: the dataframe variable to bind the result to in the kernel namespace "+ "(a python node falls back to the last expression for its preview)."),)refs = serializers.DictField(- child=serializers.CharField(),+ child=NotebookSQLV2RefSerializer(),required=False,default=dict,help_text=(- "Available upstream nodes, mapping each named node's dataframe name to its ProseMirror "- "node id. The backend inlines the ones this node references as CTEs using each node's "- "last-run query (not its live editor text); unreferenced entries are ignored."+ "Available upstream nodes, keyed by dataframe name. A SQL node inlines referenced hogql "+ "refs as CTEs — unless it references a local ref, which reroutes the run to the sandbox's "+ "DuckDB; a python node materializes the hogql refs its code reads as pandas frames."),)diff --git a/products/notebooks/backend/test/test_kernel_bootstrap.py b/products/notebooks/backend/test/test_kernel_bootstrap.pyindex 351830524e0b..aa0083016ca2 100644--- a/products/notebooks/backend/test/test_kernel_bootstrap.py+++ b/products/notebooks/backend/test/test_kernel_bootstrap.py@@ -62,6 +62,13 @@ class TestKernelSessionRunNode(SimpleTestCase):self.assertEqual(envelope["status"], "error")self.assertIn("ValueError: boom", envelope["error"])+ def test_syntax_error_surfaces_as_error_envelope(self):+ # run_cell reports compile errors via error_before_exec (error_in_exec stays None);+ # they must not masquerade as a successful empty run stored as DONE.+ envelope = self._run("def = 1")+ self.assertEqual(envelope["status"], "error")+ self.assertIn("SyntaxError", envelope["error"])+def test_hogql_input_is_bound_as_a_pandas_frame(self):# The server streams a CH result to a local Arrow file; the kernel must expose it as# a pandas frame the node code can filter — this is the Journey 4 materialization step.@@ -77,6 +84,29 @@ class TestKernelSessionRunNode(SimpleTestCase):self.assertEqual(envelope["status"], "error")self.assertIn("never_made", envelope["error"])+ def test_python_output_name_binds_the_result_for_downstream_nodes(self):+ # Journey 5 step 3: the cell's code never assigns the output name itself — the+ # kernel must bind the last-expression frame so a later SQL node can read it.+ self._run("import pandas as pd\nevents_df = pd.DataFrame({'a': [1, 2, 3]})")+ envelope = self._run("events_df.head(2)", output_name="top_events_df")+ self.assertEqual(envelope["status"], "ok")+ self.assertIn("top_events_df", self.session.shell.user_ns)+ sql = self._run_duckdb(+ "select count(*) as c from top_events_df", inputs=[{"name": "top_events_df", "kind": "local"}]+ )+ self.assertEqual(sql["status"], "ok")+ self.assertEqual(sql["first_page"], [[2]])++ def test_python_rerun_shows_the_fresh_result_not_the_previously_bound_frame(self):+ # The output binding must not shadow a rerun: after upstream data changes, running+ # the same cell again has to preview and bind this run's result, not the old frame.+ self._run("import pandas as pd\nevents_df = pd.DataFrame({'a': [1]})")+ first = self._run("events_df.head(10)", output_name="top_events_df")+ self._run("import pandas as pd\nevents_df = pd.DataFrame({'a': [1, 2, 3]})")+ second = self._run("events_df.head(10)", output_name="top_events_df")+ self.assertEqual(first["row_count"], 1)+ self.assertEqual(second["row_count"], 3)+def test_oversized_stdout_is_truncated(self):envelope = self._run("print('x' * 100_000)")self.assertLess(len(envelope["stdout"]), 33_000)@@ -99,3 +129,86 @@ class TestKernelSessionRunNode(SimpleTestCase):self.assertEqual(envelope["status"], "ok")self.assertEqual(len(envelope["media"]), _MEDIA_MAX_FIGURES)self.assertIn("1 figure(s) omitted", envelope["stderr"])++ def _run_duckdb(self, code: str, inputs=None, output_name=None) -> dict:+ return self.session.run_node(+ {"node": {"type": "duckdb", "code": code, "output_name": output_name}, "inputs": inputs or []}+ )++ def test_duckdb_node_joins_a_hogql_frame_with_a_local_frame(self):+ # Journey 5 step 4: the local frame forces the join into DuckDB, over the mmapped+ # HogQL input and the pandas frame a Python node left in the namespace.+ path = self._write_frame("df2", pa.table({"id": [1, 2, 3], "name": ["a", "b", "c"]}))+ self._run("import pandas as pd\nnew_events = pd.DataFrame({'id': [2, 3], 'n': [20, 30]})")+ envelope = self._run_duckdb(+ "select df2.id, df2.name, new_events.n from df2 join new_events on df2.id = new_events.id order by df2.id",+ inputs=[{"name": "df2", "kind": "hogql", "path": path}, {"name": "new_events", "kind": "local"}],+ output_name="joined",+ )+ self.assertEqual(envelope["status"], "ok")+ self.assertEqual(envelope["columns"], ["id", "name", "n"])+ self.assertEqual(envelope["first_page"], [[2, "b", 20], [3, "c", 30]])+ self.assertTrue(envelope["result_id"]) # frame written for /page slicing++ def test_duckdb_output_is_usable_by_a_following_python_node(self):+ self._run("import pandas as pd\nnew_events = pd.DataFrame({'id': [1, 2]})")+ self._run_duckdb(+ "select id * 10 as scaled from new_events",+ inputs=[{"name": "new_events", "kind": "local"}],+ output_name="scaled_df",+ )+ envelope = self._run("scaled_df[scaled_df.scaled > 10]", inputs=[{"name": "scaled_df", "kind": "local"}])+ self.assertEqual(envelope["status"], "ok")+ self.assertEqual(envelope["first_page"], [[20]])++ def test_duckdb_rerun_sees_the_local_frames_current_value(self):+ # Re-registration per run: an updated upstream frame must not leave SQL reading the old one.+ self._run("import pandas as pd\nnew_events = pd.DataFrame({'id': [1]})")+ first = self._run_duckdb(+ "select count(*) as c from new_events", inputs=[{"name": "new_events", "kind": "local"}]+ )+ self._run("import pandas as pd\nnew_events = pd.DataFrame({'id': [1, 2, 3]})")+ second = self._run_duckdb(+ "select count(*) as c from new_events", inputs=[{"name": "new_events", "kind": "local"}]+ )+ self.assertEqual(first["first_page"], [[1]])+ self.assertEqual(second["first_page"], [[3]])++ def test_duckdb_error_surfaces_as_error_envelope(self):+ envelope = self._run_duckdb("select * from a_table_that_does_not_exist")+ self.assertEqual(envelope["status"], "error")+ self.assertIn("a_table_that_does_not_exist", envelope["error"])++ def test_duckdb_over_a_name_rebound_to_a_non_frame_errors_instead_of_reading_stale_rows(self):+ # The first run registers the frame in DuckDB; the rebind must not leave SQL silently+ # reading that stale registration — it must fail clearly.+ self._run("import pandas as pd\nnew_events = pd.DataFrame({'id': [1]})")+ self._run_duckdb("select * from new_events", inputs=[{"name": "new_events", "kind": "local"}])+ self._run("new_events = 5")+ envelope = self._run_duckdb("select * from new_events", inputs=[{"name": "new_events", "kind": "local"}])+ self.assertEqual(envelope["status"], "error")+ self.assertIn("not a dataframe", envelope["error"])++ def test_duckdb_over_a_deleted_name_errors_instead_of_reading_stale_rows(self):+ # `del` leaves the name in DuckDB's registry but not the namespace — the third silent+ # state: neither re-registered nor rejected, serving the previous run's rows.+ self._run("import pandas as pd\nnew_events = pd.DataFrame({'id': [1, 2, 3]})")+ self._run_duckdb("select count(*) as c from new_events", inputs=[{"name": "new_events", "kind": "local"}])+ self._run("del new_events")+ envelope = self._run_duckdb(+ "select count(*) as c from new_events", inputs=[{"name": "new_events", "kind": "local"}]+ )+ self.assertEqual(envelope["status"], "error")+ self.assertIn("new_events", envelope["error"])++ def test_frameless_duckdb_rerun_invalidates_its_previous_output_binding(self):+ # A SELECT run binds output_name; a later frameless (DDL) run of the same node must+ # drop that binding, or downstream nodes keep reading the stale frame.+ self._run("import pandas as pd\nnew_events = pd.DataFrame({'id': [1]})")+ self._run_duckdb(+ "select * from new_events", inputs=[{"name": "new_events", "kind": "local"}], output_name="out"+ )+ self._run_duckdb("create table scratch as select 1", output_name="out")+ envelope = self._run_duckdb("select * from out", inputs=[{"name": "out", "kind": "local"}])+ self.assertEqual(envelope["status"], "error")+ self.assertIn("out", envelope["error"])diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.pyindex bdcdc02471ca..21a022e9f62b 100644--- a/products/notebooks/backend/test/test_sql_v2.py+++ b/products/notebooks/backend/test/test_sql_v2.py@@ -223,7 +223,7 @@ class TestSQLV2Run(APIBaseTest):data={"node_id": "join-node","code": "select * from df1 join df2 on df1.id = df2.id",- "refs": {"df1": "node-df1", "df2": "node-df2"},+ "refs": {"df1": {"node_id": "node-df1"}, "df2": {"node_id": "node-df2"}},},format="json",)@@ -243,7 +243,7 @@ class TestSQLV2Run(APIBaseTest):self._record_done_run("node-df1", "select 2 as new_col")response = self.client.post(self.run_url,- data={"node_id": "c", "code": "select * from df1", "refs": {"df1": "node-df1"}},+ data={"node_id": "c", "code": "select * from df1", "refs": {"df1": {"node_id": "node-df1"}}},format="json",)self.assertEqual(response.status_code, 200)@@ -251,12 +251,53 @@ class TestSQLV2Run(APIBaseTest):self.assertIn("new_col", run.code)self.assertNotIn("old_col", run.code)+ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_hogql_ref_whose_latest_run_was_duckdb_is_treated_as_not_run(self, _mock_enabled, mock_start):+ # A SQL node's runs can alternate engines; a duckdb run's code is raw SQL naming+ # kernel frames, so inlining it as a CTE would ship it to ClickHouse. The stale older+ # hogql run must not be used either — the node's latest result is a local frame.+ with freeze_time("2026-07-04T00:00:00Z"):+ self._record_done_run("node-c", "select id from events")+ with freeze_time("2026-07-04T00:01:00Z"):+ with team_scope(self.team.id):+ NotebookNodeRun.objects.create(+ team=self.team,+ notebook=self.notebook,+ node_id="node-c",+ code="select * from df2 join new_events on true",+ node_type=NotebookNodeRun.NodeType.DUCKDB,+ status=NotebookNodeRun.Status.DONE,+ )+ response = self.client.post(+ self.run_url,+ data={"node_id": "d", "code": "select * from sql_df", "refs": {"sql_df": {"node_id": "node-c"}}},+ format="json",+ )+ self.assertEqual(response.status_code, 400)+ self.assertIn("has not been run", response.json()["detail"])+ mock_start.assert_not_called()++ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_hogql_typo_with_refs_present_is_a_400_not_a_500(self, _mock_enabled, mock_start):+ # With refs present the user's code is parsed at dispatch, so a plain typo raises+ # ExposedHogQLError there — it must surface as a bad request, not a server error.+ self._record_done_run("node-df1", "select id from events")+ response = self.client.post(+ self.run_url,+ data={"node_id": "c", "code": "selec 1", "refs": {"df1": {"node_id": "node-df1"}}},+ format="json",+ )+ self.assertEqual(response.status_code, 400)+ mock_start.assert_not_called()+@patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")@patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)def test_run_rejects_referencing_a_never_run_node(self, _mock_enabled, mock_start):response = self.client.post(self.run_url,- data={"node_id": "c", "code": "select * from df1", "refs": {"df1": "node-df1"}},+ data={"node_id": "c", "code": "select * from df1", "refs": {"df1": {"node_id": "node-df1"}}},format="json",)self.assertEqual(response.status_code, 400)@@ -275,7 +316,7 @@ class TestSQLV2Run(APIBaseTest):"node_type": "python","code": "df1.head()","output_name": "result",- "refs": {"df1": "node-df1"},+ "refs": {"df1": {"node_id": "node-df1"}},},format="json",)@@ -293,12 +334,46 @@ class TestSQLV2Run(APIBaseTest):def test_python_node_referencing_a_never_run_node_is_rejected(self, _mock_enabled, mock_start):response = self.client.post(self.run_url,- data={"node_id": "py", "node_type": "python", "code": "df1.head()", "refs": {"df1": "node-df1"}},+ data={+ "node_id": "py",+ "node_type": "python",+ "code": "df1.head()",+ "refs": {"df1": {"node_id": "node-df1"}},+ },format="json",)self.assertEqual(response.status_code, 400)mock_start.assert_not_called()+ @patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")+ @patch("products.notebooks.backend.presentation.views.notebook.is_sql_v2_enabled", return_value=True)+ def test_sql_node_referencing_a_local_frame_reroutes_to_duckdb(self, _mock_enabled, mock_start):+ # Journey 5: a local (Python-made) frame can't push to ClickHouse, so the join runs in+ # the sandbox's DuckDB — SQL as written, hogql refs shipped as materialization inputs.+ self._record_done_run("node-df2", "select id from persons")+ code = "select * from df2 join new_events on df2.id = new_events.id"+ response = self.client.post(+ self.run_url,+ data={+ "node_id": "join-node",+ "code": code,+ "refs": {+ "df2": {"node_id": "node-df2"},+ "new_events": {"node_id": "node-py", "kind": "local"},+ },+ },+ format="json",+ )+ self.assertEqual(response.status_code, 200)+ run = NotebookNodeRun.objects.for_team(self.team.id).get(id=response.json()["run_id"])+ self.assertEqual(run.node_type, NotebookNodeRun.NodeType.DUCKDB)+ self.assertEqual(run.code, code) # not CTE-rewritten: DuckDB runs the SQL as written+ dispatched = mock_start.call_args.args[0]+ self.assertEqual(dispatched.node_type, "duckdb")+ self.assertEqual(+ [(i["name"], i["kind"]) for i in dispatched.inputs], [("df2", "hogql"), ("new_events", "local")]+ )+@patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow",side_effect=RuntimeError("temporal unavailable"),@@ -399,10 +474,23 @@ class TestSQLV2RunPage(APIBaseTest):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:+ def _create_run(+ self,+ status=NotebookNodeRun.Status.DONE,+ node_id="n1",+ code="select 1",+ node_type=NotebookNodeRun.NodeType.HOGQL,+ result_id=None,+ ) -> 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+ team=self.team,+ notebook=self.notebook,+ node_id=node_id,+ status=status,+ code=code,+ node_type=node_type,+ result_id=result_id,)def _get(self, run_id: str, offset=50, limit=50):@@ -450,6 +538,16 @@ class TestSQLV2RunPage(APIBaseTest):self.assertIn("re-run", response.json()["detail"])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_kernel_run_without_result_frame_is_rejected_before_reaching_the_kernel(self, _mock_enabled, mock_fetch):+ # A python/duckdb run pages by its result frame; no result_id means nothing to slice.+ run = self._create_run(code="df1.head()", node_type=NotebookNodeRun.NodeType.PYTHON, result_id=None)+ 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),@@ -541,6 +639,29 @@ class TestSQLV2PageDispatch(APIBaseTest):self.assertEqual(payload["code"], "select event from events")self.assertEqual((payload["offset"], payload["limit"]), (100, 25))+ @patch("products.notebooks.backend.sql_v2.requests.post")+ def test_kernel_run_pages_by_result_id_not_code(self, mock_post):+ # A python/duckdb result pages by slicing its on-sandbox frame; its code is not a HogQL+ # query, so it must never reach the data plane as one.+ mock_post.return_value.status_code = 200+ mock_post.return_value.json.return_value = {"columns": [], "types": [], "rows": [], "has_more": False}+ self._create_runtime()+ with team_scope(self.team.id):+ kernel_run = NotebookNodeRun.objects.create(+ team=self.team,+ notebook=self.notebook,+ node_id="py1",+ status=NotebookNodeRun.Status.DONE,+ code="df1.head()",+ node_type=NotebookNodeRun.NodeType.PYTHON,+ result_id="6f8ec2f4-3f42-4b0e-9a2e-5f5b1c9d0a11",+ )+ fetch_sql_v2_page(self.notebook, self.user, kernel_run, offset=50, limit=50)+ payload = mock_post.call_args.kwargs["json"]+ self.assertEqual(payload["result_id"], "6f8ec2f4-3f42-4b0e-9a2e-5f5b1c9d0a11")+ self.assertNotIn("code", payload)+ self.assertNotIn("data_plane_token", payload)+@parameterized.expand([("outdated_kernel_404", 404, None, SQLV2KernelNotRunning),@@ -826,9 +947,11 @@ class TestSQLV2DataPlaneEndpoint(APIBaseTest):[# 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).+ # set queries that must stay parenthesized, and a trailing line comment that+ # would swallow the wrapper's closing paren without the newline).("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,)]),+ ("trailing_line_comment", "select 1 as n -- top events", 10, 0, [(1,)]),])def test_query_shapes_survive_the_wrapper(self, _name, query, limit, offset, expected_rows):@@ -1164,23 +1287,64 @@ class TestSQLV2PythonNodeRun(SimpleTestCase):self.assertEqual(table.column_names, ["id", "v"])self.assertFalse(os.path.exists(dest + ".partial"))- def test_execute_run_routes_python_nodes_to_the_executor(self):+ @parameterized.expand([("python_node", "python"), ("duckdb_node", "duckdb")])+ def test_execute_run_routes_kernel_nodes_to_the_executor(self, _name, node_type):result_envelope = {"status": "ok", "columns": ["a"]}delivered: dict = {}payload = {- "run_id": "r-py",- "node": {"type": "python", "code": "1 + 1"},+ "run_id": f"r-{node_type}",+ "node": {"type": node_type, "code": "1 + 1"},"callback_url": "http://backend/cb","callback_token": "t",}with (- patch.object(kernel_runner, "_run_python_node", return_value=result_envelope) as run_python,+ patch.object(kernel_runner, "_run_kernel_node", return_value=result_envelope) as run_kernel,patch.object(kernel_runner, "_post_callback", side_effect=lambda url, token, env: delivered.update(env)),):kernel_runner.execute_run(payload)- run_python.assert_called_once()+ run_kernel.assert_called_once()self.assertEqual(delivered["status"], "ok")+ def test_result_store_pages_a_stored_frame(self):+ # Kernel-node results page by slicing the on-disk Arrow frame — offsets, bounds and+ # has_more must match what the paging UI expects from the data-plane path.+ import os+ import tempfile++ import pyarrow as pa++ from products.notebooks.backend.sandbox.kernel import result_store++ result_id = "6f8ec2f4-3f42-4b0e-9a2e-5f5b1c9d0a11"+ with tempfile.TemporaryDirectory() as tmp:+ table = pa.table({"id": list(range(10))})+ with pa.OSFile(os.path.join(tmp, f"{result_id}.arrow"), "wb") as sink:+ with pa.ipc.new_file(sink, table.schema) as writer:+ writer.write_table(table)+ page = result_store.read_page(result_id, offset=4, limit=3, results_dir=tmp)+ self.assertEqual(page["columns"], ["id"])+ self.assertEqual(page["rows"], [[4], [5], [6]])+ self.assertTrue(page["has_more"])+ last = result_store.read_page(result_id, offset=8, limit=5, results_dir=tmp)+ self.assertEqual(last["rows"], [[8], [9]])+ self.assertFalse(last["has_more"])++ @parameterized.expand(+ [+ ("path_traversal_id", "../../etc/passwd"),+ # Valid UUID whose frame was lost with the sandbox disk.+ ("missing_frame", "00000000-0000-0000-0000-000000000000"),+ ]+ )+ def test_result_store_rejects_unusable_result_ids(self, _name, result_id):+ import tempfile++ from products.notebooks.backend.sandbox.kernel import result_store++ with tempfile.TemporaryDirectory() as tmp:+ with self.assertRaises(result_store.ResultStoreError):+ result_store.read_page(result_id, offset=0, limit=10, results_dir=tmp)+def test_execute_run_keeps_hogql_nodes_off_the_kernel(self):# A pure-HogQL node must stay on the capped data-plane fetch — never spin up the kernel.payload = {@@ -1192,7 +1356,7 @@ class TestSQLV2PythonNodeRun(SimpleTestCase):"data_plane_token": "t",}with (- patch.object(kernel_runner, "_run_python_node") as run_python,+ patch.object(kernel_runner, "_run_kernel_node") as run_kernel,patch.object(kernel_runner, "_post_callback"),patch("products.notebooks.backend.sandbox.kernel.data_plane.fetch_query_page",@@ -1200,4 +1364,4 @@ class TestSQLV2PythonNodeRun(SimpleTestCase):),):kernel_runner.execute_run(payload)- run_python.assert_not_called()+ run_kernel.assert_not_called()diff --git a/products/notebooks/backend/test/test_sql_v2_references.py b/products/notebooks/backend/test/test_sql_v2_references.pyindex b0fb27977d72..24d30b656dee 100644--- a/products/notebooks/backend/test/test_sql_v2_references.py+++ b/products/notebooks/backend/test/test_sql_v2_references.py@@ -1,22 +1,27 @@from django.test import SimpleTestCasefrom products.notebooks.backend.sql_v2_references import (- PythonNodeRef,+ SQLV2Ref,SQLV2ReferenceError,resolve_python_node_inputs,+ resolve_sql_node_run,resolve_sql_v2_references,)-def _ref(query: str, node_id: str = "node-df1", run_id: str = "run-1") -> PythonNodeRef:- return PythonNodeRef(node_id=node_id, run_id=run_id, query=query)+def hogql_ref(code: str | None, node_id: str = "node-df1", run_id: str = "run-1") -> SQLV2Ref:+ # A never-run node (code None) has no run to key on, mirroring how the view builds refs.+ return SQLV2Ref(kind="hogql", node_id=node_id, run_id=None if code is None else run_id, last_run_code=code)+++LOCAL = SQLV2Ref(kind="local")class TestResolvePythonNodeInputs(SimpleTestCase):def test_only_referenced_frames_are_materialized(self):# A python node reads frames as variables; materialize only the ones its code uses.inputs = resolve_python_node_inputs(- "df1.head()", {"df1": _ref("select id from events"), "df2": _ref("select 1", node_id="node-df2")}+ "df1.head()", {"df1": hogql_ref("select id from events"), "df2": hogql_ref("select 1", node_id="node-df2")})self.assertEqual(len(inputs), 1)self.assertEqual(inputs[0]["name"], "df1")@@ -25,25 +30,96 @@ class TestResolvePythonNodeInputs(SimpleTestCase):def test_unused_refs_are_ignored(self):self.assertEqual(- resolve_python_node_inputs("import pandas as pd\npd.DataFrame()", {"df1": _ref("select 1")}), []+ resolve_python_node_inputs("import pandas as pd\npd.DataFrame()", {"df1": hogql_ref("select 1")}), [])def test_reassigned_ref_is_still_materialized(self):# Reassigning a ref (df1 = df1.assign(...)) must not drop it from the inputs — otherwise it# is never re-fetched and the node runs against the mutated frame from its previous run.- inputs = resolve_python_node_inputs("df1.columns = ['a']\ndf1 = df1.assign(x=1)", {"df1": _ref("select 1")})+ inputs = resolve_python_node_inputs(+ "df1.columns = ['a']\ndf1 = df1.assign(x=1)", {"df1": hogql_ref("select 1")}+ )self.assertEqual([i["name"] for i in inputs], ["df1"])def test_frame_is_keyed_on_the_upstream_run_id(self):# The executor caches/evicts frames by (node_id, run_id), so both must reach the spec — a# new run of the same node must key a fresh frame rather than reuse the stale one.- inputs = resolve_python_node_inputs("df1.head()", {"df1": _ref("select 1", node_id="n1", run_id="r2")})+ inputs = resolve_python_node_inputs("df1.head()", {"df1": hogql_ref("select 1", node_id="n1", run_id="r2")})self.assertEqual(inputs[0]["node_id"], "n1")self.assertEqual(inputs[0]["run_id"], "r2")def test_referencing_a_never_run_node_raises(self):with self.assertRaises(SQLV2ReferenceError):- resolve_python_node_inputs("df1.head()", {"df1": None})+ resolve_python_node_inputs("df1.head()", {"df1": hogql_ref(None)})++ def test_used_local_upstream_becomes_a_local_input(self):+ # A python upstream carries no query — the kernel only asserts the frame exists.+ inputs = resolve_python_node_inputs(+ "new_events.describe()", {"new_events": LOCAL, "df1": hogql_ref("select 1")}+ )+ self.assertEqual(inputs, [{"name": "new_events", "kind": "local"}])+++class TestResolveSQLNodeRun(SimpleTestCase):+ def test_all_hogql_refs_push_to_clickhouse(self):+ node_type, run_code, inputs = resolve_sql_node_run(+ "select * from df1", {"df1": hogql_ref("select id from events")}+ )+ self.assertEqual(node_type, "hogql")+ self.assertIn("WITH df1 AS (SELECT id FROM events)", run_code)+ self.assertEqual(inputs, [])++ def test_unreferenced_local_frame_does_not_reroute(self):+ # The local frame exists in the notebook but this query never touches it.+ node_type, run_code, inputs = resolve_sql_node_run(+ "select * from df1", {"df1": hogql_ref("select id from events"), "new_events": LOCAL}+ )+ self.assertEqual(node_type, "hogql")+ self.assertIn("WITH df1 AS", run_code)+ self.assertEqual(inputs, [])++ def test_referenced_local_frame_reroutes_to_duckdb_and_materializes_hogql_refs(self):+ # Journey 5 step 4: the join runs locally, forcing df2 into the sandbox.+ code = "select * from df2 join new_events on df2.id = new_events.id"+ node_type, run_code, inputs = resolve_sql_node_run(+ code, {"df2": hogql_ref("select id from persons"), "new_events": LOCAL}+ )+ self.assertEqual(node_type, "duckdb")+ self.assertEqual(run_code, code) # DuckDB gets the SQL as written, not a CTE rewrite+ self.assertEqual([(spec["name"], spec["kind"]) for spec in inputs], [("df2", "hogql"), ("new_events", "local")])+ self.assertEqual(inputs[0]["query"], "select id from persons")+ # DuckDB-rerouted runs key materialized frames the same way python nodes do.+ self.assertEqual(inputs[0]["node_id"], "node-df1")+ self.assertEqual(inputs[0]["run_id"], "run-1")++ def test_local_only_query_reroutes_with_no_materialization(self):+ node_type, run_code, inputs = resolve_sql_node_run("select count() from new_events", {"new_events": LOCAL})+ self.assertEqual(node_type, "duckdb")+ self.assertEqual(inputs, [{"name": "new_events", "kind": "local"}])++ def test_duckdb_run_referencing_a_never_run_hogql_node_raises(self):+ with self.assertRaises(SQLV2ReferenceError):+ resolve_sql_node_run(+ "select * from df2 join new_events on true", {"df2": hogql_ref(None), "new_events": LOCAL}+ )++ def test_unparseable_hogql_naming_a_local_frame_still_routes_to_duckdb(self):+ # DuckDB-only syntax (PIVOT isn't HogQL; QUALIFY actually parses) must still run+ # locally when it names a local frame — this is the regex fallback's positive path.+ code = "pivot new_events on category"+ node_type, run_code, inputs = resolve_sql_node_run(code, {"new_events": LOCAL})+ self.assertEqual(node_type, "duckdb")+ self.assertEqual(run_code, code)+ self.assertEqual(inputs, [{"name": "new_events", "kind": "local"}])++ def test_frame_named_only_in_a_literal_or_comment_does_not_route_to_duckdb(self):+ # The fallback scanner must not see the frame name inside a string or comment —+ # that would reroute the query to DuckDB and materialize a frame it never reads.+ code = "pivot events on label in ('new_events') -- new_events"+ node_type, run_code, inputs = resolve_sql_node_run(code, {"new_events": LOCAL})+ self.assertEqual(node_type, "hogql")+ self.assertEqual(run_code, code)+ self.assertEqual(inputs, [])class TestResolveSQLV2References(SimpleTestCase):@@ -96,6 +172,16 @@ class TestResolveSQLV2References(SimpleTestCase):self.assertIn("mine AS", resolved)self.assertIn("df1 AS", resolved)+ def test_union_query_with_a_trailing_line_comment_still_resolves(self):+ # The UNION wrap embeds the raw text in `select * from (…)`; without a newline before+ # the closing paren a trailing `--` comment swallows the wrapper and the parse crashes.+ resolved = resolve_sql_v2_references(+ "select * from df1 union all select id from events -- combined",+ {"df1": "select id from events"},+ )+ self.assertIn("WITH df1 AS", resolved)+ self.assertIn("UNION ALL", resolved)+def test_top_level_union_referencing_a_node_is_wrapped_with_the_cte(self):# A SelectSetQuery can't carry a WITH, so it gets wrapped in a SELECT that can.resolved = resolve_sql_v2_references(