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.

feat: include errors with ipynb exports (#7811)

Dylan Madisetti8048df080012
diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.py
index 79ecc4f8a8..ce23e2ed3b 100644
--- a/marimo/_server/export/__init__.py
+++ b/marimo/_server/export/__init__.py
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, Literal, Optional, cast
from marimo import _loggers
from marimo._ast.app import InternalApp
+from marimo._ast.errors import CycleError, MultipleDefinitionError
from marimo._ast.load import load_app
from marimo._cli.print import echo
from marimo._config.config import RuntimeConfig
@@ -94,9 +95,24 @@ def export_as_ipynb(
did_error=True,
)
+ # Try the requested sort mode, fall back to top-down if cycles exist
+ internal_app = InternalApp(app)
+ actual_sort_mode = sort_mode
+ if sort_mode == "topological":
+ try:
+ # Check if graph can be accessed (raises CycleError/MultipleDefinitionError)
+ _ = internal_app.graph
+ except (CycleError, MultipleDefinitionError):
+ echo(
+ "Warning: Notebook has errors, "
+ "using top-down order instead of topological.",
+ err=True,
+ )
+ actual_sort_mode = "top-down"
+
result = Exporter().export_as_ipynb(
- app=InternalApp(app),
- sort_mode=sort_mode,
+ app=internal_app,
+ sort_mode=actual_sort_mode,
)
return ExportResult(
contents=result,
@@ -153,10 +169,13 @@ async def run_app_then_export_as_ipynb(
file_manager = file_router.get_file_manager(file_key)
with patch_html_for_non_interactive_output():
+ # Use quiet=True to suppress runtime stdout/stderr since outputs
+ # are captured in the session_view and will be included in the ipynb
(session_view, did_error) = await run_app_until_completion(
file_manager,
cli_args,
argv,
+ quiet=True,
)
result = Exporter().export_as_ipynb(
@@ -235,6 +254,7 @@ async def run_app_until_completion(
file_manager: AppFileManager,
cli_args: SerializedCLIArgs,
argv: list[str] | None,
+ quiet: bool = False,
) -> tuple[SessionView, bool]:
from marimo._session.consumer import SessionConsumer
from marimo._session.events import SessionEventBus
@@ -252,7 +272,7 @@ async def run_app_until_completion(
def notify(self, notification: KernelMessage) -> None:
data = deserialize_kernel_message(notification)
- # Print errors to stderr
+ # Print errors to stderr (unless quiet mode)
if isinstance(data, CellNotification):
output = data.output
console_output = data.console
@@ -261,13 +281,14 @@ async def run_app_until_completion(
for err in errors:
# Not all errors are fatal
if is_unexpected_error(err):
- echo(
- f"{err.__class__.__name__}: {err.describe()}",
- file=sys.stderr,
- )
+ if not quiet:
+ echo(
+ f"{err.__class__.__name__}: {err.describe()}",
+ file=sys.stderr,
+ )
self.did_error = True
- if console_output:
+ if console_output and not quiet:
console_as_list: list[CellOutput] = (
console_output
if isinstance(console_output, list)
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 86274815f8..065654b139 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -6,13 +6,16 @@ import base64
import io
import json
import mimetypes
+import re
from concurrent.futures import ThreadPoolExecutor
+from html.parser import HTMLParser
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Literal, Optional, cast
+from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast
from marimo import _loggers
from marimo._ast.app import InternalApp
-from marimo._ast.cell import Cell, CellImpl
+from marimo._ast.cell import Cell, CellConfig
+from marimo._ast.errors import CycleError, MultipleDefinitionError
from marimo._ast.names import DEFAULT_CELL_NAME, is_internal_cell_name
from marimo._config.config import (
DEFAULT_CONFIG,
@@ -24,6 +27,10 @@ from marimo._config.utils import deep_copy
from marimo._convert.utils import get_markdown_from_cell
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.cell_output import CellChannel, CellOutput
+from marimo._messaging.errors import (
+ Error as MarimoError,
+ MarimoExceptionRaisedError,
+)
from marimo._messaging.mimetypes import METADATA_KEY, KnownMimeType
from marimo._runtime import dataflow
from marimo._runtime.virtual_file import read_virtual_file
@@ -278,24 +285,34 @@ class Exporter:
import nbformat # type: ignore[import-not-found]
notebook = nbformat.v4.new_notebook() # type: ignore[no-untyped-call]
- graph = app.graph
+ notebook["cells"] = []
- # Sort cells based on sort_mode
+ # Determine cell order based on sort_mode
if sort_mode == "top-down":
- cell_ids = list(app.cell_manager.cell_ids())
+ cell_data_list = list(app.cell_manager.cell_data())
else:
- cell_ids = dataflow.topological_sort(graph, graph.cells.keys())
-
- notebook["cells"] = []
- for cid in cell_ids:
- if cid not in graph.cells:
- LOGGER.warning("Cell %s not found in graph", cid)
- continue
- cell = graph.cells[cid]
+ # Topological sort - try to sort, fall back to top-down on cycle
+ try:
+ graph = app.graph
+ sorted_ids = dataflow.topological_sort(
+ graph, graph.cells.keys()
+ )
+ # Build cell_data list in topological order
+ cell_data_list = [
+ app.cell_manager.cell_data_at(cid)
+ for cid in sorted_ids
+ if cid in graph.cells
+ ]
+ except (CycleError, MultipleDefinitionError):
+ # Fall back to top-down order if graph is invalid
+ cell_data_list = list(app.cell_manager.cell_data())
+
+ for cell_data in cell_data_list:
+ cid = cell_data.cell_id
+
+ # Get outputs if session_view is provided
outputs: list[NotebookNode] = []
-
if session_view is not None:
- # Get outputs for this cell and convert to IPython format
cell_output = session_view.get_cell_outputs([cid]).get(
cid, None
)
@@ -306,22 +323,16 @@ class Exporter:
cell_output, cell_console_outputs
)
- notebook_cell = _create_notebook_cell(cell, outputs)
- # Add metadata to the cell
- marimo_metadata: dict[str, Any] = {}
- if cell.config.is_different_from_default():
- marimo_metadata["config"] = (
- cell.config.asdict_without_defaults()
- )
- name = app.cell_manager.cell_name(cid)
- if not is_internal_cell_name(name):
- marimo_metadata["name"] = name
- if marimo_metadata:
- notebook_cell["metadata"]["marimo"] = marimo_metadata
+ notebook_cell = _create_ipynb_cell(
+ cell_id=cid,
+ code=cell_data.code,
+ name=cell_data.name,
+ config=cell_data.config,
+ cell=cell_data.cell,
+ outputs=outputs,
+ )
notebook["cells"].append(notebook_cell)
- # notebook.metadata["marimo-version"] = __version__
-
stream = io.StringIO()
nbformat.write(notebook, stream) # type: ignore[no-untyped-call]
stream.seek(0)
@@ -479,29 +490,60 @@ class AutoExporter:
self._executor.shutdown(wait=False)
-def _create_notebook_cell(
- cell: CellImpl, outputs: list[NotebookNode]
+def _create_ipynb_cell(
+ cell_id: str,
+ code: str,
+ name: str,
+ config: CellConfig,
+ cell: Optional[Cell],
+ outputs: list[NotebookNode],
) -> NotebookNode:
+ """Create an ipynb cell with metadata.
+
+ Args:
+ cell_id: The cell's unique identifier
+ code: The cell's source code
+ name: The cell's name
+ config: The cell's configuration
+ cell: Optional Cell object for markdown detection
+ outputs: List of cell outputs (ignored for markdown cells)
+ """
import nbformat
- markdown_string = get_markdown_from_cell(
- Cell(_name=DEFAULT_CELL_NAME, _cell=cell), cell.code
- )
- if markdown_string is not None:
- return cast(
- nbformat.NotebookNode,
- nbformat.v4.new_markdown_cell(markdown_string, id=cell.cell_id), # type: ignore[no-untyped-call]
- )
+ # Try to extract markdown if we have a valid Cell
+ if cell is not None:
+ markdown_string = get_markdown_from_cell(cell, code)
+ if markdown_string is not None:
+ node = cast(
+ nbformat.NotebookNode,
+ nbformat.v4.new_markdown_cell(markdown_string, id=cell_id), # type: ignore[no-untyped-call]
+ )
+ _add_marimo_metadata(node, name, config)
+ return node
node = cast(
nbformat.NotebookNode,
- nbformat.v4.new_code_cell(cell.code, id=cell.cell_id), # type: ignore[no-untyped-call]
+ nbformat.v4.new_code_cell(code, id=cell_id), # type: ignore[no-untyped-call]
)
if outputs:
node.outputs = outputs
+ _add_marimo_metadata(node, name, config)
return node
+def _add_marimo_metadata(
+ node: NotebookNode, name: str, config: CellConfig
+) -> None:
+ """Add marimo-specific metadata to a notebook cell."""
+ marimo_metadata: dict[str, Any] = {}
+ if config.is_different_from_default():
+ marimo_metadata["config"] = config.asdict_without_defaults()
+ if not is_internal_cell_name(name):
+ marimo_metadata["name"] = name
+ if marimo_metadata:
+ node["metadata"]["marimo"] = marimo_metadata
+
+
def get_html_contents() -> str:
if GLOBAL_SETTINGS.DEVELOPMENT_MODE:
import marimo._utils.requests as requests
@@ -528,8 +570,70 @@ def _maybe_extract_dataurl(data: Any) -> Any:
return data
+class _HTMLTextExtractor(HTMLParser):
+ """Extract plain text from HTML."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.text_parts: list[str] = []
+
+ def handle_data(self, data: str) -> None:
+ self.text_parts.append(data)
+
+ def get_text(self) -> str:
+ return "".join(self.text_parts)
+
+
+def _strip_html_from_traceback(html_traceback: str) -> list[str]:
+ """Convert HTML-formatted traceback to plain text lines.
+
+ Also strips temporary file paths from tracebacks. Exports run cells in
+ the kernel which compiles them with temp file paths. It's not easy to
+ set anonymous source since exports are done in the kernel, so we strip
+ the paths here instead.
+ """
+ parser = _HTMLTextExtractor()
+ parser.feed(html_traceback)
+ text = parser.get_text()
+
+ # Strip temp file paths like /tmp/marimo_12345/__marimo__cell_Hbol_.py
+ # Replace with empty string to get cleaner tracebacks
+ text = re.sub(r'[^"]*__marimo__cell_[^"]*\.py', "", text)
+
+ return text.splitlines()
+
+
+def _extract_traceback_from_console(
+ console_outputs: list[CellOutput],
+) -> list[str]:
+ """Extract traceback lines from console outputs."""
+ for output in console_outputs:
+ if (
+ output.channel == CellChannel.STDERR
+ and output.mimetype == "application/vnd.marimo+traceback"
+ ):
+ return _strip_html_from_traceback(str(output.data))
+ return []
+
+
+def _get_error_info(
+ error: Union[MarimoError, dict[str, Any]],
+) -> tuple[str, str]:
+ """Extract ename and evalue from a marimo error."""
+ from marimo._messaging.msgspec_encoder import asdict
+
+ if isinstance(error, dict):
+ return error.get("type", "UnknownError"), error.get("msg", "")
+ elif isinstance(error, MarimoExceptionRaisedError):
+ return error.exception_type, error.msg.rstrip().strip(":")
+ else:
+ # For other error types, use the tag as ename and describe() as evalue
+ error_dict = asdict(error)
+ return error_dict.get("type", "Error"), error.describe()
+
+
def _convert_marimo_output_to_ipynb(
- output: Optional[CellOutput], console_outputs: list[CellOutput]
+ cell_output: Optional[CellOutput], console_outputs: list[CellOutput]
) -> list[NotebookNode]:
"""Convert marimo output format to IPython notebook format."""
import nbformat
@@ -537,41 +641,64 @@ def _convert_marimo_output_to_ipynb(
ipynb_outputs: list[NotebookNode] = []
# Handle stdout/stderr
- for output in console_outputs:
- if output.channel == CellChannel.STDOUT:
+ for console_out in console_outputs:
+ if console_out.channel == CellChannel.STDOUT:
ipynb_outputs.append(
cast(
nbformat.NotebookNode,
nbformat.v4.new_output( # type: ignore[no-untyped-call]
"stream",
name="stdout",
- text=output.data,
+ text=console_out.data,
),
)
)
- if output.channel == CellChannel.STDERR:
+ elif console_out.channel == CellChannel.STDERR:
+ # Skip tracebacks - they're included in error outputs
+ if console_out.mimetype == "application/vnd.marimo+traceback":
+ continue
ipynb_outputs.append(
cast(
nbformat.NotebookNode,
nbformat.v4.new_output( # type: ignore[no-untyped-call]
"stream",
name="stderr",
- text=output.data,
+ text=console_out.data,
),
)
)
- if not output:
+ if not cell_output:
return ipynb_outputs
- if output.data is None:
+ if cell_output.data is None:
+ return ipynb_outputs
+
+ if cell_output.channel == CellChannel.MARIMO_ERROR:
+ traceback_lines = _extract_traceback_from_console(console_outputs)
+ errors = cast(
+ list[Union[MarimoError, dict[str, Any]]], cell_output.data
+ )
+ for error in errors:
+ ename, evalue = _get_error_info(error)
+ ipynb_outputs.append(
+ cast(
+ nbformat.NotebookNode,
+ nbformat.v4.new_output( # type: ignore[no-untyped-call]
+ "error",
+ ename=ename,
+ evalue=evalue,
+ traceback=traceback_lines,
+ ),
+ )
+ )
return ipynb_outputs
- if output.channel not in (CellChannel.OUTPUT, CellChannel.MEDIA):
+ if cell_output.channel not in (CellChannel.OUTPUT, CellChannel.MEDIA):
return ipynb_outputs
- if output.mimetype == "text/plain" and (
- output.data == [] or output.data == ""
+ if cell_output.mimetype == "text/plain" and (
+ cell_output.data == [] or cell_output.data == ""
):
return ipynb_outputs
@@ -579,16 +706,16 @@ def _convert_marimo_output_to_ipynb(
data: dict[str, Any] = {}
metadata: dict[str, Any] = {}
- if output.mimetype == "application/vnd.marimo+error":
- # Captured by stdout/stderr
+ if cell_output.mimetype == "application/vnd.marimo+error":
+ # Already handled above via MARIMO_ERROR channel
return ipynb_outputs
- elif output.mimetype == "application/vnd.marimo+mimebundle":
- if isinstance(output.data, dict):
- mimebundle = output.data
- elif isinstance(output.data, str):
- mimebundle = json.loads(output.data)
+ elif cell_output.mimetype == "application/vnd.marimo+mimebundle":
+ if isinstance(cell_output.data, dict):
+ mimebundle = cell_output.data
+ elif isinstance(cell_output.data, str):
+ mimebundle = json.loads(cell_output.data)
else:
- raise ValueError(f"Invalid data type: {type(output.data)}")
+ raise ValueError(f"Invalid data type: {type(cell_output.data)}")
for mime, content in mimebundle.items():
if mime == METADATA_KEY and isinstance(content, dict):
@@ -596,7 +723,7 @@ def _convert_marimo_output_to_ipynb(
else:
data[mime] = _maybe_extract_dataurl(content)
else:
- data[output.mimetype] = _maybe_extract_dataurl(output.data)
+ data[cell_output.mimetype] = _maybe_extract_dataurl(cell_output.data)
if data:
ipynb_outputs.append(
diff --git a/tests/_cli/snapshots/ipynb_with_errors.txt b/tests/_cli/snapshots/ipynb_with_errors.txt
index a5136d1db9..a7fb9853b9 100644
--- a/tests/_cli/snapshots/ipynb_with_errors.txt
+++ b/tests/_cli/snapshots/ipynb_with_errors.txt
@@ -27,15 +27,15 @@
"metadata": {},
"outputs": [
{
- "name": "stderr",
- "output_type": "stream",
- "text": [
- "<span class=\"codehilite\"><div class=\"highlight\"><pre><span></span><span class=\"gt\">Traceback (most recent call last):</span>\n",
- "<span class=\"w\"> </span><span class=\"mi\">1</span> <span class=\"o\">/</span> <span class=\"mi\">0</span>\n",
- "<span class=\"w\"> </span><span class=\"pm\">~~^~~</span>\n",
- "<span class=\"gr\">ZeroDivisionError</span>: <span class=\"n\">division by zero</span>\n",
- "</pre></div>\n",
- "</span>"
+ "ename": "ZeroDivisionError",
+ "evalue": "division by zero",
+ "output_type": "error",
+ "traceback": [
+ "Traceback (most recent call last):",
+ " 1 / 0",
+ " ~~^~~",
+ "ZeroDivisionError: division by zero",
+ ""
]
}
],
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index 5f99668dd2..7dd7f91063 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -920,8 +920,10 @@ class TestExportIpynb:
capture_output=True,
)
assert p.returncode != 0, p.stderr.decode()
- assert "MultipleDefinitionError" in p.stderr.decode()
- assert p.stdout.decode() == ""
+ # Error is now captured in the ipynb output as a proper Jupyter error
+ output = p.stdout.decode()
+ assert "multiple-defs" in output
+ assert "was defined by another cell" in output
@pytest.mark.skipif(
not DependencyManager.nbformat.has() or is_windows(),
@@ -941,8 +943,10 @@ class TestExportIpynb:
capture_output=True,
)
assert p.returncode != 0, p.stderr.decode()
- assert " division by zero" in p.stderr.decode()
+ # Error is now captured in the ipynb output (stdout) as a proper
+ # Jupyter error output, not printed to stderr
output = p.stdout.decode()
+ assert "division by zero" in output
output = _delete_lines_with_files(output)
snapshot("ipynb_with_errors.txt", output)
diff --git a/tests/_server/export/snapshots/notebook_with_error.ipynb.txt b/tests/_server/export/snapshots/notebook_with_error.ipynb.txt
new file mode 100644
index 0000000000..25e3f4167d
--- /dev/null
+++ b/tests/_server/export/snapshots/notebook_with_error.ipynb.txt
@@ -0,0 +1,101 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "Hbol",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "cycle",
+ "evalue": "This cell is in a cycle",
+ "output_type": "error",
+ "traceback": []
+ }
+ ],
+ "source": [
+ "x = y"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "MJUe",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "Y = 0 # noqa: N806"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "vblA",
+ "metadata": {
+ "marimo": {
+ "name": "_b"
+ }
+ },
+ "outputs": [
+ {
+ "ename": "Ancestor raised",
+ "evalue": "An ancestor raised an exception (ZeroDivisionError)",
+ "output_type": "error",
+ "traceback": []
+ }
+ ],
+ "source": [
+ "Z = z # noqa: N806"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "bkHC",
+ "metadata": {
+ "marimo": {
+ "name": "_a"
+ }
+ },
+ "outputs": [
+ {
+ "ename": "ZeroDivisionError",
+ "evalue": "division by zero",
+ "output_type": "error",
+ "traceback": [
+ "Traceback (most recent call last):",
+ " File \"\", line 1, in <module>",
+ " z = 1 / 0",
+ " ~~^~~",
+ "ZeroDivisionError: division by zero",
+ ""
+ ]
+ }
+ ],
+ "source": [
+ "z = 1 / 0"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "lEQa",
+ "metadata": {},
+ "outputs": [
+ {
+ "ename": "cycle",
+ "evalue": "This cell is in a cycle",
+ "output_type": "error",
+ "traceback": []
+ }
+ ],
+ "source": [
+ "y = x\n",
+ "y = Y # noqa: F841"
+ ]
+ }
+ ],
+ "metadata": {},
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
index 7c3da0ec0a..d2c2094a04 100644
--- a/tests/_server/export/test_exporter.py
+++ b/tests/_server/export/test_exporter.py
@@ -439,12 +439,17 @@ def _as_list(data: Any) -> list[Any]:
def _delete_lines_with_files(output: str) -> str:
# Remove any line that contains "File " up until a .py ending
+ # Note: temp paths are already stripped in the exporter, so this may be
+ # a no-op for most cases now
def remove_file_name(line: str) -> str:
if "File " not in line:
return line
start = line.index("File ")
- end = line.rindex(".py") + 3
- return line[0:start] + line[end:]
+ # Check if there's a .py extension to strip
+ if ".py" in line[start:]:
+ end = line.rindex(".py") + 3
+ return line[0:start] + line[end:]
+ return line
return "\n".join(remove_file_name(line) for line in output.splitlines())
@@ -1590,3 +1595,240 @@ def test_convert_regular_output_has_empty_metadata():
# Regular outputs should have empty metadata
assert "metadata" in result[0]
assert result[0]["metadata"] == {}
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+async def test_export_ipynb_with_exception():
+ """Test that exceptions are properly formatted in ipynb output."""
+ app = App()
+
+ @app.cell()
+ def _():
+ x = undefined_variable # noqa: F821
+ return (x,)
+
+ # Run and export
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ session_view, did_error = await run_app_until_completion(
+ file_manager, cli_args={}, argv=None, quiet=True
+ )
+ assert did_error is True
+
+ result = Exporter().export_as_ipynb(
+ InternalApp(app), sort_mode="top-down", session_view=session_view
+ )
+ notebook = json.loads(result)
+
+ # Find the error output
+ outputs = notebook["cells"][0]["outputs"]
+ error_outputs = [o for o in outputs if o["output_type"] == "error"]
+ assert len(error_outputs) == 1
+ assert error_outputs[0]["ename"] == "NameError"
+ assert "undefined_variable" in error_outputs[0]["evalue"]
+ # Traceback should be a list of strings
+ assert isinstance(error_outputs[0]["traceback"], list)
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+async def test_export_ipynb_with_stdout_and_exception():
+ """Test cell with both stdout and exception."""
+ app = App()
+
+ @app.cell()
+ def _():
+ print("hello before error")
+ raise ValueError("test error")
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ session_view, did_error = await run_app_until_completion(
+ file_manager, cli_args={}, argv=None, quiet=True
+ )
+ assert did_error is True
+
+ result = Exporter().export_as_ipynb(
+ InternalApp(app), sort_mode="top-down", session_view=session_view
+ )
+ notebook = json.loads(result)
+ outputs = notebook["cells"][0]["outputs"]
+
+ # Should have both stdout and error
+ stdout_outputs = [o for o in outputs if o.get("name") == "stdout"]
+ error_outputs = [o for o in outputs if o["output_type"] == "error"]
+
+ assert len(stdout_outputs) == 1
+ assert "hello before error" in stdout_outputs[0]["text"][0]
+ assert len(error_outputs) == 1
+ assert error_outputs[0]["ename"] == "ValueError"
+ assert "test error" in error_outputs[0]["evalue"]
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+async def test_export_ipynb_redefinition_error():
+ """Test that cells depending on errored cells show ancestor error."""
+ app = App()
+
+ @app.cell()
+ def _():
+ x = 1
+ return (x,)
+
+ @app.cell()
+ def _():
+ x = 2
+ return (x,)
+
+ @app.cell()
+ def _(x):
+ y = x + 1
+ return (y,)
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ session_view, did_error = await run_app_until_completion(
+ file_manager, cli_args={}, argv=None, quiet=True
+ )
+ assert did_error is True
+
+ result = Exporter().export_as_ipynb(
+ InternalApp(app), sort_mode="top-down", session_view=session_view
+ )
+ notebook = json.loads(result)
+
+ # Second cell should have an ancestor error
+ assert len(notebook["cells"]) >= 3
+ second_cell_outputs = notebook["cells"][1]["outputs"]
+ error_outputs = [
+ o for o in second_cell_outputs if o["output_type"] == "error"
+ ]
+ # Ancestor errors might be represented differently
+ # At minimum, there should be some error indication
+ assert len(error_outputs) >= 1
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+async def test_export_ipynb_cycle_error():
+ """Test that cells in a cycle show cycle error."""
+ app = App()
+
+ @app.cell()
+ def _():
+ x = y + 1 # noqa: F821
+ return (x,)
+
+ @app.cell()
+ def _(x):
+ y = x + 1
+ return (y,)
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ session_view, did_error = await run_app_until_completion(
+ file_manager, cli_args={}, argv=None, quiet=True
+ )
+ assert did_error is True
+
+ result = Exporter().export_as_ipynb(
+ InternalApp(app), sort_mode="top-down", session_view=session_view
+ )
+ notebook = json.loads(result)
+
+ # Second cell should have an ancestor error
+ assert len(notebook["cells"]) >= 2
+ second_cell_outputs = notebook["cells"][1]["outputs"]
+ error_outputs = [
+ o for o in second_cell_outputs if o["output_type"] == "error"
+ ]
+ # Ancestor errors might be represented differently
+ # At minimum, there should be some error indication
+ assert len(error_outputs) >= 1
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+async def test_export_ipynb_ancestor_error():
+ """Test that cells depending on errored cells show ancestor error."""
+ app = App()
+
+ @app.cell()
+ def _():
+ x = undefined # noqa: F821
+ return (x,)
+
+ @app.cell()
+ def _(x):
+ y = x + 1
+ return (y,)
+
+ file_manager = AppFileManager.from_app(InternalApp(app))
+ session_view, did_error = await run_app_until_completion(
+ file_manager, cli_args={}, argv=None, quiet=True
+ )
+ assert did_error is True
+
+ result = Exporter().export_as_ipynb(
+ InternalApp(app), sort_mode="top-down", session_view=session_view
+ )
+ notebook = json.loads(result)
+
+ # Second cell should have an ancestor error
+ assert len(notebook["cells"]) >= 2
+ second_cell_outputs = notebook["cells"][1]["outputs"]
+ error_outputs = [
+ o for o in second_cell_outputs if o["output_type"] == "error"
+ ]
+ # Ancestor errors might be represented differently
+ # At minimum, there should be some error indication
+ assert len(error_outputs) >= 1
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+ sys.version_info < (3, 11), reason="3.10 has different stack trace format"
+)
+async def test_export_ipynb_with_error_snapshot(tmp_path: Path):
+ """Snapshot test for error output formatting with cycles and errors."""
+ app = App()
+
+ # Cell 1: Part of cycle (x depends on y)
+ @app.cell()
+ def _(y): # noqa: F811
+ x = y
+ return (x,)
+
+ # Cell 2: Normal cell (Y = 0)
+ @app.cell()
+ def _():
+ Y = 0 # noqa: N806
+ return (Y,)
+
+ # Cell 3: Ancestor error (depends on z which fails)
+ @app.cell()
+ def _b(z):
+ Z = z # noqa: N806
+ return (Z,)
+
+ # Cell 4: ZeroDivisionError
+ @app.cell()
+ def _a():
+ z = 1 / 0
+ return (z,)
+
+ # Cell 5: Part of cycle (y depends on x)
+ @app.cell()
+ def _(x, Y): # noqa: N803
+ y = x
+ y = Y # noqa: F841
+ return (y,)
+
+ internal_app = InternalApp(app)
+ test_file = tmp_path / "notebook.py"
+ test_file.write_text(internal_app.to_py())
+
+ result = await run_app_then_export_as_ipynb(
+ MarimoPath(test_file),
+ sort_mode="top-down",
+ cli_args={},
+ argv=None,
+ )
+ assert result.did_error is True
+
+ # Filter file paths for deterministic snapshots
+ content = _delete_lines_with_files(result.contents)
+ snapshot("notebook_with_error.ipynb.txt", content)