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.

Strict Execution (#1580)

Dylan Madisetti046b9c7ef00a
diff --git a/frontend/src/components/editor/output/MarimoErrorOutput.tsx b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
index c49fe49a9c..475f8d112d 100644
--- a/frontend/src/components/editor/output/MarimoErrorOutput.tsx
+++ b/frontend/src/components/editor/output/MarimoErrorOutput.tsx
@@ -139,6 +139,39 @@ export const MarimoErrorOutput = ({
</Tip>
</div>
);
+ case "strict-exception":
+ return error.blamed_cell == null ? (
+ <Fragment key={idx}>
+ <p>{error.msg}</p>
+ <Tip>
+ Something is wrong with your declaration of `{error.ref}`. Fix any
+ discrepancies, or turn off strict execution.
+ </Tip>
+ </Fragment>
+ ) : (
+ <div key={idx}>
+ {error.msg}
+ <CellLinkError cellId={error.blamed_cell} />
+ <Tip>
+ Ensure that&nbsp;
+ <CellLinkError cellId={error.blamed_cell} />
+ &nbsp;defines the variable {error.ref}, or turn off strict
+ execution.
+ </Tip>
+ </div>
+ );
+ case "ancestor-prevented":
+ titleContents = "Ancestor prevented from running";
+ alertVariant = "default";
+ textColor = "text-secondary-foreground";
+ return (
+ <div key={idx}>
+ {error.msg}
+ (<CellLinkError cellId={error.raising_cell} />
+ &nbsp;blames&nbsp;
+ <CellLinkError cellId={error.blamed_cell} />)
+ </div>
+ );
case "ancestor-stopped":
titleContents = "Ancestor stopped";
alertVariant = "default";
diff --git a/frontend/src/core/cells/cell.ts b/frontend/src/core/cells/cell.ts
index e047a0969a..b074b7ef24 100644
--- a/frontend/src/core/cells/cell.ts
+++ b/frontend/src/core/cells/cell.ts
@@ -75,7 +75,7 @@ export function transitionCell(
nextCell.interrupted = true;
didInterruptFromThisMessage = true;
} else if (
- message.output.data.some((error) => error.type === "ancestor-stopped")
+ message.output.data.some((error) => error.type.includes("ancestor"))
) {
// The cell didn't run, but it was intentional, so don't count as
// errored.
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index ef09f8127c..ac2e9c00ad 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -756,7 +756,7 @@ const cellErrorsAtom = atom((get) => {
// These are errors that are caused by a cell that was stopped,
// but nothing the user can take action on.
const nonAncestorErrors = cell.output.data.filter(
- (error) => error.type !== "ancestor-stopped",
+ (error) => !error.type.includes("ancestor"),
);
if (nonAncestorErrors.length > 0) {
diff --git a/frontend/src/core/kernel/messages.ts b/frontend/src/core/kernel/messages.ts
index e2610872e8..11393744ae 100644
--- a/frontend/src/core/kernel/messages.ts
+++ b/frontend/src/core/kernel/messages.ts
@@ -52,10 +52,22 @@ export type MarimoError =
msg: string;
raising_cell?: CellId;
}
+ | {
+ type: "ancestor-prevented";
+ msg: string;
+ raising_cell: CellId;
+ blamed_cell: CellId;
+ }
| { type: "ancestor-stopped"; msg: string; raising_cell: CellId }
| { type: "cycle"; edges_with_vars: Array<[CellId, string[], CellId]> }
| { type: "multiple-defs"; name: string; cells: CellId[] }
| { type: "delete-nonlocal"; name: string; cells: CellId[] }
+ | {
+ type: "strict-exception";
+ msg: string;
+ ref: string;
+ blamed_cell: CellId;
+ }
| { type: "unknown"; msg?: string };
export type OutputMessage =
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 394b5e3e5d..afb324c4f0 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -20,8 +20,6 @@ from marimo._ast.cell import (
Cell,
CellConfig,
CellId_t,
- execute_cell,
- execute_cell_async,
)
from marimo._ast.compiler import cell_factory
from marimo._ast.errors import (
@@ -36,6 +34,10 @@ from marimo._messaging.mimetypes import KnownMimeType
from marimo._messaging.types import NoopStream
from marimo._output.rich_help import mddoc
from marimo._runtime import dataflow
+from marimo._runtime.executor import (
+ execute_cell,
+ execute_cell_async,
+)
from marimo._runtime.patches import patch_main_module_context
if TYPE_CHECKING:
@@ -272,7 +274,7 @@ class App:
self._execution_context = ExecutionContext(
cell_id=cid, setting_element_value=False
)
- outputs[cid] = execute_cell(cell._cell, glbls)
+ outputs[cid] = execute_cell(cell._cell, glbls, self._graph)
for hook in post_execute_hooks:
hook()
return self._outputs_and_defs(outputs, glbls)
@@ -294,7 +296,9 @@ class App:
self._execution_context = ExecutionContext(
cell_id=cid, setting_element_value=False
)
- outputs[cid] = await execute_cell_async(cell._cell, glbls)
+ outputs[cid] = await execute_cell_async(
+ cell._cell, glbls, self._graph
+ )
for hook in post_execute_hooks:
hook()
self._execution_context = None
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index 898085b6ff..5a3d50d964 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -434,27 +434,3 @@ class Cell:
def is_ws(char: str) -> bool:
return char == " " or char == "\n" or char == "\t"
-
-
-async def execute_cell_async(cell: CellImpl, glbls: dict[Any, Any]) -> 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)
-
-
-def execute_cell(cell: CellImpl, glbls: dict[Any, Any]) -> 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)
diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.py
index e944eb543b..40699ab654 100644
--- a/marimo/_ast/compiler.py
+++ b/marimo/_ast/compiler.py
@@ -18,8 +18,9 @@ from marimo._ast.cell import (
CellId_t,
CellImpl,
)
-from marimo._ast.visitor import ScopedVisitor, is_local
+from marimo._ast.visitor import ScopedVisitor
from marimo._utils.tmpdir import get_tmpdir
+from marimo._utils.variables import is_local
if TYPE_CHECKING:
from collections.abc import Iterator
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index 03a86eec35..70e1eaf87c 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -7,6 +7,8 @@ from dataclasses import dataclass, field
from typing import Literal, Optional
from uuid import uuid4
+from marimo._utils.variables import is_local
+
Name = str
@@ -29,14 +31,22 @@ class ImportData:
class VariableData:
kind: Literal["function", "class", "import", "variable"] = "variable"
+ # If kind == function or class, it may be dependent on externally defined
+ # variables.
+ #
+ # NB: This is populated by `ScopedVisitor.ref_stack`. Ref stack holds the
+ # references required for the current context, it's more general than a
+ # "block", since it covers all variable level interactions.
+ # e.g.
+ # >> x = foo + bar
+ # x has the required refs foo and bar, and ref_stack holds that context
+ # while traversing the tree.
+ required_refs: set[Name] = field(default_factory=set)
+
# For kind == import
import_data: Optional[ImportData] = None
-def is_local(name: str) -> bool:
- return name.startswith("_") and not name.startswith("__")
-
-
@dataclass
class Block:
"""A scope in which names are declared."""
@@ -64,7 +74,7 @@ class ObscuredScope:
@dataclass
class RefData:
- """Metadata about variables referenced but not defined by a cell"""
+ """Metadata about variables referenced but not defined by a cell."""
# Whether the ref was deleted
deleted: bool
@@ -75,6 +85,8 @@ class RefData:
class ScopedVisitor(ast.NodeVisitor):
def __init__(self, mangle_prefix: Optional[str] = None) -> None:
self.block_stack: list[Block] = [Block()]
+ # Names to be loaded into a variable required_refs
+ self.ref_stack: list[set[Name]] = [set()]
self.obscured_scope_stack: list[ObscuredScope] = []
# Mapping from referenced names to their metadata
self._refs: dict[Name, RefData] = {}
@@ -152,6 +164,7 @@ class ScopedVisitor(ast.NodeVisitor):
deleted=deleted,
parent_blocks=self.block_stack[:-1],
)
+ self.ref_stack[-1].add(name)
def _remove_ref(self, name: Name) -> None:
"""Remove a referenced name."""
@@ -281,20 +294,53 @@ class ScopedVisitor(ast.NodeVisitor):
# Other nodes that don't introduce a new scope
super().generic_visit(node)
+ def _visit_and_get_refs(self, node: ast.AST) -> set[Name]:
+ """Create a ref scope for the variable to be declared (e.g. function,
+ class), visit the children the node, propagate the refs to the higher
+ scope and then return the refs."""
+ self.ref_stack.append(set())
+ self.generic_visit(node)
+ refs = self.ref_stack.pop()
+ # The scope a level up from the one just investigated also is dependent
+ # on these refs. Consider the case:
+ # >> def foo():
+ # >> def bar(): <- current scope
+ # >> print(x)
+ #
+ # the variable `foo` needs to be aware that it may require the ref `x`
+ # during execution.
+ self.ref_stack[-1].update(refs)
+ return refs
+
# ClassDef and FunctionDef nodes don't have ast.Name nodes as children
def visit_ClassDef(self, node: ast.ClassDef) -> None:
node.name = self._if_local_then_mangle(node.name)
- self._define(node.name, VariableData(kind="class"))
- self.generic_visit(node)
+ refs = self._visit_and_get_refs(node)
+ self._define(
+ node.name,
+ VariableData(kind="class", required_refs=refs),
+ )
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
node.name = self._if_local_then_mangle(node.name)
- self._define(node.name, VariableData(kind="function"))
- self.generic_visit(node)
+ refs = self._visit_and_get_refs(node)
+ self._define(
+ node.name,
+ VariableData(kind="function", required_refs=refs),
+ )
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
node.name = self._if_local_then_mangle(node.name)
- self._define(node.name, VariableData(kind="function"))
+ refs = self._visit_and_get_refs(node)
+ self._define(
+ node.name,
+ VariableData(kind="function", required_refs=refs),
+ )
+
+ def visit_Lambda(self, node: ast.Lambda) -> None:
+ # Inject the dummy name `_lambda` into ref scope to denote there's a
+ # callable that might require additional refs.
+ self.ref_stack[-1].add("_lambda")
self.generic_visit(node)
def visit_arg(self, node: ast.arg) -> None:
@@ -333,19 +379,32 @@ class ScopedVisitor(ast.NodeVisitor):
# x = x
#
# Handling value first is required to register `x` as a ref.
+ self.ref_stack.append(set())
self.visit(node.value)
for target in node.targets:
self.visit(target)
+ refs = self.ref_stack.pop()
+ self.ref_stack[-1].update(refs)
def visit_AugAssign(self, node: ast.AugAssign) -> None:
+ # Augmented assign (has op)
+ # e.g., x += 1
+ self.ref_stack.append(set())
self.visit(node.value)
self.visit(node.target)
+ refs = self.ref_stack.pop()
+ self.ref_stack[-1].update(refs)
def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
+ # Annotated assign
+ # e.g., x: int = 0
+ self.ref_stack.append(set())
if node.value is not None:
self.visit(node.value)
self.visit(node.annotation)
self.visit(node.target)
+ refs = self.ref_stack.pop()
+ self.ref_stack[-1].update(refs)
def visit_NamedExpr(self, node: ast.NamedExpr) -> None:
self.visit(node.value)
@@ -397,7 +456,12 @@ class ScopedVisitor(ast.NodeVisitor):
if isinstance(node.ctx, ast.Store):
node.id = self._if_local_then_mangle(node.id)
- self._define(node.id, VariableData(kind="variable"))
+ self._define(
+ node.id,
+ VariableData(
+ kind="variable", required_refs=self.ref_stack[-1]
+ ),
+ )
elif (
isinstance(node.ctx, ast.Load)
and not self._is_defined(node.id)
@@ -422,6 +486,19 @@ class ScopedVisitor(ast.NodeVisitor):
elif block.is_defined(node.id):
break
+ # Handle refs on the block scope level, or capture cell level
+ # references.
+ if (
+ isinstance(node.ctx, ast.Load)
+ and self._is_defined(node.id)
+ and node.id not in self.ref_stack[-1]
+ and (
+ node.id not in self.block_stack[-1].defs
+ or len(self.block_stack) == 1
+ )
+ ):
+ self.ref_stack[-1].add(node.id)
+
self.generic_visit(node)
def visit_Global(self, node: ast.Global) -> None:
@@ -431,6 +508,7 @@ class ScopedVisitor(ast.NodeVisitor):
]
for name in node.names:
self.block_stack[-1].global_names.add(name)
+ self._add_ref(name, deleted=False)
def visit_Import(self, node: ast.Import) -> None:
for alias_node in node.names:
@@ -475,7 +553,10 @@ class ScopedVisitor(ast.NodeVisitor):
def visit_MatchAs(self, node: ast.MatchAs) -> None:
if node.name is not None:
node.name = self._if_local_then_mangle(node.name)
- self._define(node.name, VariableData(kind="variable"))
+ self._define(
+ node.name,
+ VariableData(kind="variable"),
+ )
if node.pattern is not None:
# pattern may contain additional MatchAs statements in it
self.visit(node.pattern)
@@ -483,7 +564,10 @@ class ScopedVisitor(ast.NodeVisitor):
def visit_MatchMapping(self, node: ast.MatchMapping) -> None:
if node.rest is not None:
node.rest = self._if_local_then_mangle(node.rest)
- self._define(node.rest, VariableData(kind="variable"))
+ self._define(
+ node.rest,
+ VariableData(kind="variable"),
+ )
for key in node.keys:
self.visit(key)
for pattern in node.patterns:
@@ -492,13 +576,21 @@ class ScopedVisitor(ast.NodeVisitor):
def visit_MatchStar(self, node: ast.MatchStar) -> None:
if node.name is not None:
node.name = self._if_local_then_mangle(node.name)
- self._define(node.name, VariableData(kind="variable"))
+ self._define(
+ node.name,
+ VariableData(kind="variable"),
+ )
if sys.version_info >= (3, 12):
def visit_TypeVar(self, node: ast.TypeVar) -> None:
# node.name is a str, not an ast.Name node
- self._define(node.name, VariableData(kind="variable"))
+ self._define(
+ node.name,
+ VariableData(
+ kind="variable", required_refs=self.ref_stack[-1]
+ ),
+ )
if isinstance(node.bound, tuple):
for name in node.bound:
self.visit(name)
@@ -507,8 +599,18 @@ class ScopedVisitor(ast.NodeVisitor):
def visit_ParamSpec(self, node: ast.ParamSpec) -> None:
# node.name is a str, not an ast.Name node
- self._define(node.name, VariableData(kind="variable"))
+ self._define(
+ node.name,
+ VariableData(
+ kind="variable", required_refs=self.ref_stack[-1]
+ ),
+ )
def visit_TypeVarTuple(self, node: ast.TypeVarTuple) -> None:
# node.name is a str, not an ast.Name node
- self._define(node.name, VariableData(kind="variable"))
+ self._define(
+ node.name,
+ VariableData(
+ kind="variable", required_refs=self.ref_stack[-1]
+ ),
+ )
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 35a036f57a..21cf2af1f5 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -67,6 +67,7 @@ class KeymapConfig(TypedDict, total=False):
OnCellChangeType = Literal["lazy", "autorun"]
+ExecutionType = Literal["relaxed", "strict"]
@mddoc
@@ -86,6 +87,9 @@ class RuntimeConfig(TypedDict):
- `on_cell_change`: if `lazy`, cells will be marked stale when their
ancestors run but won't autorun; if `autorun`, cells will automatically
run when their ancestors run.
+ - `execution_type`: if `relaxed`, marimo will not clone cell declarations;
+ if `strict` marimo will clone cell declarations by default, avoiding
+ hidden potential state build up.
"""
auto_instantiate: bool
diff --git a/marimo/_messaging/errors.py b/marimo/_messaging/errors.py
index fd5bb3200f..5711fc8c4a 100644
--- a/marimo/_messaging/errors.py
+++ b/marimo/_messaging/errors.py
@@ -33,6 +33,14 @@ class MarimoInterruptionError:
type: str = "interruption"
+@dataclass
+class MarimoAncestorPreventedError:
+ msg: str
+ raising_cell: CellId_t
+ blamed_cell: CellId_t
+ type: str = "ancestor-prevented"
+
+
@dataclass
class MarimoAncestorStoppedError:
msg: str
@@ -61,12 +69,22 @@ class UnknownError:
type: str = "unknown"
+@dataclass
+class MarimoStrictExecutionError:
+ msg: str
+ ref: str
+ blamed_cell: CellId_t
+ type: str = "strict-exception"
+
+
Error = Union[
CycleError,
MultipleDefinitionError,
DeleteNonlocalError,
MarimoAncestorStoppedError,
+ MarimoAncestorPreventedError,
MarimoExceptionRaisedError,
+ MarimoStrictExecutionError,
MarimoInterruptionError,
MarimoSyntaxError,
UnknownError,
diff --git a/marimo/_runtime/copy.py b/marimo/_runtime/copy.py
new file mode 100644
index 0000000000..f920b90138
--- /dev/null
+++ b/marimo/_runtime/copy.py
@@ -0,0 +1,177 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import inspect
+import sys
+import weakref
+from copy import copy
+from typing import (
+ Any,
+ Callable,
+ Generic,
+ Type,
+ TypeVar,
+ Union,
+ cast,
+)
+
+T = TypeVar("T")
+if sys.version_info < (3, 9):
+ # Future does not seem to work for this in CI.
+ Ref = Union["weakref.ReferenceType[T]", Callable[[], T]]
+else:
+ Ref = Union[weakref.ReferenceType[T], Callable[[], T]]
+
+
+class CloneError(Exception):
+ """Thrown when strict execution fail to deep copy or clone."""
+
+
+class ReadOnlyError(Exception):
+ """Thrown when attempting to modify a read-only object."""
+
+
+class _Copy(Generic[T]):
+ """Base wrapper class for strict execution."""
+
+ __ref__: Ref[T]
+
+
+class ZeroCopy(_Copy[T]):
+ """Wrapper class for strict execution (stops deepcopy)."""
+
+
+class ShallowCopy(_Copy[T]):
+ """Wrapper class for strict execution (does copy over deepcopy)."""
+
+
+def _ro_fail() -> None:
+ raise ReadOnlyError(
+ "Weakly copied objects are directly read only."
+ " Modification is not encouraged, but is"
+ " possible by utilizing the marimo.unwrap_copy() function."
+ )
+
+
+def shadow_wrap(ref_cls: Type[_Copy[T]], base: T) -> T:
+ """
+ Wraps the base object by copying all attributes over to slots, and the then
+ restricting write access to the object attributes / items directly. This is
+ very agrressive and makes the wrapped object difficult to tell apart from
+ the base object without inspect.
+
+ However, there are some limitations, e.g. some operations of the wrapped
+ object may not be associative if they are not defined for both the left
+ and right operations. For instance:
+
+ >>> a = shadow_wrap(ZeroCopy, [1, 2, 3])
+ >>> b = [4, 5, 6]
+ >>> a + b
+ [1, 2, 3, 4, 5, 6]
+
+ will work, but:
+
+ >>> b + a
+
+ will not work, as the `__add__` method is not defined for custom objects in
+ the right operand. However, The original wrapped object can still be
+ accessed with unwrap_copy(). The internal class is named as a hint for this
+ reason, although most times this will be invisible.
+ """
+
+ # Apply attributes as slots reflection, but remove the attributes that are
+ # set explicitly by the wrapper class (or not allowed like __dict__).
+ slots = set(dir(base)) - set(
+ [
+ "__new__",
+ "__setattr__",
+ "__setitem__",
+ "__doc__",
+ "__class__",
+ "__dict__",
+ "__module__",
+ "__slots__",
+ "__dir__",
+ "__init__",
+ "__weakref__",
+ "__ref__",
+ ]
+ )
+ # pointer off the class to lock attributes / items.
+ _fixed = [False]
+
+ # Not seeing a non-verbose work around for mypy, as this needs to inherit
+ # from the provided class and not some generic for this to work.
+ class ReadOnly_try_marimo_unwrap_copy(ref_cls): # type: ignore
+ __doc__ = base.__class__.__doc__
+ __slots__ = list(slots)
+ # ensure reference for gc
+ __base = base
+ __class__ = type(
+ base.__class__.__name__, (base.__class__, ref_cls), {}
+ )
+
+ def __init__(self) -> None:
+ """No-op constructor to prevent parent constructor from running."""
+
+ def __setattr__(self, name: str, value: Any) -> None:
+ # Has to be read only as wouldn't actually mutate the underlying
+ # object. Easier to defer and require and an unwrap then trying to
+ # manage it,
+ if _fixed[0]:
+ _ro_fail()
+ super.__setattr__(self, name, value)
+
+ def __setitem__(self, name: str, value: Any) -> None:
+ _ro_fail()
+
+ def __new__(cls) -> ReadOnly_try_marimo_unwrap_copy:
+ instance = ref_cls.__new__(cls)
+ for n, m in inspect.getmembers(base):
+ if n != "__weakref__":
+ setattr(instance, n, m)
+ # Not a weak ref, but reasonable fallback
+ ref: Ref[T] = lambda: base # noqa: E731
+ if hasattr(base, "__weakref__"):
+ maybe_ref = weakref.ref(base)
+ if maybe_ref is not None:
+ ref = maybe_ref
+ instance.__ref__ = ref
+ _fixed[0] = True
+ return instance
+
+ return cast(T, ReadOnly_try_marimo_unwrap_copy())
+
+
+def unwrap_copy(base: T) -> T:
+ """
+ Given a ZeroCopy or ShallowCopy object, returns the original object.
+ """
+ for cls in [ZeroCopy, ShallowCopy]:
+ if isinstance(base, cls):
+ # It's pretty hidden, but it's there
+ ref: Ref[T] = super(cls, base).__dict__["__ref__"] # type: ignore
+ return cast(T, ref())
+ return base
+
+
+def zero_copy(base: T) -> T:
+ """
+ Wraps object in a ZeroCopy wrapper to mark the object for no copying /
+ cloning when running in strict execution mode.
+ """
+ if isinstance(base, ShallowCopy):
+ return cast(T, shadow_wrap(ZeroCopy, unwrap_copy(base)))
+ if isinstance(base, ZeroCopy):
+ return cast(T, base)
+ return cast(T, shadow_wrap(ZeroCopy, base))
+
+
+def shallow_copy(base: T) -> T:
+ """
+ Wraps object in a ShallowCopy wrapper to mark the object for "copy" over
+ "deepcopy" when running in strict execution mode.
+ """
+ if isinstance(base, _Copy):
+ return cast(T, shadow_wrap(ShallowCopy, copy(unwrap_copy(base))))
+ return cast(T, shadow_wrap(ShallowCopy, copy(base)))
diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.py
index 8f72bddfe1..8f77afb30b 100644
--- a/marimo/_runtime/dataflow.py
+++ b/marimo/_runtime/dataflow.py
@@ -9,11 +9,11 @@ from marimo import _loggers
from marimo._ast.cell import (
CellId_t,
CellImpl,
- execute_cell,
- execute_cell_async,
)
from marimo._ast.compiler import code_key
-from marimo._ast.visitor import Name
+from marimo._ast.visitor import Name, VariableData
+from marimo._runtime.executor import execute_cell, execute_cell_async
+from marimo._utils.variables import is_mangled_local
if TYPE_CHECKING:
from collections.abc import Collection
@@ -318,6 +318,53 @@ class DirectedGraph:
def get_stale(self) -> set[CellId_t]:
return set([cid for cid, cell in self.cells.items() if cell.stale])
+ def get_transitive_references(
+ self,
+ refs: set[Name],
+ inclusive: bool = True,
+ predicate: Callable[[Name, VariableData], bool] | None = None,
+ ) -> set[Name]:
+ """Return a set of the passed-in cells' references and their
+ references on the block (function / class) level.
+
+ If inclusive, includes the references of the passed-in cells in the
+ set.
+
+ If predicate, only references satisfying predicate(ref) are included
+ """
+ # TODO: Consider caching on the graph level and updating on register /
+ # delete
+ processed = set()
+ queue = set(refs & self.definitions.keys())
+ predicate = predicate or (lambda *_: True)
+
+ while queue:
+ # Should ideally be one cell per ref, but for completion, stay
+ # agnostic to potenital cycles.
+ cells = set().union(*[self.definitions[ref] for ref in queue])
+ for cell_id in cells:
+ data = self.cells[cell_id].variable_data
+ variables = set(data.keys())
+ # intersection of variables and queue
+ newly_processed = variables & queue
+ 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)
+
+ if inclusive:
+ return processed
+ return processed - refs
+
def transitive_closure(
graph: DirectedGraph,
@@ -483,11 +530,11 @@ class Runner:
glbls: dict[str, Any] = {}
for cid in topological_sort(graph, ancestor_ids):
- await execute_cell_async(graph.cells[cid], glbls)
+ await execute_cell_async(graph.cells[cid], glbls, graph)
Runner._substitute_refs(cell_impl, glbls, kwargs)
output = await execute_cell_async(
- graph.cells[cell_impl.cell_id], glbls
+ graph.cells[cell_impl.cell_id], glbls, graph
)
defs = Runner._returns(cell_impl, glbls)
return output, defs
@@ -522,9 +569,9 @@ class Runner:
glbls: dict[str, Any] = {}
for cid in topological_sort(graph, ancestor_ids):
- execute_cell(graph.cells[cid], glbls)
+ execute_cell(graph.cells[cid], glbls, graph)
self._substitute_refs(cell_impl, glbls, kwargs)
- output = execute_cell(graph.cells[cell_impl.cell_id], glbls)
+ output = execute_cell(graph.cells[cell_impl.cell_id], glbls, graph)
defs = Runner._returns(cell_impl, glbls)
return output, defs
diff --git a/marimo/_runtime/executor.py b/marimo/_runtime/executor.py
new file mode 100644
index 0000000000..bbf53bd0b5
--- /dev/null
+++ b/marimo/_runtime/executor.py
@@ -0,0 +1,382 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import inspect
+import numbers
+import re
+import weakref
+from abc import ABC, abstractmethod
+from copy import deepcopy
+from typing import TYPE_CHECKING, Any, Callable, Optional, Type
+
+from marimo._ast.cell import CellImpl, _is_coroutine
+from marimo._runtime.copy import (
+ CloneError,
+ ShallowCopy,
+ ZeroCopy,
+ shallow_copy,
+)
+from marimo._utils.variables import is_mangled_local
+
+if TYPE_CHECKING:
+ from marimo._ast.visitor import Name, VariableData
+ from marimo._runtime.dataflow import DirectedGraph
+
+
+UNCLONABLE_TYPES = [
+ "marimo._runtime.state.State",
+ "marimo._runtime.state.SetFunctor",
+]
+
+UNCLONABLE_MODULES = ["_asyncio", "marimo._ast", "marimo._plugins.ui"]
+PRIMITIVES = (weakref.ref, str, numbers.Number, type(None))
+
+EXECUTION_TYPES: dict[str, Type[Executor]] = {}
+
+
+class MarimoNameError(NameError):
+ """Wrap a name error to rethrow later."""
+
+
+class MarimoMissingRefError(BaseException):
+ def __init__(self, ref: str) -> None:
+ super().__init__(f"Missing reference: {ref}")
+ self.ref = ref
+
+
+def register_execution_type(
+ key: str,
+) -> Callable[[Type[Executor]], Type[Executor]]:
+ # Potentially expose as part of custom kernel API
+ def wrapper(cls: Type[Executor]) -> Type[Executor]:
+ EXECUTION_TYPES[key] = cls
+ return cls
+
+ return wrapper
+
+
+async def execute_cell_async(
+ cell: CellImpl,
+ glbls: dict[str, Any],
+ graph: DirectedGraph,
+ execution_type: str = "relaxed",
+) -> Any:
+ return await EXECUTION_TYPES[execution_type].execute_cell_async(
+ cell, glbls, graph
+ )
+
+
+def execute_cell(
+ cell: CellImpl,
+ glbls: dict[str, Any],
+ graph: DirectedGraph,
+ execution_type: str = "relaxed",
+) -> Any:
+ return EXECUTION_TYPES[execution_type].execute_cell(cell, glbls, graph)
+
+
+class Executor(ABC):
+ @staticmethod
+ @abstractmethod
+ def execute_cell(
+ cell: CellImpl,
+ glbls: dict[str, Any],
+ graph: DirectedGraph,
+ ) -> Any:
+ pass
+
+ @staticmethod
+ @abstractmethod
+ async def execute_cell_async(
+ cell: CellImpl,
+ glbls: dict[str, Any],
+ graph: DirectedGraph,
+ ) -> Any:
+ pass
+
+
+@register_execution_type("relaxed")
+class DefaultExecutor(Executor):
+ @staticmethod
+ async def execute_cell_async(
+ cell: CellImpl,
+ glbls: dict[str, Any],
+ _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)
+
+ @staticmethod
+ def execute_cell(
+ cell: CellImpl,
+ glbls: dict[str, Any],
+ _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)
+
+
+@register_execution_type("strict")
+class StrictExecutor(Executor):
+ @staticmethod
+ async def execute_cell_async(
+ cell: CellImpl, glbls: dict[str, Any], graph: DirectedGraph
+ ) -> Any:
+ # Manage globals and references, but refers to the default beyond that.
+ refs = graph.get_transitive_references(
+ cell.refs, predicate=build_ref_predicate(glbls)
+ )
+ 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
+ finally:
+ # Restore globals from backup and backfill outputs
+ StrictExecutor.update_outputs(cell, glbls, backup)
+ return response
+
+ @staticmethod
+ def execute_cell(
+ cell: CellImpl, glbls: dict[str, Any], graph: DirectedGraph
+ ) -> Any:
+ refs = graph.get_transitive_references(
+ cell.refs, predicate=build_ref_predicate(glbls)
+ )
+ 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
+ finally:
+ StrictExecutor.update_outputs(cell, glbls, backup)
+ return response
+
+ @staticmethod
+ def sanitize_inputs(
+ cell: CellImpl, refs: set[str], glbls: dict[str, Any]
+ ) -> dict[str, Any]:
+ # Some attributes should remain global
+ lcls = {
+ key: glbls[key]
+ for key in [
+ "_MicropipFinder",
+ "_MicropipLoader",
+ "__builtin__",
+ "__doc__",
+ "__file__",
+ "__marimo__",
+ "__name__",
+ "__package__",
+ "__loader__",
+ "__spec__",
+ "input",
+ ]
+ if key in glbls
+ }
+
+ for ref in refs:
+ if ref in glbls:
+ if (
+ isinstance(
+ glbls[ref],
+ (ZeroCopy),
+ )
+ or inspect.ismodule(glbls[ref])
+ or inspect.isfunction(glbls[ref])
+ or from_unclonable_module(glbls[ref])
+ or is_unclonable_type(glbls[ref])
+ ):
+ lcls[ref] = glbls[ref]
+ elif isinstance(glbls[ref], ShallowCopy):
+ lcls[ref] = shallow_copy(glbls[ref])
+ else:
+ try:
+ lcls[ref] = deepcopy(glbls[ref])
+ except TypeError as e:
+ raise CloneError(
+ f"Could not clone reference `{ref}` of type "
+ f"{getattr(glbls[ref], '__module__', '<module>')}."
+ f"{glbls[ref].__class__.__name__}"
+ " try wrapping the object in a `zero_copy`"
+ "call. If this is a common object type, consider "
+ "making an issue on the marimo GitHub "
+ "repository to never deepcopy."
+ ) from e
+ elif ref not in glbls["__builtins__"]:
+ if ref in cell.defs:
+ raise MarimoNameError(
+ f"name `{ref}` is referenced before definition."
+ )
+ raise MarimoMissingRefError(ref)
+
+ # NOTE: Execution expects the globals dictionary by memory reference,
+ # so we need to clear it and update it with the sanitized locals,
+ # returning a backup of the original globals for later restoration.
+ # This must be performed at the end of the function to ensure valid
+ # state in case of failure.
+ backup = {**glbls}
+ glbls.clear()
+ glbls.update(lcls)
+ return backup
+
+ @staticmethod
+ def update_outputs(
+ cell: CellImpl, glbls: dict[str, Any], backup: dict[str, Any]
+ ) -> None:
+ # NOTE: After execution, restore global state and update outputs.
+ lcls = {**glbls}
+ glbls.clear()
+ glbls.update(backup)
+
+ defs = cell.defs
+ for df in defs:
+ if df in lcls:
+ # Overwrite will delete the reference.
+ # Weak copy holds on with references.
+ glbls[df] = lcls[df]
+ # Captures the case where a variable was previously defined by the
+ # cell but this most recent run did not define it. The value is now
+ # stale and needs to be flushed.
+ elif df in glbls:
+ del glbls[df]
+
+ # Flush all private variables from memory
+ for df in backup:
+ if is_mangled_local(df, cell.cell_id):
+ del glbls[df]
+
+ # Now repopulate all private variables.
+ for df in lcls:
+ if is_mangled_local(df, cell.cell_id):
+ glbls[df] = lcls[df]
+
+
+def build_ref_predicate(
+ glbls: dict[str, Any],
+) -> Callable[[Name, VariableData], bool]:
+ """
+ Builds a predicate function to determine if a reference should be included
+
+ Args:
+ glbls: The global variables dictionary to base the predicate on
+ Returns:
+ A function that takes a variable name and associated data and
+ returns True if its reference should be included in a reference search.
+
+ All declared variables are tied together under the graph of required_refs.
+ Strict execution gets the minimum graph of definitions for execution.
+ Certain definitions, like lambdas, functions, and classes contain an
+ executable body and require their `required_refs` to be scope (included in
+ this graph). This function determines if a potential reference should be
+ included in the graph based on its computed type. Consider:
+
+ >>> def foo():
+ ... return bar()
+
+ here `foo` is a function with `bar` as a reference in the execution body,
+ so if `foo` is a reference, both `bar` and `foo` should be included in the
+ graph, otherwise we'll get a NameError on `bar` if `foo` is called.
+ Compare that to:
+
+ >>> x = foo()
+
+ if `x` is the only reference, should `foo` be included in the graph? It
+ depends on the context, so we defer to the type of `x` which has already
+ been computed at this point. If `x` is a known 'primitive' type, and thus
+ does not have an executable body, we can exclude `foo` from the graph.
+ However, `foo` may return a object or another function, which in turn may
+ have references; so if x doesn't match the very low bar 'primitive', its
+ `required_refs` are included in the graph.
+
+ NB: lambdas, as anonymous functions, do not have a name to refer to them-
+ so visitor injects the dummy variable `_lambda` into the `required_refs` to
+ denote their presence.
+ """
+
+ def check_ref(ref: Name) -> bool:
+ return ref in glbls and (
+ inspect.isfunction(glbls[ref])
+ or inspect.ismodule(glbls[ref])
+ or inspect.isclass(glbls[ref])
+ or callable(glbls[ref])
+ )
+
+ def only_scoped_refs(ref: Name, data: VariableData) -> bool:
+ # Weakref instances should be disassociated from related references,
+ # as should other "primitives" as they are results and hopefully not
+ # hiding some scoped reference. Other common types could be added here,
+ # like numpy arrays that are not dtype=object, etc.. that are known not
+ # to be dependent on the functions that created them.
+
+ # This errs on the side of including too much, but that's a better user
+ # experience than not having definitions available.
+ return (
+ ref in glbls
+ and not isinstance(glbls[ref], PRIMITIVES)
+ and (
+ "_lambda" in data.required_refs
+ or any(map(check_ref, data.required_refs | {ref}))
+ )
+ )
+
+ return only_scoped_refs
+
+
+def is_instance_by_name(obj: object, name: str) -> bool:
+ if not (hasattr(obj, "__module__") and hasattr(obj, "__class__")):
+ return False
+ obj_name = f"{obj.__module__}.{obj.__class__.__name__}"
+ return obj_name == name
+
+
+def is_unclonable_type(obj: object) -> bool:
+ return any([is_instance_by_name(obj, name) for name in UNCLONABLE_TYPES])
+
+
+def from_unclonable_module(obj: object) -> bool:
+ obj = obj if hasattr(obj, "__module__") else obj.__class__
+ return hasattr(obj, "__module__") and any(
+ [obj.__module__.startswith(name) for name in UNCLONABLE_MODULES]
+ )
diff --git a/marimo/_runtime/runner/cell_runner.py b/marimo/_runtime/runner/cell_runner.py
index a39ed9a9cc..2a0b0115c5 100644
--- a/marimo/_runtime/runner/cell_runner.py
+++ b/marimo/_runtime/runner/cell_runner.py
@@ -9,19 +9,26 @@ import signal
import threading
import traceback
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional
+from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, Union
from marimo._ast.cell import (
CellId_t,
CellImpl,
- execute_cell,
- execute_cell_async,
)
-from marimo._config.config import OnCellChangeType
+from marimo._config.config import ExecutionType, OnCellChangeType
from marimo._loggers import marimo_logger
+from marimo._messaging.errors import Error, MarimoStrictExecutionError
from marimo._messaging.tracebacks import write_traceback
from marimo._runtime import dataflow
-from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
+from marimo._runtime.control_flow import (
+ MarimoInterrupt,
+ MarimoStopError,
+)
+from marimo._runtime.executor import (
+ MarimoMissingRefError,
+ execute_cell,
+ execute_cell_async,
+)
from marimo._runtime.marimo_pdb import MarimoPdb
LOGGER = marimo_logger()
@@ -38,12 +45,15 @@ def cell_filename(cell_id: CellId_t) -> str:
return f"<cell-{cell_id}>"
+ErrorObjects = Union[BaseException, Error]
+
+
@dataclass
class RunResult:
# Raw output of cell: last expression
output: Any
# Exception raised by cell, if any
- exception: Optional[BaseException]
+ exception: Optional[ErrorObjects]
# Accumulated output: via imperative mo.output.append()
accumulated_output: Any = None
@@ -62,6 +72,7 @@ class Runner:
glbls: dict[Any, Any],
debugger: MarimoPdb | None,
execution_mode: OnCellChangeType = "autorun",
+ execution_type: ExecutionType = "relaxed",
excluded_cells: set[CellId_t] | None = None,
execution_context: Callable[
[CellId_t], contextlib._GeneratorContextManager[ExecutionContext]
@@ -98,6 +109,7 @@ class Runner:
# runtime globals
self.glbls = glbls
self.execution_mode = execution_mode
+ self.execution_type = execution_type
# cells that the runner will run, subtracting out cells with errors:
#
@@ -130,7 +142,7 @@ class Runner:
# whether the runner has been interrupted
self.interrupted = False
# mapping from cell_id to exception it raised
- self.exceptions: dict[CellId_t, BaseException] = {}
+ self.exceptions: dict[CellId_t, ErrorObjects] = {}
# each cell's position in the run queue
self._run_position = {
@@ -288,7 +300,12 @@ class Runner:
try:
if cell.is_coroutine():
return_value_future = asyncio.ensure_future(
- execute_cell_async(cell, self.glbls)
+ execute_cell_async(
+ cell,
+ self.glbls,
+ self.graph,
+ execution_type=self.execution_type,
+ )
)
if threading.current_thread() == threading.main_thread():
# edit mode: need to handle user interrupts
@@ -299,7 +316,12 @@ class Runner:
# by user anyway.
return_value = await return_value_future
else:
- return_value = execute_cell(cell, self.glbls)
+ return_value = execute_cell(
+ cell,
+ self.glbls,
+ self.graph,
+ execution_type=self.execution_type,
+ )
run_result = RunResult(output=return_value, exception=None)
except (MarimoInterrupt, asyncio.exceptions.CancelledError) as e:
# User interrupt
@@ -320,6 +342,24 @@ class Runner:
run_result = RunResult(output=e.output, exception=e)
# don't print a traceback, since quitting is the intended
# behavior (like sys.exit())
+ 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:
+ # This should never happen, but just in case
+ blamed_cell = e.ref
+
+ output = MarimoStrictExecutionError(
+ f"marimo was unable to resolve "
+ f"a reference to `{e.ref}` in cell : ",
+ e.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
diff --git a/marimo/_runtime/runner/hooks_on_finish.py b/marimo/_runtime/runner/hooks_on_finish.py
index 6ab0e6cbab..fcab77359a 100644
--- a/marimo/_runtime/runner/hooks_on_finish.py
+++ b/marimo/_runtime/runner/hooks_on_finish.py
@@ -2,9 +2,11 @@
from marimo import _loggers
from marimo._messaging.errors import (
Error,
+ MarimoAncestorPreventedError,
MarimoAncestorStoppedError,
MarimoExceptionRaisedError,
MarimoInterruptionError,
+ MarimoStrictExecutionError,
)
from marimo._messaging.ops import CellOp
from marimo._runtime.control_flow import MarimoStopError
@@ -45,6 +47,16 @@ def _send_cancellation_errors(runner: cell_runner.Runner) -> None:
),
raising_cell=raising_cell,
)
+ elif isinstance(exception, MarimoStrictExecutionError):
+ data = MarimoAncestorPreventedError(
+ msg=(
+ "This cell wasn't run because an "
+ f"ancestor failed to resolve the "
+ f"reference `{exception.ref}` : "
+ ),
+ raising_cell=raising_cell,
+ blamed_cell=exception.blamed_cell,
+ )
else:
exception_type = type(runner.exceptions[raising_cell]).__name__
data = MarimoExceptionRaisedError(
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
index 47e15510c0..fd544a963b 100644
--- a/marimo/_runtime/runner/hooks_post_execution.py
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -8,6 +8,7 @@ from marimo._messaging.cell_output import CellChannel
from marimo._messaging.errors import (
MarimoExceptionRaisedError,
MarimoInterruptionError,
+ MarimoStrictExecutionError,
)
from marimo._messaging.ops import (
CellOp,
@@ -129,6 +130,15 @@ def _broadcast_outputs(
cell_id=cell.cell_id,
status=cell.status,
)
+ elif isinstance(run_result.exception, MarimoStrictExecutionError):
+ LOGGER.debug("Cell %s raised a strict error", cell.cell_id)
+ # Cell never runs, so clear console
+ CellOp.broadcast_error(
+ data=[run_result.output],
+ clear_console=True,
+ cell_id=cell.cell_id,
+ status=cell.status,
+ )
elif isinstance(run_result.exception, MarimoInterrupt):
LOGGER.debug("Cell %s was interrupted", cell.cell_id)
# don't clear console because this cell was running and
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index ba7ef08222..1190df6df3 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -21,8 +21,8 @@ from uuid import uuid4
from marimo import _loggers
from marimo._ast.cell import CellConfig, CellId_t
from marimo._ast.compiler import compile_cell
-from marimo._ast.visitor import Name, is_local
-from marimo._config.config import MarimoConfig, OnCellChangeType
+from marimo._ast.visitor import 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
from marimo._messaging.errors import Error, MarimoSyntaxError, UnknownError
@@ -111,6 +111,7 @@ from marimo._server.types import QueueType
from marimo._utils.platform import is_pyodide
from marimo._utils.signals import restore_signals
from marimo._utils.typed_connection import TypedConnection
+from marimo._utils.variables import is_local
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
@@ -333,6 +334,9 @@ class Kernel:
self.reactive_execution_mode: OnCellChangeType = user_config[
"runtime"
]["on_cell_change"]
+ self.execution_type: ExecutionType = user_config.get(
+ "experimental", {}
+ ).get("execution_type", "relaxed")
self._update_runtime_from_user_config(user_config)
# Set up the execution context
@@ -632,6 +636,10 @@ class Kernel:
get_context().cell_lifecycle_registry.dispose(
cell_id, deletion=deletion
)
+ for descendent in self.graph.descendants(cell_id):
+ get_context().cell_lifecycle_registry.dispose(
+ descendent, deletion=deletion
+ )
RemoveUIElements(cell_id=cell_id).broadcast()
def _deactivate_cell(self, cell_id: CellId_t) -> set[CellId_t]:
@@ -931,6 +939,7 @@ class Kernel:
excluded_cells=set(self.errors.keys()),
debugger=self.debugger,
execution_mode=self.reactive_execution_mode,
+ execution_type=self.execution_type,
execution_context=self._install_execution_context,
preparation_hooks=PREPARATION_HOOKS + [invalidate_state],
pre_execution_hooks=PRE_EXECUTION_HOOKS,
diff --git a/marimo/_runtime/state.py b/marimo/_runtime/state.py
index 44a12d766e..1fbc6c8f7e 100644
--- a/marimo/_runtime/state.py
+++ b/marimo/_runtime/state.py
@@ -16,14 +16,21 @@ class State(Generic[T]):
def __init__(self, value: T, allow_self_loops: bool = False) -> None:
self._value = value
self.allow_self_loops = allow_self_loops
+ self._set_value = SetFunctor(self)
def __call__(self) -> T:
return self._value
- def _set_value(self, update: T | Callable[[T], T]) -> None:
- """Update the state and register the update with the kernel"""
- self._value = (
- update(self._value)
+
+class SetFunctor(Generic[T]):
+ """Typed function tied to a state instance"""
+
+ def __init__(self, state: State[T]):
+ self._state = state
+
+ def __call__(self, update: T | Callable[[T], T]) -> None:
+ self._state._value = (
+ update(self._state._value)
if isinstance(update, (types.MethodType, types.FunctionType))
else update
)
@@ -31,7 +38,7 @@ class State(Generic[T]):
ctx = get_context()
except ContextNotInitializedError:
return
- ctx.register_state_update(self)
+ ctx.register_state_update(self._state)
@mddoc
diff --git a/marimo/_utils/variables.py b/marimo/_utils/variables.py
new file mode 100644
index 0000000000..c3a2f5ec35
--- /dev/null
+++ b/marimo/_utils/variables.py
@@ -0,0 +1,15 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from marimo._ast.cell import CellId_t
+
+
+def is_mangled_local(name: str, cell_id: CellId_t) -> bool:
+ return name.startswith(f"_cell_{cell_id}")
+
+
+def is_local(name: str) -> bool:
+ return name.startswith("_") and not name.startswith("__")
diff --git a/tests/_ast/test_visitor.py b/tests/_ast/test_visitor.py
index ca8482c226..9754293bcd 100644
--- a/tests/_ast/test_visitor.py
+++ b/tests/_ast/test_visitor.py
@@ -103,7 +103,19 @@ def test_assign_same_name() -> None:
v.visit(mod)
assert v.defs == set(["x"])
assert v.refs == set(["x"])
- assert v.variable_data == {"x": VariableData(kind="variable")}
+ assert v.variable_data == {
+ "x": VariableData(kind="variable", required_refs={"x"})
+ }
+
+ expr = "x=1; x = x"
+ v = visitor.ScopedVisitor()
+ mod = ast.parse(expr)
+ v.visit(mod)
+ assert v.defs == set(["x"])
+ assert v.refs == set()
+ assert v.variable_data == {
+ "x": VariableData(kind="variable", required_refs={"x"})
+ }
expr = "(x := x)"
v = visitor.ScopedVisitor()
@@ -111,7 +123,9 @@ def test_assign_same_name() -> None:
v.visit(mod)
assert v.defs == set(["x"])
assert v.refs == set(["x"])
- assert v.variable_data == {"x": VariableData(kind="variable")}
+ assert v.variable_data == {
+ "x": VariableData(kind="variable", required_refs={"x"})
+ }
expr = "x += x"
v = visitor.ScopedVisitor()
@@ -119,7 +133,9 @@ def test_assign_same_name() -> None:
v.visit(mod)
assert v.defs == set(["x"])
assert v.refs == set(["x"])
- assert v.variable_data == {"x": VariableData(kind="variable")}
+ assert v.variable_data == {
+ "x": VariableData(kind="variable", required_refs={"x"})
+ }
expr = "def f(): x = x; return x"
v = visitor.ScopedVisitor()
@@ -127,7 +143,9 @@ def test_assign_same_name() -> None:
v.visit(mod)
assert v.defs == set(["f"])
assert v.refs == set(["x"])
- assert v.variable_data == {"f": VariableData(kind="function")}
+ assert v.variable_data == {
+ "f": VariableData(kind="function", required_refs={"x"})
+ }
expr = "class F(): x = x"
v = visitor.ScopedVisitor()
@@ -135,7 +153,9 @@ def test_assign_same_name() -> None:
v.visit(mod)
assert v.defs == set(["F"])
assert v.refs == set(["x"])
- assert v.variable_data == {"F": VariableData(kind="class")}
+ assert v.variable_data == {
+ "F": VariableData(kind="class", required_refs={"x"})
+ }
expr = "{x: x}"
v = visitor.ScopedVisitor()
@@ -243,7 +263,7 @@ def test_walrus_leaks_to_global_in_comprehension() -> None:
"b": VariableData(kind="variable"),
"c": VariableData(kind="variable"),
"d": VariableData(kind="variable"),
- "foo": VariableData(kind="function"),
+ "foo": VariableData(kind="function", required_refs={"a"}),
}
@@ -292,7 +312,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"),
+ "f": VariableData(kind="function", required_refs={"range"}),
}
@@ -334,7 +354,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"),
+ "foo": VariableData(kind="function", required_refs={"z"}),
}
@@ -350,8 +370,9 @@ def test_function_with_defaults() -> None:
v.visit(mod)
assert v.defs == set(["foo"])
assert v.refs == set(["x", "y", "a"])
+ # TODO: Are these required refs?
assert v.variable_data == {
- "foo": VariableData(kind="function"),
+ "foo": VariableData(kind="function", required_refs={"x", "y", "a"}),
}
@@ -370,7 +391,7 @@ 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"),
+ "foo": VariableData(kind="function", required_refs={"z"}),
"x": VariableData(kind="variable"),
}
@@ -389,7 +410,7 @@ def test_global_def() -> None:
assert v.defs == set(["foo", "x"])
assert v.refs == set()
assert v.variable_data == {
- "foo": VariableData(kind="function"),
+ "foo": VariableData(kind="function", required_refs={"x"}),
"x": VariableData(kind="variable"),
}
@@ -408,7 +429,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"),
+ "foo": VariableData(kind="function", required_refs={"x", "print"}),
}
@@ -428,7 +449,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"),
+ "foo": VariableData(kind="function", required_refs={"x", "print"}),
}
@@ -810,3 +831,30 @@ def test_type_var_generic_function() -> None:
assert v.defs == set(["test"])
# U should not be a ref
assert v.refs == set()
+
+
+def test_private_ref_requirement_caught() -> None:
+ code = "\n".join(
+ [
+ "x = 1",
+ "_x = 1",
+ "def foo():",
+ " z = _x + x + X",
+ ]
+ )
+ v = visitor.ScopedVisitor()
+ mod = ast.parse(code)
+ v.visit(mod)
+ assert len(v.defs & set(["foo", "x"])) == 2
+ assert len(v.defs - set(["foo", "x"])) == 1
+ (private,) = v.defs - set(["foo", "x"])
+ assert private.startswith("_")
+ 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}
+ ),
+ }
diff --git a/tests/_runtime/reload/test_module_watcher.py b/tests/_runtime/reload/test_module_watcher.py
index 0d755dfa6b..71f4a7c810 100644
--- a/tests/_runtime/reload/test_module_watcher.py
+++ b/tests/_runtime/reload/test_module_watcher.py
@@ -22,9 +22,10 @@ from tests.conftest import ExecReqProvider
async def test_reload_function(
tmp_path: pathlib.Path,
py_modname: str,
- k: Kernel,
+ 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(
@@ -70,9 +71,10 @@ async def test_reload_function(
async def test_reload_nested_module_function(
tmp_path: pathlib.Path,
py_modname: str,
- k: Kernel,
+ execution_kernel: Kernel,
exec_req: ExecReqProvider,
):
+ k = execution_kernel
sys.path.append(str(tmp_path))
b = tmp_path / (b_name := random_modname())
b.mkdir()
@@ -124,9 +126,10 @@ async def test_reload_nested_module_function(
async def test_reload_nested_module_import_module(
tmp_path: pathlib.Path,
py_modname: str,
- k: Kernel,
+ execution_kernel: Kernel,
exec_req: ExecReqProvider,
):
+ k = execution_kernel
sys.path.append(str(tmp_path))
b = tmp_path / (b_name := random_modname())
b.mkdir()
@@ -184,9 +187,10 @@ async def test_reload_nested_module_import_module(
async def test_reload_nested_module_import_module_autorun(
tmp_path: pathlib.Path,
py_modname: str,
- k: Kernel,
+ execution_kernel: Kernel,
exec_req: ExecReqProvider,
):
+ k = execution_kernel
sys.path.append(str(tmp_path))
b = tmp_path / (b_name := random_modname())
b.mkdir()
@@ -239,9 +243,10 @@ async def test_reload_nested_module_import_module_autorun(
async def test_reload_package(
tmp_path: pathlib.Path,
- k: Kernel,
+ execution_kernel: Kernel,
exec_req: ExecReqProvider,
):
+ k = execution_kernel
sys.path.append(str(tmp_path))
b = tmp_path / (b_name := random_modname())
b.mkdir()
@@ -286,9 +291,10 @@ async def test_reload_package(
async def test_reload_third_party(
tmp_path: pathlib.Path,
py_modname: str,
- k: Kernel,
+ execution_kernel: Kernel,
exec_req: ExecReqProvider,
):
+ k = execution_kernel
# make sure that importing a third-party package like numpy doesn't
# break the module finder
sys.path.append(str(tmp_path))
@@ -338,9 +344,10 @@ async def test_reload_third_party(
async def test_reload_with_modified_cell(
tmp_path: pathlib.Path,
py_modname: str,
- k: Kernel,
+ 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(
diff --git a/tests/_runtime/runner/test_cell_runner.py b/tests/_runtime/runner/test_cell_runner.py
index 70d49c68c3..8e30da1861 100644
--- a/tests/_runtime/runner/test_cell_runner.py
+++ b/tests/_runtime/runner/test_cell_runner.py
@@ -5,7 +5,10 @@ from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
-async def test_cell_output(k: Kernel, exec_req: ExecReqProvider) -> None:
+async def test_cell_output(
+ execution_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k = execution_kernel
# run the cell to populate the graph, globals
await k.run([er := exec_req.get("'hello'; 123")])
@@ -21,8 +24,9 @@ async def test_cell_output(k: Kernel, exec_req: ExecReqProvider) -> None:
async def test_traceback_includes_lineno(
- k: Kernel, exec_req: ExecReqProvider
+ execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = execution_kernel
# Raise an exception and test that the runner generates a traceback that
# includes the line number where the exception was raised
#
@@ -50,8 +54,9 @@ async def test_traceback_includes_lineno(
async def test_base_exception_caught(
- k: Kernel, exec_req: ExecReqProvider
+ execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = execution_kernel
# Raise an exception and test that the runner generates a traceback that
# includes the line number where the exception was raised
#
diff --git a/tests/_runtime/test_context.py b/tests/_runtime/test_context.py
index d04349b50e..7944b938f4 100644
--- a/tests/_runtime/test_context.py
+++ b/tests/_runtime/test_context.py
@@ -3,7 +3,10 @@ from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
-async def test_context_installed(k: Kernel, exec_req: ExecReqProvider) -> None:
+async def test_context_installed(
+ execution_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get(
diff --git a/tests/_runtime/test_control_flow.py b/tests/_runtime/test_control_flow.py
index e578697749..783c00b30e 100644
--- a/tests/_runtime/test_control_flow.py
+++ b/tests/_runtime/test_control_flow.py
@@ -7,7 +7,8 @@ from marimo._runtime.runner import cell_runner
from marimo._runtime.runtime import Kernel
-async def test_stop_false(k: Kernel) -> None:
+async def test_stop_false(execution_kernel: Kernel) -> None:
+ k = execution_kernel
await k.run(
[
ExecutionRequest(
@@ -22,7 +23,8 @@ async def test_stop_false(k: Kernel) -> None:
assert k.globals["z"] == 2
-async def test_stop_true(k: Kernel) -> None:
+async def test_stop_true(execution_kernel: Kernel) -> None:
+ k = execution_kernel
# Populate the kernel and its globals
await k.run(
[
@@ -51,7 +53,8 @@ async def test_stop_true(k: Kernel) -> None:
assert "z" not in k.globals
-async def test_stop_output(k: Kernel) -> None:
+async def test_stop_output(execution_kernel: Kernel) -> None:
+ k = execution_kernel
# Run a cell through the kernel to populate graph
await k.run(
[
diff --git a/tests/_runtime/test_copy.py b/tests/_runtime/test_copy.py
new file mode 100644
index 0000000000..3697da98ec
--- /dev/null
+++ b/tests/_runtime/test_copy.py
@@ -0,0 +1,137 @@
+import pytest
+
+from marimo._runtime.copy import (
+ ReadOnlyError,
+ ShallowCopy,
+ ZeroCopy,
+ _Copy,
+ shadow_wrap,
+ shallow_copy,
+ unwrap_copy,
+ zero_copy,
+)
+
+
+def test_shadow_wrap() -> None:
+ base = 1
+ shadow = shadow_wrap(_Copy, base)
+ assert shadow == base
+ assert base == shadow
+ assert isinstance(shadow, _Copy)
+ assert isinstance(shadow, int)
+ assert str(shadow) == "1"
+ assert shadow.__class__.__name__ == "int"
+ assert shadow + 1 == 2
+ assert 1 + shadow == 2
+
+
+def test_shadow_wrap_ro_attr() -> None:
+ class namespace: ...
+
+ base = namespace()
+ base.attr = 1
+ shadow = shadow_wrap(_Copy, base)
+
+ assert isinstance(shadow, _Copy)
+ assert isinstance(shadow, namespace)
+ assert shadow.__class__.__name__ == "namespace"
+ assert shadow.attr == 1
+ # assignment should fail
+ with pytest.raises(ReadOnlyError):
+ shadow.attr = 2
+
+
+def test_shadow_wrap_ro_get() -> None:
+ base = [1, 2, 3]
+ shadow = shadow_wrap(_Copy, base)
+
+ assert base == shadow
+ # assignment should fail
+ with pytest.raises(ReadOnlyError):
+ shadow[0] = 2
+
+
+def test_shadow_wrap_mutable_ref() -> None:
+ class namespace: ...
+
+ base = namespace()
+ base.attr = 1
+ base.arr = [1, 2, 3]
+ shadow = shadow_wrap(_Copy, base)
+
+ assert base.attr == shadow.attr
+ assert base.arr is shadow.arr
+
+ base.arr[0] = 2
+ base.arr[2] = 2
+ base.arr.append(4)
+ base.attr = 2
+
+ assert base.attr == shadow.attr
+ assert base.arr is shadow.arr
+
+
+def test_zero_copy() -> None:
+ base = [1]
+ shadow = zero_copy(base)
+ assert shadow == base
+ assert base == shadow
+ assert isinstance(shadow, ZeroCopy)
+ assert isinstance(shadow, list)
+ assert str(shadow) == "[1]"
+ assert shadow.__class__.__name__ == "list"
+ assert shadow + [1] == [1, 1]
+ assert id(unwrap_copy(shadow)) == id(base)
+
+
+def test_shallow_copy() -> None:
+ base = [1]
+ shadow = shallow_copy(base)
+ assert shadow == base
+ assert base == shadow
+ assert isinstance(shadow, ShallowCopy)
+ assert isinstance(shadow, list)
+ assert str(shadow) == "[1]"
+ assert shadow.__class__.__name__ == "list"
+ assert shadow + [1] == [1, 1]
+ assert id(unwrap_copy(shadow)) != id(base)
+
+
+def test_double_zero() -> None:
+ base = [1]
+ shadow = zero_copy(base)
+ shadow2 = zero_copy(shadow)
+ assert shadow2 == base
+ assert isinstance(unwrap_copy(shadow2), list)
+ assert not isinstance(unwrap_copy(shadow2), ZeroCopy)
+ assert id(unwrap_copy(shadow2)) == id(base)
+
+
+def test_double_shallow() -> None:
+ base = [1]
+ shadow = shallow_copy(base)
+ shadow2 = shallow_copy(shadow)
+ assert shadow2 == base
+ assert isinstance(unwrap_copy(shadow2), list)
+ assert not isinstance(unwrap_copy(shadow2), ShallowCopy)
+ assert id(unwrap_copy(shadow2)) != id(base)
+
+
+def test_cross_zero_shallow() -> None:
+ base = [1]
+ shadow = zero_copy(base)
+ shadow2 = shallow_copy(shadow)
+ assert shadow2 == base
+ assert isinstance(unwrap_copy(shadow2), list)
+ assert not isinstance(unwrap_copy(shadow2), ZeroCopy)
+ assert id(unwrap_copy(shadow2)) != id(base)
+
+
+def test_cross_shallow_zero() -> None:
+ base = [1]
+ shadow = shallow_copy(base)
+ shadow2 = zero_copy(shadow)
+ assert shadow2 == base
+ assert isinstance(unwrap_copy(shadow2), list)
+ assert not isinstance(unwrap_copy(shadow2), ShallowCopy)
+ assert id(unwrap_copy(shadow2)) != id(base)
diff --git a/tests/_runtime/test_marimo_pdb.py b/tests/_runtime/test_marimo_pdb.py
index 62334413ff..f52a71ae70 100644
--- a/tests/_runtime/test_marimo_pdb.py
+++ b/tests/_runtime/test_marimo_pdb.py
@@ -3,7 +3,10 @@ from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
-async def test_pdb_patched(k: Kernel, exec_req: ExecReqProvider) -> None:
+async def test_pdb_patched(
+ execution_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k = execution_kernel
await k.run([exec_req.get("import pdb")])
pdb = k.globals["pdb"]
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 0656522ae3..e5458b641b 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -53,6 +53,8 @@ class TestExecution:
er2 := ExecutionRequest(cell_id="2", code="z = x + y"),
]
)
+
+ assert not k.errors
assert k.globals["x"] == 1
assert k.globals["y"] == 2
assert k.globals["z"] == 3
@@ -603,15 +605,24 @@ class TestExecution:
exec_req.get(
"from runtime_data.cell_ui_element import make_slider"
),
+ exec_req.get("import weakref"),
exec_req.get("_, defs = make_slider.run()"),
exec_req.get("_, second_defs = make_slider.run()"),
- exec_req.get("counter = [0]"),
+ exec_req.get(
+ """
+ class namespace:
+ ...
+ ns = namespace()
+ ns.count = 0
+ ref = weakref.ref(ns)
+ """
+ ),
er := exec_req.get("slider_value = defs['slider'].value + 1"),
- exec_req.get("second_defs; counter[0] += 1"),
+ exec_req.get("second_defs; ref().count += 1"),
]
)
assert k.globals["defs"]["slider"].value == 0
- assert k.globals["counter"][0] == 1
+ assert k.globals["ns"].count == 1
assert k.globals["slider_value"] == 1
element_id = k.globals["defs"]["slider"]._id
@@ -626,7 +637,7 @@ class TestExecution:
assert k.globals["slider_value"] == 6
# reactive execution on the slider in `defs` shouldn't trigger reactive
# execution on `second_defs`
- assert k.globals["counter"][0] == 1
+ assert k.globals["ns"].count == 1
async def test_set_ui_element_value_not_found_doesnt_fail(
self,
@@ -701,10 +712,14 @@ class TestExecution:
pickle_output = None
pickle_output = pickle.dumps(foo)
+ post_pickle_var = 1
"""
),
]
)
+ assert not k.errors
+ assert "post_pickle_var" in k.globals
+ assert k.globals["post_pickle_var"] == 1
assert k.globals["pickle_output"] is not None
def test_sys_path_updated(self, tmp_path: pathlib.Path) -> None:
@@ -809,6 +824,169 @@ class TestExecution:
assert "e" in k.globals
+class TestStrictExecution:
+ @staticmethod
+ async def test_cell_lambda(
+ strict_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = strict_kernel
+ await k.run(
+ [
+ exec_req.get("""Y = 1"""),
+ exec_req.get(
+ """
+ _x = 1
+ X = 1
+ L = lambda x: x + _x + X + Y
+ """
+ ),
+ exec_req.get(
+ """
+ V = L(1)
+ V
+ """
+ ),
+ ]
+ )
+ assert not k.errors
+ assert "X" in k.globals
+ assert "Y" in k.globals
+ assert "L" in k.globals
+ assert "V" in k.globals
+ assert k.globals["V"] == 4
+
+ @staticmethod
+ async def test_cell_indirect_lambda(
+ strict_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = strict_kernel
+ await k.run(
+ [
+ exec_req.get("""Y = 1"""),
+ exec_req.get(
+ """
+ _x = 1
+ X = 1
+ L = [lambda x: x + _x + X + Y]
+ """
+ ),
+ exec_req.get("V = L[0](1)"),
+ ]
+ )
+ assert not k.errors
+ assert "X" in k.globals
+ assert "Y" in k.globals
+ assert "L" in k.globals
+ assert "V" in k.globals
+ assert k.globals["V"] == 4
+
+ @staticmethod
+ async def test_cell_indirect_private(
+ strict_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = strict_kernel
+ await k.run(
+ [
+ exec_req.get("""
+ Y = 1
+ _y = 1
+ def f(x):
+ return x + _y
+ """),
+ exec_req.get(
+ """
+ _x = 1
+ X = 1
+ L = [lambda x: f(x + _x + X + Y)]
+ """
+ ),
+ exec_req.get("V = L[0](1)"),
+ ]
+ )
+ assert not k.errors
+ assert "X" in k.globals
+ assert "Y" in k.globals
+ assert "L" in k.globals
+ assert "V" in k.globals
+ assert "f" in k.globals
+ assert k.globals["V"] == 5
+
+ @staticmethod
+ async def test_cell_copy_works(
+ strict_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = strict_kernel
+ await k.run(
+ [
+ exec_req.get("""
+ class namespace:
+ ...
+ X = namespace()
+ X.count = 1
+ """),
+ exec_req.get(
+ """
+ X.count += 1
+ V0 = X.count
+ """
+ ),
+ exec_req.get(
+ """
+ X.count += 10
+ V1 = X.count
+ """
+ ),
+ ]
+ )
+ assert not k.errors
+ assert "X" in k.globals
+ assert "V0" in k.globals
+ assert "V1" in k.globals
+ assert k.globals["X"].count == 1
+ assert k.globals["V0"] == 2
+ assert k.globals["V1"] == 11
+
+ @staticmethod
+ async def test_cell_zero_copy_works(
+ strict_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = strict_kernel
+ await k.run(
+ [
+ exec_req.get("""
+ import marimo as mo
+ class namespace:
+ ...
+ X = namespace()
+ X.count = 1
+ X = mo._runtime.copy.zero_copy(X)
+ """),
+ exec_req.get(
+ """
+ mo._runtime.copy.unwrap_copy(X).count += 1
+ V0 = X.count
+ """
+ ),
+ exec_req.get(
+ """
+ mo._runtime.copy.unwrap_copy(X).count += 10
+ V1 = X.count
+ """
+ ),
+ ]
+ )
+ assert not k.errors
+ assert "X" in k.globals
+ assert "V0" in k.globals
+ assert "V1" in k.globals
+ assert k.globals["X"].count == 12
+ assert k.globals["V0"] in (2, 12)
+ if k.globals["V0"] == 2:
+ assert k.globals["V1"] == 12
+ else:
+ assert k.globals["V1"] == 11
+
+
class TestStoredOutput:
async def test_ui_element_in_output_stored(
self, any_kernel: Kernel, exec_req: ExecReqProvider
@@ -912,13 +1090,15 @@ class TestDisable:
[
exec_req.get(
"""
+ import weakref
class namespace:
...
ns = namespace()
ns.count = 0
+ ref = weakref.ref(ns)
"""
),
- (er_2 := exec_req.get("ns.count += 1")),
+ er_2 := exec_req.get("ref().count += 1"),
]
)
assert k.globals["ns"].count == 1
@@ -948,17 +1128,17 @@ class TestDisable:
graph = k.graph
await k.run(
[
- (
- er_1 := exec_req.get(
- """
+ er_1 := exec_req.get(
+ """
class namespace:
...
ns = namespace()
ns.count = 0
+ import weakref
+ ref = weakref.ref(ns)
"""
- )
),
- er_2 := exec_req.get("ns.count += 1"),
+ er_2 := exec_req.get("ref().count += 1"),
]
)
assert k.globals["ns"].count == 1
@@ -978,6 +1158,8 @@ class TestDisable:
...
ns = namespace()
ns.count = 10
+ import weakref
+ ref = weakref.ref(ns)
""",
)
]
diff --git a/tests/_runtime/test_state.py b/tests/_runtime/test_state.py
index 463df7405a..6c92c8fd4e 100644
--- a/tests/_runtime/test_state.py
+++ b/tests/_runtime/test_state.py
@@ -3,7 +3,10 @@ from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
-async def test_set_and_get_state(k: Kernel, exec_req: ExecReqProvider) -> None:
+async def test_set_and_get_state(
+ execution_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get("import marimo as mo"),
@@ -23,8 +26,9 @@ async def test_set_and_get_state(k: Kernel, exec_req: ExecReqProvider) -> None:
async def test_set_and_get_iteration(
- k: Kernel, exec_req: ExecReqProvider
+ execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get("import marimo as mo"),
@@ -43,7 +47,10 @@ async def test_set_and_get_iteration(
assert k.globals["x"] == 5
-async def test_no_self_loops(k: Kernel, exec_req: ExecReqProvider) -> None:
+async def test_no_self_loops(
+ execution_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get("import marimo as mo"),
@@ -55,7 +62,10 @@ async def test_no_self_loops(k: Kernel, exec_req: ExecReqProvider) -> None:
assert k.globals["x"] == 0
-async def test_allow_self_loops(k: Kernel, exec_req: ExecReqProvider) -> None:
+async def test_allow_self_loops(
+ execution_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get("import marimo as mo"),
@@ -76,8 +86,9 @@ async def test_allow_self_loops(k: Kernel, exec_req: ExecReqProvider) -> None:
async def test_update_with_function(
- k: Kernel, exec_req: ExecReqProvider
+ execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get("import marimo as mo"),
@@ -91,8 +102,9 @@ async def test_update_with_function(
async def test_set_to_callable_object(
- k: Kernel, exec_req: ExecReqProvider
+ execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get("import marimo as mo"),
@@ -115,30 +127,38 @@ async def test_set_to_callable_object(
assert not k.globals["x"].called
-async def test_non_stale_not_run(k: Kernel, exec_req: ExecReqProvider) -> None:
+async def test_non_stale_not_run(
+ execution_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get("import marimo as mo"),
+ exec_req.get("import weakref"),
exec_req.get(
"""
class ns:
...
private = ns()
private.counter = 0
+ ref = weakref.ref(private)
"""
),
exec_req.get("state, set_state = mo.state(0)"),
exec_req.get("set_state(1); x = 0"),
# this cell runs as a result of the dag; the setter above
# shouldn't cause it to re-run, even though it calls the getter
- exec_req.get("x; private.counter += state()"),
+ exec_req.get("x; ref().counter += state()"),
]
)
assert k.globals["private"].counter == 1
-async def test_cancelled_not_run(k: Kernel, exec_req: ExecReqProvider) -> None:
+async def test_cancelled_not_run(
+ execution_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get("import marimo as mo"),
@@ -154,8 +174,9 @@ async def test_cancelled_not_run(k: Kernel, exec_req: ExecReqProvider) -> None:
async def test_set_state_with_overridden_eq(
- k: Kernel, exec_req: ExecReqProvider
+ execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = execution_kernel
create_class = """
class A:
def __eq__(self, other):
@@ -181,3 +202,19 @@ async def test_set_state_with_overridden_eq(
)
assert type(k.globals["x"]).__name__ == "A"
+
+
+async def test_set_state_not_strict_copied(
+ strict_kernel: Kernel, exec_req: ExecReqProvider
+) -> None:
+ k = strict_kernel
+ await k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get("state, set_state = mo.state(None)"),
+ exec_req.get("a, b = state, set_state"),
+ ]
+ )
+
+ assert id(k.globals["a"]) == id(k.globals["state"])
+ assert id(k.globals["b"]) == id(k.globals["set_state"])
diff --git a/tests/_runtime/test_virtual_file.py b/tests/_runtime/test_virtual_file.py
index 32afbc42d1..cffe5277ab 100644
--- a/tests/_runtime/test_virtual_file.py
+++ b/tests/_runtime/test_virtual_file.py
@@ -8,8 +8,9 @@ from tests.conftest import ExecReqProvider
async def test_virtual_file_creation(
- k: Kernel, exec_req: ExecReqProvider
+ execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get(
@@ -28,8 +29,9 @@ async def test_virtual_file_creation(
async def test_virtual_file_deletion(
- k: Kernel, exec_req: ExecReqProvider
+ execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = execution_kernel
await k.run(
[
er := exec_req.get(
@@ -51,8 +53,9 @@ async def test_virtual_file_deletion(
async def test_cached_virtual_file_not_deleted(
- k: Kernel, exec_req: ExecReqProvider
+ execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get(
@@ -94,8 +97,9 @@ async def test_cached_virtual_file_not_deleted(
async def test_cell_deletion_clears_vfiles(
- k: Kernel, exec_req: ExecReqProvider
+ execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get(
@@ -125,8 +129,9 @@ async def test_cell_deletion_clears_vfiles(
async def test_vfile_refcount_incremented(
- k: Kernel, exec_req: ExecReqProvider
+ execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get(
@@ -159,8 +164,9 @@ async def test_vfile_refcount_incremented(
async def test_vfile_refcount_decremented(
- k: Kernel, exec_req: ExecReqProvider
+ execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get(
@@ -201,8 +207,9 @@ async def test_vfile_refcount_decremented(
async def test_cached_vfile_disposal(
- k: Kernel, exec_req: ExecReqProvider
+ execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = execution_kernel
await k.run(
[
exec_req.get(
@@ -210,18 +217,26 @@ async def test_cached_vfile_disposal(
import io
import marimo as mo
import functools
+ import weakref
"""
),
exec_req.get(
"""
- vfiles = []
+ class namespace:
+ ...
+ vfiles = namespace()
+ vfiles.files = []
+ ref = weakref.ref(vfiles)
+
def create_vfile(arg):
del arg
bytestream = io.BytesIO(b"hello world")
return mo.pdf(bytestream)
"""
),
- append_vfile := exec_req.get("vfiles.append(create_vfile(1))"),
+ append_vfile := exec_req.get(
+ "ref().files.append(create_vfile(1))"
+ ),
]
)
ctx = get_context()
@@ -232,7 +247,7 @@ async def test_cached_vfile_disposal(
assert ctx.virtual_file_registry.refcount(vfile) == 1
# clear the list, refcount should be decremented
- await k.run([exec_req.get("vfiles[:] = []")])
+ await k.run([exec_req.get("ref().files[:] = []")])
# NB: this test may be flaky! refcount decremented when `__del__` is called
# but we can't rely on when it will be called.
await k.run([exec_req.get("import gc; gc.collect()")])
@@ -245,8 +260,9 @@ async def test_cached_vfile_disposal(
async def test_virtual_files_not_supported(
- k: Kernel, exec_req: ExecReqProvider
+ execution_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = execution_kernel
get_context().virtual_files_supported = False
await k.run(
diff --git a/tests/conftest.py b/tests/conftest.py
index 61e6866013..8e262a5665 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -130,11 +130,27 @@ def k() -> Generator[Kernel, None, None]:
# kernel configured with runtime=lazy
@pytest.fixture
def lazy_kernel(k: Kernel) -> Kernel:
+ k.execution_type = "relaxed"
k.reactive_execution_mode = "lazy"
return k
[email protected](params=["k", "lazy_kernel"])
+# kernel configured with strict execution
+def strict_kernel() -> Generator[Kernel, None, None]:
+ mocked = MockedKernel()
+ mocked.k.execution_type = "strict"
+ mocked.k.reactive_execution_mode = "autorun"
+ yield mocked.k
+ mocked.teardown()
+
+
[email protected](params=["k", "strict_kernel"])
+def execution_kernel(request: Any) -> Kernel:
+ return request.getfixturevalue(request.param)
+
+
[email protected](params=["k", "strict_kernel", "lazy_kernel"])
def any_kernel(request: Any) -> Kernel:
return request.getfixturevalue(request.param)