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.

Enrich code_mode `NotebookCell` with runtime status and error (#9056)

Trevor Manzc95aee6fd854
diff --git a/marimo/_code_mode/__init__.py b/marimo/_code_mode/__init__.py
index dfbbadd536..b9fafd36ad 100644
--- a/marimo/_code_mode/__init__.py
+++ b/marimo/_code_mode/__init__.py
@@ -34,12 +34,14 @@ from __future__ import annotations
from marimo._code_mode._context import (
AsyncCodeModeContext,
+ CellStatusType,
+ NotebookCell,
get_context,
)
-from marimo._messaging.notebook.document import NotebookCell
__all__ = [
"AsyncCodeModeContext",
+ "CellStatusType",
"NotebookCell",
"get_context",
]
diff --git a/marimo/_code_mode/_context.py b/marimo/_code_mode/_context.py
index 74c77d7e06..89c663dd48 100644
--- a/marimo/_code_mode/_context.py
+++ b/marimo/_code_mode/_context.py
@@ -24,10 +24,15 @@ Usage::
from __future__ import annotations
import sys
-from typing import TYPE_CHECKING, Any, overload
+from typing import TYPE_CHECKING, Any, Literal, Protocol, overload
from marimo import _loggers
-from marimo._ast.cell import CellConfig, CellImpl
+from marimo._ast.cell import (
+ CellConfig,
+ CellImpl,
+ RunResultStatusType,
+ RuntimeStateType,
+)
from marimo._ast.cell_id import CellIdGenerator
from marimo._ast.compiler import compile_cell
from marimo._ast.names import SETUP_CELL_NAME
@@ -51,7 +56,10 @@ from marimo._messaging.notebook.changes import (
SetName,
Transaction,
)
-from marimo._messaging.notebook.document import NotebookCell, NotebookDocument
+from marimo._messaging.notebook.document import (
+ NotebookCell as _NotebookCell,
+ NotebookDocument,
+)
from marimo._messaging.notification import (
NotebookDocumentTransactionNotification,
Notification,
@@ -71,13 +79,40 @@ from marimo._types.ids import CellId_t, UIElementId
from marimo._utils.formatter import DefaultFormatter
if TYPE_CHECKING:
- from collections.abc import Iterator
+ from collections.abc import Iterator, Sequence
from types import TracebackType
from marimo._ast.cell_manager import CellManager
from marimo._runtime.dataflow import DirectedGraph
from marimo._runtime.runtime import Kernel
+CellStatusType = Literal[
+ "idle",
+ "exception",
+ "stale",
+ "cancelled",
+ "interrupted",
+ "marimo-error",
+ "disabled",
+ "queued",
+ "running",
+]
+
+
+class CellRuntimeState(Protocol):
+ """The subset of ``CellImpl`` that ``NotebookCell`` reads."""
+
+ @property
+ def code(self) -> str: ...
+ @property
+ def runtime_state(self) -> RuntimeStateType | None: ...
+ @property
+ def run_result_status(self) -> RunResultStatusType | None: ...
+ @property
+ def stale(self) -> bool: ...
+ @property
+ def exception(self) -> Exception | None: ...
+
LOGGER = _loggers.marimo_logger()
@@ -116,6 +151,139 @@ def get_context(*, skip_validation: bool = False) -> AsyncCodeModeContext:
)
+class NotebookCell:
+ """Read-only view of a single cell with runtime status.
+
+ Wraps the document-level cell data and enriches it with
+ live execution state from the kernel's dependency graph.
+
+ Properties
+ ----------
+ id : CellId_t
+ code : str
+ name : str
+ config : CellConfig
+ status : CellStatusType | None
+ 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.
+ """
+
+ __slots__ = ("_cell", "_impl")
+
+ def __init__(
+ self, cell: _NotebookCell, cell_impl: CellRuntimeState | None
+ ) -> None:
+ self._cell = cell
+ self._impl = cell_impl
+
+ # -- document properties (delegated) --
+
+ @property
+ def id(self) -> CellId_t:
+ """The unique cell identifier."""
+ return self._cell.id
+
+ @property
+ def code(self) -> str:
+ """The current source code of the cell."""
+ return self._cell.code
+
+ @property
+ def name(self) -> str:
+ """The cell's display name (empty string if unnamed)."""
+ return self._cell.name
+
+ @property
+ def config(self) -> CellConfig:
+ """The cell's configuration (e.g. disabled, hide_code)."""
+ return self._cell.config
+
+ # -- runtime properties --
+
+ def _is_stale(self) -> bool:
+ """Whether the cell needs to be (re-)run.
+
+ True when:
+ - The cell has code but was never run (no impl in the graph).
+ - The cell's code was edited since it was last run.
+ - The runtime marked the cell stale (lazy mode: inputs changed).
+ """
+ if self._impl is None:
+ return bool(self._cell.code)
+ return self._cell.code != self._impl.code or self._impl.stale
+
+ @property
+ def status(self) -> CellStatusType | None:
+ """Synthesized cell status.
+
+ Possible values:
+
+ - ``"idle"`` — ran successfully, up to date.
+ - ``"exception"`` — cell raised an exception.
+ - ``"stale"`` — needs re-run (code edited, inputs changed, or never run).
+ - ``"cancelled"`` — ancestor raised an exception.
+ - ``"interrupted"`` — execution was interrupted.
+ - ``"marimo-error"`` — prevented from executing (e.g. multiply-defined name).
+ - ``"disabled"`` — cell is disabled.
+ - ``"queued"`` — waiting to run.
+ - ``"running"`` — currently executing.
+ - ``None`` — empty cell, never registered in the graph.
+
+ Priority: transient state (queued/running/disabled) >
+ stale > last run result.
+ """
+ if self._impl is None:
+ return "stale" if self._cell.code else None
+ # Transient runtime state takes priority.
+ rs = self._impl.runtime_state
+ if rs == "queued":
+ return "queued"
+ if rs == "running":
+ return "running"
+ if rs == "disabled-transitively":
+ return "disabled"
+ # Stale overrides last run result.
+ if self._is_stale():
+ return "stale"
+ # Fall back to last execution result.
+ rr = self._impl.run_result_status
+ if rr is None:
+ # Registered in the graph but never executed.
+ return "stale" if self._cell.code else None
+ if rr == "success":
+ return "idle"
+ return rr
+
+ @property
+ def error(self) -> Exception | None:
+ """The exception from the last run, if any.
+
+ Persists even when ``status`` changes to ``"stale"`` after
+ an edit — useful for inspecting what went wrong before the fix.
+ """
+ return self._impl.exception if self._impl else None
+
+ # -- display --
+
+ def __repr__(self) -> str:
+ first_line = self.code.split("\n", 1)[0]
+ if len(first_line) > 80:
+ code_preview = first_line[:80] + "..."
+ elif "\n" in self.code:
+ code_preview = first_line + "..."
+ else:
+ 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 ""
+ return (
+ f"NotebookCell(id={self.id!r}{name_part}"
+ f"{status_part}, code={code_preview!r})"
+ )
+
+
class _CellsView:
"""Read-only, ordered view over notebook cells.
@@ -126,16 +294,16 @@ class _CellsView:
ctx.cells["Abcd1234"] # by cell ID
ctx.cells["my_cell"] # by cell name
- Iteration yields ``NotebookCell`` objects directly::
+ Iteration yields ``NotebookCell`` objects with runtime status::
for cell in ctx.cells:
- print(cell.id, cell.code)
+ print(cell.id, cell.code, cell.status)
Dict-like access is also available::
ctx.cells.keys() # list of CellId_t
- ctx.cells.values() # list of NotebookCell
- ctx.cells.items() # list of (CellId_t, NotebookCell)
+ ctx.cells.values() # sequence of NotebookCell
+ ctx.cells.items() # sequence of (CellId_t, NotebookCell)
"my_cell" in ctx.cells # membership test
"""
@@ -146,6 +314,15 @@ class _CellsView:
def _doc(self) -> NotebookDocument:
return self._ctx._document
+ def _cell_view(self, cell: _NotebookCell) -> NotebookCell:
+ """Wrap a document cell with runtime state from the graph."""
+ try:
+ graph = self._ctx.graph
+ impl = graph.cells.get(cell.id)
+ except AttributeError:
+ impl = None
+ return NotebookCell(cell, impl)
+
def _cell_ids(self) -> list[CellId_t]:
return list(self._doc)
@@ -186,12 +363,12 @@ class _CellsView:
def __getitem__(self, key: int | str) -> NotebookCell:
if isinstance(key, int):
- return self._doc.cells[key]
- return self._doc.get_cell(self._resolve(key))
+ return self._cell_view(self._doc.cells[key])
+ return self._cell_view(self._doc.get_cell(self._resolve(key)))
def __iter__(self) -> Iterator[NotebookCell]:
for cell_id in self._doc.cell_ids:
- yield self._doc.get_cell(cell_id)
+ yield self._cell_view(self._doc.get_cell(cell_id))
def __contains__(self, key: object) -> bool:
if isinstance(key, int):
@@ -204,23 +381,23 @@ class _CellsView:
return False
return False
- def keys(self) -> list[CellId_t]:
+ def keys(self) -> Sequence[CellId_t]:
"""Return cell IDs in notebook order."""
return self._doc.cell_ids
- def values(self) -> list[NotebookCell]:
+ def values(self) -> Sequence[NotebookCell]:
"""Return cell data in notebook order."""
- return self._doc.cells
+ return [self._cell_view(c) for c in self._doc.cells]
- def items(self) -> list[tuple[CellId_t, NotebookCell]]:
+ def items(self) -> Sequence[tuple[CellId_t, NotebookCell]]:
"""Return (cell_id, cell_data) pairs in notebook order."""
- return [(c.id, c) for c in self._doc.cells]
+ return [(c.id, self._cell_view(c)) for c in self._doc.cells]
# ------------------------------------------------------------------
# Content search
# ------------------------------------------------------------------
- def find(self, substring: str) -> list[NotebookCell]:
+ def find(self, substring: str) -> Sequence[NotebookCell]:
"""Return cells whose code contains *substring*.
Performs a case-sensitive substring search on each cell's code.
@@ -229,9 +406,11 @@ class _CellsView:
ctx.cells.find("import marimo")
"""
- return [c for c in self._doc.cells if substring in c.code]
+ return [
+ self._cell_view(c) for c in self._doc.cells if substring in c.code
+ ]
- def grep(self, pattern: str) -> list[NotebookCell]:
+ def grep(self, pattern: str) -> Sequence[NotebookCell]:
"""Return cells whose code matches the regex *pattern*.
Uses :func:`re.search` so the pattern can match anywhere in
@@ -244,31 +423,37 @@ class _CellsView:
import re
compiled = re.compile(pattern)
- return [c for c in self._doc.cells if compiled.search(c.code)]
+ return [
+ self._cell_view(c)
+ for c in self._doc.cells
+ if compiled.search(c.code)
+ ]
# ------------------------------------------------------------------
# Display
# ------------------------------------------------------------------
def __repr__(self) -> str:
- cells = self._doc.cells
- n = len(cells)
+ doc_cells = self._doc.cells
+ n = len(doc_cells)
max_shown = 10
lines = [f"CellsView({n} cell{'s' if n != 1 else ''}):"]
- def _fmt(i: int, c: NotebookCell) -> str:
+ def _fmt(i: int, c: _NotebookCell) -> str:
+ cv = self._cell_view(c)
first_line = c.code.split("\n", 1)[0]
code_preview = first_line[:50]
if len(first_line) > 50:
code_preview += "..."
name_part = f" ({c.name})" if c.name else ""
- return f" [{i}] {c.id}{name_part} | {code_preview}"
+ status_part = f" [{cv.status}]" if cv.status else ""
+ return f" [{i}] {c.id}{name_part}{status_part} | {code_preview}"
if n <= max_shown:
- for i, c in enumerate(cells):
+ for i, c in enumerate(doc_cells):
lines.append(_fmt(i, c))
else:
- for i, c in enumerate(cells[:max_shown]):
+ for i, c in enumerate(doc_cells[:max_shown]):
lines.append(_fmt(i, c))
omitted = n - max_shown - 1
if omitted > 0:
@@ -276,7 +461,7 @@ class _CellsView:
f" ... {omitted} more cell"
f"{'s' if omitted != 1 else ''} ..."
)
- lines.append(_fmt(n - 1, cells[-1]))
+ lines.append(_fmt(n - 1, doc_cells[-1]))
return "\n".join(lines)
diff --git a/tests/_code_mode/test_cells_view.py b/tests/_code_mode/test_cells_view.py
index a5eaf3b204..d797a999ce 100644
--- a/tests/_code_mode/test_cells_view.py
+++ b/tests/_code_mode/test_cells_view.py
@@ -1,6 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import dataclasses
from contextlib import contextmanager
from typing import TYPE_CHECKING
@@ -11,8 +12,14 @@ if TYPE_CHECKING:
import re
+from inline_snapshot import snapshot
+
from marimo._ast.cell import CellConfig
-from marimo._code_mode._context import AsyncCodeModeContext, _CellsView
+from marimo._code_mode._context import (
+ AsyncCodeModeContext,
+ NotebookCell as EnrichedCell,
+ _CellsView,
+)
from marimo._messaging.notebook.document import (
NotebookCell,
NotebookDocument,
@@ -211,7 +218,7 @@ def _cell(cell_id: str, code: str, name: str = "") -> NotebookCell:
def _view(cells: list[NotebookCell]) -> _CellsView:
doc = NotebookDocument(cells)
ctx = type("_MockCtx", (), {"_document": doc})()
- return _CellsView(ctx) # type: ignore[arg-type]
+ return _CellsView(ctx)
# ------------------------------------------------------------------
@@ -222,20 +229,20 @@ def _view(cells: list[NotebookCell]) -> _CellsView:
class TestCellsViewRepr:
def test_repr_empty(self) -> None:
v = _view([])
- assert repr(v) == "CellsView(0 cells):"
+ assert repr(v) == snapshot("CellsView(0 cells):")
def test_repr_single_cell(self) -> None:
v = _view([_cell("a1", "x = 1")])
- r = repr(v)
- assert r.startswith("CellsView(1 cell):")
- assert "[0] a1 | x = 1" in r
+ assert repr(v) == snapshot("""\
+CellsView(1 cell):
+ [0] a1 [stale] | x = 1""")
def test_repr_multiple_cells(self) -> None:
v = _view([_cell("a", "x = 1"), _cell("b", "y = 2")])
- r = repr(v)
- assert "CellsView(2 cells):" in r
- assert "[0] a | x = 1" in r
- assert "[1] b | y = 2" in r
+ assert repr(v) == snapshot("""\
+CellsView(2 cells):
+ [0] a [stale] | x = 1
+ [1] b [stale] | y = 2""")
def test_repr_with_name(self) -> None:
v = _view([_cell("a", "import marimo as mo", name="setup")])
@@ -246,7 +253,6 @@ class TestCellsViewRepr:
v = _view([_cell("a", long_code)])
r = repr(v)
assert "..." in r
- # First 50 chars of first line + "..."
assert long_code[:50] + "..." in r
def test_repr_multiline_shows_first_line(self) -> None:
@@ -264,13 +270,9 @@ class TestCellsViewRepr:
v = _view(cells)
r = repr(v)
assert "CellsView(15 cells):" in r
- # First 10 shown
assert "[9]" in r
- # Last cell shown
assert "[14]" in r
- # Middle omitted
assert "... 4 more cells ..." in r
- # Cell 11 not individually shown
assert "[11]" not in r
@@ -383,6 +385,171 @@ class TestCellsViewGrep:
# ------------------------------------------------------------------
+# ------------------------------------------------------------------
+# NotebookCell (enriched) status
+# ------------------------------------------------------------------
+
+
+class _MockImpl:
+ """Minimal stand-in for CellImpl — satisfies ``CellRuntimeState`` protocol."""
+
+ code: str = ""
+ runtime_state: str | None = None
+ run_result_status: str | None = None
+ stale: bool = False
+ exception: Exception | None = None
+
+
+class TestEnrichedCellStatus:
+ def test_no_impl_empty_returns_none(self) -> None:
+ cell = _cell("a", "")
+ enriched = EnrichedCell(cell, None)
+ assert enriched.status is None
+
+ def test_no_impl_with_code_returns_stale(self) -> None:
+ cell = _cell("a", "x = 1")
+ enriched = EnrichedCell(cell, None)
+ assert enriched.status == "stale"
+
+ def test_success_maps_to_idle(self) -> None:
+ cell = _cell("a", "x = 1")
+ impl = _MockImpl(code="x = 1", run_result_status="success")
+ enriched = EnrichedCell(cell, impl)
+ assert enriched.status == "idle"
+
+ def test_exception_status(self) -> None:
+ err = ValueError("boom")
+ cell = _cell("a", "x = 1")
+ impl = _MockImpl(
+ code="x = 1", run_result_status="exception", exception=err
+ )
+ enriched = EnrichedCell(cell, impl)
+ assert enriched.status == "exception"
+ assert enriched.error is err
+
+ def test_code_edited_becomes_stale(self) -> None:
+ cell = _cell("a", "x = 2")
+ impl = _MockImpl(code="x = 1", run_result_status="success")
+ enriched = EnrichedCell(cell, impl)
+ assert enriched.status == "stale"
+
+ def test_code_edited_after_error_becomes_stale(self) -> None:
+ err = ZeroDivisionError()
+ cell = _cell("a", "x = 1")
+ impl = _MockImpl(
+ code="1 / 0", run_result_status="exception", exception=err
+ )
+ enriched = EnrichedCell(cell, impl)
+ assert enriched.status == "stale"
+ # Error persists for inspection
+ assert enriched.error is err
+
+ def test_runtime_stale_flag(self) -> None:
+ """Lazy mode: inputs changed but code is the same."""
+ cell = _cell("a", "y = x + 1")
+ impl = _MockImpl(
+ code="y = x + 1", run_result_status="success", stale=True
+ )
+ enriched = EnrichedCell(cell, impl)
+ assert enriched.status == "stale"
+
+ def test_registered_but_never_run_is_stale(self) -> None:
+ """Cell registered in graph with matching code but never executed."""
+ cell = _cell("a", "x = 1")
+ impl = _MockImpl(code="x = 1") # run_result_status=None
+ enriched = EnrichedCell(cell, impl)
+ assert enriched.status == "stale"
+
+ def test_registered_empty_never_run_is_none(self) -> None:
+ """Empty cell registered in graph but never executed."""
+ cell = _cell("a", "")
+ impl = _MockImpl(code="")
+ enriched = EnrichedCell(cell, impl)
+ assert enriched.status is None
+
+ def test_queued_takes_priority(self) -> None:
+ cell = _cell("a", "x = 1")
+ impl = _MockImpl(code="x = 1", runtime_state="queued")
+ enriched = EnrichedCell(cell, impl)
+ assert enriched.status == "queued"
+
+ def test_running_takes_priority(self) -> None:
+ cell = _cell("a", "x = 1")
+ impl = _MockImpl(code="x = 1", runtime_state="running")
+ enriched = EnrichedCell(cell, impl)
+ assert enriched.status == "running"
+
+ def test_disabled_transitively_maps_to_disabled(self) -> None:
+ cell = _cell("a", "x = 1")
+ impl = _MockImpl(code="x = 1", runtime_state="disabled-transitively")
+ enriched = EnrichedCell(cell, impl)
+ assert enriched.status == "disabled"
+
+ def test_cancelled_status(self) -> None:
+ cell = _cell("a", "x = 1")
+ impl = _MockImpl(code="x = 1", run_result_status="cancelled")
+ enriched = EnrichedCell(cell, impl)
+ assert enriched.status == "cancelled"
+
+ def test_marimo_error_status(self) -> None:
+ cell = _cell("a", "x = 1")
+ impl = _MockImpl(code="x = 1", run_result_status="marimo-error")
+ enriched = EnrichedCell(cell, impl)
+ assert enriched.status == "marimo-error"
+
+ def test_delegates_document_properties(self) -> None:
+ cell = _cell("a1", "x = 1", name="my_cell")
+ enriched = EnrichedCell(cell, None)
+ assert enriched.id == "a1"
+ assert enriched.code == "x = 1"
+ assert enriched.name == "my_cell"
+ assert enriched.config == CellConfig()
+
+ def test_error_none_when_no_impl(self) -> None:
+ cell = _cell("a", "x = 1")
+ enriched = EnrichedCell(cell, None)
+ assert enriched.error is None
+
+
+class TestEnrichedCellRepr:
+ def test_repr_no_impl_with_code(self) -> None:
+ cell = _cell("a1", "x = 1")
+ enriched = EnrichedCell(cell, None)
+ assert repr(enriched) == snapshot(
+ "NotebookCell(id='a1', status='stale', code='x = 1')"
+ )
+
+ def test_repr_no_impl_empty(self) -> None:
+ cell = _cell("a1", "")
+ enriched = EnrichedCell(cell, None)
+ assert repr(enriched) == snapshot("NotebookCell(id='a1', code='')")
+
+ def test_repr_with_status(self) -> None:
+ cell = _cell("a1", "x = 1")
+ impl = _MockImpl(code="x = 1", run_result_status="exception")
+ enriched = EnrichedCell(cell, impl)
+ assert repr(enriched) == snapshot(
+ "NotebookCell(id='a1', status='exception', code='x = 1')"
+ )
+
+ def test_repr_with_name_and_status(self) -> None:
+ cell = _cell("a1", "import os", name="setup")
+ impl = _MockImpl(code="import os", run_result_status="success")
+ enriched = EnrichedCell(cell, impl)
+ assert repr(enriched) == snapshot(
+ "NotebookCell(id='a1', name='setup', status='idle', code='import os')"
+ )
+
+ def test_repr_stale_from_code_edit(self) -> None:
+ cell = _cell("a1", "x = 2")
+ impl = _MockImpl(code="x = 1", run_result_status="success")
+ enriched = EnrichedCell(cell, impl)
+ assert repr(enriched) == snapshot(
+ "NotebookCell(id='a1', status='stale', code='x = 2')"
+ )
+
+
class TestCellsViewErrorMessages:
def test_error_lists_available_ids(self) -> None:
v = _view([_cell("abcd", "x = 1"), _cell("efgh", "y = 2")])