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.

improvement: strict mode NameError fix + cleaner exceptions (#1829)

Dylan Madisetti2b7c32ff97ee
diff --git a/marimo/_runtime/app/script_runner.py b/marimo/_runtime/app/script_runner.py
index 84bf53c10e..8eabc85b2d 100644
--- a/marimo/_runtime/app/script_runner.py
+++ b/marimo/_runtime/app/script_runner.py
@@ -13,7 +13,12 @@ from marimo._runtime.context.types import (
runtime_context_installed,
teardown_context,
)
-from marimo._runtime.executor import execute_cell, execute_cell_async
+from marimo._runtime.executor import (
+ MarimoMissingRefError,
+ MarimoRuntimeException,
+ execute_cell,
+ execute_cell_async,
+)
from marimo._runtime.patches import (
create_main_module,
patch_main_module_context,
@@ -83,6 +88,27 @@ class AppScriptRunner:
post_execute_hooks=post_execute_hooks,
)
return outputs, defs
+
+ # Cell runner manages the exception handling for kernel
+ # runner, but script runner should raise the wrapped
+ # exception if invoked directly.
+ except MarimoRuntimeException as e:
+ # MarimoMissingRefError, wraps the under lying NameError
+ # for context, so we raise the NameError directly.
+ if isinstance(e.__cause__, MarimoMissingRefError):
+ # For type checking + sanity check
+ if not isinstance(e.__cause__.name_error, NameError):
+ raise MarimoRuntimeException(
+ "Unexpected error occurred while running the app. "
+ "Improperly wrapped MarimoMissingRefError exception. "
+ "Please report this issue to "
+ "https://github.com/marimo-team/marimo/issues"
+ ) from e.__cause__
+ raise e.__cause__.name_error from e.__cause__
+ # For all other exceptions, we raise the wrapped exception
+ # from "None" to indicate this is an Error propagation, and to not
+ # muddy the stacktrace from the failing cells themselves.
+ raise e.__cause__ from None # type: ignore
finally:
if installed_script_context:
teardown_context()
diff --git a/marimo/_runtime/executor.py b/marimo/_runtime/executor.py
index 604495502a..54650adc65 100644
--- a/marimo/_runtime/executor.py
+++ b/marimo/_runtime/executor.py
@@ -16,7 +16,7 @@ from marimo._runtime.copy import (
ZeroCopy,
shallow_copy,
)
-from marimo._utils.variables import is_mangled_local
+from marimo._utils.variables import is_mangled_local, unmangle_local
if TYPE_CHECKING:
from marimo._ast.visitor import Name, VariableData
@@ -42,14 +42,61 @@ PRIMITIVES = (weakref.ref, str, numbers.Number, type(None))
EXECUTION_TYPES: dict[str, Type[Executor]] = {}
+class MarimoRuntimeException(BaseException):
+ """Wrapper for all marimo runtime exceptions."""
+
+
class MarimoNameError(NameError):
"""Wrap a name error to rethrow later."""
+ def __init__(self, msg: str, ref: str) -> None:
+ super().__init__(msg)
+ self.ref = ref
+
class MarimoMissingRefError(BaseException):
- def __init__(self, ref: str) -> None:
- super().__init__(f"Missing reference: {ref}")
+ def __init__(
+ self, ref: str, name_error: Optional[NameError] = None
+ ) -> None:
+ super(MarimoMissingRefError, self).__init__(ref)
self.ref = ref
+ self.name_error = name_error
+
+
+def raise_name_error(
+ graph: Optional[DirectedGraph], name_error: NameError
+) -> None:
+ if graph is None:
+ raise MarimoRuntimeException from name_error
+ # The best static analysis can do for variable level references is to
+ # use the top level definition. For example, consider the following
+ # cells:
+ # --- Cell 1 ---
+ # >> X = 1
+ # >> Y = 2
+ # >> l = lambda x: x + X
+ # >> L = l # Static analysis can fail on reassignment
+ # >> l = lambda x: x + Y
+ #
+ # --- Cell 2 ---
+ # >> L(1) # This fails because:
+ # globals == {'Y': 2, 'l': lambda x: x + Y, 'L': lambda x: x + X}
+ # # note no X
+ #
+ # The code could be taken to use the last definition of `l`, but theres
+ # the case of condition definition and dynamic definition, so making a
+ # best effort and resolving the error at runtime is the best approach.
+ #
+ # marimo lint (#1543) could potentially detect these runtime
+ # problems. Throwing a compilation error seems excessive since if
+ # carefully managed, the code could still be correct.
+ (missing_name,) = re.findall(r"'([^']*)'", str(name_error))
+ _, private_cell_id = unmangle_local(missing_name)
+ if missing_name in graph.definitions or private_cell_id:
+ raise MarimoRuntimeException from MarimoMissingRefError(
+ missing_name, name_error
+ )
+ raise MarimoRuntimeException from name_error
def register_execution_type(
@@ -109,33 +156,45 @@ class DefaultExecutor(Executor):
async def execute_cell_async(
cell: CellImpl,
glbls: dict[str, Any],
- _graph: Optional[DirectedGraph] = None,
+ graph: Optional[DirectedGraph] = None,
) -> Any:
if cell.body is None:
return None
assert cell.last_expr is not None
-
- if _is_coroutine(cell.body):
- await eval(cell.body, glbls)
- else:
- exec(cell.body, glbls)
-
- if _is_coroutine(cell.last_expr):
- return await eval(cell.last_expr, glbls)
- else:
- return eval(cell.last_expr, glbls)
+ try:
+ if _is_coroutine(cell.body):
+ await eval(cell.body, glbls)
+ else:
+ exec(cell.body, glbls)
+
+ if _is_coroutine(cell.last_expr):
+ return await eval(cell.last_expr, glbls)
+ else:
+ return eval(cell.last_expr, glbls)
+ except NameError as e:
+ raise_name_error(graph, e)
+ except (BaseException, Exception) as e:
+ # Raising from a BaseException will fold in the stacktrace prior
+ # to execution
+ raise MarimoRuntimeException from e
@staticmethod
def execute_cell(
cell: CellImpl,
glbls: dict[str, Any],
- _graph: Optional[DirectedGraph] = None,
+ graph: Optional[DirectedGraph] = None,
) -> Any:
- if cell.body is None:
- return None
- assert cell.last_expr is not None
- exec(cell.body, glbls)
- return eval(cell.last_expr, glbls)
+ try:
+ if cell.body is None:
+ return None
+ assert cell.last_expr is not None
+
+ exec(cell.body, glbls)
+ return eval(cell.last_expr, glbls)
+ except NameError as e:
+ raise_name_error(graph, e)
+ except (BaseException, Exception) as e:
+ raise MarimoRuntimeException from e
@register_execution_type("strict")
@@ -150,33 +209,9 @@ class StrictExecutor(Executor):
)
backup = StrictExecutor.sanitize_inputs(cell, refs, glbls)
try:
- response = await DefaultExecutor.execute_cell_async(cell, glbls)
- # The best static analysis can do for variable level references is to
- # use the top level definition. For example, consider the following
- # cells:
- # --- Cell 1 ---
- # >> X = 1
- # >> Y = 2
- # >> l = lambda x: x + X
- # >> L = l # Static analysis can fail on reassignment
- # >> l = lambda x: x + Y
- #
- # --- Cell 2 ---
- # >> L(1) # This fails because:
- # globals = {'X': 1, 'l': lambda x: x + Y, 'L': lambda x: x + Y}
- #
- # The code could be taken to use the last definition of `l`, but theres
- # the case of condition definition and dynamic definition, so making a
- # best effort and resolving the error at runtime is the best approach.
- #
- # marimo lint (#1543) could potentially detect these runtime
- # problems. Throwing a compilation error seems excessive since if
- # carefully managed, the code could still be correct.
- except MarimoNameError as name_error:
- (missing_name,) = re.findall(r"'([^']*)'", str(name_error))
- if missing_name in graph.definitions:
- raise MarimoMissingRefError(missing_name) from name_error
- raise name_error
+ response = await DefaultExecutor.execute_cell_async(
+ cell, glbls, graph
+ )
finally:
# Restore globals from backup and backfill outputs
StrictExecutor.update_outputs(cell, glbls, backup)
@@ -191,12 +226,7 @@ class StrictExecutor(Executor):
)
backup = StrictExecutor.sanitize_inputs(cell, refs, glbls)
try:
- response = DefaultExecutor.execute_cell(cell, glbls)
- except MarimoNameError as name_error:
- (missing_name,) = re.findall(r"'([^']*)'", str(name_error))
- if missing_name in graph.definitions:
- raise MarimoMissingRefError(missing_name) from name_error
- raise name_error
+ response = DefaultExecutor.execute_cell(cell, glbls, graph)
finally:
StrictExecutor.update_outputs(cell, glbls, backup)
return response
@@ -255,7 +285,7 @@ class StrictExecutor(Executor):
elif ref not in glbls["__builtins__"]:
if ref in cell.defs:
raise MarimoNameError(
- f"name `{ref}` is referenced before definition."
+ f"name `{ref}` is referenced before definition.", ref
)
raise MarimoMissingRefError(ref)
diff --git a/marimo/_runtime/runner/cell_runner.py b/marimo/_runtime/runner/cell_runner.py
index cf90e97e19..8da7b8ab98 100644
--- a/marimo/_runtime/runner/cell_runner.py
+++ b/marimo/_runtime/runner/cell_runner.py
@@ -14,16 +14,24 @@ from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, Union
from marimo._ast.cell import CellId_t, CellImpl
from marimo._config.config import ExecutionType, OnCellChangeType
from marimo._loggers import marimo_logger
-from marimo._messaging.errors import Error, MarimoStrictExecutionError
+from marimo._messaging.errors import (
+ Error,
+ MarimoExceptionRaisedError,
+ MarimoStrictExecutionError,
+ UnknownError,
+)
from marimo._messaging.tracebacks import write_traceback
from marimo._runtime import dataflow
from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
from marimo._runtime.executor import (
MarimoMissingRefError,
+ MarimoNameError,
+ MarimoRuntimeException,
execute_cell,
execute_cell_async,
)
from marimo._runtime.marimo_pdb import MarimoPdb
+from marimo._utils.variables import unmangle_local
LOGGER = marimo_logger()
@@ -319,56 +327,135 @@ class Runner:
execution_type=self.execution_type,
)
run_result = RunResult(output=return_value, exception=None)
- except (MarimoInterrupt, asyncio.exceptions.CancelledError) as e:
+ except asyncio.exceptions.CancelledError:
# User interrupt
# interrupt the entire runner
- if isinstance(e, asyncio.exceptions.CancelledError):
- # Async cells can only be cancelled via a user interrupt
- e = MarimoInterrupt()
- self.interrupted = True
- run_result = RunResult(output=None, exception=e)
+ # Async cells can only be cancelled via a user interrupt
+ run_result = RunResult(output=None, exception=MarimoInterrupt())
+ # Still provide a general traceback.
tmpio = io.StringIO()
traceback.print_exc(file=tmpio)
tmpio.seek(0)
write_traceback(tmpio.read())
- except MarimoStopError as e:
- # Raised by mo.stop().
- # cancel only the descendants of this cell
+ # Strict mode errors may also raise errors outside of execution.
+ except MarimoNameError as e:
self.cancel(cell_id)
- run_result = RunResult(output=e.output, exception=e)
- # don't print a traceback, since quitting is the intended
- # behavior (like sys.exit())
+ strict_exception = MarimoStrictExecutionError(str(e), e.ref, None)
+ run_result = RunResult(
+ output=strict_exception, exception=strict_exception
+ )
except MarimoMissingRefError as e:
# In strict mode, marimo refuses to evaluate a cell if there are
# missing definitions. Since the cell hasn't run, this is a pre
# check error, but still mark descendants as cancelled.
self.cancel(cell_id)
- try:
- (blamed_cell, *_) = self.graph.get_defining_cells(e.ref)
- except KeyError:
- # The reference is not found anywhere else in the graph
- blamed_cell = None
-
- output = MarimoStrictExecutionError(
- f"marimo was unable to resolve "
- f"a reference to `{e.ref}` in cell : ",
- e.ref,
+ ref, blamed_cell = self._get_blamed_cell(e)
+ name_output = MarimoStrictExecutionError(
+ "marimo was unable to resolve "
+ f"a reference to `{ref}` in cell : ",
+ ref,
blamed_cell,
)
- run_result = RunResult(output=output, exception=output)
- except BaseException as e:
- # Catch-all: some libraries have bugs and raise BaseExceptions,
- # which shouldn't crash the marimo kernel
- if isinstance(e, ModuleNotFoundError):
+ run_result = RunResult(output=name_output, exception=name_output)
+ # Should cover all cell runtime exceptions.
+ except MarimoRuntimeException as e:
+ print_traceback = True
+ output: Any = None
+ unwrapped_exception: Optional[BaseException] = e.__cause__
+ exception: Optional[ErrorObjects] = unwrapped_exception
+
+ # Exceptions trigger cancellation of descendants.
+ self.cancel(cell_id)
+
+ if isinstance(exception, MarimoMissingRefError):
+ ref, blamed_cell = self._get_blamed_cell(exception)
+ # All MarimoMissingRefErrors should be caused caused by
+ # NameErrors if they are the cause of MarimoRuntimeExceptions.
+ if exception.name_error is not None:
+ unwrapped_exception = exception.name_error
+ # Provide output context for said missing reference errors.
+ if self.execution_type == "strict":
+ output = MarimoExceptionRaisedError(
+ f"marimo came across the undefined variable `{ref}` "
+ "during runtime. This is possible in strict mode when "
+ "static analysis is unable to properly resolve the "
+ "reference due to direct access (e.g. "
+ "`globals()['var']`) or circuitous definitions (e.g. "
+ "by reassigning variables to different functions). If "
+ "this failure is not the result of either of these "
+ "cases, please consider reporting this issue to "
+ "https://github.com/marimo-team/marimo/issues. "
+ "Definition expected in cell : ",
+ "NameError",
+ blamed_cell,
+ )
+ exception = output
+ elif blamed_cell != cell_id:
+ output = MarimoExceptionRaisedError(
+ f"marimo came across the undefined variable `{ref}` "
+ "during runtime. Definition expected in cell : ",
+ "NameError",
+ blamed_cell,
+ )
+ exception = output
+ else:
+ # Default to regular error for self reference in relaxed
+ # mode.
+ exception = unwrapped_exception
+
+ # Handle other special runtime errors.
+ elif isinstance(unwrapped_exception, ModuleNotFoundError):
self.missing_packages = True
- self.cancel(cell_id)
- run_result = RunResult(output=None, exception=e)
- tmpio = io.StringIO()
- traceback.print_exc(file=tmpio)
- tmpio.seek(0)
- write_traceback(tmpio.read())
+ elif isinstance(unwrapped_exception, MarimoStopError):
+ output = unwrapped_exception.output
+ exception = unwrapped_exception
+ # don't print a traceback, since quitting is the intended
+ # behavior (like sys.exit())
+ print_traceback = False
+
+ run_result = RunResult(output=output, exception=exception)
+ if print_traceback:
+ tmpio = io.StringIO()
+ # The executors explicitly raise cell exceptions from base
+ # exceptions such that the stack trace is cleaner.
+ # Verbosity is for Python < 3.10 compat
+ # See https://docs.python.org/3/library/traceback.html
+ exception_type = (
+ type(unwrapped_exception) if unwrapped_exception else None
+ )
+ maybe_traceback = (
+ unwrapped_exception.__traceback__
+ if unwrapped_exception
+ else None
+ )
+ traceback.print_exception(
+ exception_type,
+ unwrapped_exception,
+ maybe_traceback,
+ file=tmpio,
+ )
+ tmpio.seek(0)
+ write_traceback(tmpio.read())
+ except BaseException as e:
+ # Check that MarimoRuntimeException has't already handled the
+ # error, since exceptions fall through except blocks.
+ # If not, then this is an unexpected error.
+ if not isinstance(e, MarimoRuntimeException):
+ LOGGER.error(f"Unexpected error type: {e}")
+ self.cancel(cell_id)
+ unknown_error = UnknownError(f"{e}")
+ run_result = RunResult(output=None, exception=unknown_error)
+ tmpio = io.StringIO()
+ traceback.print_exc(file=tmpio)
+ tmpio.seek(0)
+ write_traceback(tmpio.read())
finally:
+ # Mark as interrupted if the cell raised a MarimoInterrupt
+ # Set here since failed async can also trigger an Interrupt.
+ if isinstance(run_result.exception, MarimoInterrupt):
+ self.interrupted = True
+
# if a debugger is active, force it to skip past marimo code.
try:
# Bdb defines the botframe attribute and sets it to non-None
@@ -398,6 +485,21 @@ class Runner:
return run_result
+ def _get_blamed_cell(
+ self, e: MarimoMissingRefError
+ ) -> tuple[str, Optional[CellId_t]]:
+ ref = e.ref
+ blamed_cell = None
+ try:
+ (blamed_cell, *_) = self.graph.get_defining_cells(ref)
+ except KeyError:
+ # The reference is not found anywhere else in the graph
+ # but it might be private
+ ref, var_cell_id = unmangle_local(ref)
+ if var_cell_id:
+ blamed_cell = var_cell_id
+ return ref, blamed_cell
+
async def run_all(self) -> None:
for prep_hook in self.preparation_hooks:
prep_hook(self)
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index c6eaa346b8..71bfd6c1f0 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -195,6 +195,12 @@ def _broadcast_outputs(
clear_console=False,
cell_id=cell.cell_id,
)
+ elif isinstance(run_result.exception, MarimoExceptionRaisedError):
+ CellOp.broadcast_error(
+ data=[run_result.exception],
+ clear_console=False,
+ cell_id=cell.cell_id,
+ )
elif run_result.exception is not None:
LOGGER.debug(
"Cell %s raised %s",
diff --git a/marimo/_utils/variables.py b/marimo/_utils/variables.py
index 89004ec46c..c97a71d742 100644
--- a/marimo/_utils/variables.py
+++ b/marimo/_utils/variables.py
@@ -17,10 +17,12 @@ def is_local_then_mangle(ref: str, cell_id: CellId_t) -> str:
def unmangle_local(name: str) -> tuple[str, str]:
- return re.sub(r"^_cell_\w+", "_", name), name[6:10]
+ if not is_mangled_local(name):
+ return name, ""
+ return re.sub(r"^_cell_\w+_", "_", name), name.split("_")[2]
-def is_mangled_local(name: str, cell_id: CellId_t) -> bool:
+def is_mangled_local(name: str, cell_id: CellId_t = "") -> bool:
return name.startswith(f"_cell_{cell_id}")
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index f169d63e45..1dd38539e4 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -869,6 +869,54 @@ class TestExecution:
assert "exc" not in k.graph.cells[er_1.cell_id].defs
assert "e" in k.globals
+ @staticmethod
+ async def test_runtime_name_error_reference_caught(
+ execution_kernel: Kernel,
+ ) -> None:
+ k = execution_kernel
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="0",
+ code=textwrap.dedent(
+ """
+ try:
+ R = R # Causes error since no def
+ C = 0 # Unaccessible
+ except:
+ pass
+ """
+ ),
+ ),
+ ExecutionRequest(
+ cell_id="1",
+ code=textwrap.dedent(
+ """
+ C
+ """
+ ),
+ ),
+ ]
+ )
+ # Runtime error expected- since not a kernel error check stderr
+ assert "C" not in k.globals
+ if k.execution_type == "strict":
+ assert (
+ "name `R` is referenced before definition."
+ in k.stream.messages[-4][1]["output"]["data"][0]["msg"]
+ )
+ assert (
+ "This cell wasn't run"
+ in k.stream.messages[-1][1]["output"]["data"][0]["msg"]
+ )
+ else:
+ assert (
+ "marimo came across the undefined variable `C` during runtime."
+ in k.stream.messages[-2][1]["output"]["data"][0]["msg"]
+ )
+ assert "NameError" in k.stderr.messages[0]
+ assert "NameError" in k.stderr.messages[-1]
+
@staticmethod
async def test_run_scratch(mocked_kernel: MockedKernel) -> None:
k = mocked_kernel.k
@@ -1145,6 +1193,87 @@ class TestStrictExecution:
assert "x" in k.globals
assert not k.errors
+ @staticmethod
+ async def test_runtime_resolution_failure(strict_kernel: Kernel) -> None:
+ k = strict_kernel
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="0",
+ code=textwrap.dedent(
+ """
+ X = 1
+ Y = 2
+ l = lambda x: x + X
+ L = l # Static analysis can fail on reassignment
+ l = lambda x: x + Y
+ """
+ ),
+ ),
+ ExecutionRequest(
+ cell_id="1",
+ code=textwrap.dedent(
+ """
+ try:
+ x = L(1)
+ except NameError as e:
+ E = e
+ raise E
+ """
+ ),
+ ),
+ ]
+ )
+ # Runtime error expected- since not a kernel error check stderr
+ assert "x" not in k.globals
+ assert "E" in k.globals
+ assert k.errors == {}
+
+ assert (
+ "marimo came across the undefined variable `X` during runtime."
+ in k.stream.messages[-2][1]["output"]["data"][0]["msg"]
+ )
+ assert "NameError" in k.stderr.messages[-1]
+
+ @staticmethod
+ async def test_runtime_resolution_failure_private(
+ strict_kernel: Kernel,
+ ) -> None:
+ k = strict_kernel
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="0",
+ code=textwrap.dedent(
+ """
+ _X = 1
+ Y = 2
+ l = lambda x: x + _X
+ L = l # Static analysis can fail on reassignment
+ l = lambda x: x + Y
+ """
+ ),
+ ),
+ ExecutionRequest(
+ cell_id="1",
+ code=textwrap.dedent(
+ """
+ x = L(1)
+ x
+ """
+ ),
+ ),
+ ]
+ )
+ # Runtime error expected- since not a kernel error check stderr
+ assert "x" not in k.globals
+
+ assert (
+ "marimo came across the undefined variable `_X` during runtime."
+ in k.stream.messages[-2][1]["output"]["data"][0]["msg"]
+ )
+ assert "NameError" in k.stderr.messages[-1]
+
class TestStoredOutput:
async def test_ui_element_in_output_stored(