Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Surface graph errors on code_mode NotebookCell (#9057)

Trevor Manz8ade7be31ba0
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.py
index 89c663dd48..9a342e0b32 100644
--- a/marimo/_code_mode/_context.py
+++ b/marimo/_code_mode/_context.py
@@ -24,6 +24,7 @@ Usage::
from __future__ import annotations
import sys
+from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Literal, Protocol, overload
from marimo import _loggers
@@ -46,6 +47,7 @@ from marimo._code_mode._plan import (
_UpdateOp,
_validate_ops,
)
+from marimo._messaging.errors import Error
from marimo._messaging.notebook.changes import (
CreateCell,
DeleteCell,
@@ -98,6 +100,33 @@ CellStatusType = Literal[
"running",
]
+CellErrorKind = Literal["graph", "runtime"]
+
+
+@dataclass(frozen=True, slots=True)
+class CellError:
+ """An error affecting a notebook cell.
+
+ Parameters
+ ----------
+ kind : ``"graph"`` or ``"runtime"``
+ ``"graph"`` — a dataflow-graph error that *prevents* execution
+ (multiply-defined variable, cycle, etc.).
+ ``"runtime"`` — an exception raised during execution.
+ msg : str
+ Human-readable description.
+ exception : Exception | None
+ The original ``Exception`` for runtime errors; ``None`` for
+ graph errors.
+ """
+
+ kind: CellErrorKind
+ msg: str
+ exception: Exception | None = None
+
+ def __repr__(self) -> str:
+ return f"CellError(kind={self.kind!r}, msg={self.msg!r})"
+
class CellRuntimeState(Protocol):
"""The subset of ``CellImpl`` that ``NotebookCell`` reads."""
@@ -167,17 +196,25 @@ class NotebookCell:
Synthesized execution status. Priority order:
transient state (queued/running/disabled) > stale > last run result.
``None`` if the cell has never been registered in the graph.
- error : Exception | None
- The exception from the last run, if any.
+ errors : list[CellError]
+ Structured errors affecting this cell.
+ Each entry is a ``CellError`` with ``kind``, ``msg``, and
+ ``exception`` fields. Covers both runtime exceptions
+ (e.g. ``NameError``) and graph errors (multiply-defined
+ variables, cycles, etc.).
"""
- __slots__ = ("_cell", "_impl")
+ __slots__ = ("_cell", "_graph_errors", "_impl")
def __init__(
- self, cell: _NotebookCell, cell_impl: CellRuntimeState | None
+ self,
+ cell: _NotebookCell,
+ cell_impl: CellRuntimeState | None,
+ graph_errors: tuple[Error, ...] = (),
) -> None:
self._cell = cell
self._impl = cell_impl
+ self._graph_errors = graph_errors
# -- document properties (delegated) --
@@ -258,13 +295,29 @@ class NotebookCell:
return rr
@property
- def error(self) -> Exception | None:
- """The exception from the last run, if any.
+ def errors(self) -> list[CellError]:
+ """All errors affecting this cell.
- Persists even when ``status`` changes to ``"stale"`` after
- an edit — useful for inspecting what went wrong before the fix.
+ Returns a list of :class:`CellError` objects. Each has a
+ ``kind`` (``"graph"`` or ``"runtime"``), a human-readable
+ ``msg``, and for runtime errors the original ``exception``.
+
+ Returns an empty list when the cell is healthy.
"""
- return self._impl.exception if self._impl else None
+ result: list[CellError] = [
+ CellError(kind="graph", msg=err.describe())
+ for err in self._graph_errors
+ ]
+ if self._impl and self._impl.exception is not None:
+ exc = self._impl.exception
+ result.append(
+ CellError(
+ kind="runtime",
+ msg=f"{type(exc).__name__}: {exc}",
+ exception=exc,
+ )
+ )
+ return result
# -- display --
@@ -278,9 +331,11 @@ class NotebookCell:
code_preview = first_line
name_part = f", name={self.name!r}" if self.name else ""
status_part = f", status={self.status!r}" if self.status else ""
+ errors = self.errors
+ errors_part = f", errors={errors!r}" if errors else ""
return (
f"NotebookCell(id={self.id!r}{name_part}"
- f"{status_part}, code={code_preview!r})"
+ f"{status_part}{errors_part}, code={code_preview!r})"
)
@@ -319,9 +374,11 @@ class _CellsView:
try:
graph = self._ctx.graph
impl = graph.cells.get(cell.id)
+ graph_errors = self._ctx._kernel.errors.get(cell.id, ())
except AttributeError:
impl = None
- return NotebookCell(cell, impl)
+ graph_errors = ()
+ return NotebookCell(cell, impl, graph_errors=graph_errors)
def _cell_ids(self) -> list[CellId_t]:
return list(self._doc)
@@ -577,7 +634,16 @@ class AsyncCodeModeContext:
self._dry_run_compile(ops)
await self._apply_ops(ops, cells_to_run)
elif cells_to_run:
- await self._kernel._run_cells(cells_to_run)
+ code_lookup = {c.id: c.code for c in self._document.cells}
+ await self._kernel.run(
+ [
+ ExecuteCellCommand(
+ cell_id=cid,
+ code=code_lookup[cid],
+ )
+ for cid in cells_to_run
+ ]
+ )
# Flush queued UI updates as a single batch.
if ui_updates:
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index d423b6a0eb..b705864a5f 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -272,6 +272,14 @@ async def execute_code(
body = await parse_request(request, cls=ExecuteScratchpadRequest)
session = app_state.require_current_session()
+ # Register cells into the graph without executing them so that
+ # code_mode's run_cell can resolve dependencies. The kernel
+ # no-ops if already instantiated.
+ session.instantiate(
+ InstantiateNotebookRequest(object_ids=[], values=[], auto_run=False),
+ http_request=HTTPRequest.from_request(request),
+ )
+
async def _watch_disconnect() -> None:
"""Wait for client disconnect and interrupt the kernel."""
while True:
diff --git a/tests/_code_mode/test_cells_view.py b/tests/_code_mode/test_cells_view.py
index d797a999ce..fd62b96f3f 100644
--- a/tests/_code_mode/test_cells_view.py
+++ b/tests/_code_mode/test_cells_view.py
@@ -426,7 +426,9 @@ class TestEnrichedCellStatus:
)
enriched = EnrichedCell(cell, impl)
assert enriched.status == "exception"
- assert enriched.error is err
+ assert len(enriched.errors) == 1
+ assert enriched.errors[0].kind == "runtime"
+ assert enriched.errors[0].exception is err
def test_code_edited_becomes_stale(self) -> None:
cell = _cell("a", "x = 2")
@@ -443,7 +445,8 @@ class TestEnrichedCellStatus:
enriched = EnrichedCell(cell, impl)
assert enriched.status == "stale"
# Error persists for inspection
- assert enriched.error is err
+ assert len(enriched.errors) == 1
+ assert enriched.errors[0].exception is err
def test_runtime_stale_flag(self) -> None:
"""Lazy mode: inputs changed but code is the same."""
@@ -506,10 +509,10 @@ class TestEnrichedCellStatus:
assert enriched.name == "my_cell"
assert enriched.config == CellConfig()
- def test_error_none_when_no_impl(self) -> None:
+ def test_errors_empty_when_no_impl(self) -> None:
cell = _cell("a", "x = 1")
enriched = EnrichedCell(cell, None)
- assert enriched.error is None
+ assert enriched.errors == []
class TestEnrichedCellRepr: