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
Better tracebacks when running as script (#1893)
Dylan Madisettia7f647c68a77
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex 0f2d946960..7c8b3661e3 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -161,6 +161,10 @@ class App:self._unparsable = Falseself._initialized = False+ # injection hook set by contexts like tests such that script traces are+ # deterministic and not dependent on the test itself.+ # Set as a private attribute as not to pollute AppConfig or kwargs.+ self._anonymous_file = Falseself._app_kernel_runner: AppKernelRunner | None = None@@ -364,6 +368,7 @@ class App:if running_in_notebook():app_kernel_runner = self._get_kernel_runner()+if not app_kernel_runner.outputs:outputs, glbls = await app_kernel_runner.run(set(self._execution_order)@@ -421,7 +426,11 @@ class CellManager:cell_config = CellConfig(disabled=disabled, hide_code=hide_code)def _register(func: Callable[..., Any]) -> Cell:- cell = cell_factory(func, cell_id=self.create_cell_id())+ cell = cell_factory(+ func,+ cell_id=self.create_cell_id(),+ anonymous_file=app._app._anonymous_file if app else False,+ )cell._cell.configure(cell_config)self._register_cell(cell, app=app)return celldiff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex c1c2451f23..cea0d3d4eb 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -459,5 +459,12 @@ class Cell:)+class SourcePosition:+ filename: str+ lineno: int+ col_offset: int++def is_ws(char: str) -> bool:return char == " " or char == "\n" or char == "\t"diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.pyindex 40699ab654..bbc218af6d 100644--- a/marimo/_ast/compiler.py+++ b/marimo/_ast/compiler.py@@ -7,16 +7,16 @@ import ioimport linecacheimport osimport re-import sysimport textwrapimport token as token_typesfrom tokenize import TokenInfo, tokenize-from typing import TYPE_CHECKING, Any, Callable, Optional, Union+from typing import TYPE_CHECKING, Any, Callable, Optionalfrom marimo._ast.cell import (Cell,CellId_t,CellImpl,+ SourcePosition,)from marimo._ast.visitor import ScopedVisitorfrom marimo._utils.tmpdir import get_tmpdir@@ -54,7 +54,47 @@ def cache(filename: str, code: str) -> None:)-def compile_cell(code: str, cell_id: CellId_t) -> CellImpl:+def fix_source_position(node: Any, source_position: SourcePosition) -> Any:+ # NOTE: This function closely mirrors python's native ast.increment_lineno+ # however, utilized here to also increment the col_offset of the node.+ # See https://docs.python.org/3/library/ast.html#ast.increment_lineno+ # for reference.+ line_offset = source_position.lineno+ col_offset = source_position.col_offset+ for child in ast.walk(node):+ # TypeIgnore is a special case where lineno is not an attribute+ # but rather a field of the node itself.+ # Note, TypeIgnore does not have a "col_offset"+ if isinstance(child, ast.TypeIgnore):+ child.lineno = getattr(child, "lineno", 0) + line_offset+ continue++ if "lineno" in child._attributes:+ child.lineno = getattr(child, "lineno", 0) + line_offset++ if "col_offset" in child._attributes:+ child.col_offset = getattr(child, "col_offset", 0) + col_offset++ if (+ "end_lineno" in child._attributes+ and (end_lineno := getattr(child, "end_lineno", 0)) is not None+ ):+ child.end_lineno = end_lineno + line_offset++ if (+ "end_col_offset" in child._attributes+ and (end_col_offset := getattr(child, "end_col_offset", 0))+ is not None+ ):+ child.end_col_offset = end_col_offset + col_offset+ return node+++def compile_cell(+ code: str,+ cell_id: CellId_t,+ source_position: Optional[SourcePosition] = None,+) -> CellImpl:# Replace non-breaking spaces with regular spaces -- some frontends# send nbsp in place of space, which is a syntax error.#@@ -85,26 +125,39 @@ def compile_cell(code: str, cell_id: CellId_t) -> CellImpl:v = ScopedVisitor("cell_" + cell_id)v.visit(module)- expr: Union[ast.Expression, str]- if isinstance(module.body[-1], ast.Expr):+ expr: ast.Expression+ final_expr = module.body[-1]+ if isinstance(final_expr, ast.Expr):expr = ast.Expression(module.body.pop().value)+ expr.lineno = final_expr.linenoelse:- expr = "None"-- # store the cell's code in Python's linecache so debuggers can find it- body_filename = get_filename(cell_id)- last_expr_filename = get_filename(cell_id, suffix="_output")- # cache the entire cell's code- cache(body_filename, code)- if sys.version_info >= (3, 9):- # ast.unparse only available >= 3.9- cache(- last_expr_filename,- ast.unparse(expr) if not isinstance(expr, str) else "None",- )+ const = ast.Constant(value=None)+ const.col_offset = final_expr.end_col_offset+ const.end_col_offset = final_expr.end_col_offset+ expr = ast.Expression(const)+ # use code over body since lineno corresponds to source+ const.lineno = len(code.splitlines()) + 1+ expr.lineno = const.lineno+ # Creating an expression clears source info, so it needs to be set back+ expr.col_offset = final_expr.end_col_offset+ expr.end_col_offset = final_expr.end_col_offset++ filename: str+ if source_position:+ # Modify the "source" position for meaningful stacktraces+ fix_source_position(module, source_position)+ fix_source_position(expr, source_position)+ filename = source_position.filename+ else:+ # store the cell's code in Python's linecache so debuggers can find it+ filename = get_filename(cell_id)+ # cache the entire cell's code, doesn't need to be done in source case+ # since there is an actual file to read from.+ cache(filename, code)+flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT- body = compile(module, body_filename, mode="exec", flags=flags)- last_expr = compile(expr, last_expr_filename, mode="eval", flags=flags)+ body = compile(module, filename, mode="exec", flags=flags)+ last_expr = compile(expr, filename, mode="eval", flags=flags)glbls = {name for name in v.defs if not is_local(name)}return CellImpl(@@ -129,6 +182,7 @@ def compile_cell(code: str, cell_id: CellId_t) -> CellImpl:def cell_factory(f: Callable[..., Any],cell_id: CellId_t,+ anonymous_file: bool = False,) -> Cell:"""Creates a cell from a function.@@ -136,7 +190,8 @@ def cell_factory(to generate refs and defs. If the user introduced errors to thesignature, marimo will autofix them on save."""- function_code = textwrap.dedent(inspect.getsource(f))+ code, lnum = inspect.getsourcelines(f)+ function_code = textwrap.dedent("".join(code))# tokenize to find the start of the function body, including# comments --- we have to use tokenize because the ast treats the first@@ -197,6 +252,8 @@ def cell_factory(start_line = fn_body_token.start[0] - 1start_col = fn_body_token.start[1]+ col_offset = fn_body_token.end[1] - start_col+# it would be difficult to tell if the last return token were in fact the# last statement of the function body, so we use the ast, which lets us# easily find the last statement of the function body;@@ -229,6 +286,29 @@ def cell_factory(# handle return written on same line as last statement in cellcell_code += "\n" + lines[end_line][:return_offset]+ # anonymous file is required for deterministic testing.+ if not anonymous_file:+ # Fallback won't capture embedded scripts+ is_script = f.__globals__["__name__"] == "__main__"+ # TODO: spec is None for markdown notebooks, which is fine for now+ if module := inspect.getmodule(f):+ spec = module.__spec__+ is_script = spec is None or spec.name != "marimo_app"+ else:+ is_script = False+ source_position = (+ SourcePosition(+ filename=f.__code__.co_filename,+ lineno=lnum + start_line - 1,+ col_offset=col_offset,+ )+ if is_script+ else None+ )+return Cell(- _name=f.__name__, _cell=compile_cell(cell_code, cell_id=cell_id)+ _name=f.__name__,+ _cell=compile_cell(+ cell_code, cell_id=cell_id, source_position=source_position+ ),)diff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.pyindex 114bdb5ebc..8db3871953 100644--- a/marimo/_runtime/app/kernel_runner.py+++ b/marimo/_runtime/app/kernel_runner.py@@ -93,6 +93,11 @@ class AppKernelRunner:)finalizer.atexit = False+ # Register cells through the kernel runner, so that compilation only+ # occurs once.+ for cell_id, cell in app.cell_manager.valid_cells():+ self._kernel._register_cell(cell_id, cell._cell)+@propertydef outputs(self) -> dict[CellId_t, Any]:return self._outputsdiff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 296ca98c2c..f242f33b3e 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -528,18 +528,32 @@ class Kernel:reload=False,)- def _try_registering_cell(- self,- cell_id: CellId_t,- code: str,- ) -> Optional[Error]:- """Attempt to register a cell with given id and code.+ def _register_cell(self, cell_id: CellId_t, cell: CellImpl) -> None:+ if cell_id in self.cell_metadata:+ # If we already have a config for this cell id, restore it+ # This can happen when a cell was previously deactivated (due to a+ # syntax error or multiple definition error, for example) and then+ # re-registered+ cell.configure(self.cell_metadata[cell_id].config)+ elif cell_id not in self.cell_metadata:+ self.cell_metadata[cell_id] = CellMetadata()- Precondition: a cell with the supplied id must not already exist in the- graph.+ self.graph.register_cell(cell_id, cell)+ # leaky abstraction: the graph doesn't know about stale modules, so+ # we have to check for them here.+ module_reloader = self.module_reloader+ if (+ module_reloader is not None+ and module_reloader.cell_uses_stale_modules(cell)+ ):+ self.graph.set_stale(set([cell.cell_id]))+ LOGGER.debug("registered cell %s", cell_id)+ LOGGER.debug("parents: %s", self.graph.parents[cell_id])+ LOGGER.debug("children: %s", self.graph.children[cell_id])- If cell was unable to be registered, returns an Error object.- """+ def _try_compiling_cell(+ self, cell_id: CellId_t, code: str+ ) -> tuple[Optional[CellImpl], Optional[Error]]:error: Optional[Error] = Nonetry:cell = compile_cell(code, cell_id=cell_id)@@ -560,29 +574,24 @@ class Kernel:traceback.print_exc(file=tmpio)tmpio.seek(0)error = UnknownError(msg=tmpio.read())+ return cell, error- if cell_id in self.cell_metadata and cell is not None:- # If we already have a config for this cell id, restore it- # This can happen when a cell was previously deactivated (due to a- # syntax error or multiple definition error, for example) and then- # re-registered- cell.configure(self.cell_metadata[cell_id].config)- elif cell_id not in self.cell_metadata:- self.cell_metadata[cell_id] = CellMetadata()+ def _try_registering_cell(+ self,+ cell_id: CellId_t,+ code: str,+ ) -> Optional[Error]:+ """Attempt to register a cell with given id and code.++ Precondition: a cell with the supplied id must not already exist in the+ graph.++ If cell was unable to be registered, returns an Error object.+ """+ cell, error = self._try_compiling_cell(cell_id, code)if cell is not None:- self.graph.register_cell(cell_id, cell)- # leaky abstraction: the graph doesn't know about stale modules, so- # we have to check for them here.- module_reloader = self.module_reloader- if (- module_reloader is not None- and module_reloader.cell_uses_stale_modules(cell)- ):- self.graph.set_stale(set([cell.cell_id]))- LOGGER.debug("registered cell %s", cell_id)- LOGGER.debug("parents: %s", self.graph.parents[cell_id])- LOGGER.debug("children: %s", self.graph.children[cell_id])+ self._register_cell(cell_id, cell)return error@@ -1110,12 +1119,18 @@ class Kernel:roots = {SCRATCH_CELL_ID}# If cannot compile, don't run- try:- cell = compile_cell(code, SCRATCH_CELL_ID)- cell.defs.clear() # remove definitions- cell.refs.clear() # remove definitions- except SyntaxError:+ cell, error = self._try_compiling_cell(SCRATCH_CELL_ID, code)+ if error:+ CellOp.broadcast_error(+ data=[error],+ clear_console=True,+ cell_id=SCRATCH_CELL_ID,+ )+ return+ elif not cell:return+ cell.defs.clear() # remove definitions+ cell.refs.clear() # remove references# Create graph of just the scratchpad cellgraph = dataflow.DirectedGraph()diff --git a/tests/_runtime/script_data/func.py b/tests/_runtime/script_data/func.pynew file mode 100644index 0000000000..8b4f855197--- /dev/null+++ b/tests/_runtime/script_data/func.py@@ -0,0 +1,4 @@+def divide_by_zero(y):+ x = 0+ y = y / x+ return x, ydiff --git a/tests/_runtime/script_data/script_exception.py b/tests/_runtime/script_data/script_exception.pynew file mode 100644index 0000000000..c92dcfc75f--- /dev/null+++ b/tests/_runtime/script_data/script_exception.py@@ -0,0 +1,15 @@+import marimo++__generated_with = "0.6.19"+app = marimo.App()+++def __(y):+ x = 0+ y = y / x+ return x, y+++if __name__ == "__main__":+ app.run()diff --git a/tests/_runtime/script_data/script_exception_with_imported_function.py b/tests/_runtime/script_data/script_exception_with_imported_function.pynew file mode 100644index 0000000000..8fcc9cce03--- /dev/null+++ b/tests/_runtime/script_data/script_exception_with_imported_function.py@@ -0,0 +1,16 @@+import marimo++__generated_with = "0.6.19"+app = marimo.App()+++def __(y):+ import func++ x, y = func.divide_by_zero(10)+ return x, y+++if __name__ == "__main__":+ app.run()diff --git a/tests/_runtime/script_data/script_exception_with_output.py b/tests/_runtime/script_data/script_exception_with_output.pynew file mode 100644index 0000000000..3e5bf40720--- /dev/null+++ b/tests/_runtime/script_data/script_exception_with_output.py@@ -0,0 +1,16 @@+import marimo++__generated_with = "0.6.19"+app = marimo.App()+++def __():+ x = 0+ y = 0+ y / x+ return x, y+++if __name__ == "__main__":+ app.run()diff --git a/tests/_runtime/test_trace.py b/tests/_runtime/test_trace.pynew file mode 100644index 0000000000..3db45176b8--- /dev/null+++ b/tests/_runtime/test_trace.py@@ -0,0 +1,260 @@+# Copyright 2024 Marimo. All rights reserved.+import os+import re+import subprocess+import sys+import textwrap++from marimo._runtime.requests import (+ ExecutionRequest,+)+from marimo._runtime.runtime import Kernel+++class TestScriptTrace:+ @staticmethod+ def test_script_trace() -> None:+ p = subprocess.run(+ [sys.executable, "tests/_runtime/script_data/script_exception.py"],+ capture_output=True,+ )+ assert p.returncode == 1++ result = p.stderr.decode()+ assert "NameError: name 'y' is not defined" in result+ assert (+ 'tests/_runtime/script_data/script_exception.py", line 10'+ in result+ )+ assert "y = y / x" in result+ # Test col_offset+ # Expected output:+ # y = y / x+ # ^+ # exact line numbers differ by python version+ if sys.version_info >= (3, 11):+ assert (+ result.split("y / x")[1].split("\n")[1].startswith(" ^")+ )++ @staticmethod+ def test_script_trace_with_output() -> None:+ p = subprocess.run(+ [+ sys.executable,+ "tests/_runtime/script_data/script_exception_with_output.py",+ ],+ capture_output=True,+ )+ assert p.returncode == 1++ result = p.stderr.decode()+ assert "ZeroDivisionError: division by zero" in result+ assert (+ 'tests/_runtime/script_data/script_exception_with_output.py"'+ ", line 11"+ ) in result+ assert "y / x" in result++ @staticmethod+ def test_script_trace_with_imported_file() -> None:+ p = subprocess.run(+ [+ sys.executable,+ "tests/_runtime/script_data/script_exception_with_imported_function.py",+ ],+ capture_output=True,+ )+ assert p.returncode == 1++ result = p.stderr.decode()+ assert "ZeroDivisionError: division by zero" in result++ # windows compatibility+ file_path = os.path.normpath("tests/_runtime/script_data/func.py")+ assert f'{file_path}", line 3' in result++ assert (+ 'tests/_runtime/script_data/script_exception_with_imported_function.py"'+ + ", line 11"+ in result+ )+ assert "y = y / x" in result+++class TestAppTrace:+ @staticmethod+ async def test_app_trace_body_line_number(+ execution_kernel: Kernel,+ ) -> None:+ k = execution_kernel+ await k.run(+ [+ ExecutionRequest(+ cell_id="0",+ code=textwrap.dedent(+ """+ x = 0 #L2+ y = 0 #L3+ y = y / x #L4+ # filler line L5+ # filler line L6+ None #L7 for output expression+ """+ ),+ )+ ]+ )++ # Naively strip tags to check trace+ tag_re = re.compile(r"(<!--.*?-->|<[^>]*>)")+ result = k.stderr.messages[-1]+ result = tag_re.sub("", result)++ assert "ZeroDivisionError: division by zero" in result+ assert "y / x" in result+ assert "__marimo__cell_0_.py" in result+ # Test col_offset+ # Expected output:+ # File "/tmp/marimo_0000000/__marimo__cell_0_.py", line 4 ...+ # y = y / x #L4+ # ~~^~~+ # ZeroDivisionError: division by zero+ post_file = result.split("marimo__cell")[1].split("\n")+ assert "line 4" in post_file[0]+ assert post_file[1].startswith(" y = y / x #L4")+ if sys.version_info >= (3, 11):+ assert post_file[2].startswith(" ~~^~~")++ @staticmethod+ async def test_app_trace_output_line_number(+ execution_kernel: Kernel,+ ) -> None:+ k = execution_kernel+ await k.run(+ [+ ExecutionRequest(+ cell_id="0",+ code=textwrap.dedent(+ """+ def foo(): #L2+ x = 0 #L3+ y = 0 #L4+ y = y / x #L5+ # filler line L5+ # filler line L6+ None #L7 for output expression+ """+ ),+ ),+ ExecutionRequest(+ cell_id="1",+ code="foo()",+ ),+ ]+ )++ # Naively strip tags to check trace+ tag_re = re.compile(r"(<!--.*?-->|<[^>]*>)")+ result = k.stderr.messages[-1]+ result = tag_re.sub("", result)++ # Test col_offset+ # Expected output:+ # File .../__marimo__cell_1_.py", line 1, in ...+ # foo()+ # File .../__marimo__cell_0_.py", line 4, in foo+ # y = y / x #L5+ # ~~^~~+ # ZeroDivisionError: division by zero+ post_file_call = result.split("marimo__cell_1")[1].split("\n")+ assert "line 1" in post_file_call[0]+ assert "foo()" in post_file_call[1]+ post_file_error = result.split("marimo__cell_0")[1].split("\n")+ assert post_file_error[1].startswith(" y = y / x #L5")+ if sys.version_info >= (3, 11):+ assert post_file_error[2].startswith(" ~~^~~")++ @staticmethod+ async def test_app_trace_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]+++class TestEmbedTrace:+ @staticmethod+ async def test_embed_trace(+ k: Kernel,+ ) -> None:+ await k.run(+ [+ ExecutionRequest(+ cell_id="0",+ code=textwrap.dedent(+ """+ from tests._runtime.script_data import (+ script_exception_with_output+ )+ await script_exception_with_output.app.embed()+ """+ ),+ )+ ]+ )++ # Naively strip tags to check trace+ tag_re = re.compile(r"(<!--.*?-->|<[^>]*>)")+ result = k.stderr.messages[-1]+ result = tag_re.sub("", result)++ # windows support+ file_path = os.path.normpath(+ "tests/_runtime/script_data/script_exception_with_output.py"+ )++ assert "ZeroDivisionError: division by zero" in result+ assert (file_path + "", line 11") in result+ assert "y / x" in resultdiff --git a/tests/_save/test_cache.py b/tests/_save/test_cache.pyindex 9aa6a966ab..c24968b259 100644--- a/tests/_save/test_cache.py+++ b/tests/_save/test_cache.py@@ -13,6 +13,7 @@ class TestScriptCache:@staticmethoddef test_cache_miss() -> None:app = App()+ app._anonymous_file = True@app.celldef one() -> tuple[int]:@@ -33,6 +34,7 @@ class TestScriptCache:@staticmethoddef test_cache_hit() -> None:app = App()+ app._anonymous_file = True@app.celldef one() -> tuple[int]:@@ -55,6 +57,7 @@ class TestScriptCache:@staticmethoddef test_cache_hit_whitespace() -> None:app = App()+ app._anonymous_file = True@app.celldef one() -> tuple[int]:diff --git a/tests/_save/test_hash.py b/tests/_save/test_hash.pyindex 5ec0ec1890..7cab27a483 100644--- a/tests/_save/test_hash.py+++ b/tests/_save/test_hash.py@@ -11,6 +11,7 @@ class TestHash:@staticmethoddef test_content_hash() -> None:app = App()+ app._anonymous_file = True@app.celldef one() -> tuple[int]:@@ -31,6 +32,7 @@ class TestHash:)def test_content_reproducibility() -> None:app = App()+ app._anonymous_file = True@app.celldef load() -> tuple[int]:@@ -78,6 +80,7 @@ class TestHash:@staticmethoddef test_execution_hash() -> None:app = App()+ app._anonymous_file = True@app.celldef one() -> tuple[int]:@@ -99,6 +102,7 @@ class TestHash:)def test_execution_reproducibility() -> None:app = App()+ app._anonymous_file = True@app.celldef load() -> tuple[int]: