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.

Restore plain text tracebacks and fix exit codes for code mode (#9224)

Trevor Manz3def675ed145
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.py
index ea6d2cbca8..1a5b92ae4d 100644
--- a/marimo/_code_mode/_context.py
+++ b/marimo/_code_mode/_context.py
@@ -737,9 +737,18 @@ class AsyncCodeModeContext:
op_cell_ids.add(cell_id)
label = self._cell_label(cell_id)
ran = cell_id in _run
+ errored = ran and self._cell_errored(cell_id)
if isinstance(op, _AddOp):
- verb = "created and ran" if ran else "created"
- lines.append(f"{verb} cell {label}")
+ if errored:
+ verb = "created and ran"
+ suffix = " (error)"
+ elif ran:
+ verb = "created and ran"
+ suffix = ""
+ else:
+ verb = "created"
+ suffix = ""
+ lines.append(f"{verb} cell {label}{suffix}")
elif isinstance(op, _UpdateOp):
parts = []
if op.code is not None:
@@ -747,7 +756,12 @@ class AsyncCodeModeContext:
if op.config is not None:
parts.append("config")
detail = " and ".join(parts) if parts else "config"
- suffix = " and ran" if ran else ""
+ if errored:
+ suffix = " and ran (error)"
+ elif ran:
+ suffix = " and ran"
+ else:
+ suffix = ""
lines.append(f"edited {detail} of cell {label}{suffix}")
elif isinstance(op, _DeleteOp):
lines.append(f"deleted cell {label}")
@@ -759,7 +773,9 @@ class AsyncCodeModeContext:
for cell_id in _run:
if cell_id not in op_cell_ids:
label = self._cell_label(cell_id)
- lines.append(f"re-ran cell {label}")
+ errored = self._cell_errored(cell_id)
+ suffix = " (error)" if errored else ""
+ lines.append(f"re-ran cell {label}{suffix}")
if ui_updates:
lines.append(f"updated {len(ui_updates)} UI element(s)")
@@ -767,20 +783,18 @@ class AsyncCodeModeContext:
if not lines:
return
+ # Add a blank line before the summary when cells errored,
+ # so the summary is visually separated from streamed tracebacks.
+ has_errors = _run and any(self._cell_errored(cid) for cid in _run)
+ if has_errors:
+ sys.stdout.write("\n")
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_errored(self, cell_id: CellId_t) -> bool:
+ """Return True if the cell raised an exception."""
+ cell = self.graph.cells.get(cell_id)
+ return cell is not None and cell.exception is not None
def _cell_label(self, cell_id: CellId_t) -> str:
"""Return a display label: ``'id' (name)`` or ``'id'``."""
diff --git a/marimo/_mcp/code_server/main.py b/marimo/_mcp/code_server/main.py
index c6dc1302f7..4a3f5dc310 100644
--- a/marimo/_mcp/code_server/main.py
+++ b/marimo/_mcp/code_server/main.py
@@ -140,7 +140,7 @@ def setup_code_mcp_server(
error=f"Execution timed out after {EXECUTION_TIMEOUT}s",
)
- return extract_result(session)
+ return extract_result(session, listener)
# Build the streamable HTTP app
mcp_app = mcp.streamable_http_app()
diff --git a/marimo/_messaging/tracebacks.py b/marimo/_messaging/tracebacks.py
index 0afc36d68f..a6061204c1 100644
--- a/marimo/_messaging/tracebacks.py
+++ b/marimo/_messaging/tracebacks.py
@@ -43,8 +43,9 @@ def _show_tracebacks_enabled() -> bool:
def write_traceback(traceback: str) -> None:
in_run_mode = get_mode() == "run"
+ code_mode = is_code_mode_request()
- if isinstance(sys.stderr, Stderr) and not is_code_mode_request():
+ if isinstance(sys.stderr, Stderr) and not code_mode:
# In run mode, only forward to the frontend if show_tracebacks is on.
if in_run_mode and not _show_tracebacks_enabled():
return
@@ -63,13 +64,16 @@ def write_traceback(traceback: str) -> None:
if in_run_mode and not _show_tracebacks_enabled():
sys.stderr.write(traceback)
return
+ trimmed = _trim_traceback(traceback)
broadcast_notification(
CellNotification(
cell_id=ctx.cell_id,
console=CellOutput(
channel=CellChannel.STDERR,
mimetype="application/vnd.marimo+traceback",
- data=_highlight_traceback(_trim_traceback(traceback)),
+ data=trimmed
+ if code_mode
+ else _highlight_traceback(trimmed),
),
),
ctx.stream,
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index 56d1197fc1..74dda0c48d 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -312,7 +312,7 @@ async def execute_code(
async for event in listener.stream():
yield event
- yield build_done_event(session)
+ yield build_done_event(session, listener)
finally:
disconnect_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
diff --git a/marimo/_server/scratchpad.py b/marimo/_server/scratchpad.py
index 5b5d2a12e9..f395f0df28 100644
--- a/marimo/_server/scratchpad.py
+++ b/marimo/_server/scratchpad.py
@@ -92,6 +92,7 @@ class ScratchCellListener(EventAwareExtension):
super().__init__()
self._queue: asyncio.Queue[CellNotification | None] = asyncio.Queue()
self.timed_out = False
+ self.child_error_summaries: list[str] = []
def on_notification_sent(
self, session: Session, notification: KernelMessage
@@ -105,10 +106,24 @@ class ScratchCellListener(EventAwareExtension):
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)
+ else:
+ if msg.console is not None:
+ # Stream console output from cells run by _code_mode
+ # during this scratchpad execution.
+ self._queue.put_nowait(msg)
+ if (
+ msg.output is not None
+ and msg.output.channel == CellChannel.MARIMO_ERROR
+ and isinstance(msg.output.data, list)
+ and msg.output.data
+ ):
+ err = msg.output.data[0]
+ exc_type = (
+ getattr(err, "exception_type", None) or type(err).__name__
+ )
+ self.child_error_summaries.append(
+ f"cell '{msg.cell_id}' raised {exc_type}"
+ )
async def stream(self) -> AsyncGenerator[str, None]:
"""Yield SSE-formatted stdout/stderr events until execution completes.
@@ -180,7 +195,10 @@ def _format_console(msg: CellNotification) -> list[str]:
]
-def build_done_event(session: Session) -> str:
+def build_done_event(
+ session: Session,
+ listener: ScratchCellListener | None = None,
+) -> str:
"""Build the ``done`` SSE event from the session's scratch cell state."""
cell_notif = session.session_view.cell_notifications.get(SCRATCH_CELL_ID)
if cell_notif is None:
@@ -188,7 +206,7 @@ def build_done_event(session: Session) -> str:
output = cell_notif.output
- # Error case
+ # Error case — scratch cell itself errored
if (
output is not None
and output.channel == CellChannel.MARIMO_ERROR
@@ -212,6 +230,20 @@ def build_done_event(session: Session) -> str:
)
return _format_sse("done", DoneError(success=False, error=error_data))
+ # Error case — child cells (created/run by code_mode) errored.
+ # Full traceback was already streamed; msg is just a summary.
+ if listener and listener.child_error_summaries:
+ return _format_sse(
+ "done",
+ DoneError(
+ success=False,
+ error=ErrorData(
+ type="CellExecutionError",
+ msg="; ".join(listener.child_error_summaries),
+ ),
+ ),
+ )
+
# Success case
if output is not None:
data = output.data
@@ -244,7 +276,10 @@ def build_timeout_event(timeout: float) -> str:
)
-def extract_result(session: Session) -> CodeExecutionResult:
+def extract_result(
+ session: Session,
+ listener: ScratchCellListener | None = None,
+) -> CodeExecutionResult:
"""Read the scratch cell's final state from the session view."""
cell_notif = session.session_view.cell_notifications.get(SCRATCH_CELL_ID)
if cell_notif is None:
@@ -279,6 +314,10 @@ def extract_result(session: Session) -> CodeExecutionResult:
for err in cell_notif.output.data:
errors.append(str(getattr(err, "msg", None) or err))
+ # Include child cell error summaries.
+ if listener:
+ errors.extend(listener.child_error_summaries)
+
return CodeExecutionResult(
success=len(errors) == 0,
output=output_data,
diff --git a/tests/_code_mode/test_context.py b/tests/_code_mode/test_context.py
index 2a8f5be5bd..c8d0a9584c 100644
--- a/tests/_code_mode/test_context.py
+++ b/tests/_code_mode/test_context.py
@@ -1013,15 +1013,19 @@ class TestDocumentKernelDivergence:
class TestErrorReporting:
- async def test_print_summary_reports_cell_errors(
+ async def test_print_summary_does_not_duplicate_errors(
self, k: Kernel, capsys: pytest.CaptureFixture[str]
) -> None:
- """_print_summary writes cell runtime errors to stderr."""
+ """_print_summary does not write cell errors to stderr.
+
+ Runtime errors are surfaced by ScratchCellListener via the done
+ event, not duplicated to stderr by _print_summary.
+ """
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.err
+ assert "created and ran" in captured.out
+ assert "error in cell" not in captured.err
diff --git a/tests/_server/test_scratchpad.py b/tests/_server/test_scratchpad.py
index ec9fc8cd3e..565eed36e6 100644
--- a/tests/_server/test_scratchpad.py
+++ b/tests/_server/test_scratchpad.py
@@ -5,6 +5,7 @@ import json
from unittest.mock import MagicMock
import pytest
+from inline_snapshot import snapshot
from marimo._ai._tools.types import CodeExecutionResult
from marimo._messaging.cell_output import CellChannel, CellOutput
@@ -139,6 +140,26 @@ class TestExtractResult:
assert len(result.errors) == 1
assert "NameError" in result.errors[0]
+ def test_child_cell_errors_included(self) -> None:
+ """extract_result reports failure when listener saw child errors."""
+ notif = CellNotification(
+ cell_id=SCRATCH_CELL_ID,
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/plain",
+ data="summary",
+ ),
+ console=None,
+ status="idle",
+ )
+ listener = ScratchCellListener()
+ listener.child_error_summaries.append(
+ "cell 'abc12345' raised ZeroDivisionError"
+ )
+ result = extract_result(_make_session(notif), listener)
+ assert result.success is False
+ assert result.errors == ["cell 'abc12345' raised ZeroDivisionError"]
+
def test_none_console_entries_skipped(self) -> None:
notif = CellNotification(
cell_id=SCRATCH_CELL_ID,
@@ -320,6 +341,52 @@ class TestBuildDoneEvent:
assert data["success"] is False
assert "ctx.install_packages" in data["error"]["msg"]
+ def test_child_cell_error_reports_failure(self) -> None:
+ """done event reports failure when listener saw child errors."""
+ notif = CellNotification(
+ cell_id=SCRATCH_CELL_ID,
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/plain",
+ data="summary",
+ ),
+ status="idle",
+ )
+ listener = ScratchCellListener()
+ listener.child_error_summaries.append(
+ "cell 'abc12345' raised ZeroDivisionError"
+ )
+ _, data = _parse_sse(build_done_event(_make_session(notif), listener))
+ assert data == snapshot(
+ {
+ "success": False,
+ "error": {
+ "type": "CellExecutionError",
+ "msg": "cell 'abc12345' raised ZeroDivisionError",
+ },
+ }
+ )
+
+ def test_no_child_errors_still_succeeds(self) -> None:
+ """done event succeeds when listener has no child errors."""
+ listener = ScratchCellListener()
+ notif = CellNotification(
+ cell_id=SCRATCH_CELL_ID,
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/plain",
+ data="42",
+ ),
+ status="idle",
+ )
+ _, data = _parse_sse(build_done_event(_make_session(notif), listener))
+ assert data == snapshot(
+ {
+ "success": True,
+ "output": {"mimetype": "text/plain", "data": "42"},
+ }
+ )
+
def test_timeout(self) -> None:
_, data = _parse_sse(build_timeout_event(30.0))
assert data["success"] is False