Skip to content

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

fix(notebooks): let cells read a sql result made in the sandbox (#82487)

Sinan Kucukkoseler5a48e96392c7
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
index b36ff585c301..cba53819df6a 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
@@ -384,7 +384,7 @@ const Settings = ({
updateAttributes,
}: NotebookNodeAttributeProperties<NotebookNodeSQLV2Attributes>): JSX.Element => {
const nodeLogic = useMountedLogic(notebookNodeLogic)
- const { nodeId, notebookLogic } = useValues(nodeLogic)
+ const { nodeId, notebookLogic, sqlV2ReturnVariable } = useValues(nodeLogic)
const notebookShortId = notebookLogic.props.shortId
const dataLogic = notebookNodeSQLV2Logic({
@@ -406,8 +406,13 @@ const Settings = ({
persistConnection
// Refs come from the notebook content, not the tiptap editor: markdown notebooks
// (the only surface with SQLV2 cells) have no tiptap editor at all.
+ // outputName is what a rerouted (DuckDB) run binds its result to in the kernel, so
+ // downstream cells can read this cell's frame; a ClickHouse run ignores it.
onRunQuery={(code, connection) =>
- runQuery(code, collectSqlV2Refs(notebookLogic.values.content, nodeId), connection)
+ runQuery(code, collectSqlV2Refs(notebookLogic.values.content, nodeId), {
+ ...connection,
+ outputName: sqlV2ReturnVariable,
+ })
}
runQueryLoading={isRunning}
runQueryDisabledReason={operationBlockReason ?? undefined}
diff --git a/products/notebooks/backend/presentation/views/notebook.py b/products/notebooks/backend/presentation/views/notebook.py
index 25d13f4bd268..c876cc03e723 100644
--- a/products/notebooks/backend/presentation/views/notebook.py
+++ b/products/notebooks/backend/presentation/views/notebook.py
@@ -112,9 +112,10 @@ _CROSS_ENGINE_REF_ERROR_FOR_PYTHON = (
"'{name}' ran on a warehouse connection, and Python cells can only read PostHog results. "
"Re-run '{name}' on PostHog to use it here."
)
+# Covers both kinds of local frame: one a Python cell bound, and one a SQL cell left behind when
+# reading a Python dataframe rerouted it to the sandbox. Neither is reachable from a warehouse.
_LOCAL_FRAME_REF_ERROR = (
- "'{name}' is a Python dataframe, so only a cell running on PostHog can read it. "
- "Switch this cell to PostHog to use it."
+ "You can't query the local dataframe '{name}' because this cell points to a data source other than PostHog."
)
@@ -1188,7 +1189,14 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
# that warehouse's SQL. Inlining either elsewhere would ship the wrong query.
latest_by_node: dict[str, tuple[str, str]] = {}
other_engine_nodes: set[str] = set()
+ # A SQL node rerouted to DuckDB binds its result into the kernel namespace under its
+ # dataframe name, exactly like a Python node — there is no ClickHouse query to inline,
+ # but the frame is there to read. So it becomes a local ref rather than an absent one.
+ kernel_frame_nodes: set[str] = set()
for other_node_id, run_id, run_code, run_type, run_connection_id, run_send_raw in latest_runs:
+ if run_type == NotebookNodeRun.NodeType.DUCKDB:
+ kernel_frame_nodes.add(other_node_id)
+ continue
if run_type != NotebookNodeRun.NodeType.HOGQL:
continue
if run_connection_id == connection_id and bool(run_send_raw) == send_raw_query:
@@ -1198,7 +1206,7 @@ class NotebookViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidD
cross_engine_error = _CROSS_ENGINE_REF_ERROR_FOR_PYTHON if node_type == "python" else _CROSS_ENGINE_REF_ERROR
refs: dict[str, SQLV2Ref] = {}
for name, spec in ref_specs.items():
- if spec["kind"] == "local":
+ if spec["kind"] == "local" or spec["node_id"] in kernel_frame_nodes:
# A kernel frame lives in the sandbox, which only reaches PostHog's own data — a
# connection run can't be rerouted there, so mark it unusable instead.
refs[name] = (
diff --git a/products/notebooks/backend/test/test_sql_v2.py b/products/notebooks/backend/test/test_sql_v2.py
index 0d53d2be8e37..19bdb579ef91 100644
--- a/products/notebooks/backend/test/test_sql_v2.py
+++ b/products/notebooks/backend/test/test_sql_v2.py
@@ -570,12 +570,22 @@ class TestSQLV2Run(APIBaseTest):
self.assertIn("new_col", run.code)
self.assertNotIn("old_col", run.code)
+ @parameterized.expand(
+ [
+ ("sql_consumer", "hogql", "select * from sql_df", NotebookNodeRun.NodeType.DUCKDB),
+ ("python_consumer", "python", "print(sql_df)", NotebookNodeRun.NodeType.PYTHON),
+ ]
+ )
@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.
+ def test_ref_whose_latest_run_was_duckdb_reads_it_as_a_kernel_frame(
+ self, _name, consumer_node_type, code, expected_node_type, _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, and the stale older hogql
+ # run must not be used either. But the run did happen: a duckdb run binds its result into
+ # the kernel namespace under its dataframe name, so downstream cells read it as a local
+ # frame instead of being told the node never ran.
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"):
@@ -590,12 +600,20 @@ class TestSQLV2Run(APIBaseTest):
)
response = self.client.post(
self.run_url,
- data={"node_id": "d", "code": "select * from sql_df", "refs": {"sql_df": {"node_id": "node-c"}}},
+ data={
+ "node_id": "d",
+ "code": code,
+ "node_type": consumer_node_type,
+ "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()
+ 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, expected_node_type)
+ self.assertEqual(run.code, code) # never CTE-rewritten: the upstream result is a frame
+ dispatched = mock_start.call_args.args[0]
+ self.assertEqual([(i["name"], i["kind"]) for i in dispatched.inputs], [("sql_df", "local")])
@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)
@@ -879,20 +897,33 @@ class TestSQLV2RunOnAConnection(APIBaseTest):
run.refresh_from_db()
self.assertEqual(run.status, NotebookNodeRun.Status.FAILED)
+ @parameterized.expand([("python_frame", False), ("duckdb_node_frame", True)])
@patch("products.notebooks.backend.presentation.views.notebook.start_sql_v2_run_workflow")
@patch("products.notebooks.backend.presentation.views.notebook.enqueue_direct_run")
- def test_local_frame_reference_never_reroutes_a_connection_run_to_the_sandbox(
- self, mock_enqueue, mock_start, _mock_enabled
+ def test_a_local_frame_never_reroutes_a_connection_run_to_the_sandbox(
+ self, _name, from_duckdb_run, mock_enqueue, mock_start, _mock_enabled
):
- # Without the guard this takes Journey 5's DuckDB reroute, where the sandbox would run
- # the query against a kernel frame instead of the warehouse the user picked.
- response = self._post(
- code="select * from new_events",
- refs={"new_events": {"node_id": "node-py", "kind": "local"}},
- connection_id=str(self.source_id),
- )
+ # Without the guard this takes Journey 5's DuckDB reroute, where the sandbox would run the
+ # query against a kernel frame instead of the warehouse the user picked. A SQL node whose
+ # last run was duckdb left its result in that same namespace, so it takes the same guard.
+ if from_duckdb_run:
+ with team_scope(self.team.id):
+ NotebookNodeRun.objects.create(
+ team=self.team,
+ notebook=self.notebook,
+ node_id="node-duck",
+ code="select * from new_events",
+ node_type=NotebookNodeRun.NodeType.DUCKDB,
+ status=NotebookNodeRun.Status.DONE,
+ )
+ refs = {"sql_df": {"node_id": "node-duck"}}
+ code = "select * from sql_df"
+ else:
+ refs = {"new_events": {"node_id": "node-py", "kind": "local"}}
+ code = "select * from new_events"
+ response = self._post(code=code, refs=refs, connection_id=str(self.source_id))
self.assertEqual(response.status_code, 400)
- self.assertIn("Python dataframe", response.json()["detail"])
+ self.assertIn("local dataframe", response.json()["detail"])
mock_start.assert_not_called()
mock_enqueue.assert_not_called()