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): Warn when a Python node doesn't yield an output dataframe (#70418)

Sinan Kucukkoseler7761f00ae2e1
diff --git a/products/notebooks/backend/sandbox/kernel/bootstrap.py b/products/notebooks/backend/sandbox/kernel/bootstrap.py
index a491b4b68bc5..6e18b973d0ec 100644
--- a/products/notebooks/backend/sandbox/kernel/bootstrap.py
+++ b/products/notebooks/backend/sandbox/kernel/bootstrap.py
@@ -106,6 +106,9 @@ class KernelSession:
if node_type == "duckdb":
return self._run_duckdb_node(node, preview_rows)
+ output_name = str(node.get("output_name") or "")
+ # Binding identities before the run, so a missed save can name the frames the run created.
+ ns_ids_before = {name: id(value) for name, value in self.shell.user_ns.items()} if output_name else {}
self._plt.close("all") # start from a clean figure state so we only capture this run's plots
# display=False: only stdout/stderr are consumed (figures come from matplotlib
# directly). Capturing display would also swap the ZMQ shell's display machinery,
@@ -140,7 +143,6 @@ class KernelSession:
media=media,
)
- 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:
@@ -153,6 +155,7 @@ class KernelSession:
# 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)
+ stderr += self._missed_save_note(output_name, ns_ids_before)
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
@@ -247,6 +250,21 @@ class KernelSession:
result_id=result_id,
)
+ def _missed_save_note(self, output_name: str, ns_ids_before: dict[str, int]) -> str:
+ """A stderr note when the run made dataframes but none reached `output_name`."""
+ created = sorted(
+ name
+ for name, value in self.shell.user_ns.items()
+ if not name.startswith("_") and isinstance(value, pd.DataFrame) and ns_ids_before.get(name) != id(value)
+ )
+ if not created:
+ return ""
+ names = ", ".join(f"'{name}'" for name in created)
+ return (
+ f"\n[nothing was saved as '{output_name}': this run created {names}. "
+ f"Assign the dataframe to '{output_name}' or end the cell with it as the last expression.]"
+ )
+
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
diff --git a/products/notebooks/backend/test/test_kernel_bootstrap.py b/products/notebooks/backend/test/test_kernel_bootstrap.py
index cc8c8c90d46e..d31d04b78d67 100644
--- a/products/notebooks/backend/test/test_kernel_bootstrap.py
+++ b/products/notebooks/backend/test/test_kernel_bootstrap.py
@@ -115,6 +115,23 @@ class TestKernelSessionRunNode(SimpleTestCase):
self.assertEqual(first["row_count"], 1)
self.assertEqual(second["row_count"], 3)
+ def test_missed_save_names_the_created_frame_and_leaves_the_output_unbound(self):
+ # The silent-miss footgun: the cell assigns `top50` while its output name says
+ # `top50_people` — the run must say so instead of succeeding with an empty preview.
+ envelope = self._run("import pandas as pd\ntop50 = pd.DataFrame({'id': [1, 2]})", output_name="top50_people")
+ self.assertEqual(envelope["status"], "ok")
+ self.assertIn("nothing was saved as 'top50_people'", envelope["stderr"])
+ self.assertIn("'top50'", envelope["stderr"])
+ self.assertNotIn("top50_people", self.session.shell.user_ns)
+
+ def test_frameless_run_does_not_warn_about_a_missed_save(self):
+ # Every cell carries a default output name, so a print-only cell warning on each
+ # run would flag ordinary side-effect cells as failures (stderr renders red).
+ self._run("import pandas as pd\ntop50 = pd.DataFrame({'id': [1, 2]})", output_name="top50")
+ envelope = self._run("print(top50)", output_name="df")
+ self.assertEqual(envelope["status"], "ok")
+ self.assertNotIn("nothing was saved", envelope["stderr"])
+
def test_oversized_stdout_is_truncated(self):
envelope = self._run("print('x' * 100_000)")
self.assertLess(len(envelope["stdout"]), 33_000)