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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Surface cell errors from `_code_mode` through scratchpad (#9030)
Trevor Manzeba1740e09d3
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.pyindex b4bf67101b..cbe968cd0f 100644--- a/marimo/_code_mode/_context.py+++ b/marimo/_code_mode/_context.py@@ -459,6 +459,18 @@ class AsyncCodeModeContext:for line in lines:sys.stdout.write(line + "\n")+ # Report runtime errors for cells that were executed.+ # This runs after _run_cells returns and the nested+ # redirect_streams context has exited, so stderr is routed+ # back to the scratch cell and captured by the SSE listener.+ if _run:+ for cell_id in _run:+ cell = self.graph.cells.get(cell_id)+ if cell is None or cell.exception is None:+ continue+ label = self._cell_label(cell_id)+ sys.stderr.write(f"error in cell {label}:\n{cell.exception}\n")+def _cell_label(self, cell_id: CellId_t) -> str:"""Return a display label: ``'id' (name)`` or ``'id'``."""short = repr(str(cell_id)[:8])diff --git a/marimo/_server/scratchpad.py b/marimo/_server/scratchpad.pyindex 098b5e2287..5b5d2a12e9 100644--- a/marimo/_server/scratchpad.py+++ b/marimo/_server/scratchpad.py@@ -79,6 +79,13 @@ class ScratchCellListener(EventAwareExtension):Supports both SSE streaming (via ``stream()``) and simple blockingwait (via ``wait()``) so the same listener works for the HTTP``/execute`` endpoint and the MCP ``execute_code`` tool.++ In addition to the scratch cell's own output, the listener captures+ console output (stdout/stderr) from *other* cells that execute while+ the scratchpad is active — e.g. cells created and run by+ ``_code_mode``. Only the scratch cell's ``idle`` status triggers+ the done sentinel; non-scratch notifications are streamed but never+ signal completion."""def __init__(self) -> None:@@ -93,11 +100,15 @@ class ScratchCellListener(EventAwareExtension):msg = deserialize_kernel_message(notification)if not isinstance(msg, CellNotification):return- if msg.cell_id != SCRATCH_CELL_ID:- return- self._queue.put_nowait(msg)- if msg.status == "idle":- self._queue.put_nowait(None) # sentinel++ if msg.cell_id == SCRATCH_CELL_ID:+ self._queue.put_nowait(msg)+ if msg.status == "idle":+ self._queue.put_nowait(None) # sentinel+ elif msg.console is not None:+ # Stream console output from cells run by _code_mode+ # during this scratchpad execution.+ self._queue.put_nowait(msg)async def stream(self) -> AsyncGenerator[str, None]:"""Yield SSE-formatted stdout/stderr events until execution completes.diff --git a/tests/_code_mode/test_context.py b/tests/_code_mode/test_context.pyindex 05a948f6c5..f78a847f54 100644--- a/tests/_code_mode/test_context.py+++ b/tests/_code_mode/test_context.py@@ -718,3 +718,18 @@ class TestDocumentKernelDivergence:new_id = nb.create_cell("x = 1")assert new_id not in {c.id for c in doc_only}+++class TestErrorReporting:+ async def test_print_summary_reports_cell_errors(+ self, k: Kernel, capsys: pytest.CaptureFixture[str]+ ) -> None:+ """_print_summary writes cell runtime errors to stderr."""+ with _ctx(k) as ctx:+ async with ctx as nb:+ cid = nb.create_cell("raise ValueError('boom')")+ nb.run_cell(cid)++ captured = capsys.readouterr()+ assert "error in cell" in captured.err+ assert "boom" in captured.errdiff --git a/tests/_server/test_scratchpad.py b/tests/_server/test_scratchpad.pyindex c8e3181c0c..ec9fc8cd3e 100644--- a/tests/_server/test_scratchpad.py+++ b/tests/_server/test_scratchpad.py@@ -360,7 +360,8 @@ class TestScratchCellListener:assert payload["data"] == "hello\n"@pytest.mark.asyncio- async def test_ignores_other_cells(self) -> None:+ async def test_ignores_other_cell_status(self) -> None:+ """Status-only notifications from non-scratch cells are ignored."""from marimo._messaging.serde import serialize_kernel_messagelistener = ScratchCellListener()@@ -377,6 +378,37 @@ class TestScratchCellListener:)assert listener._queue.empty()+ @pytest.mark.asyncio+ async def test_captures_other_cell_console(self) -> None:+ """Console output from non-scratch cells is captured."""+ from marimo._messaging.serde import serialize_kernel_message++ listener = ScratchCellListener()+ event_bus = MagicMock()+ session = MagicMock()+ listener.on_attach(session, event_bus)++ other_console = CellNotification(+ cell_id="other_cell_id",+ console=CellOutput.stderr("error trace\n"),+ )+ listener.on_notification_sent(+ session, serialize_kernel_message(other_console)+ )+ assert not listener._queue.empty()++ idle = CellNotification(cell_id=SCRATCH_CELL_ID, status="idle")+ listener.on_notification_sent(session, serialize_kernel_message(idle))++ events: list[str] = []+ async for event in listener.stream():+ events.append(event)++ assert len(events) == 1+ name, payload = _parse_sse(events[0])+ assert name == "stderr"+ assert payload["data"] == "error trace\n"+@pytest.mark.asyncioasync def test_stream_cancelled_on_disconnect(self) -> None:"""stream() can be cancelled externally (simulating client disconnect)."""