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): Fix chart column-types of the outputs of Python nodes (#80372)

Sinan Kucukkoseler2b99e9649a1a
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.test.ts b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.test.ts
new file mode 100644
index 000000000000..5ea35b0482a9
--- /dev/null
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.test.ts
@@ -0,0 +1,25 @@
+import { NotebookNodeSQLV2Result, toCachedResults } from './NotebookNodeSQLV2'
+
+describe('NotebookNodeSQLV2', () => {
+ const resultTyped = (type: string): NotebookNodeSQLV2Result => ({
+ columns: ['total'],
+ types: [['total', type]],
+ row_count: 1,
+ first_page: [[7]],
+ })
+
+ // A saved cell can hold pandas dtypes from the sandbox kernel. Charts read these names to
+ // find a numeric axis, so a stored 'float64' must resolve without a re-run of the cell.
+ it.each([
+ ['float64', 'Float64'],
+ ['int64', 'Int64'],
+ ['uint8', 'Int64'],
+ ['bool', 'Bool'],
+ ['datetime64[ns, UTC]', 'DateTime'],
+ ['str', 'String'],
+ ['object', 'String'],
+ ['Nullable(Int64)', 'Nullable(Int64)'],
+ ])('names a %s column %s', (stored, expected) => {
+ expect(toCachedResults(resultTyped(stored)).types).toEqual([['total', expected]])
+ })
+})
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
index 285d0f9d8a84..b36ff585c301 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodeSQLV2.tsx
@@ -99,10 +99,40 @@ const inferTypes = (result: NotebookNodeSQLV2Result): [string, string][] =>
return [column, typeof sample === 'number' ? 'Float64' : 'String']
})
-const toCachedResults = (result: NotebookNodeSQLV2Result): HogQLQueryResponse => ({
+// A notebook stores the whole result envelope, and a cell the sandbox kernel ran can hold raw
+// pandas dtypes ('float64', 'str'). The chart layer reads ClickHouse names to decide which
+// columns can go on a numeric axis, so map those over rather than make a saved cell re-run.
+const PANDAS_DTYPE_NAMES: Record<string, string> = {
+ bool: 'Bool',
+ boolean: 'Bool',
+ category: 'String',
+ object: 'String',
+ str: 'String',
+}
+
+const toClickhouseTypeName = (type: string): string => {
+ const dtype = type.toLowerCase()
+ if (PANDAS_DTYPE_NAMES[dtype]) {
+ return PANDAS_DTYPE_NAMES[dtype]
+ }
+ if (dtype.startsWith('datetime64')) {
+ return 'DateTime'
+ }
+ if (/^u?int(8|16|32|64)$/.test(dtype)) {
+ return 'Int64'
+ }
+ if (/^float(16|32|64)$/.test(dtype)) {
+ return 'Float64'
+ }
+ return type
+}
+
+export const toCachedResults = (result: NotebookNodeSQLV2Result): HogQLQueryResponse => ({
results: result.first_page ?? [],
columns: result.columns ?? [],
- types: result.types?.length ? result.types : inferTypes(result),
+ types: result.types?.length
+ ? result.types.map(([column, type]): [string, string] => [column, toClickhouseTypeName(type)])
+ : inferTypes(result),
})
const Component = ({
diff --git a/products/notebooks/backend/sandbox/kernel/bootstrap.py b/products/notebooks/backend/sandbox/kernel/bootstrap.py
index 80ffef55cae5..5ea94d975e98 100644
--- a/products/notebooks/backend/sandbox/kernel/bootstrap.py
+++ b/products/notebooks/backend/sandbox/kernel/bootstrap.py
@@ -110,6 +110,25 @@ def _preview_safe_cell(value: Any) -> Any:
return str(value)
+def _column_type_name(dtype: Any) -> str:
+ """Name a pandas dtype in the envelope's ClickHouse-style vocabulary.
+
+ The other producers of `types` (`data_plane`, and HogQL itself) report ClickHouse
+ names, and the frontend reads those names to decide which columns a chart can put on
+ a numeric axis. A raw pandas dtype ('float64') is not one of them, so such a column
+ reads as non-numeric there and drops out of every axis picker.
+ """
+ if pd.api.types.is_bool_dtype(dtype):
+ return "Bool"
+ if pd.api.types.is_integer_dtype(dtype):
+ return "Int64"
+ if pd.api.types.is_float_dtype(dtype):
+ return "Float64"
+ if pd.api.types.is_datetime64_any_dtype(dtype):
+ return "DateTime"
+ return "String"
+
+
def _load_headless_pyplot() -> Any:
# matplotlib is heavy and sandbox-only; keep it off the module import path (ruff TID253),
# and force the Agg backend before pyplot loads so figures render without a display.
@@ -478,7 +497,7 @@ class KernelSession:
if df is None:
return [], [], [], 0, False
columns = [str(column) for column in df.columns]
- types = [[str(column), str(dtype)] for column, dtype in zip(df.columns, df.dtypes)]
+ types = [[str(column), _column_type_name(dtype)] for column, dtype in zip(df.columns, df.dtypes)]
# to_json coerces numpy scalars, NaN and datetimes to JSON-native values in one pass.
try:
rows = json.loads(df.head(limit).to_json(orient="values", date_format="iso"))
diff --git a/products/notebooks/backend/test/test_kernel_bootstrap.py b/products/notebooks/backend/test/test_kernel_bootstrap.py
index 3a668cc6fecf..3c2fcaec3d8f 100644
--- a/products/notebooks/backend/test/test_kernel_bootstrap.py
+++ b/products/notebooks/backend/test/test_kernel_bootstrap.py
@@ -5,6 +5,7 @@ import tempfile
from django.test import SimpleTestCase
import pyarrow as pa
+from parameterized import parameterized
from products.notebooks.backend.sandbox.kernel.bootstrap import _MEDIA_MAX_FIGURES, KernelSession
@@ -58,6 +59,22 @@ class TestKernelSessionRunNode(SimpleTestCase):
self.assertEqual(envelope["media"][0]["mime_type"], "image/png")
self.assertTrue(envelope["media"][0]["data"])
+ @parameterized.expand(
+ [
+ ("integers", "pd.DataFrame({'c': [1, 2]})", "Int64"),
+ ("floats", "pd.DataFrame({'c': [1.5, 2.5]})", "Float64"),
+ ("booleans", "pd.DataFrame({'c': [True, False]})", "Bool"),
+ ("timestamps", "pd.DataFrame({'c': pd.to_datetime(['2026-01-01', '2026-01-02'])})", "DateTime"),
+ ("strings", "pd.DataFrame({'c': ['a', 'b']})", "String"),
+ ]
+ )
+ def test_column_types_use_the_envelope_vocabulary(self, _name, frame, expected):
+ # The frontend reads these names to decide which columns a chart can put on a numeric
+ # axis, and only knows the ClickHouse spellings the data plane emits. A raw pandas
+ # dtype ('float64') reads as non-numeric there, which drops the column from every chart.
+ envelope = self._run(f"import pandas as pd\n{frame}")
+ self.assertEqual(envelope["types"], [["c", expected]])
+
def test_exception_surfaces_as_error_envelope(self):
envelope = self._run("raise ValueError('boom')")
self.assertEqual(envelope["status"], "error")