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: import cells (#1955)

Akshay Agrawal9a7304dd569a
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index cea0d3d4eb..95c99346c6 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -56,18 +56,50 @@ CellConfigKeys = frozenset(
)
-# Cell Statuses
+# States in a cell's runtime state machine
#
# idle: cell has run with latest inputs
# queued: cell is queued to run
# running: cell is running
# disabled-transitively: cell is disabled because a parent is disabled
-CellStatusType = Literal["idle", "queued", "running", "disabled-transitively"]
+RuntimeStateType = Literal[
+ "idle", "queued", "running", "disabled-transitively"
+]
@dataclasses.dataclass
-class CellStatus:
- state: Optional[CellStatusType] = None
+class RuntimeState:
+ state: Optional[RuntimeStateType] = None
+
+
+# Statuses for a cell's attempted execution
+#
+# cancelled: an ancestor raised an exception
+# marimo-error: cell was prevented from executing
+# disabled: skipped because the cell is disabled
+RunResultStatusType = Literal[
+ "success",
+ "exception",
+ "cancelled",
+ "interrupted",
+ "marimo-error",
+ "disabled",
+]
+
+
+class RunResultStatus:
+ state: Optional[RunResultStatusType] = None
+
+
+class ImportWorkspace:
+ """A workspace for runtimes to use to manage a cell's imports."""
+
+ # A cell is an import block if all statements are import statements
+ is_import_block: bool = False
+ # Defs that have been imported by the runtime
+ imported_defs: set[Name] = dataclasses.field(default_factory=set)
def _is_coroutine(code: Optional[CodeType]) -> bool:
@@ -100,7 +132,7 @@ class CellImpl:
defs: set[Name]
refs: set[Name]
# metadata about definitions
- variable_data: dict[Name, VariableData]
+ variable_data: dict[Name, list[VariableData]]
deleted_refs: set[Name]
body: Optional[CodeType]
last_expr: Optional[CodeType]
@@ -108,10 +140,17 @@ class CellImpl:
cell_id: CellId_t
# Mutable fields
- # config: explicit configuration of cell
+ # explicit configuration of cell
config: CellConfig = dataclasses.field(default_factory=CellConfig)
- # status: execution status, inferred at runtime
- _status: CellStatus = dataclasses.field(default_factory=CellStatus)
+ # workspace for runtimes to use to store metadata about imports
+ import_workspace: ImportWorkspace = dataclasses.field(
+ default_factory=ImportWorkspace
+ )
+ # execution status, inferred at runtime
+ _status: RuntimeState = dataclasses.field(default_factory=RuntimeState)
+ _run_result_status: RunResultStatus = dataclasses.field(
+ default_factory=RunResultStatus
+ )
# whether the cell is stale, inferred at runtime
_stale: CellStaleState = dataclasses.field(default_factory=CellStaleState)
# cells can optionally hold a reference to their output
@@ -130,9 +169,13 @@ class CellImpl:
return self
@property
- def status(self) -> Optional[CellStatusType]:
+ def runtime_state(self) -> Optional[RuntimeStateType]:
return self._status.state
+ @property
+ def run_result_status(self) -> Optional[RunResultStatusType]:
+ return self._run_result_status.state
+
@property
def sqls(self) -> list[str]:
"""Return a list of SQL statements for this cell."""
@@ -155,24 +198,27 @@ class CellImpl:
@property
def disabled_transitively(self) -> bool:
- return self.status == "disabled-transitively"
+ return self.runtime_state == "disabled-transitively"
@property
def imports(self) -> Iterable[ImportData]:
"""Return a set of import data for this cell."""
- return [
- data.import_data
- for _, data in self.variable_data.items()
- if data.import_data is not None
- ]
+ import_data = []
+ for data in self.variable_data.values():
+ import_data.extend(
+ [
+ datum.import_data
+ for datum in data
+ if datum.import_data is not None
+ ]
+ )
+ return import_data
@property
def imported_namespaces(self) -> set[Name]:
"""Return a set of the namespaces imported by this cell."""
return set(
- data.import_data.module.split(".")[0]
- for _, data in self.variable_data.items()
- if data.import_data is not None
+ import_data.module.split(".")[0] for import_data in self.imports
)
def namespace_to_variable(self, namespace: str) -> Name | None:
@@ -184,19 +230,16 @@ class CellImpl:
In this case the namespace is "matplotlib" but the name is "plt".
"""
- for name, data in self.variable_data.items():
- if (
- data.import_data is not None
- and data.import_data.namespace == namespace
- ):
- return name
+ for import_data in self.imports:
+ if import_data.namespace == namespace:
+ return import_data.definition
return None
def is_coroutine(self) -> bool:
return _is_coroutine(self.body) or _is_coroutine(self.last_expr)
- def set_status(
- self, status: CellStatusType, stream: Stream | None = None
+ def set_runtime_state(
+ self, status: RuntimeStateType, stream: Stream | None = None
) -> None:
"""Set execution status and broadcast to frontends."""
from marimo._messaging.ops import CellOp
@@ -216,6 +259,11 @@ class CellImpl:
cell_id=self.cell_id, status=status, stream=stream
)
+ def set_run_result_status(
+ self, run_result_status: RunResultStatusType
+ ) -> None:
+ self._run_result_status.state = run_result_status
+
def set_stale(self, stale: bool, stream: Stream | None = None) -> None:
from marimo._messaging.ops import CellOp
diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.py
index bbc218af6d..488837fadc 100644
--- a/marimo/_ast/compiler.py
+++ b/marimo/_ast/compiler.py
@@ -16,9 +16,10 @@ from marimo._ast.cell import (
Cell,
CellId_t,
CellImpl,
+ ImportWorkspace,
SourcePosition,
)
-from marimo._ast.visitor import ScopedVisitor
+from marimo._ast.visitor import ImportData, Name, ScopedVisitor
from marimo._utils.tmpdir import get_tmpdir
from marimo._utils.variables import is_local
@@ -94,6 +95,7 @@ def compile_cell(
code: str,
cell_id: CellId_t,
source_position: Optional[SourcePosition] = None,
+ carried_imports: list[ImportData] | None = None,
) -> CellImpl:
# Replace non-breaking spaces with regular spaces -- some frontends
# send nbsp in place of space, which is a syntax error.
@@ -122,6 +124,10 @@ def compile_cell(
cell_id=cell_id,
)
+ is_import_block = all(
+ isinstance(stmt, (ast.Import, ast.ImportFrom)) for stmt in module.body
+ )
+
v = ScopedVisitor("cell_" + cell_id)
v.visit(module)
@@ -159,19 +165,39 @@ def compile_cell(
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)}
+ nonlocals = {name for name in v.defs if not is_local(name)}
+ variable_data = {
+ name: v.variable_data[name]
+ for name in nonlocals
+ if name in v.variable_data
+ }
+
+ # If this cell is an import cell, we carry over any imports in
+ # `carried_imports` that are also in this cell to the import workspace's
+ # definitions.
+ imported_defs: set[Name] = set()
+ if is_import_block and carried_imports is not None:
+ for data in variable_data.values():
+ for datum in data:
+ import_data = datum.import_data
+ if import_data is None:
+ continue
+ for previous_import_data in carried_imports:
+ if previous_import_data == import_data:
+ imported_defs.add(import_data.definition)
+
return CellImpl(
# keyed by original (user) code, for cache lookups
key=code_key(code),
code=code,
mod=module,
- defs=glbls,
+ defs=nonlocals,
refs=v.refs,
- variable_data={
- name: v.variable_data[name]
- for name in glbls
- if name in v.variable_data
- },
+ variable_data=variable_data,
+ import_workspace=ImportWorkspace(
+ is_import_block=is_import_block,
+ imported_defs=imported_defs,
+ ),
deleted_refs=v.deleted_refs,
body=body,
last_expr=last_expr,
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index a5fc6249a1..fb68326a84 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import ast
import sys
+from collections import defaultdict
from dataclasses import dataclass, field
from typing import Literal, Optional
from uuid import uuid4
@@ -22,6 +23,8 @@ class ImportData:
# full module name
# e.g., a.b.c.
module: str
+ # variable name
+ definition: str
# fully qualified import symbol:
# import a.b => symbol == None
# from a.b import c => symbol == a.b.c
@@ -61,7 +64,9 @@ class Block:
# Names defined with the global keyword
global_names: set[Name] = field(default_factory=set)
# Map from defined names to metadata about their variables
- variable_data: dict[Name, VariableData] = field(default_factory=dict)
+ variable_data: dict[Name, list[VariableData]] = field(
+ default_factory=lambda: defaultdict(list)
+ )
# Comprehensions have special scoping rules
is_comprehension: bool = False
@@ -111,7 +116,7 @@ class ScopedVisitor(ast.NodeVisitor):
return self.block_stack[0].defs
@property
- def variable_data(self) -> dict[Name, VariableData]:
+ def variable_data(self) -> dict[Name, list[VariableData]]:
"""Get data accompanying globals."""
return self.block_stack[0].variable_data
@@ -186,7 +191,7 @@ class ScopedVisitor(ast.NodeVisitor):
"""Define a name in a given block."""
self.block_stack[block_idx].defs.add(name)
- self.block_stack[block_idx].variable_data[name] = variable_data
+ self.block_stack[block_idx].variable_data[name].append(variable_data)
# If `name` is added to the top-level block, it is also evicted from
# any captured refs (if present) --- this handles cases where a name is
# encountered and captured before it is declared, such as in
@@ -592,7 +597,9 @@ class ScopedVisitor(ast.NodeVisitor):
VariableData(
kind="import",
import_data=ImportData(
- module=alias_node.name, imported_symbol=None
+ module=alias_node.name,
+ definition=variable_name,
+ imported_symbol=None,
),
),
)
@@ -610,6 +617,7 @@ class ScopedVisitor(ast.NodeVisitor):
kind="import",
import_data=ImportData(
module=module,
+ definition=variable_name,
imported_symbol=module + "." + original_name,
import_level=node.level,
),
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 68fc94a729..b38d5c9093 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -17,7 +17,7 @@ import marimo._server.models.home as home
import marimo._server.models.models as models
import marimo._snippets.snippets as snippets
from marimo import __version__
-from marimo._ast.cell import CellConfig, CellStatusType
+from marimo._ast.cell import CellConfig, RuntimeStateType
from marimo._cli.print import orange
from marimo._config.config import MarimoConfig
from marimo._messaging.cell_output import CellChannel, CellOutput
@@ -39,7 +39,7 @@ def _generate_schema() -> dict[str, Any]:
MESSAGES = [
# Base
MIME,
- CellStatusType,
+ RuntimeStateType,
KnownMimeType,
CellChannel,
data.NonNestedLiteral,
@@ -185,7 +185,7 @@ def _generate_schema() -> dict[str, Any]:
KnownMimeType: "MimeType",
data.DataType: "DataType",
data.NonNestedLiteral: "NonNestedLiteral",
- CellStatusType: "CellStatus",
+ RuntimeStateType: "RuntimeState",
CellChannel: "CellChannel",
ops.MessageOperation: "MessageOperation",
}
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
index 2064dd3af3..3e347e49f2 100644
--- a/marimo/_messaging/ops.py
+++ b/marimo/_messaging/ops.py
@@ -26,7 +26,7 @@ from typing import (
from marimo import _loggers as loggers
from marimo._ast.app import _AppConfig
-from marimo._ast.cell import CellConfig, CellId_t, CellStatusType
+from marimo._ast.cell import CellConfig, CellId_t, RuntimeStateType
from marimo._data.models import ColumnSummary, DataTable, DataTableSource
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.cell_output import CellChannel, CellOutput
@@ -115,7 +115,7 @@ class CellOp(Op):
cell_id: CellId_t
output: Optional[CellOutput] = None
console: Optional[Union[CellOutput, List[CellOutput]]] = None
- status: Optional[CellStatusType] = None
+ status: Optional[RuntimeStateType] = None
stale_inputs: Optional[bool] = None
timestamp: float = field(default_factory=lambda: time.time())
@@ -161,7 +161,7 @@ class CellOp(Op):
mimetype: KnownMimeType,
data: str,
cell_id: Optional[CellId_t],
- status: Optional[CellStatusType],
+ status: Optional[RuntimeStateType],
stream: Stream | None = None,
) -> None:
mimetype, data = CellOp.maybe_truncate_output(mimetype, data)
@@ -182,7 +182,7 @@ class CellOp(Op):
@staticmethod
def broadcast_empty_output(
cell_id: Optional[CellId_t],
- status: Optional[CellStatusType],
+ status: Optional[RuntimeStateType],
stream: Stream | None = None,
) -> None:
cell_id = (
@@ -205,7 +205,7 @@ class CellOp(Op):
mimetype: KnownMimeType,
data: str,
cell_id: Optional[CellId_t],
- status: Optional[CellStatusType],
+ status: Optional[RuntimeStateType],
stream: Stream | None = None,
) -> None:
mimetype, data = CellOp.maybe_truncate_output(mimetype, data)
@@ -225,7 +225,9 @@ class CellOp(Op):
@staticmethod
def broadcast_status(
- cell_id: CellId_t, status: CellStatusType, stream: Stream | None = None
+ cell_id: CellId_t,
+ status: RuntimeStateType,
+ stream: Stream | None = None,
) -> None:
if status != "running":
CellOp(cell_id=cell_id, status=status).broadcast()
diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.py
index 44b8ccaad6..375c5b3144 100644
--- a/marimo/_runtime/dataflow.py
+++ b/marimo/_runtime/dataflow.py
@@ -168,7 +168,7 @@ class DirectedGraph:
self.set_stale(set([cell_id]))
if self.is_any_ancestor_disabled(cell_id):
- cell.set_status(status="disabled-transitively")
+ cell.set_runtime_state(status="disabled-transitively")
def is_any_ancestor_stale(self, cell_id: CellId_t) -> bool:
return any(self.cells[cid].stale for cid in self.ancestors(cell_id))
@@ -191,7 +191,7 @@ class DirectedGraph:
for cid in transitive_closure(self, set([cell_id])) - set([cell_id]):
cell = self.cells[cid]
- cell.set_status(status="disabled-transitively")
+ cell.set_runtime_state(status="disabled-transitively")
def enable_cell(self, cell_id: CellId_t) -> set[CellId_t]:
"""
@@ -215,7 +215,7 @@ class DirectedGraph:
cells_to_run.add(cid)
if child.disabled_transitively:
# cell is no longer disabled: status -> idle
- child.set_status("idle")
+ child.set_runtime_state("idle")
return cells_to_run
def delete_cell(self, cell_id: CellId_t) -> set[CellId_t]:
@@ -311,8 +311,11 @@ class DirectedGraph:
self, set([cell_id]), children=False, inclusive=False
)
- def set_stale(self, cell_ids: set[CellId_t]) -> None:
- for cid in transitive_closure(self, cell_ids):
+ def set_stale(
+ self, cell_ids: set[CellId_t], prune_imports: bool = False
+ ) -> None:
+ relatives = None if not prune_imports else import_block_relatives
+ for cid in transitive_closure(self, cell_ids, relatives=relatives):
self.cells[cid].set_stale(stale=True)
def get_stale(self) -> set[CellId_t]:
@@ -350,16 +353,19 @@ class DirectedGraph:
processed.update(newly_processed)
queue.difference_update(newly_processed)
for variable in newly_processed:
- if predicate(variable, data[variable]):
- to_process = data[variable].required_refs - processed
- queue.update(to_process & self.definitions.keys())
- # Private variables referenced by public functions have
- # to be included.
- for maybe_private in (
- to_process - self.definitions.keys()
- ):
- if is_mangled_local(maybe_private, cell_id):
- processed.add(maybe_private)
+ # variables can be defined multiple times in a single
+ # cell ...
+ for datum in data[variable]:
+ if predicate(variable, datum):
+ to_process = datum.required_refs - processed
+ queue.update(to_process & self.definitions.keys())
+ # Private variables referenced by public functions
+ # have to be included.
+ for maybe_private in (
+ to_process - self.definitions.keys()
+ ):
+ if is_mangled_local(maybe_private, cell_id):
+ processed.add(maybe_private)
if inclusive:
return processed | refs
@@ -371,6 +377,8 @@ def transitive_closure(
cell_ids: set[CellId_t],
children: bool = True,
inclusive: bool = True,
+ relatives: Callable[[DirectedGraph, CellId_t, bool], set[CellId_t]]
+ | None = None,
predicate: Callable[[CellImpl], bool] | None = None,
) -> set[CellId_t]:
"""Return a set of the passed-in cells and their descendants or ancestors
@@ -379,15 +387,22 @@ def transitive_closure(
If inclusive, includes passed-in cells in the set.
- If predicate, only cells satisfying predicate(cell) are included
+ If relatives is not None, it computes the parents/children of a
+ cell
+
+ If predicate, only cells satisfying predicate(cell) are included; applied
+ after the relatives are computed
"""
seen = set()
cells = set()
queue = list(cell_ids)
predicate = predicate or (lambda _: True)
- def relatives(cid: CellId_t) -> set[CellId_t]:
- return graph.children[cid] if children else graph.parents[cid]
+ def _relatives(cid: CellId_t) -> set[CellId_t]:
+ if relatives is None:
+ return graph.children[cid] if children else graph.parents[cid]
+
+ return relatives(graph, cid, children)
while queue:
cid = queue.pop(0)
@@ -397,7 +412,7 @@ def transitive_closure(
cells.add(cid)
elif cid not in cell_ids and predicate(cell):
cells.add(cid)
- for relative in relatives(cid):
+ for relative in _relatives(cid):
if relative not in seen:
queue.append(relative)
return cells
@@ -447,6 +462,42 @@ def topological_sort(
return sorted_cell_ids
+def import_block_relatives(
+ graph: DirectedGraph, cid: CellId_t, children: bool
+) -> set[CellId_t]:
+ if not children:
+ return graph.parents[cid]
+
+ cell = graph.cells[cid]
+ if not cell.import_workspace.is_import_block:
+ return graph.children[cid]
+
+ # This cell is an import block, which should be special cased:
+ #
+ # We prune definitions that have already been imported from the set of
+ # definitions used to find the descendants of this cell.
+ unimported_defs = cell.defs - cell.import_workspace.imported_defs
+ children_ids = set().union(
+ *[graph.get_referring_cells(name) for name in unimported_defs]
+ )
+
+ # If children haven't been executed, then still use imported defs;
+ # handle an edge case when an import cell is interrupted by an
+ # exception or user interrupt, so that a module is imported but the
+ # cell's children haven't run.
+ for name in cell.import_workspace.imported_defs:
+ for child_id in graph.get_referring_cells(name):
+ if graph.cells[child_id].run_result_status in (
+ "interrupted",
+ "cancelled",
+ "marimo-error",
+ None,
+ ):
+ children_ids.add(child_id)
+
+ return children_ids
+
+
class Runner:
"""Utility for running individual cells in a graph
diff --git a/marimo/_runtime/executor.py b/marimo/_runtime/executor.py
index 54650adc65..3df9f2abe8 100644
--- a/marimo/_runtime/executor.py
+++ b/marimo/_runtime/executor.py
@@ -68,28 +68,6 @@ def raise_name_error(
) -> 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:
diff --git a/marimo/_runtime/reload/module_watcher.py b/marimo/_runtime/reload/module_watcher.py
index 220d8ab971..403eafcb64 100644
--- a/marimo/_runtime/reload/module_watcher.py
+++ b/marimo/_runtime/reload/module_watcher.py
@@ -147,13 +147,26 @@ def watch_modules(
if stale_modules:
with graph.lock:
+ for modname in stale_modules.keys():
+ # prune definitions that are derived from stale modules
+ cell = graph.cells[modname_to_cell_id[modname]]
+ defs_to_prune = [
+ import_data.definition
+ for import_data in cell.imports
+ if import_data.module == modname
+ ]
+ cell.import_workspace.imported_defs -= set(defs_to_prune)
+
# If any modules are stale, communicate that to the FE
+ # and update the backend's view of the importing cells'
+ # staleness
stale_cell_ids = dataflow.transitive_closure(
graph,
set(
modname_to_cell_id[modname]
for modname in stale_modules
),
+ relatives=dataflow.import_block_relatives,
)
for cid in stale_cell_ids:
graph.cells[cid].set_stale(stale=True, stream=stream)
diff --git a/marimo/_runtime/runner/cell_runner.py b/marimo/_runtime/runner/cell_runner.py
index 7671e61c1c..755c0d7118 100644
--- a/marimo/_runtime/runner/cell_runner.py
+++ b/marimo/_runtime/runner/cell_runner.py
@@ -112,7 +112,7 @@ class Runner:
# runtime globals
self.glbls = glbls
- self.execution_mode = execution_mode
+ self.execution_mode: OnCellChangeType = execution_mode
self.execution_type = execution_type
# cells that the runner will run, subtracting out cells with errors:
@@ -120,24 +120,11 @@ class Runner:
# cells with errors can't be run, but are still in the graph
# so that they can be transitioned out of error if a future
# run request repairs the graph
+ self.roots = roots
self.cells_to_run: list[CellId_t]
- # Runner always runs stale ancestors, if any.
- cells_to_run = roots.union(
- dataflow.transitive_closure(
- graph,
- roots,
- children=False,
- inclusive=False,
- predicate=lambda cell: cell.stale,
- )
- )
- if self.execution_mode == "autorun":
- # in autorun/eager mode, descendants are also run
- cells_to_run = dataflow.transitive_closure(graph, cells_to_run)
- self.cells_to_run = dataflow.topological_sort(
- graph,
- cells_to_run - self.excluded_cells,
+ self.cells_to_run = Runner.compute_cells_to_run(
+ self.graph, self.roots, self.excluded_cells, self.execution_mode
)
# map from a cell that was cancelled to its descendants that have
@@ -153,6 +140,34 @@ class Runner:
cell_id: index for index, cell_id in enumerate(self.cells_to_run)
}
+ @staticmethod
+ def compute_cells_to_run(
+ graph: dataflow.DirectedGraph,
+ roots: set[CellId_t],
+ excluded_cells: set[CellId_t],
+ execution_mode: OnCellChangeType,
+ ) -> list[CellId_t]:
+ # Runner always runs stale ancestors, if any.
+ cells_to_run = roots.union(
+ dataflow.transitive_closure(
+ graph,
+ roots,
+ children=False,
+ inclusive=False,
+ predicate=lambda cell: cell.stale,
+ )
+ )
+ if execution_mode == "autorun":
+ # in autorun/eager mode, descendants are also run;
+ cells_to_run = dataflow.transitive_closure(
+ graph, cells_to_run, relatives=dataflow.import_block_relatives
+ )
+
+ return dataflow.topological_sort(
+ graph,
+ cells_to_run - excluded_cells,
+ )
+
# Adapted from
# https://github.com/ipython/ipykernel/blob/eddd3e666a82ebec287168b0da7cfa03639a3772/ipykernel/ipkernel.py#L312 # noqa: E501
@staticmethod
@@ -207,6 +222,8 @@ class Runner:
for cid in dataflow.transitive_closure(self.graph, set([cell_id]))
if cid in self.cells_to_run
)
+ for cid in self.cells_cancelled[cell_id]:
+ self.graph.cells[cid].set_run_result_status("cancelled")
def cancelled(self, cell_id: CellId_t) -> bool:
"""Return whether a cell has been cancelled."""
@@ -506,17 +523,25 @@ class Runner:
while self.pending():
cell_id = self.pop_cell()
+ cell = self.graph.cells[cell_id]
+
+ # Update run result status for cells that won't run.
+ #
+ # Hack: frontend sets status to queued on run, so we also have to
+ # set runtime_state to get FE to transition.
if self.cancelled(cell_id):
+ cell.set_run_result_status("cancelled")
+ cell.set_runtime_state("idle")
continue
- cell = self.graph.cells[cell_id]
if cell.config.disabled:
- cell.set_status("idle")
+ cell.set_run_result_status("disabled")
+ cell.set_runtime_state("idle")
continue
if self.graph.is_disabled(cell_id):
- # hack: frontend sets status to queued on run, have to
- # set status here to get FE to transition.
- cell.set_status("disabled-transitively")
+ cell.set_run_result_status("disabled")
+ cell.set_runtime_state("disabled-transitively")
continue
+
for pre_hook in self.pre_execution_hooks:
pre_hook(cell, self)
if self.execution_context is not None:
diff --git a/marimo/_runtime/runner/hooks_on_finish.py b/marimo/_runtime/runner/hooks_on_finish.py
index a3abc68d69..2f3120ce36 100644
--- a/marimo/_runtime/runner/hooks_on_finish.py
+++ b/marimo/_runtime/runner/hooks_on_finish.py
@@ -26,7 +26,7 @@ def _send_interrupt_errors(runner: cell_runner.Runner) -> None:
assert runner.interrupted
for cid in runner.cells_to_run:
# `cid` was not run
- runner.graph.cells[cid].set_status("idle")
+ runner.graph.cells[cid].set_runtime_state("idle")
CellOp.broadcast_error(
data=[MarimoInterruptionError()],
# these cells are transitioning from queued to stopped
@@ -42,10 +42,10 @@ def _send_cancellation_errors(runner: cell_runner.Runner) -> None:
for cid in runner.cells_cancelled[raising_cell]:
# `cid` was not run
cell = runner.graph.cells[cid]
- if cell.status != "idle":
+ if cell.runtime_state != "idle":
# the cell raising an exception will already be
# idle, but its descendants won't be.
- cell.set_status("idle")
+ cell.set_runtime_state("idle")
exception = runner.exceptions[raising_cell]
data: Error
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index 7d01a2281b..bbb8176fa4 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -38,6 +38,19 @@ PostExecutionHookType = Callable[
]
+def _set_imported_defs(
+ cell: CellImpl,
+ runner: cell_runner.Runner,
+ run_result: cell_runner.RunResult,
+) -> None:
+ del run_result
+ with runner.graph.lock:
+ if cell.import_workspace.is_import_block:
+ cell.import_workspace.imported_defs = set(
+ name for name in cell.defs if name in runner.glbls
+ )
+
+
def _set_status_idle(
cell: CellImpl,
runner: cell_runner.Runner,
@@ -45,7 +58,22 @@ def _set_status_idle(
) -> None:
del run_result
del runner
- cell.set_status(status="idle")
+ cell.set_runtime_state(status="idle")
+
+
+def _set_run_result_status(
+ cell: CellImpl,
+ runner: cell_runner.Runner,
+ run_result: cell_runner.RunResult,
+) -> None:
+ if isinstance(run_result.exception, MarimoInterruptionError):
+ cell.set_run_result_status("interrupted")
+ elif runner.cancelled(cell.cell_id):
+ cell.set_run_result_status("cancelled")
+ elif run_result.exception is not None:
+ cell.set_run_result_status("exception")
+ else:
+ cell.set_run_result_status("success")
def _broadcast_variables(
@@ -243,6 +271,8 @@ def _reset_matplotlib_context(
POST_EXECUTION_HOOKS: list[PostExecutionHookType] = [
+ _set_imported_defs,
+ _set_run_result_status,
_store_reference_to_output,
_broadcast_variables,
_broadcast_datasets,
diff --git a/marimo/_runtime/runner/hooks_pre_execution.py b/marimo/_runtime/runner/hooks_pre_execution.py
index 8aed36df82..711cbb5353 100644
--- a/marimo/_runtime/runner/hooks_pre_execution.py
+++ b/marimo/_runtime/runner/hooks_pre_execution.py
@@ -30,7 +30,7 @@ def _set_status_to_running(
runner: cell_runner.Runner,
) -> None:
del runner
- cell.set_status("running")
+ cell.set_runtime_state("running")
PRE_EXECUTION_HOOKS: list[PreExecutionHookType] = [
diff --git a/marimo/_runtime/runner/hooks_preparation.py b/marimo/_runtime/runner/hooks_preparation.py
index ab32eb3a73..cd9dcc9946 100644
--- a/marimo/_runtime/runner/hooks_preparation.py
+++ b/marimo/_runtime/runner/hooks_preparation.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from typing import Callable
from marimo._runtime import dataflow
+from marimo._runtime.dataflow import import_block_relatives
from marimo._runtime.runner import cell_runner
PreparationHookType = Callable[[cell_runner.Runner], None]
@@ -14,7 +15,10 @@ def _update_stale_statuses(runner: cell_runner.Runner) -> None:
if runner.execution_mode == "lazy":
for cid in dataflow.transitive_closure(
- graph, set(runner.cells_to_run), inclusive=False
+ graph,
+ set(runner.cells_to_run),
+ inclusive=False,
+ relatives=import_block_relatives,
):
graph.cells[cid].set_stale(stale=True)
@@ -22,7 +26,7 @@ def _update_stale_statuses(runner: cell_runner.Runner) -> None:
if graph.is_disabled(cid):
graph.cells[cid].set_stale(stale=True)
else:
- graph.cells[cid].set_status(status="queued")
+ graph.cells[cid].set_runtime_state(status="queued")
if graph.cells[cid].stale:
if runner.execution_mode == "autorun":
graph.cells[cid].set_stale(stale=False)
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index da6bf17cc5..2abb3329a0 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -16,20 +16,13 @@ import time
import traceback
from copy import copy
from multiprocessing import connection
-from typing import (
- TYPE_CHECKING,
- Any,
- Callable,
- Iterator,
- Optional,
- cast,
-)
+from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, cast
from uuid import uuid4
from marimo import _loggers
from marimo._ast.cell import CellConfig, CellId_t, CellImpl
from marimo._ast.compiler import compile_cell
-from marimo._ast.visitor import Name
+from marimo._ast.visitor import ImportData, Name
from marimo._config.config import ExecutionType, MarimoConfig, OnCellChangeType
from marimo._data.preview_column import get_column_preview
from marimo._messaging.cell_output import CellChannel
@@ -548,17 +541,19 @@ class Kernel:
module_reloader is not None
and module_reloader.cell_uses_stale_modules(cell)
):
- self.graph.set_stale(set([cell.cell_id]))
+ self.graph.set_stale(set([cell.cell_id]), prune_imports=True)
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])
def _try_compiling_cell(
- self, cell_id: CellId_t, code: str
+ self, cell_id: CellId_t, code: str, carried_imports: list[ImportData]
) -> tuple[Optional[CellImpl], Optional[Error]]:
error: Optional[Error] = None
try:
- cell = compile_cell(code, cell_id=cell_id)
+ cell = compile_cell(
+ code, cell_id=cell_id, carried_imports=carried_imports
+ )
except Exception as e:
cell = None
if isinstance(e, SyntaxError):
@@ -579,9 +574,7 @@ class Kernel:
return cell, error
def _try_registering_cell(
- self,
- cell_id: CellId_t,
- code: str,
+ self, cell_id: CellId_t, code: str, carried_imports: list[ImportData]
) -> Optional[Error]:
"""Attempt to register a cell with given id and code.
@@ -590,7 +583,7 @@ class Kernel:
If cell was unable to be registered, returns an Error object.
"""
- cell, error = self._try_compiling_cell(cell_id, code)
+ cell, error = self._try_compiling_cell(cell_id, code, carried_imports)
if cell is not None:
self._register_cell(cell_id, cell)
@@ -607,7 +600,8 @@ class Kernel:
same id but different code is registered.
Returns:
- - a set of ids for cells that were previously children of `cell_id`;
+ - a set of ids for cells that were previously children of `cell_id`
+ but are no longer children of `cell_id` after registration;
only non-empty when `cell-id` was already registered but with
different code.
- an `Error` if the cell couldn't be registered, `None` otherwise
@@ -615,10 +609,31 @@ class Kernel:
previous_children: set[CellId_t] = set()
error = None
if not self.graph.is_cell_cached(cell_id, code):
- if cell_id in self.graph.cells:
+ previous_cell = self.graph.cells.get(cell_id, None)
+
+ if (
+ previous_cell is not None
+ and previous_cell.import_workspace.is_import_block
+ ):
+ # If the previous is being replaced by another import block,
+ # then the new cell should try to carry over the previous
+ # cell's imports to prevent unnecessary re-runs.
+ carried_imports = [
+ import_data
+ for import_data in previous_cell.imports
+ if import_data.definition in self.globals
+ and import_data.definition
+ in previous_cell.import_workspace.imported_defs
+ ]
+ else:
+ carried_imports = []
+
+ if previous_cell is not None:
LOGGER.debug("Deleting cell %s", cell_id)
previous_children = self._deactivate_cell(cell_id)
- error = self._try_registering_cell(cell_id, code)
+ error = self._try_registering_cell(
+ cell_id, code, carried_imports=carried_imports
+ )
LOGGER.debug(
"graph:\n\tcell id %s\n\tparents %s\n\tchildren %s\n\tsiblings %s",
@@ -627,7 +642,12 @@ class Kernel:
self.graph.children,
self.graph.siblings,
)
- return previous_children, error
+
+ # We only return cells that were previously children of cell_id
+ # but are no longer children of the newly registered cell; these
+ # returned cells are stale.
+ children = self.graph.children.get(cell_id, set())
+ return previous_children - children, error
def _delete_names(
self, names: Iterable[Name], exclude_defs: set[Name]
@@ -659,6 +679,7 @@ class Kernel:
elements.
"""
cell = self.graph.cells[cell_id]
+ cell.import_workspace.imported_defs = set()
missing_modules_before_deletion = (
self.module_registry.missing_modules()
)
@@ -735,6 +756,8 @@ class Kernel:
Deletion from graph is forwarded to graph object.
"""
del self.cell_metadata[cell_id]
+ cell = self.graph.cells[cell_id]
+ cell.import_workspace.imported_defs = set()
return self._deactivate_cell(cell_id)
def mutate_graph(
@@ -854,6 +877,7 @@ class Kernel:
cells_with_errors_before_mutation
- cells_with_errors_after_mutation
) & cells_in_graph
+
if self.reactive_execution_mode == "autorun":
for cid in cells_that_no_longer_have_errors:
# clear error outputs before running
@@ -887,6 +911,7 @@ class Kernel:
if cid not in self.graph.cells:
# error is a registration error
continue
+ self.graph.cells[cid].set_run_result_status("marimo-error")
self._invalidate_cell_state(cid, exclude_defs=keep_alive_defs)
self.errors = all_errors
@@ -899,7 +924,9 @@ class Kernel:
):
# this may be the first time we're seeing the cell: set its
# status
- self.graph.cells[cid].set_status("disabled-transitively")
+ self.graph.cells[cid].set_runtime_state(
+ "disabled-transitively"
+ )
CellOp.broadcast_error(
data=self.errors[cid],
clear_console=True,
@@ -935,7 +962,7 @@ class Kernel:
) & cells_in_graph
if self.reactive_execution_mode == "lazy":
- self.graph.set_stale(stale_cells)
+ self.graph.set_stale(stale_cells, prune_imports=True)
return cells_registered_without_error
else:
return cells_registered_without_error.union(stale_cells)
@@ -952,7 +979,7 @@ class Kernel:
while cell_ids := await self._run_cells_internal(cell_ids):
LOGGER.debug("Running state updates ...")
if self.lazy() and cell_ids:
- self.graph.set_stale(cell_ids)
+ self.graph.set_stale(cell_ids, prune_imports=True)
break
LOGGER.debug("Finished run.")
@@ -962,7 +989,9 @@ class Kernel:
if self.reactive_execution_mode == "autorun":
await self._run_cells(cell_ids)
else:
- self.graph.set_stale(cell_ids)
+ # We prune imports so that only cells depending on unimported
+ # modules are marked as stale
+ self.graph.set_stale(cell_ids, prune_imports=True)
def _broadcast_missing_packages(self, runner: cell_runner.Runner) -> None:
if (
@@ -1137,7 +1166,7 @@ class Kernel:
roots = {SCRATCH_CELL_ID}
# If cannot compile, don't run
- cell, error = self._try_compiling_cell(SCRATCH_CELL_ID, code)
+ cell, error = self._try_compiling_cell(SCRATCH_CELL_ID, code, [])
if error:
CellOp.broadcast_error(
data=[error],
@@ -1178,10 +1207,12 @@ class Kernel:
for cid, cell_impl in self.graph.cells.items():
if cell_impl.stale and not self.graph.is_disabled(cid):
cells_to_run.add(cid)
- # TODO: should there just be one reactive exec mode, and one
- # reload mode? ie no mix and match? otherwise what do we do here?
await self._run_cells(
- dataflow.transitive_closure(self.graph, cells_to_run)
+ dataflow.transitive_closure(
+ self.graph,
+ cells_to_run,
+ relatives=dataflow.import_block_relatives,
+ )
)
if self.module_watcher is not None:
self.module_watcher.run_is_processed.set()
@@ -1357,9 +1388,11 @@ class Kernel:
if self.reactive_execution_mode == "autorun":
await self._run_cells(referring_cells)
else:
+ # Any cells referring to a UI element cannot be import cells,
+ # so not necessary to specify `prune_imports`.
self.graph.set_stale(referring_cells)
- # process any state updates that may have been queued by the
- # on_change handlers
+ # Process any state updates that may have been queued by the
+ # on_change handlers.
await self._run_cells(set())
for component in updated_components:
diff --git a/tests/_ast/test_compiler.py b/tests/_ast/test_compiler.py
index b30d2cb99a..320fcdf12a 100644
--- a/tests/_ast/test_compiler.py
+++ b/tests/_ast/test_compiler.py
@@ -5,6 +5,7 @@ from functools import partial
from marimo._ast import compiler
from marimo._ast.app import CellManager
+from marimo._ast.visitor import ImportData
compile_cell = partial(compiler.compile_cell, cell_id="0")
@@ -64,6 +65,8 @@ class TestParseCell:
assert cell.refs == set()
assert not cell.imported_namespaces
+
+class TestImportWorkspace:
@staticmethod
def test_import() -> None:
code = "from a.b.c import d; x = None"
@@ -73,6 +76,172 @@ class TestParseCell:
assert cell.refs == set()
# but "a" is the module from which it was imported
assert cell.imported_namespaces == {"a"}
+ assert not cell.import_workspace.is_import_block
+
+ @staticmethod
+ def test_simple_import_statement() -> None:
+ code = "import foo"
+ cell = compile_cell(code)
+ assert cell.defs == set(["foo"])
+ assert cell.import_workspace.is_import_block
+ assert not cell.import_workspace.imported_defs
+ assert len(list(cell.imports)) == 1
+ assert list(cell.imports)[0].definition == "foo"
+ assert list(cell.imports)[0].imported_symbol is None
+ assert list(cell.imports)[0].module == "foo"
+ assert list(cell.imports)[0].namespace == "foo"
+ assert list(cell.imports)[0].import_level is None
+
+ @staticmethod
+ def test_dotted_import_statement() -> None:
+ code = "import foo.bar"
+ cell = compile_cell(code)
+ assert cell.defs == set(["foo"])
+ assert cell.import_workspace.is_import_block
+ assert not cell.import_workspace.imported_defs
+ assert len(list(cell.imports)) == 1
+ assert list(cell.imports)[0].definition == "foo"
+ assert list(cell.imports)[0].imported_symbol is None
+ assert list(cell.imports)[0].module == "foo.bar"
+ assert list(cell.imports)[0].namespace == "foo"
+ assert list(cell.imports)[0].import_level is None
+
+ @staticmethod
+ def test_from_import() -> None:
+ code = "from foo.bar import baz"
+ cell = compile_cell(code)
+ assert cell.defs == set(["baz"])
+ assert cell.import_workspace.is_import_block
+ assert not cell.import_workspace.imported_defs
+ assert len(list(cell.imports)) == 1
+ assert list(cell.imports)[0].definition == "baz"
+ assert list(cell.imports)[0].imported_symbol == "foo.bar.baz"
+ assert list(cell.imports)[0].module == "foo.bar"
+ assert list(cell.imports)[0].namespace == "foo"
+ assert list(cell.imports)[0].import_level == 0
+
+ @staticmethod
+ def test_multiple_imports() -> None:
+ code = "import foo; import foo.bar; from foo.bar import baz"
+ cell = compile_cell(code)
+ assert cell.defs == set(["foo", "baz"])
+ assert cell.import_workspace.is_import_block
+ assert not cell.import_workspace.imported_defs
+ assert len(list(cell.imports)) == 3
+
+ foo = ImportData(
+ definition="foo",
+ imported_symbol=None,
+ module="foo",
+ import_level=None,
+ )
+ foo_bar = ImportData(
+ definition="foo",
+ imported_symbol=None,
+ module="foo.bar",
+ import_level=None,
+ )
+ foo_bar_baz = ImportData(
+ definition="baz",
+ imported_symbol="foo.bar.baz",
+ module="foo.bar",
+ import_level=0,
+ )
+ assert foo in cell.imports
+ assert foo_bar in cell.imports
+ assert foo_bar_baz in cell.imports
+
+ @staticmethod
+ def test_mixed_statements_not_import_block() -> None:
+ code = "import foo; foo.configure()"
+ cell = compile_cell(code)
+ assert not cell.import_workspace.is_import_block
+ assert not cell.import_workspace.imported_defs
+
+ code = "x = 0; import foo"
+ cell = compile_cell(code)
+ assert not cell.import_workspace.is_import_block
+ assert not cell.import_workspace.imported_defs
+
+ @staticmethod
+ def test_single_carried_import() -> None:
+ foo = ImportData(
+ definition="foo",
+ imported_symbol=None,
+ module="foo",
+ import_level=None,
+ )
+ foo_bar = ImportData(
+ definition="foo",
+ imported_symbol=None,
+ module="foo.bar",
+ import_level=None,
+ )
+ foo_bar_baz = ImportData(
+ definition="baz",
+ imported_symbol="foo.bar.baz",
+ module="foo.bar",
+ import_level=0,
+ )
+
+ code = "import foo; import foo.bar; from foo.bar import baz"
+ cell = compile_cell(code, carried_imports=[foo])
+ assert cell.defs == set(["foo", "baz"])
+ assert cell.import_workspace.is_import_block
+ assert cell.import_workspace.imported_defs == set(["foo"])
+
+ assert len(list(cell.imports)) == 3
+ assert foo in cell.imports
+ assert foo_bar in cell.imports
+ assert foo_bar_baz in cell.imports
+
+ @staticmethod
+ def test_multiple_carried_imports() -> None:
+ foo = ImportData(
+ definition="foo",
+ imported_symbol=None,
+ module="foo",
+ import_level=None,
+ )
+ foo_bar = ImportData(
+ definition="foo",
+ imported_symbol=None,
+ module="foo.bar",
+ import_level=None,
+ )
+ foo_bar_baz = ImportData(
+ definition="baz",
+ imported_symbol="foo.bar.baz",
+ module="foo.bar",
+ import_level=0,
+ )
+
+ code = "import foo; import foo.bar; from foo.bar import baz"
+ cell = compile_cell(code, carried_imports=[foo, foo_bar, foo_bar_baz])
+ assert cell.defs == set(["foo", "baz"])
+ assert cell.import_workspace.is_import_block
+ assert cell.import_workspace.imported_defs == set(["foo", "baz"])
+
+ assert len(list(cell.imports)) == 3
+ assert foo in cell.imports
+ assert foo_bar in cell.imports
+ assert foo_bar_baz in cell.imports
+
+ @staticmethod
+ def test_carried_imports_mismatch() -> None:
+ # import foo and import foo.bar both define "foo", but they are
+ # different imports; as such, the import should not be carried over
+ foo = ImportData(
+ definition="foo",
+ imported_symbol=None,
+ module="foo",
+ import_level=None,
+ )
+ code = "import foo.bar"
+ cell = compile_cell(code, carried_imports=[foo])
+ assert cell.defs == set(["foo"])
+ assert cell.import_workspace.is_import_block
+ assert not cell.import_workspace.imported_defs
class TestCellFactory:
diff --git a/tests/_ast/test_visitor.py b/tests/_ast/test_visitor.py
index c4565f27b1..6334801b76 100644
--- a/tests/_ast/test_visitor.py
+++ b/tests/_ast/test_visitor.py
@@ -22,7 +22,7 @@ def test_assign_simple() -> None:
v.visit(mod)
assert v.defs == set(["x"])
assert v.refs == set()
- assert v.variable_data == {"x": VariableData(kind="variable")}
+ assert v.variable_data == {"x": [VariableData(kind="variable")]}
def test_multiple_assign() -> None:
@@ -33,8 +33,8 @@ def test_multiple_assign() -> None:
assert v.defs == set(["x", "y"])
assert v.refs == set()
assert v.variable_data == {
- "x": VariableData(kind="variable"),
- "y": VariableData(kind="variable"),
+ "x": [VariableData(kind="variable")],
+ "y": [VariableData(kind="variable")],
}
@@ -46,8 +46,8 @@ def test_assign_multiple_statements() -> None:
assert v.defs == set(["x", "y"])
assert v.refs == set()
assert v.variable_data == {
- "x": VariableData(kind="variable"),
- "y": VariableData(kind="variable"),
+ "x": [VariableData(kind="variable")],
+ "y": [VariableData(kind="variable")],
}
@@ -78,7 +78,7 @@ def test_read_attr_of_defined_variable() -> None:
v.visit(mod)
assert v.defs == set(["x"])
assert v.refs == set()
- assert v.variable_data == {"x": VariableData(kind="variable")}
+ assert v.variable_data == {"x": [VariableData(kind="variable")]}
def test_assign_nested_attr() -> None:
@@ -109,7 +109,7 @@ def test_assign_same_name() -> None:
assert v.defs == set(["x"])
assert v.refs == set(["x"])
assert v.variable_data == {
- "x": VariableData(kind="variable", required_refs={"x"})
+ "x": [VariableData(kind="variable", required_refs={"x"})]
}
expr = "x=1; x = x"
@@ -119,7 +119,10 @@ def test_assign_same_name() -> None:
assert v.defs == set(["x"])
assert v.refs == set()
assert v.variable_data == {
- "x": VariableData(kind="variable", required_refs={"x"})
+ "x": [
+ VariableData(kind="variable", required_refs=set()),
+ VariableData(kind="variable", required_refs={"x"}),
+ ]
}
expr = "(x := x)"
@@ -129,7 +132,7 @@ def test_assign_same_name() -> None:
assert v.defs == set(["x"])
assert v.refs == set(["x"])
assert v.variable_data == {
- "x": VariableData(kind="variable", required_refs={"x"})
+ "x": [VariableData(kind="variable", required_refs={"x"})]
}
expr = "x += x"
@@ -139,7 +142,7 @@ def test_assign_same_name() -> None:
assert v.defs == set(["x"])
assert v.refs == set(["x"])
assert v.variable_data == {
- "x": VariableData(kind="variable", required_refs={"x"})
+ "x": [VariableData(kind="variable", required_refs={"x"})]
}
expr = "def f(): x = x; return x"
@@ -149,7 +152,7 @@ def test_assign_same_name() -> None:
assert v.defs == set(["f"])
assert v.refs == set(["x"])
assert v.variable_data == {
- "f": VariableData(kind="function", required_refs={"x"})
+ "f": [VariableData(kind="function", required_refs={"x"})]
}
expr = "class F(): x = x"
@@ -159,7 +162,7 @@ def test_assign_same_name() -> None:
assert v.defs == set(["F"])
assert v.refs == set(["x"])
assert v.variable_data == {
- "F": VariableData(kind="class", required_refs={"x"})
+ "F": [VariableData(kind="class", required_refs={"x"})]
}
expr = "{x: x}"
@@ -190,14 +193,14 @@ def test_structured_assignment() -> None:
assert v.defs == names
assert v.refs == set()
assert v.variable_data == {
- "a": VariableData(kind="variable"),
- "b": VariableData(kind="variable"),
- "c": VariableData(kind="variable"),
- "d": VariableData(kind="variable"),
- "e": VariableData(kind="variable"),
- "f": VariableData(kind="variable"),
- "g": VariableData(kind="variable"),
- "h": VariableData(kind="variable"),
+ "a": [VariableData(kind="variable")],
+ "b": [VariableData(kind="variable")],
+ "c": [VariableData(kind="variable")],
+ "d": [VariableData(kind="variable")],
+ "e": [VariableData(kind="variable")],
+ "f": [VariableData(kind="variable")],
+ "g": [VariableData(kind="variable")],
+ "h": [VariableData(kind="variable")],
}
@@ -209,8 +212,8 @@ def test_starred_assignment() -> None:
assert v.defs == set(["a", "b"])
assert v.refs == set()
assert v.variable_data == {
- "a": VariableData(kind="variable"),
- "b": VariableData(kind="variable"),
+ "a": [VariableData(kind="variable")],
+ "b": [VariableData(kind="variable")],
}
@@ -228,7 +231,7 @@ def test_scope_does_not_leak() -> None:
assert v.defs == set(["foo"])
assert v.refs == set("z")
assert v.variable_data == {
- "foo": VariableData(kind="function"),
+ "foo": [VariableData(kind="function")],
}
@@ -264,11 +267,11 @@ def test_walrus_leaks_to_global_in_comprehension() -> None:
# "a" should not be a ref!
assert v.refs == set(["range"])
assert v.variable_data == {
- "a": VariableData(kind="variable"),
- "b": VariableData(kind="variable"),
- "c": VariableData(kind="variable"),
- "d": VariableData(kind="variable"),
- "foo": VariableData(kind="function", required_refs={"a"}),
+ "a": [VariableData(kind="variable")],
+ "b": [VariableData(kind="variable")],
+ "c": [VariableData(kind="variable")],
+ "d": [VariableData(kind="variable")],
+ "foo": [VariableData(kind="function", required_refs={"a"})],
}
@@ -280,8 +283,8 @@ def test_nested_walrus_leaks_to_global_in_comprehension() -> None:
assert v.defs == set(["a", "b"])
assert v.refs == set(["range"])
assert v.variable_data == {
- "a": VariableData(kind="variable"),
- "b": VariableData(kind="variable"),
+ "a": [VariableData(kind="variable")],
+ "b": [VariableData(kind="variable")],
}
@@ -293,7 +296,7 @@ def test_pep572_walrus_comprehension_examples() -> None:
assert v.defs == set(["y"])
assert v.refs == set(["input_data", "f"])
assert v.variable_data == {
- "y": VariableData(kind="variable"),
+ "y": [VariableData(kind="variable")],
}
code = "[[y := f(x), x/y] for x in range(5)]"
@@ -303,7 +306,7 @@ def test_pep572_walrus_comprehension_examples() -> None:
assert v.defs == set(["y"])
assert v.refs == set(["f", "range"])
assert v.variable_data == {
- "y": VariableData(kind="variable"),
+ "y": [VariableData(kind="variable")],
}
@@ -317,7 +320,7 @@ def test_walrus_in_comp_in_fn_block_does_not_leak_to_global() -> None:
assert v.defs == set(["f"]) # x should _not_ leak to global scope
assert v.refs == set(["range"]) # x should leak to f's scope
assert v.variable_data == {
- "f": VariableData(kind="function", required_refs={"range"}),
+ "f": [VariableData(kind="function", required_refs={"range"})],
}
@@ -339,9 +342,9 @@ def test_assignments_in_multiple_scopes() -> None:
assert v.defs == set(["a", "e", "foo"])
assert v.refs == set()
assert v.variable_data == {
- "a": VariableData(kind="variable"),
- "e": VariableData(kind="variable"),
- "foo": VariableData(kind="function"),
+ "a": [VariableData(kind="variable")],
+ "e": [VariableData(kind="variable")],
+ "foo": [VariableData(kind="function")],
}
@@ -359,7 +362,7 @@ def test_function_with_args() -> None:
assert v.defs == set(["foo"])
assert v.refs == set("z")
assert v.variable_data == {
- "foo": VariableData(kind="function", required_refs={"z"}),
+ "foo": [VariableData(kind="function", required_refs={"z"})],
}
@@ -377,7 +380,7 @@ def test_function_with_defaults() -> None:
assert v.refs == set(["x", "y", "a"])
# TODO: Are these required refs?
assert v.variable_data == {
- "foo": VariableData(kind="function", required_refs={"x", "y", "a"}),
+ "foo": [VariableData(kind="function", required_refs={"x", "y", "a"})],
}
@@ -396,8 +399,8 @@ def test_async_function_def() -> None:
assert v.defs == set(["foo", "x"])
assert v.refs == set("z")
assert v.variable_data == {
- "foo": VariableData(kind="function", required_refs={"z"}),
- "x": VariableData(kind="variable"),
+ "foo": [VariableData(kind="function", required_refs={"z"})],
+ "x": [VariableData(kind="variable")],
}
@@ -415,8 +418,8 @@ def test_global_def() -> None:
assert v.defs == set(["foo", "x"])
assert v.refs == set()
assert v.variable_data == {
- "foo": VariableData(kind="function", required_refs={"x"}),
- "x": VariableData(kind="variable"),
+ "foo": [VariableData(kind="function", required_refs={"x"})],
+ "x": [VariableData(kind="variable")],
}
@@ -434,7 +437,7 @@ def test_global_ref() -> None:
assert v.defs == set(["foo"])
assert v.refs == set(["x", "print"])
assert v.variable_data == {
- "foo": VariableData(kind="function", required_refs={"x", "print"}),
+ "foo": [VariableData(kind="function", required_refs={"x", "print"})],
}
@@ -454,7 +457,7 @@ def test_nested_local_def_and_global_ref() -> None:
assert v.defs == set(["foo"])
assert v.refs == set(["x", "print"])
assert v.variable_data == {
- "foo": VariableData(kind="function", required_refs={"x", "print"}),
+ "foo": [VariableData(kind="function", required_refs={"x", "print"})],
}
@@ -482,7 +485,7 @@ def test_call_defined() -> None:
assert v.defs == set(["foo"])
assert v.refs == set()
assert v.variable_data == {
- "foo": VariableData(kind="function"),
+ "foo": [VariableData(kind="function")],
}
@@ -494,7 +497,7 @@ def test_mutation_generates_def() -> None:
assert v.defs == set(["x"])
assert v.refs == set()
assert v.variable_data == {
- "x": VariableData(kind="variable"),
+ "x": [VariableData(kind="variable")],
}
@@ -594,12 +597,12 @@ def test_matchas() -> None:
assert v.defs == set(["a", "b", "c", "d", "e", "f"])
assert v.refs == set(["value"])
assert v.variable_data == {
- "a": VariableData(kind="variable"),
- "b": VariableData(kind="variable"),
- "c": VariableData(kind="variable"),
- "d": VariableData(kind="variable"),
- "e": VariableData(kind="variable"),
- "f": VariableData(kind="variable"),
+ "a": [VariableData(kind="variable")],
+ "b": [VariableData(kind="variable")],
+ "c": [VariableData(kind="variable")],
+ "d": [VariableData(kind="variable")],
+ "e": [VariableData(kind="variable")],
+ "f": [VariableData(kind="variable")],
}
@@ -620,7 +623,7 @@ def test_matchstar() -> None:
assert v.defs == set(["rest"])
assert v.refs == set(["value"])
assert v.variable_data == {
- "rest": VariableData(kind="variable"),
+ "rest": [VariableData(kind="variable")],
}
@@ -643,8 +646,8 @@ def test_matchmapping() -> None:
assert v.defs == set(["a", "b"])
assert v.refs == set(["value"])
assert v.variable_data == {
- "a": VariableData(kind="variable"),
- "b": VariableData(kind="variable"),
+ "a": [VariableData(kind="variable")],
+ "b": [VariableData(kind="variable")],
}
@@ -655,10 +658,14 @@ def test_import_nested() -> None:
v.visit(mod)
assert v.defs == set(["a"])
assert v.refs == set()
- assert v.variable_data["a"] == VariableData(
- kind="import",
- import_data=ImportData(module="a.b.c", imported_symbol=None),
- )
+ assert v.variable_data["a"] == [
+ VariableData(
+ kind="import",
+ import_data=ImportData(
+ definition="a", module="a.b.c", imported_symbol=None
+ ),
+ )
+ ]
def test_import_as() -> None:
@@ -668,10 +675,14 @@ def test_import_as() -> None:
v.visit(mod)
assert v.defs == set(["d"])
assert v.refs == set()
- assert v.variable_data["d"] == VariableData(
- kind="import",
- import_data=ImportData(module="a.b.c", imported_symbol=None),
- )
+ assert v.variable_data["d"] == [
+ VariableData(
+ kind="import",
+ import_data=ImportData(
+ definition="d", module="a.b.c", imported_symbol=None
+ ),
+ )
+ ]
def test_import_multiple() -> None:
@@ -681,13 +692,22 @@ def test_import_multiple() -> None:
v.visit(mod)
assert v.defs == set(["a", "d"])
assert v.refs == set()
- assert v.variable_data["a"] == VariableData(
- kind="import",
- import_data=ImportData(module="a.b.c", imported_symbol=None),
- )
- assert v.variable_data["d"] == VariableData(
- kind="import", import_data=ImportData(module="d", imported_symbol=None)
- )
+ assert v.variable_data["a"] == [
+ VariableData(
+ kind="import",
+ import_data=ImportData(
+ definition="a", module="a.b.c", imported_symbol=None
+ ),
+ )
+ ]
+ assert v.variable_data["d"] == [
+ VariableData(
+ kind="import",
+ import_data=ImportData(
+ definition="d", module="d", imported_symbol=None
+ ),
+ )
+ ]
def test_from_import() -> None:
@@ -697,12 +717,17 @@ def test_from_import() -> None:
v.visit(mod)
assert v.defs == set(["d"])
assert v.refs == set()
- assert v.variable_data["d"] == VariableData(
- kind="import",
- import_data=ImportData(
- module="a.b.c", imported_symbol="a.b.c.d", import_level=0
- ),
- )
+ assert v.variable_data["d"] == [
+ VariableData(
+ kind="import",
+ import_data=ImportData(
+ definition="d",
+ module="a.b.c",
+ imported_symbol="a.b.c.d",
+ import_level=0,
+ ),
+ )
+ ]
def test_relative_from_import() -> None:
@@ -712,12 +737,17 @@ def test_relative_from_import() -> None:
v.visit(mod)
assert v.defs == set(["d"])
assert v.refs == set()
- assert v.variable_data["d"] == VariableData(
- kind="import",
- import_data=ImportData(
- module="a.b.c", imported_symbol="a.b.c.d", import_level=2
- ),
- )
+ assert v.variable_data["d"] == [
+ VariableData(
+ kind="import",
+ import_data=ImportData(
+ definition="d",
+ module="a.b.c",
+ imported_symbol="a.b.c.d",
+ import_level=2,
+ ),
+ )
+ ]
def test_from_import_star() -> None:
@@ -857,11 +887,11 @@ def test_private_ref_requirement_caught() -> None:
assert private.endswith("_x")
assert v.refs == set(["X"])
assert v.variable_data == {
- private: VariableData(kind="variable"),
- "x": VariableData(kind="variable"),
- "foo": VariableData(
- kind="function", required_refs={"X", "x", private}
- ),
+ private: [VariableData(kind="variable")],
+ "x": [VariableData(kind="variable")],
+ "foo": [
+ VariableData(kind="function", required_refs={"X", "x", private})
+ ],
}
diff --git a/tests/_runtime/reload/test_module_watcher.py b/tests/_runtime/reload/test_module_watcher.py
index 3d9d0e6e72..9f5b1e7adc 100644
--- a/tests/_runtime/reload/test_module_watcher.py
+++ b/tests/_runtime/reload/test_module_watcher.py
@@ -447,3 +447,79 @@ async def test_reload_with_modified_cell(
# modify the first cell and make sure it is still marked as stale;
k._maybe_register_cell(er_1.cell_id, f"from {py_modname} import foo; 1")
assert er_1.cell_id in k.graph.get_stale()
+
+
+ True,
+ reason=(
+ "watcher sometimes takes a long time to pick up file change to "
+ "an import block on CI"
+ ),
+ strict=False,
+)
+async def test_reload_function_in_import_block(
+ tmp_path: pathlib.Path,
+ py_modname: str,
+ execution_kernel: Kernel,
+ exec_req: ExecReqProvider,
+):
+ k = execution_kernel
+ sys.path.append(str(tmp_path))
+ py_file = tmp_path / pathlib.Path(py_modname + ".py")
+ py_file.write_text(
+ textwrap.dedent(
+ """
+ def foo():
+ return 1
+ """
+ )
+ )
+
+ config = copy.deepcopy(DEFAULT_CONFIG)
+ config["runtime"]["auto_reload"] = "lazy"
+ k.set_user_config(SetUserConfigRequest(config=config))
+ await k.run(
+ [
+ # We will modify py_modname but not "random" ...
+ er_1 := exec_req.get(
+ f"import random; from {py_modname} import foo"
+ ),
+ er_2 := exec_req.get("x = foo()"),
+ er_3 := exec_req.get("pass"),
+ er_4 := exec_req.get("y = random.randint(0, 10000000)"),
+ er_5 := exec_req.get("random, foo"),
+ ]
+ )
+ assert k.globals["x"] == 1
+ y = k.globals["y"]
+
+ update_file(
+ py_file,
+ """
+ def foo():
+ return 2
+ """,
+ )
+
+ # wait for the watcher to pick up the change
+ elapsed = 0
+ while elapsed < 10:
+ await asyncio.sleep(1)
+ elapsed += 1
+ if k.graph.cells[er_1.cell_id].stale:
+ break
+
+ assert k.graph.cells[er_1.cell_id].stale
+ assert k.graph.cells[er_2.cell_id].stale
+ assert not k.graph.cells[er_3.cell_id].stale
+ # "random" wasn't modified, so it should be pruned from descendants
+ assert not k.graph.cells[er_4.cell_id].stale
+ # er_5 depends on random and foo, and foo is stale
+ assert k.graph.cells[er_5.cell_id].stale
+
+ await k.run_stale_cells()
+ assert not k.graph.cells[er_1.cell_id].stale
+ assert not k.graph.cells[er_2.cell_id].stale
+ assert not k.graph.cells[er_3.cell_id].stale
+ assert k.globals["x"] == 2
+ assert k.globals["y"] == y
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index fbb8375503..7b64360328 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -1229,8 +1229,10 @@ class TestStrictExecution:
assert not k.errors
@staticmethod
- async def test_runtime_resolution_failure(strict_kernel: Kernel) -> None:
+ async def test_runtime_failure(strict_kernel: Kernel) -> None:
k = strict_kernel
+ # We keep variable data for reassignments, so static analysis should
+ # succeed
await k.run(
[
ExecutionRequest(
@@ -1240,7 +1242,7 @@ class TestStrictExecution:
X = 1
Y = 2
l = lambda x: x + X
- L = l # Static analysis can fail on reassignment
+ L = l
l = lambda x: x + Y
"""
),
@@ -1249,32 +1251,22 @@ class TestStrictExecution:
cell_id="1",
code=textwrap.dedent(
"""
- try:
- x = L(1)
- except NameError as e:
- E = e
- raise E
+ x = L(1)
"""
),
),
]
)
- # 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]
+ assert "x" in k.globals
+ assert k.globals["x"] == 2
@staticmethod
- async def test_runtime_resolution_failure_private(
+ async def test_runtime_resolution_private(
strict_kernel: Kernel,
) -> None:
k = strict_kernel
+ # We keep variable data for reassignments, so static analysis should
+ # succeed
await k.run(
[
ExecutionRequest(
@@ -1284,7 +1276,7 @@ class TestStrictExecution:
_X = 1
Y = 2
l = lambda x: x + _X
- L = l # Static analysis can fail on reassignment
+ L = l
l = lambda x: x + Y
"""
),
@@ -1294,20 +1286,101 @@ class TestStrictExecution:
code=textwrap.dedent(
"""
x = L(1)
- x
"""
),
),
]
)
- # Runtime error expected- since not a kernel error check stderr
+ assert "x" in k.globals
+ assert k.globals["x"] == 2
+
+
+class TestImports:
+ async def test_import_triggers_execution(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run([exec_req.get("random; x = 0")])
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"]
+ await k.run([exec_req.get("import random")])
+ assert k.globals["x"] == 0
+
+ async def test_reimport_doesnt_trigger_execution(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run([er := exec_req.get("import random")])
+
+ await k.run([exec_req.get("x = random.randint(0, 100000)")])
+ x = k.globals["x"]
+
+ # re-running an import shouldn't retrigger execution
+ await k.run([er])
+ assert k.globals["x"] == x
+
+ async def test_incremental_import_doesnt_trigger_execution(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run([er := exec_req.get("import random")])
+
+ await k.run([exec_req.get("x = random.randint(0, 100000)")])
+ x = k.globals["x"]
+
+ # adding another import to the cell shouldn't rerun dependents
+ # of already imported modules
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id=er.cell_id, code="import random; import time"
+ )
+ ]
+ )
+ assert k.globals["x"] == x
+
+ async def test_transition_out_of_error_triggers_run(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get("import random"),
+ er := exec_req.get("import random"),
+ exec_req.get("random; x = 0"),
+ ]
+ )
+ assert "x" not in k.globals
+
+ await k.delete(DeleteCellRequest(cell_id=er.cell_id))
+ assert "x" in k.globals
+
+ async def test_different_import_same_def(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run([er := exec_req.get("import random")])
+
+ await k.run([exec_req.get("x = random.randint(0, 100000)")])
+ assert "x" in k.globals
+
+ # er.cell_id is still an import block, still defines random,
+ # but brings random from another place; descendant should run
+ await k.run(
+ [ExecutionRequest(er.cell_id, code="from random import random")]
)
- assert "NameError" in k.stderr.messages[-1]
+ assert "random" in k.globals
+ # randint is on toplevel random, not random.random
+ assert "x" not in k.globals
+
+ async def test_after_import_error(
+ self, k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ er := exec_req.get("import time; import fake_module"),
+ exec_req.get("time; x = 1"),
+ ]
+ )
+ assert "x" not in k.globals
+
+ await k.run([ExecutionRequest(er.cell_id, code="import time")])
+ assert k.globals["x"] == 1
class TestStoredOutput:
@@ -1721,7 +1794,7 @@ class TestDisable:
)
assert not k.graph.cells[er_1.cell_id].config.disabled
assert not k.graph.cells[er_2.cell_id].disabled_transitively
- assert k.graph.cells[er_2.cell_id].status == "idle"
+ assert k.graph.cells[er_2.cell_id].runtime_state == "idle"
class TestAsyncIO:
@@ -2077,8 +2150,8 @@ class TestStateTransitions:
n_idle = sum([1 for op in cell_ops if op.status == "idle"])
assert n_idle == 2
- assert k.graph.cells[er_1.cell_id].status == "idle"
- assert k.graph.cells[er_2.cell_id].status == "idle"
+ assert k.graph.cells[er_1.cell_id].runtime_state == "idle"
+ assert k.graph.cells[er_2.cell_id].runtime_state == "idle"
async def test_descendant_status_reset_to_idle_on_interrupt(
self, mocked_kernel: MockedKernel, exec_req: ExecReqProvider
@@ -2116,5 +2189,5 @@ class TestStateTransitions:
n_idle = sum([1 for op in cell_ops if op.status == "idle"])
assert n_idle == 2
- assert k.graph.cells[er_1.cell_id].status == "idle"
- assert k.graph.cells[er_2.cell_id].status == "idle"
+ assert k.graph.cells[er_1.cell_id].runtime_state == "idle"
+ assert k.graph.cells[er_2.cell_id].runtime_state == "idle"
diff --git a/tests/_server/session/test_session_view.py b/tests/_server/session/test_session_view.py
index 62c5350e35..ce16f5a134 100644
--- a/tests/_server/session/test_session_view.py
+++ b/tests/_server/session/test_session_view.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from typing import Any
from unittest.mock import patch
-from marimo._ast.cell import CellId_t, CellStatusType
+from marimo._ast.cell import CellId_t, RuntimeStateType
from marimo._data.models import DataTable, DataTableColumn
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.ops import (
@@ -38,8 +38,8 @@ updated_output = CellOutput(
mimetype="text/plain",
)
-initial_status: CellStatusType = "running"
-updated_status: CellStatusType = "running"
+initial_status: RuntimeStateType = "running"
+updated_status: RuntimeStateType = "running"
def test_session_view_cell_op() -> None: