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: lazy runtime (#1302)

Akshay Agrawalc30975d9c242
diff --git a/docs/guides/editor_features.md b/docs/guides/editor_features.md
index 35dba8ad79..e5a64aecaa 100644
--- a/docs/guides/editor_features.md
+++ b/docs/guides/editor_features.md
@@ -91,13 +91,10 @@ by your notebook's imported modules too.
Autoreloading comes in two types:
-- "detect": automatically marks cells affected by module
+- "lazy": automatically marks cells affected by module
modifications as stale, letting you know which cells need to be re-run.
- "autorun": automatically re-runs cells affected by module modification.
-**Note:** Make sure the imported modules are in packages/folders with
-`__init__.py` files, otherwise marimo's detection may fail.
-
**Why autoreload?** Autoreloading enables a workflow that many developers find
productive: develop complex logic in Python modules, and use the marimo
notebook as a DAG or main script that orchestrates your logic.
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 18cc66e581..0819d45d24 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -343,6 +343,38 @@ export const UserConfigForm: React.FC = () => {
</FormItem>
)}
/>
+ <FormField
+ control={form.control}
+ name="runtime.on_cell_change"
+ render={({ field }) => (
+ <div className="flex flex-col gap-y-1">
+ <FormItem className="flex flex-row items-start space-x-2 space-y-0">
+ <FormControl>
+ <NativeSelect
+ data-testid="on-cell-change-select"
+ onChange={(e) => field.onChange(e.target.value)}
+ value={field.value}
+ className="inline-flex mr-2"
+ >
+ {["lazy", "autorun"].map((option) => (
+ <option value={option} key={option}>
+ {option}
+ </option>
+ ))}
+ </NativeSelect>
+ </FormControl>
+ <FormLabel className="font-normal">On cell change</FormLabel>
+ </FormItem>
+ <FormDescription>
+ Whether marimo should automatically run cells or just mark
+ them as stale. If "autorun", marimo will automatically run
+ affected cells when a cell is run or a UI element is
+ interacted with; if "lazy", marimo will mark affected cells as
+ stale but won't re-run them.
+ </FormDescription>
+ </div>
+ )}
+ />
<FormField
control={form.control}
name="runtime.auto_reload"
@@ -357,7 +389,7 @@ export const UserConfigForm: React.FC = () => {
disabled={isWasm}
className="inline-flex mr-2"
>
- {["off", "detect", "autorun"].map((option) => (
+ {["off", "lazy", "autorun"].map((option) => (
<option value={option} key={option}>
{option}
</option>
@@ -365,14 +397,14 @@ export const UserConfigForm: React.FC = () => {
</NativeSelect>
</FormControl>
<FormLabel className="font-normal">
- Autoreload modules
+ On module change
</FormLabel>
</FormItem>
<FormDescription>
Whether marimo should automatically reload modules before
- executing cells. If "detect", marimo will mark cells affected
- by module modifications as stale; if "automatic", affected
- cells will be automatically re-run.
+ executing cells. If "lazy", marimo will mark cells affected by
+ module modifications as stale; if "autorun", affected cells
+ will be automatically re-run.
</FormDescription>
</div>
)}
diff --git a/frontend/src/components/editor/cell/CellStatus.tsx b/frontend/src/components/editor/cell/CellStatus.tsx
index ba73934a6f..c3cd09f7dc 100644
--- a/frontend/src/components/editor/cell/CellStatus.tsx
+++ b/frontend/src/components/editor/cell/CellStatus.tsx
@@ -157,15 +157,25 @@ export const CellStatusComponent: React.FC<CellStatusComponentProps> = ({
);
}
- // outdated
+ // outdated: cell needs to be re-run
if (edited || interrupted || staleInputs) {
const elapsedTimeStr = formatElapsedTime(elapsedTime);
- const title = interrupted
- ? "This cell was interrupted when it was last run"
- : "This cell has been modified since it was last run";
- const timerTitle = interrupted
- ? `This cell ran for ${elapsedTimeStr} before being interrupted`
- : `This cell took ${elapsedTimeStr} to run`;
+
+ // Customize tooltips based on why the cell needs to be re-run
+ let title = "";
+ let timerTitle = "";
+ if (interrupted) {
+ title = "This cell was interrupted when it was last run";
+ timerTitle = `This cell ran for ${elapsedTimeStr} before being interrupted`;
+ } else if (edited) {
+ title = "This cell has been modified since it was last run";
+ timerTitle = `This cell took ${elapsedTimeStr} to run`;
+ } else {
+ // staleInputs
+ title = "This cell has not been run with the latest inputs.";
+ timerTitle = `This cell took ${elapsedTimeStr} to run`;
+ }
+
return (
<div className="cell-status-icon flex items-center gap-2">
<Tooltip content={title} usePortal={false}>
diff --git a/frontend/src/core/config/__tests__/config-schema.test.ts b/frontend/src/core/config/__tests__/config-schema.test.ts
index 5010551801..7caf2f2fc4 100644
--- a/frontend/src/core/config/__tests__/config-schema.test.ts
+++ b/frontend/src/core/config/__tests__/config-schema.test.ts
@@ -51,6 +51,7 @@ test("default UserConfig - empty", () => {
"runtime": {
"auto_instantiate": true,
"auto_reload": "off",
+ "on_cell_change": "autorun",
},
"save": {
"autosave": "after_delay",
@@ -96,6 +97,7 @@ test("default UserConfig - one level", () => {
"runtime": {
"auto_instantiate": true,
"auto_reload": "off",
+ "on_cell_change": "autorun",
},
"save": {
"autosave": "after_delay",
diff --git a/frontend/src/core/config/config-schema.ts b/frontend/src/core/config/config-schema.ts
index 5f87be7fa5..a142ffa360 100644
--- a/frontend/src/core/config/config-schema.ts
+++ b/frontend/src/core/config/config-schema.ts
@@ -50,7 +50,8 @@ export const UserConfigSchema = z
runtime: z
.object({
auto_instantiate: z.boolean().default(true),
- auto_reload: z.enum(["off", "detect", "autorun"]).default("off"),
+ on_cell_change: z.enum(["lazy", "autorun"]).default("autorun"),
+ auto_reload: z.enum(["off", "lazy", "autorun"]).default("off"),
})
.default({}),
display: z
diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsx
index 24835c06c6..6fd8d771c2 100644
--- a/frontend/src/stories/cell.stories.tsx
+++ b/frontend/src/stories/cell.stories.tsx
@@ -67,6 +67,7 @@ const props: CellProps = {
},
runtime: {
auto_instantiate: true,
+ on_cell_change: "autorun",
auto_reload: "off",
},
keymap: {
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index 9fc6164270..4d8238355a 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -104,7 +104,7 @@ class CellImpl:
_stale: CellStaleState = dataclasses.field(default_factory=CellStaleState)
def configure(self, update: dict[str, Any] | CellConfig) -> CellImpl:
- """Update the cel config.
+ """Update the cell config.
`update` can be a partial config.
"""
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 2fd5478125..f99fc1846d 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -60,6 +60,9 @@ class KeymapConfig(TypedDict, total=False):
preset: Literal["default", "vim"]
+OnCellChangeType = Literal["lazy", "autorun"]
+
+
@mddoc
class RuntimeConfig(TypedDict):
"""Configuration for runtime.
@@ -70,13 +73,17 @@ class RuntimeConfig(TypedDict):
run on startup. This only applies when editing a notebook,
and not when running as an application.
The default is `True`.
- - `auto_reload`: if `detect`, cells importing modified modules will marked
+ - `auto_reload`: if `lazy`, cells importing modified modules will marked
as stale; if `autorun`, affected cells will be automatically run. similar
to IPython's %autoreload extension but with more code intelligence.
+ - `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.
"""
auto_instantiate: bool
- auto_reload: Literal["off", "detect", "autorun"]
+ auto_reload: Literal["off", "lazy", "autorun"]
+ on_cell_change: OnCellChangeType
@mddoc
@@ -181,7 +188,11 @@ DEFAULT_CONFIG: MarimoConfig = {
},
"formatting": {"line_length": 79},
"keymap": {"preset": "default"},
- "runtime": {"auto_instantiate": True, "auto_reload": "off"},
+ "runtime": {
+ "auto_instantiate": True,
+ "auto_reload": "off",
+ "on_cell_change": "autorun",
+ },
"save": {
"autosave": "after_delay",
"autosave_delay": 1000,
@@ -216,7 +227,12 @@ def merge_config(
if (
merged["runtime"]["auto_reload"] is True # type:ignore[comparison-overlap]
):
- merged["runtime"]["auto_reload"] = "detect"
+ merged["runtime"]["auto_reload"] = "lazy"
+ if (
+ merged["runtime"]["auto_reload"] == "detect" # type:ignore[comparison-overlap]
+ ):
+ merged["runtime"]["auto_reload"] = "lazy"
+
return merged
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
index 564275337d..a4a68e52ae 100644
--- a/marimo/_messaging/ops.py
+++ b/marimo/_messaging/ops.py
@@ -51,7 +51,17 @@ class Op:
# TODO(akshayka): fix typing once mypy has stricter typing for asdict
def broadcast(self, stream: Optional[Stream] = None) -> None:
- stream = stream if stream is not None else get_context().stream
+ from marimo._runtime.context.types import ContextNotInitializedError
+
+ if stream is None:
+ try:
+ ctx = get_context()
+ except ContextNotInitializedError:
+ LOGGER.debug("No context initialized.")
+ return
+ else:
+ stream = ctx.stream
+
LOGGER.debug("Broadcasting op: %s", self)
stream.write(op=self.name, data=serialize(self))
diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.py
index 1ca0f60b01..b596829243 100644
--- a/marimo/_runtime/dataflow.py
+++ b/marimo/_runtime/dataflow.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import threading
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, List, Optional, Tuple
+from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple
from marimo import _loggers
from marimo._ast.cell import (
@@ -164,6 +164,20 @@ class DirectedGraph:
self.cycles.add(tuple([(other_id, cell_id)] + path))
self.children[other_id].add(cell_id)
+ if self.is_any_ancestor_stale(cell_id):
+ self.set_stale(set([cell_id]))
+
+ if self.is_any_ancestor_disabled(cell_id):
+ cell.set_status(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))
+
+ def is_any_ancestor_disabled(self, cell_id: CellId_t) -> bool:
+ return any(
+ self.cells[cid].config.disabled for cid in self.ancestors(cell_id)
+ )
+
def disable_cell(self, cell_id: CellId_t) -> None:
"""
Disables a cell in the graph.
@@ -199,7 +213,7 @@ class DirectedGraph:
# cell was previously disabled, is no longer
# disabled, and is stale: needs to run.
cells_to_run.add(cid)
- elif child.disabled_transitively:
+ if child.disabled_transitively:
# cell is no longer disabled: status -> idle
child.set_status("idle")
return cells_to_run
@@ -291,25 +305,55 @@ class DirectedGraph:
return ref
return None
+ def descendants(self, cell_id: CellId_t) -> set[CellId_t]:
+ return transitive_closure(self, set([cell_id]), inclusive=False)
+
+ def ancestors(self, cell_id: CellId_t) -> set[CellId_t]:
+ return transitive_closure(
+ 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):
+ self.cells[cid].set_stale(stale=True)
+
+ def get_stale(self) -> set[CellId_t]:
+ return set([cid for cid, cell in self.cells.items() if cell.stale])
+
def transitive_closure(
- graph: DirectedGraph, cell_ids: set[CellId_t], children: bool = True
+ graph: DirectedGraph,
+ cell_ids: set[CellId_t],
+ children: bool = True,
+ inclusive: bool = True,
+ predicate: Callable[[CellImpl], bool] | None = None,
) -> set[CellId_t]:
"""Return a set of the passed-in cells and their descendants or ancestors
If children is True, returns descendants; otherwise, returns ancestors
+
+ If inclusive, includes passed-in cells in the set.
+
+ If predicate, only cells satisfying predicate(cell) are included
"""
+ 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]
while queue:
cid = queue.pop(0)
- cells.add(cid)
+ seen.add(cid)
+ cell = graph.cells[cid]
+ if inclusive and predicate(cell):
+ cells.add(cid)
+ elif cid not in cell_ids and predicate(cell):
+ cells.add(cid)
for relative in relatives(cid):
- if relative not in cells:
+ if relative not in seen:
queue.append(relative)
return cells
diff --git a/marimo/_runtime/reload/module_watcher.py b/marimo/_runtime/reload/module_watcher.py
index 043b2e657b..20914e8c7d 100644
--- a/marimo/_runtime/reload/module_watcher.py
+++ b/marimo/_runtime/reload/module_watcher.py
@@ -140,7 +140,7 @@ def _check_modules(
def watch_modules(
graph: dataflow.DirectedGraph,
- mode: Literal["detect", "autorun"],
+ mode: Literal["lazy", "autorun"],
enqueue_run_stale_cells: Callable[[], None],
should_exit: threading.Event,
run_is_processed: threading.Event,
@@ -205,7 +205,7 @@ class ModuleWatcher:
def __init__(
self,
graph: dataflow.DirectedGraph,
- mode: Literal["detect", "autorun"],
+ mode: Literal["lazy", "autorun"],
enqueue_run_stale_cells: Callable[[], None],
stream: Stream,
) -> None:
diff --git a/marimo/_runtime/runner/__init__.py b/marimo/_runtime/runner/__init__.py
new file mode 100644
index 0000000000..be52407b50
--- /dev/null
+++ b/marimo/_runtime/runner/__init__.py
@@ -0,0 +1 @@
+# Copyright 2024 Marimo. All rights reserved.
diff --git a/marimo/_runtime/cell_runner.py b/marimo/_runtime/runner/cell_runner.py
similarity index 74%
rename from marimo/_runtime/cell_runner.py
rename to marimo/_runtime/runner/cell_runner.py
index 3317b830e1..a39ed9a9cc 100644
--- a/marimo/_runtime/cell_runner.py
+++ b/marimo/_runtime/runner/cell_runner.py
@@ -9,9 +9,15 @@ import signal
import threading
import traceback
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any, Iterator, Optional
-
-from marimo._ast.cell import CellId_t, execute_cell, execute_cell_async
+from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional
+
+from marimo._ast.cell import (
+ CellId_t,
+ CellImpl,
+ execute_cell,
+ execute_cell_async,
+)
+from marimo._config.config import OnCellChangeType
from marimo._loggers import marimo_logger
from marimo._messaging.tracebacks import write_traceback
from marimo._runtime import dataflow
@@ -21,8 +27,9 @@ from marimo._runtime.marimo_pdb import MarimoPdb
LOGGER = marimo_logger()
if TYPE_CHECKING:
- from collections.abc import Container
+ from collections.abc import Sequence
+ from marimo._runtime.context.types import ExecutionContext
from marimo._runtime.state import State
@@ -33,10 +40,12 @@ def cell_filename(cell_id: CellId_t) -> str:
@dataclass
class RunResult:
- # Raw output of cell
+ # Raw output of cell: last expression
output: Any
# Exception raised by cell, if any
exception: Optional[BaseException]
+ # Accumulated output: via imperative mo.output.append()
+ accumulated_output: Any = None
def success(self) -> bool:
"""Whether the cell expected successfully"""
@@ -48,17 +57,73 @@ class Runner:
def __init__(
self,
- cell_ids: set[CellId_t],
+ roots: set[CellId_t],
graph: dataflow.DirectedGraph,
glbls: dict[Any, Any],
debugger: MarimoPdb | None,
+ execution_mode: OnCellChangeType = "autorun",
+ excluded_cells: set[CellId_t] | None = None,
+ execution_context: Callable[
+ [CellId_t], contextlib._GeneratorContextManager[ExecutionContext]
+ ]
+ | None = None,
+ preparation_hooks: Sequence[Callable[["Runner"], Any]] | None = None,
+ pre_execution_hooks: Sequence[Callable[[CellImpl, "Runner"], Any]]
+ | None = None,
+ post_execution_hooks: Sequence[
+ Callable[[CellImpl, "Runner", RunResult], Any]
+ ]
+ | None = None,
+ on_finish_hooks: Sequence[Callable[["Runner"], Any]] | None = None,
):
self.graph = graph
self.debugger = debugger
+ self.excluded_cells = excluded_cells or set()
+
+ # injected context and hooks
+ self.execution_context = execution_context
+ self.preparation_hooks: Sequence[Callable[["Runner"], Any]] = (
+ preparation_hooks or []
+ )
+ self.pre_execution_hooks: Sequence[
+ Callable[[CellImpl, "Runner"], Any]
+ ] = pre_execution_hooks or []
+ self.post_execution_hooks: Sequence[
+ Callable[[CellImpl, "Runner", RunResult], Any]
+ ] = post_execution_hooks or []
+ self.on_finish_hooks: Sequence[Callable[["Runner"], Any]] = (
+ on_finish_hooks or []
+ )
+
# runtime globals
self.glbls = glbls
- # cells that the runner will run.
- self.cells_to_run = dataflow.topological_sort(graph, cell_ids)
+ self.execution_mode = execution_mode
+
+ # cells that the runner will run, subtracting out cells with errors:
+ #
+ # 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.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,
+ )
+
# map from a cell that was cancelled to its descendants that have
# not yet run:
self.cells_cancelled: dict[CellId_t, set[CellId_t]] = {}
@@ -162,7 +227,6 @@ class Runner:
def resolve_state_updates(
self,
state_updates: dict[State[Any], CellId_t],
- errored_cells: Container[CellId_t],
) -> set[CellId_t]:
"""
Get cells that need to be run as a consequence of state updates
@@ -203,7 +267,7 @@ class Runner:
if cid == setter_cell_id and not state.allow_self_loops:
continue
# No errorred/cancelled cells (4)
- if cid in errored_cells or self.cancelled(cid):
+ if cid in self.excluded_cells or self.cancelled(cid):
continue
# State object in refs (5)
for ref in cell.refs:
@@ -297,3 +361,28 @@ class Runner:
self.exceptions[cell_id] = run_result.exception
return run_result
+
+ async def run_all(self) -> None:
+ for prep_hook in self.preparation_hooks:
+ prep_hook(self)
+
+ while self.pending():
+ cell_id = self.pop_cell()
+ if self.cancelled(cell_id):
+ continue
+ if self.graph.is_disabled(cell_id):
+ continue
+ cell = self.graph.cells[cell_id]
+ for pre_hook in self.pre_execution_hooks:
+ pre_hook(cell, self)
+ if self.execution_context is not None:
+ with self.execution_context(cell_id) as exc_ctx:
+ run_result = await self.run(cell_id)
+ run_result.accumulated_output = exc_ctx.output
+ else:
+ run_result = await self.run(cell_id)
+ for post_hook in self.post_execution_hooks:
+ post_hook(cell, self, run_result)
+
+ for finish_hook in self.on_finish_hooks:
+ finish_hook(self)
diff --git a/marimo/_runtime/runner/execution_hooks.py b/marimo/_runtime/runner/execution_hooks.py
new file mode 100644
index 0000000000..0df081ca51
--- /dev/null
+++ b/marimo/_runtime/runner/execution_hooks.py
@@ -0,0 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
+from marimo import _loggers
+
+LOGGER = _loggers.marimo_logger()
diff --git a/marimo/_runtime/runner/hooks.py b/marimo/_runtime/runner/hooks.py
new file mode 100644
index 0000000000..a93f373494
--- /dev/null
+++ b/marimo/_runtime/runner/hooks.py
@@ -0,0 +1,17 @@
+# Copyright 2024 Marimo. All rights reserved.
+__all__ = [
+ # hooks to run before the runner starts running its subgraph
+ "PREPARATION_HOOKS",
+ # hooks to run right before each cell is run
+ "PRE_EXECUTION_HOOKS",
+ # hooks to run right after each cell is run
+ "POST_EXECUTION_HOOKS",
+ # hooks to run once the runner has finished executing its subgraph
+ "ON_FINISH_HOOKS",
+]
+
+
+from marimo._runtime.runner.hooks_on_finish import ON_FINISH_HOOKS
+from marimo._runtime.runner.hooks_post_execution import POST_EXECUTION_HOOKS
+from marimo._runtime.runner.hooks_pre_execution import PRE_EXECUTION_HOOKS
+from marimo._runtime.runner.hooks_preparation import PREPARATION_HOOKS
diff --git a/marimo/_runtime/runner/hooks_on_finish.py b/marimo/_runtime/runner/hooks_on_finish.py
new file mode 100644
index 0000000000..6ab0e6cbab
--- /dev/null
+++ b/marimo/_runtime/runner/hooks_on_finish.py
@@ -0,0 +1,69 @@
+# Copyright 2024 Marimo. All rights reserved.
+from marimo import _loggers
+from marimo._messaging.errors import (
+ Error,
+ MarimoAncestorStoppedError,
+ MarimoExceptionRaisedError,
+ MarimoInterruptionError,
+)
+from marimo._messaging.ops import CellOp
+from marimo._runtime.control_flow import MarimoStopError
+from marimo._runtime.runner import cell_runner
+
+LOGGER = _loggers.marimo_logger()
+
+
+def _send_interrupt_errors(runner: cell_runner.Runner) -> None:
+ if runner.cells_to_run:
+ assert runner.interrupted
+ for cid in runner.cells_to_run:
+ # `cid` was not run
+ runner.graph.cells[cid].set_status("idle")
+ CellOp.broadcast_error(
+ data=[MarimoInterruptionError()],
+ # these cells are transitioning from queued to stopped
+ # (interrupted); they didn't get to run, so their consoles
+ # reflect a previous run and should be cleared
+ clear_console=True,
+ cell_id=cid,
+ status="idle",
+ )
+
+
+def _send_cancellation_errors(runner: cell_runner.Runner) -> None:
+ for raising_cell in runner.cells_cancelled:
+ for cid in runner.cells_cancelled[raising_cell]:
+ # `cid` was not run
+ runner.graph.cells[cid].set_status("idle")
+ exception = runner.exceptions[raising_cell]
+ data: Error
+ if isinstance(exception, MarimoStopError):
+ data = MarimoAncestorStoppedError(
+ msg=(
+ "This cell wasn't run because an "
+ "ancestor was stopped with `mo.stop`: "
+ ),
+ raising_cell=raising_cell,
+ )
+ else:
+ exception_type = type(runner.exceptions[raising_cell]).__name__
+ data = MarimoExceptionRaisedError(
+ msg=(
+ "An ancestor raised an exception "
+ f"({exception_type}): "
+ ),
+ exception_type=exception_type,
+ raising_cell=raising_cell,
+ )
+ CellOp.broadcast_error(
+ data=[data],
+ # these cells are transitioning from queued to stopped
+ # (interrupted); they didn't get to run, so their consoles
+ # reflect a previous run and should be cleared
+ clear_console=True,
+ cell_id=cid,
+ status="idle",
+ )
+
+
+ON_FINISH_HOOKS = [_send_interrupt_errors, _send_cancellation_errors]
diff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.py
new file mode 100644
index 0000000000..6478209ad1
--- /dev/null
+++ b/marimo/_runtime/runner/hooks_post_execution.py
@@ -0,0 +1,146 @@
+# Copyright 2024 Marimo. All rights reserved.
+from marimo import _loggers
+from marimo._ast.cell import CellImpl
+from marimo._messaging.cell_output import CellChannel
+from marimo._messaging.errors import (
+ MarimoExceptionRaisedError,
+ MarimoInterruptionError,
+)
+from marimo._messaging.ops import CellOp, VariableValue, VariableValues
+from marimo._messaging.tracebacks import write_traceback
+from marimo._output import formatting
+from marimo._runtime.context.types import get_global_context
+from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
+from marimo._runtime.runner import cell_runner
+
+LOGGER = _loggers.marimo_logger()
+
+
+def _set_status_idle(
+ cell: CellImpl,
+ runner: cell_runner.Runner,
+ run_result: cell_runner.RunResult,
+) -> None:
+ del run_result
+ del runner
+ cell.set_status(status="idle")
+
+
+def _broadcast_variables(
+ cell: CellImpl,
+ runner: cell_runner.Runner,
+ run_result: cell_runner.RunResult,
+) -> None:
+ del run_result
+ values = [
+ VariableValue(
+ name=variable,
+ value=(
+ runner.glbls[variable] if variable in runner.glbls else None
+ ),
+ )
+ for variable in cell.defs
+ ]
+ if values:
+ VariableValues(variables=values).broadcast()
+
+
+def _broadcast_outputs(
+ cell: CellImpl,
+ runner: cell_runner.Runner,
+ run_result: cell_runner.RunResult,
+) -> None:
+ # TODO: clean this logic up ...
+ #
+ # Send the output to the frontend
+ #
+ # Don't rebroadcast an output that was already sent
+ #
+ # 1. if run_result.output is not None, need to send it
+ # 2. otherwise if exc_ctx.output is None, then need to send
+ # the (empty) output (to clear it)
+ should_send_output = (
+ run_result.output is not None or run_result.accumulated_output is None
+ )
+ if (
+ run_result.success()
+ or isinstance(run_result.exception, MarimoStopError)
+ ) and should_send_output:
+
+ def format_output() -> formatting.FormattedOutput:
+ formatted_output = formatting.try_format(run_result.output)
+ if formatted_output.traceback is not None:
+ write_traceback(formatted_output.traceback)
+ return formatted_output
+
+ if runner.execution_context is not None:
+ with runner.execution_context(cell.cell_id):
+ formatted_output = format_output()
+ else:
+ formatted_output = format_output()
+ CellOp.broadcast_output(
+ channel=CellChannel.OUTPUT,
+ mimetype=formatted_output.mimetype,
+ data=formatted_output.data,
+ 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
+ # its console outputs are not stale
+ CellOp.broadcast_error(
+ data=[MarimoInterruptionError()],
+ clear_console=False,
+ cell_id=cell.cell_id,
+ status=cell.status,
+ )
+ elif run_result.exception is not None:
+ LOGGER.debug(
+ "Cell %s raised %s",
+ cell.cell_id,
+ type(run_result.exception).__name__,
+ )
+ # don't clear console because this cell was running and
+ # its console outputs are not stale
+ exception_type = type(run_result.exception).__name__
+ CellOp.broadcast_error(
+ data=[
+ MarimoExceptionRaisedError(
+ msg="This cell raised an exception: %s%s"
+ % (
+ exception_type,
+ (
+ f"('{str(run_result.exception)}')"
+ if str(run_result.exception)
+ else ""
+ ),
+ ),
+ exception_type=exception_type,
+ raising_cell=None,
+ )
+ ],
+ clear_console=False,
+ cell_id=cell.cell_id,
+ status=cell.status,
+ )
+
+
+def _reset_matplotlib_context(
+ cell: CellImpl,
+ runner: cell_runner.Runner,
+ run_result: cell_runner.RunResult,
+) -> None:
+ del cell
+ del run_result
+ if get_global_context().mpl_installed:
+ # ensures that every cell gets a fresh axis.
+ exec("__marimo__._output.mpl.close_figures()", runner.glbls)
+
+
+POST_EXECUTION_HOOKS = [
+ _set_status_idle,
+ _broadcast_variables,
+ _broadcast_outputs,
+ _reset_matplotlib_context,
+]
diff --git a/marimo/_runtime/runner/hooks_pre_execution.py b/marimo/_runtime/runner/hooks_pre_execution.py
new file mode 100644
index 0000000000..f7c42348ff
--- /dev/null
+++ b/marimo/_runtime/runner/hooks_pre_execution.py
@@ -0,0 +1,30 @@
+# Copyright 2024 Marimo. All rights reserved.
+from marimo._ast.cell import CellImpl
+from marimo._runtime.runner import cell_runner
+
+
+def _set_staleness(
+ cell: CellImpl,
+ runner: cell_runner.Runner,
+) -> None:
+ graph = runner.graph
+
+ if runner.execution_mode == "lazy" and not graph.is_any_ancestor_stale(
+ cell.cell_id
+ ):
+ # TODO: The above check could be omitted as an optimization as long as
+ # parents are guaranteed to run before child.
+ #
+ # Only no longer stale if its parents are not stale
+ cell.set_stale(stale=False)
+
+
+def _set_status_to_running(
+ cell: CellImpl,
+ runner: cell_runner.Runner,
+) -> None:
+ del runner
+ cell.set_status("running")
+
+
+PRE_EXECUTION_HOOKS = [_set_staleness, _set_status_to_running]
diff --git a/marimo/_runtime/runner/hooks_preparation.py b/marimo/_runtime/runner/hooks_preparation.py
new file mode 100644
index 0000000000..b34e80d0fa
--- /dev/null
+++ b/marimo/_runtime/runner/hooks_preparation.py
@@ -0,0 +1,25 @@
+# Copyright 2024 Marimo. All rights reserved.
+from marimo._runtime import dataflow
+from marimo._runtime.runner import cell_runner
+
+
+def _update_stale_statuses(runner: cell_runner.Runner) -> None:
+ graph = runner.graph
+
+ if runner.execution_mode == "lazy":
+ for cid in dataflow.transitive_closure(
+ graph, set(runner.cells_to_run), inclusive=False
+ ):
+ graph.cells[cid].set_stale(stale=True)
+
+ for cid in runner.cells_to_run:
+ if graph.is_disabled(cid):
+ graph.cells[cid].set_stale(stale=True)
+ else:
+ graph.cells[cid].set_status(status="queued")
+ if graph.cells[cid].stale:
+ if runner.execution_mode == "autorun":
+ graph.cells[cid].set_stale(stale=False)
+
+
+PREPARATION_HOOKS = [_update_stale_statuses]
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index e45c0e8e1e..9eac0dc711 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -21,16 +21,9 @@ 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
+from marimo._config.config import MarimoConfig, OnCellChangeType
from marimo._messaging.cell_output import CellChannel
-from marimo._messaging.errors import (
- Error,
- MarimoAncestorStoppedError,
- MarimoExceptionRaisedError,
- MarimoInterruptionError,
- MarimoSyntaxError,
- UnknownError,
-)
+from marimo._messaging.errors import Error, MarimoSyntaxError, UnknownError
from marimo._messaging.ops import (
Alert,
CellOp,
@@ -60,26 +53,18 @@ from marimo._messaging.types import (
Stdout,
Stream,
)
-from marimo._output import formatting
from marimo._output.rich_help import mddoc
from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._core.ui_element import MarimoConvertValueException
-from marimo._runtime import (
- cell_runner,
- dataflow,
- handlers,
- marimo_pdb,
- patches,
-)
+from marimo._runtime import dataflow, handlers, marimo_pdb, patches
from marimo._runtime.complete import complete, completion_worker
from marimo._runtime.context import (
ContextNotInitializedError,
ExecutionContext,
get_context,
- get_global_context,
)
from marimo._runtime.context.kernel_context import initialize_kernel_context
-from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
+from marimo._runtime.control_flow import MarimoInterrupt
from marimo._runtime.input_override import input_override
from marimo._runtime.packages.module_registry import ModuleRegistry
from marimo._runtime.packages.package_manager import PackageManager
@@ -105,6 +90,13 @@ from marimo._runtime.requests import (
SetUserConfigRequest,
StopRequest,
)
+from marimo._runtime.runner import cell_runner
+from marimo._runtime.runner.hooks import (
+ ON_FINISH_HOOKS,
+ POST_EXECUTION_HOOKS,
+ PRE_EXECUTION_HOOKS,
+ PREPARATION_HOOKS,
+)
from marimo._runtime.state import State
from marimo._runtime.validate_graph import check_for_errors
from marimo._runtime.win32_interrupt_handler import Win32InterruptHandler
@@ -318,6 +310,9 @@ class Kernel:
self.module_reloader: ModuleReloader | None = None
self.module_watcher: ModuleWatcher | None = None
# Load runtime settings from user config
+ self.reactive_execution_mode: OnCellChangeType = user_config[
+ "runtime"
+ ]["on_cell_change"]
self._update_runtime_from_user_config(user_config)
# Set up the execution context
@@ -336,6 +331,9 @@ class Kernel:
exec("import sys; sys.path.append(''); del sys", self.globals)
exec("import marimo as __marimo__", self.globals)
+ def lazy(self) -> bool:
+ return self.reactive_execution_mode == "lazy"
+
def _execute_stale_cells_callback(self) -> None:
return self.enqueue_control_request(ExecuteStaleRequest())
@@ -349,13 +347,15 @@ class Kernel:
def _update_runtime_from_user_config(self, config: MarimoConfig) -> None:
package_manager = config["package_management"]["manager"]
autoreload_mode = config["runtime"]["auto_reload"]
+ self.reactive_execution_mode = config["runtime"]["on_cell_change"]
+
if (
self.package_manager is None
or package_manager != self.package_manager.name
):
self.package_manager = create_package_manager(package_manager)
- if autoreload_mode == "detect" or autoreload_mode == "autorun":
+ if autoreload_mode == "lazy" or autoreload_mode == "autorun":
if self.module_reloader is None:
self.module_reloader = ModuleReloader()
@@ -433,7 +433,9 @@ class Kernel:
)
def _try_registering_cell(
- self, cell_id: CellId_t, code: str
+ self,
+ cell_id: CellId_t,
+ code: str,
) -> Optional[Error]:
"""Attempt to register a cell with given id and code.
@@ -724,15 +726,16 @@ class Kernel:
cells_with_errors_before_mutation
- cells_with_errors_after_mutation
) & cells_in_graph
- for cid in cells_that_no_longer_have_errors:
- # clear error outputs before running
- CellOp.broadcast_output(
- channel=CellChannel.OUTPUT,
- mimetype="text/plain",
- data="",
- cell_id=cid,
- status=None,
- )
+ if self.reactive_execution_mode == "autorun":
+ for cid in cells_that_no_longer_have_errors:
+ # clear error outputs before running
+ CellOp.broadcast_output(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/plain",
+ data="",
+ cell_id=cid,
+ status=None,
+ )
# Cells that were successfully registered need to be run
cells_registered_without_error = (
@@ -758,25 +761,6 @@ class Kernel:
continue
self._invalidate_cell_state(cid, exclude_defs=keep_alive_defs)
- roots = (
- set(
- itertools.chain(
- cells_registered_without_error,
- cells_that_were_children_of_mutated_cells,
- cells_transitioned_to_error,
- cells_that_no_longer_have_errors,
- )
- )
- & cells_in_graph
- )
- descendants = (
- dataflow.transitive_closure(self.graph, roots)
- # 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
- - cells_with_errors_after_mutation
- )
-
self.errors = all_errors
for cid in self.errors:
if (
@@ -805,7 +789,29 @@ class Kernel:
for variable, declared_by in self.graph.definitions.items()
]
).broadcast()
- return descendants
+
+ stale_cells = (
+ set(
+ itertools.chain(
+ cells_that_were_children_of_mutated_cells,
+ set().union(
+ *[
+ self.graph.children[cid]
+ for cid in cells_transitioned_to_error
+ if cid in self.graph.children
+ ]
+ ),
+ cells_that_no_longer_have_errors,
+ )
+ )
+ - cells_registered_without_error
+ ) & cells_in_graph
+
+ if self.reactive_execution_mode == "lazy":
+ self.graph.set_stale(stale_cells)
+ return cells_registered_without_error
+ else:
+ return cells_registered_without_error.union(stale_cells)
async def _run_cells(self, cell_ids: set[CellId_t]) -> None:
"""Run cells and any state updates they trigger"""
@@ -816,231 +822,76 @@ class Kernel:
# common cases. We could also be more aggressive and run this before
# every cell, or even before pickle.dump/pickle.dumps()
patches.patch_sys_module(self._module)
- while cells_with_stale_state := await self._run_cells_internal(
- cell_ids
- ):
+ while cell_ids := await self._run_cells_internal(cell_ids):
LOGGER.debug("Running state updates ...")
- cell_ids = dataflow.transitive_closure(
- self.graph, cells_with_stale_state
- )
+ if self.lazy() and cell_ids:
+ self.graph.set_stale(cell_ids)
+ break
LOGGER.debug("Finished run.")
- async def _run_cells_internal(
- self, cell_ids: set[CellId_t]
- ) -> set[CellId_t]:
+ async def _run_cells_internal(self, roots: set[CellId_t]) -> set[CellId_t]:
"""Run cells, send outputs to frontends
Returns set of cells that need to be re-run due to state updates.
"""
- LOGGER.debug("preparing to evaluate cells %s", cell_ids)
- # Status updates: cells transition to queued, except for
- # cells that are disabled (explicitly or implicitly).
- for cid in cell_ids:
- if self.graph.is_disabled(cid):
- self.graph.cells[cid].set_stale(stale=True)
- else:
- self.graph.cells[cid].set_status(status="queued")
- if self.graph.cells[cid].stale:
- self.graph.cells[cid].set_stale(stale=False)
- # State clean-up: don't leak names, UI elements, ...
- #
- # Clean-up state for all cells upfront, before running
- # cells, to relieve memory pressure
- self._invalidate_cell_state(cid)
+ # Some hooks that are leaky and require the kernel
+ # Free cell state ahead of running to relieve memory pressure
+ #
+ # NB: lazy kernels don't invalidate state of cancelled cells
+ # descendants (cancelled == cells that raise exceptions), whereas
+ # eager kernels do (since we clear all state ahead of time, and
+ # have the closure of the roots in cells to run)
+ def invalidate_state(runner: cell_runner.Runner) -> None:
+ for cid in runner.cells_to_run:
+ self._invalidate_cell_state(cid)
+
+ def broadcast_missing_packages(runner: cell_runner.Runner) -> None:
+ if (
+ any(
+ isinstance(e, ModuleNotFoundError)
+ for e in runner.exceptions.values()
+ )
+ and self.package_manager is not None
+ ):
+ missing_packages = [
+ self.package_manager.module_to_package(mod)
+ for mod in self.module_registry.missing_modules()
+ ]
+
+ if missing_packages:
+ if self.package_manager.should_auto_install():
+ self._execute_install_missing_packages_callback(
+ self.package_manager.name
+ )
+ else:
+ MissingPackageAlert(
+ packages=list(sorted(missing_packages)),
+ isolated=is_python_isolated(),
+ ).broadcast()
runner = cell_runner.Runner(
- cell_ids=cell_ids,
+ roots=roots,
graph=self.graph,
glbls=self.globals,
+ excluded_cells=set(self.errors.keys()),
debugger=self.debugger,
+ execution_mode=self.reactive_execution_mode,
+ execution_context=self._install_execution_context,
+ preparation_hooks=PREPARATION_HOOKS + [invalidate_state],
+ pre_execution_hooks=PRE_EXECUTION_HOOKS,
+ post_execution_hooks=POST_EXECUTION_HOOKS,
+ on_finish_hooks=ON_FINISH_HOOKS + [broadcast_missing_packages],
)
# I/O
#
- # TODO(akshayka): ignore stdin (always read empty string)
- # TODO(akshayka): redirect input to frontend (override builtins.input)
- # or ignore/disallow input, since most users will use a
- # marimo UI component anyway
# TODO(akshayka): when no logger is configured, log output is not
# redirected to frontend (it's printed to console),
# which is incorrect
- # TODO(akshayka): pdb support
- LOGGER.debug("final set of cells to run %s", runner.cells_to_run)
-
- while runner.pending():
- cell_id = runner.pop_cell()
- if runner.cancelled(cell_id):
- continue
- cell = self.graph.cells[cell_id]
- if cell.stale:
- continue
-
- LOGGER.debug("running cell %s", cell_id)
- cell.set_status(status="running")
-
- with self._install_execution_context(cell_id) as exc_ctx:
- run_result = await runner.run(cell_id)
- # Don't rebroadcast an output that was already sent
- #
- # 1. if run_result.output is not None, need to send it
- # 2. otherwise if exc_ctx.output is None, then need to send
- # the (empty) output (to clear it)
- new_output = (
- run_result.output is not None or exc_ctx.output is None
- )
-
- values = [
- VariableValue(
- name=variable,
- value=(
- self.globals[variable]
- if variable in self.globals
- else None
- ),
- )
- for variable in self.graph.cells[cell_id].defs
- ]
-
- if values:
- VariableValues(variables=values).broadcast()
-
- cell.set_status(status="idle")
- if (
- run_result.success()
- or isinstance(run_result.exception, MarimoStopError)
- ) and new_output:
- with self._install_execution_context(cell_id) as exc_ctx:
- formatted_output = formatting.try_format(run_result.output)
- if formatted_output.traceback is not None:
- with self._install_execution_context(cell_id):
- write_traceback(formatted_output.traceback)
- CellOp.broadcast_output(
- channel=CellChannel.OUTPUT,
- mimetype=formatted_output.mimetype,
- data=formatted_output.data,
- cell_id=cell_id,
- status=cell.status,
- )
- elif isinstance(run_result.exception, MarimoInterrupt):
- LOGGER.debug("Cell %s was interrupted", cell_id)
- # don't clear console because this cell was running and
- # its console outputs are not stale
- CellOp.broadcast_error(
- data=[MarimoInterruptionError()],
- clear_console=False,
- cell_id=cell_id,
- status=cell.status,
- )
- elif run_result.exception is not None:
- LOGGER.debug(
- "Cell %s raised %s",
- cell_id,
- type(run_result.exception).__name__,
- )
- # don't clear console because this cell was running and
- # its console outputs are not stale
- exception_type = type(run_result.exception).__name__
- CellOp.broadcast_error(
- data=[
- MarimoExceptionRaisedError(
- msg="This cell raised an exception: %s%s"
- % (
- exception_type,
- (
- f"('{str(run_result.exception)}')"
- if str(run_result.exception)
- else ""
- ),
- ),
- exception_type=exception_type,
- raising_cell=None,
- )
- ],
- clear_console=False,
- cell_id=cell_id,
- status=cell.status,
- )
-
- if get_global_context().mpl_installed:
- # ensures that every cell gets a fresh axis.
- exec("__marimo__._output.mpl.close_figures()", self.globals)
-
- if runner.cells_to_run:
- assert runner.interrupted
- for cid in runner.cells_to_run:
- # `cid` was not run
- self.graph.cells[cid].set_status("idle")
- CellOp.broadcast_error(
- data=[MarimoInterruptionError()],
- # these cells are transitioning from queued to stopped
- # (interrupted); they didn't get to run, so their consoles
- # reflect a previous run and should be cleared
- clear_console=True,
- cell_id=cid,
- status="idle",
- )
-
- for raising_cell in runner.cells_cancelled:
- for cid in runner.cells_cancelled[raising_cell]:
- # `cid` was not run
- self.graph.cells[cid].set_status("idle")
- exception = runner.exceptions[raising_cell]
- data: Error
- if isinstance(exception, MarimoStopError):
- data = MarimoAncestorStoppedError(
- msg=(
- "This cell wasn't run because an "
- "ancestor was stopped with `mo.stop`: "
- ),
- raising_cell=raising_cell,
- )
- else:
- exception_type = type(
- runner.exceptions[raising_cell]
- ).__name__
- data = MarimoExceptionRaisedError(
- msg=(
- "An ancestor raised an exception "
- f"({exception_type}): "
- ),
- exception_type=exception_type,
- raising_cell=raising_cell,
- )
- CellOp.broadcast_error(
- data=[data],
- # these cells are transitioning from queued to stopped
- # (interrupted); they didn't get to run, so their consoles
- # reflect a previous run and should be cleared
- clear_console=True,
- cell_id=cid,
- status="idle",
- )
-
- if (
- any(
- isinstance(e, ModuleNotFoundError)
- for e in runner.exceptions.values()
- )
- and self.package_manager is not None
- ):
- missing_packages = [
- self.package_manager.module_to_package(mod)
- for mod in self.module_registry.missing_modules()
- ]
- if missing_packages:
- if self.package_manager.should_auto_install():
- self._execute_install_missing_packages_callback(
- self.package_manager.name
- )
- else:
- MissingPackageAlert(
- packages=list(sorted(missing_packages)),
- isolated=is_python_isolated(),
- ).broadcast()
-
+ await runner.run_all()
cells_with_stale_state = runner.resolve_state_updates(
- self.state_updates, self.errors
+ self.state_updates
)
self.state_updates.clear()
return cells_with_stale_state
@@ -1088,6 +939,8 @@ 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)
)
@@ -1099,10 +952,8 @@ class Kernel:
Cells that are enabled (via config) but stale are run as a side-effect.
"""
- # TODO: state transitions to disabled-transitively, stale, idle should
- # be handled by the graph, not by kernel ...
# Stale cells that are enabled will need to be run.
- cells_to_run: set[CellId_t] = set()
+ stale_cells: set[CellId_t] = set()
for cell_id, config in request.configs.items():
# store the config, regardless of whether we've seen the cell yet
self.cell_metadata[cell_id] = CellMetadata(
@@ -1113,14 +964,12 @@ class Kernel:
continue
cell.configure(config)
if not cell.config.disabled:
- cells_to_run = self.graph.enable_cell(cell_id)
+ stale_cells = self.graph.enable_cell(cell_id)
elif cell.config.disabled:
self.graph.disable_cell(cell_id)
- if cells_to_run:
- await self._run_cells(
- dataflow.transitive_closure(self.graph, cells_to_run)
- )
+ if stale_cells and self.reactive_execution_mode == "autorun":
+ await self._run_cells(stale_cells)
def set_user_config(self, request: SetUserConfigRequest) -> None:
self._update_runtime_from_user_config(request.config)
@@ -1239,9 +1088,14 @@ class Kernel:
if variable_values:
VariableValues(variables=variable_values).broadcast()
- await self._run_cells(
- dataflow.transitive_closure(self.graph, referring_cells)
- )
+
+ if self.reactive_execution_mode == "autorun":
+ await self._run_cells(referring_cells)
+ else:
+ self.graph.set_stale(referring_cells)
+ # process any state updates that may have been queued by the
+ # on_change handlers
+ await self._run_cells(set())
def get_ui_initial_value(self, object_id: str) -> Any:
"""Get an initial value for a UIElement, if any
@@ -1394,9 +1248,12 @@ class Kernel:
if (cid := self.module_registry.defining_cell(module)) is not None
)
if cells_to_run:
- await self._run_cells(
- dataflow.transitive_closure(self.graph, cells_to_run)
- )
+ if self.reactive_execution_mode == "autorun":
+ await self._run_cells(
+ dataflow.transitive_closure(self.graph, cells_to_run)
+ )
+ else:
+ self.graph.set_stale(cells_to_run)
async def handle_message(self, request: ControlRequest) -> None:
"""Handle a message from the client.
diff --git a/tests/_runtime/reload/test_module_watcher.py b/tests/_runtime/reload/test_module_watcher.py
index 846f29b568..9fc6c401d2 100644
--- a/tests/_runtime/reload/test_module_watcher.py
+++ b/tests/_runtime/reload/test_module_watcher.py
@@ -37,7 +37,7 @@ async def test_reload_function(
)
config = copy.deepcopy(DEFAULT_CONFIG)
- config["runtime"]["auto_reload"] = "detect"
+ config["runtime"]["auto_reload"] = "lazy"
k.set_user_config(SetUserConfigRequest(config=config))
await k.run(
[
@@ -97,7 +97,7 @@ async def test_reload_nested_module_function(
)
config = copy.deepcopy(DEFAULT_CONFIG)
- config["runtime"]["auto_reload"] = "detect"
+ config["runtime"]["auto_reload"] = "lazy"
k.set_user_config(SetUserConfigRequest(config=config))
await k.run(
[
@@ -151,7 +151,7 @@ async def test_reload_nested_module_import_module(
)
config = copy.deepcopy(DEFAULT_CONFIG)
- config["runtime"]["auto_reload"] = "detect"
+ config["runtime"]["auto_reload"] = "lazy"
k.set_user_config(SetUserConfigRequest(config=config))
await k.run(
[
@@ -254,7 +254,7 @@ async def test_reload_package(
nested_module.write_text("func = lambda: 1")
config = copy.deepcopy(DEFAULT_CONFIG)
- config["runtime"]["auto_reload"] = "detect"
+ config["runtime"]["auto_reload"] = "lazy"
k.set_user_config(SetUserConfigRequest(config=config))
await k.run(
[
@@ -305,7 +305,7 @@ async def test_reload_third_party(
)
config = copy.deepcopy(DEFAULT_CONFIG)
- config["runtime"]["auto_reload"] = "detect"
+ config["runtime"]["auto_reload"] = "lazy"
k.set_user_config(SetUserConfigRequest(config=config))
await k.run(
[
diff --git a/tests/_runtime/test_cell_runner.py b/tests/_runtime/runner/test_cell_runner.py
similarity index 91%
rename from tests/_runtime/test_cell_runner.py
rename to tests/_runtime/runner/test_cell_runner.py
index eee21c375e..70d49c68c3 100644
--- a/tests/_runtime/test_cell_runner.py
+++ b/tests/_runtime/runner/test_cell_runner.py
@@ -1,6 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
from marimo._runtime.capture import capture_stderr
-from marimo._runtime.cell_runner import Runner
+from marimo._runtime.runner.cell_runner import Runner
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
@@ -10,7 +10,7 @@ async def test_cell_output(k: Kernel, exec_req: ExecReqProvider) -> None:
await k.run([er := exec_req.get("'hello'; 123")])
runner = Runner(
- cell_ids=set(k.graph.cells.keys()),
+ roots=set(k.graph.cells.keys()),
graph=k.graph,
glbls=k.globals,
debugger=k.debugger,
@@ -39,7 +39,7 @@ async def test_traceback_includes_lineno(
)
runner = Runner(
- cell_ids=set(k.graph.cells.keys()),
+ roots=set(k.graph.cells.keys()),
graph=k.graph,
glbls=k.globals,
debugger=k.debugger,
@@ -70,7 +70,7 @@ async def test_base_exception_caught(
)
runner = Runner(
- cell_ids=set(k.graph.cells.keys()),
+ roots=set(k.graph.cells.keys()),
graph=k.graph,
glbls=k.globals,
debugger=k.debugger,
diff --git a/tests/_runtime/test_context.py b/tests/_runtime/test_context.py
new file mode 100644
index 0000000000..d04349b50e
--- /dev/null
+++ b/tests/_runtime/test_context.py
@@ -0,0 +1,29 @@
+from marimo._runtime import context
+from marimo._runtime.runtime import Kernel
+from tests.conftest import ExecReqProvider
+
+
+async def test_context_installed(k: Kernel, exec_req: ExecReqProvider) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+
+ installed = mo._runtime.context.runtime_context_installed()
+ """
+ )
+ ]
+ )
+
+ assert k.globals["installed"]
+
+
+def test_context_not_installed() -> None:
+ assert not context.runtime_context_installed()
+
+
+def test_not_running_in_notebook() -> None:
+ from marimo._runtime.context.utils import running_in_notebook
+
+ assert not running_in_notebook()
diff --git a/tests/_runtime/test_control_flow.py b/tests/_runtime/test_control_flow.py
index 38e8f7ecdc..e578697749 100644
--- a/tests/_runtime/test_control_flow.py
+++ b/tests/_runtime/test_control_flow.py
@@ -1,10 +1,9 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from marimo._runtime import cell_runner, control_flow
-from marimo._runtime.requests import (
- ExecutionRequest,
-)
+from marimo._runtime import control_flow
+from marimo._runtime.requests import ExecutionRequest
+from marimo._runtime.runner import cell_runner
from marimo._runtime.runtime import Kernel
diff --git a/tests/_runtime/test_dataflow.py b/tests/_runtime/test_dataflow.py
index d36a2d22fa..693911343c 100644
--- a/tests/_runtime/test_dataflow.py
+++ b/tests/_runtime/test_dataflow.py
@@ -73,6 +73,34 @@ def test_graph_closure() -> None:
assert graph.cells == {"0": first_cell, "1": second_cell}
assert graph.parents == {"0": set(), "1": set(["0"])}
assert graph.children == {"0": set(["1"]), "1": set()}
+ assert dataflow.transitive_closure(graph, cell_ids=set(["0"])) == set(
+ ["0", "1"]
+ )
+
+
+def test_graph_closure_predicate() -> None:
+ graph = dataflow.DirectedGraph()
+ code = "x = 0"
+ first_cell = parse_cell(code)
+ graph.register_cell("0", first_cell)
+
+ code = "def foo():\n return x"
+ second_cell = parse_cell(code)
+ graph.register_cell("1", second_cell)
+ graph.set_stale(set(["1"]))
+
+ code = "x"
+ third_cell = parse_cell(code)
+ graph.register_cell("2", third_cell)
+
+ # 0 --> 1
+ assert graph.cells == {"0": first_cell, "1": second_cell, "2": third_cell}
+ assert graph.parents == {"0": set(), "1": set(["0"]), "2": set(["0"])}
+ assert graph.children == {"0": set(["1", "2"]), "1": set(), "2": set()}
+
+ assert dataflow.transitive_closure(
+ graph, cell_ids=set(["0"]), predicate=lambda cell: not cell.stale
+ ) == set(["0", "2"])
def test_graph_redefine() -> None:
@@ -89,3 +117,106 @@ def test_graph_redefine() -> None:
assert graph.cells == {"0": first_cell, "1": second_cell}
assert graph.parents == {"0": set(), "1": set()}
assert graph.children == {"0": set(), "1": set()}
+
+
+def test_set_stale() -> None:
+ # 0 --> 1 --> 2, 0 --> 2, 3
+ graph = dataflow.DirectedGraph()
+ code = "x = 0"
+ first_cell = parse_cell(code)
+ graph.register_cell("0", first_cell)
+
+ code = "y = x"
+ second_cell = parse_cell(code)
+ graph.register_cell("1", second_cell)
+
+ code = "z = y\nzz = x"
+ third_cell = parse_cell(code)
+ graph.register_cell("2", third_cell)
+
+ code = "a = 0"
+ fourth_cell = parse_cell(code)
+ graph.register_cell("3", fourth_cell)
+
+ # no cells are stale originally
+ assert not graph.get_stale()
+
+ # 0 and its children are stale
+ graph.set_stale(set(["0"]))
+ assert graph.get_stale() == set(["0", "1", "2"])
+
+ graph.cells["0"].set_stale(stale=False)
+ graph.cells["1"].set_stale(stale=False)
+ graph.cells["2"].set_stale(stale=False)
+ assert not graph.get_stale()
+
+
+def test_ancestors() -> None:
+ # 0 --> 1 --> 2, 0 --> 2, 3
+ graph = dataflow.DirectedGraph()
+ code = "x = 0"
+ first_cell = parse_cell(code)
+ graph.register_cell("0", first_cell)
+
+ code = "y = x"
+ second_cell = parse_cell(code)
+ graph.register_cell("1", second_cell)
+
+ code = "z = y\nzz = x"
+ third_cell = parse_cell(code)
+ graph.register_cell("2", third_cell)
+
+ code = "a = 0"
+ fourth_cell = parse_cell(code)
+ graph.register_cell("3", fourth_cell)
+
+ assert not graph.ancestors("0")
+ assert graph.ancestors("1") == set(["0"])
+ assert graph.ancestors("2") == set(["0", "1"])
+ assert not graph.ancestors("3")
+
+
+def test_descendants() -> None:
+ # 0 --> 1 --> 2, 0 --> 2, 3
+ graph = dataflow.DirectedGraph()
+ code = "x = 0"
+ first_cell = parse_cell(code)
+ graph.register_cell("0", first_cell)
+
+ code = "y = x"
+ second_cell = parse_cell(code)
+ graph.register_cell("1", second_cell)
+
+ code = "z = y\nzz = x"
+ third_cell = parse_cell(code)
+ graph.register_cell("2", third_cell)
+
+ code = "a = 0"
+ fourth_cell = parse_cell(code)
+ graph.register_cell("3", fourth_cell)
+
+ assert graph.descendants("0") == set(["1", "2"])
+ assert graph.descendants("1") == set(["2"])
+ assert not graph.descendants("2")
+ assert not graph.ancestors("3")
+
+
+def test_register_with_stale_ancestor() -> None:
+ # 0 [stale]
+ # register 0 [stale] --> 1, ensure 1 is stale
+ graph = dataflow.DirectedGraph()
+ code = "x = 0"
+ first_cell = parse_cell(code)
+ graph.register_cell("0", first_cell)
+ graph.set_stale(set(["0"]))
+
+ code = "y = x"
+ second_cell = parse_cell(code)
+ graph.register_cell("1", second_cell)
+ assert graph.get_stale() == set(["0", "1"])
+
+ # add a third cell not related to the others
+ code = "a = 0"
+ third_cell = parse_cell(code)
+ graph.register_cell("3", third_cell)
+ assert graph.get_stale() == set(["0", "1"])
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 723a458a10..dd35e9e829 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -39,881 +39,1028 @@ def _check_edges(error: Error, expected_edges: Sequence[EdgeWithVar]) -> None:
assert edge in error.edges_with_vars
-# Test Basic Reactivity
-async def test_triangle(k: Kernel) -> None:
- # x
- # x --> y
- # x, y --> z
- await k.run(
- [
- ExecutionRequest(cell_id="0", code="x = 1"),
- ExecutionRequest(cell_id="1", code="y = x + 1"),
- ExecutionRequest(cell_id="2", code="z = x + y"),
- ]
- )
- assert k.globals["x"] == 1
- assert k.globals["y"] == 2
- assert k.globals["z"] == 3
-
- await k.run([ExecutionRequest(cell_id="0", code="x = 2")])
- assert k.globals["x"] == 2
- assert k.globals["y"] == 3
- assert k.globals["z"] == 5
-
- await k.run([ExecutionRequest(cell_id="1", code="y = 0")])
- assert k.globals["x"] == 2
- assert k.globals["y"] == 0
- assert k.globals["z"] == 2
-
- await k.delete(DeleteRequest(cell_id="1"))
- assert k.globals["x"] == 2
- assert "y" not in k.globals
- assert "z" not in k.globals
-
- await k.delete(DeleteRequest(cell_id="0"))
- assert "x" not in k.globals
- assert "y" not in k.globals
- assert "z" not in k.globals
-
-
-async def test_set_ui_element_value(k: Kernel) -> None:
- await k.run([ExecutionRequest(cell_id="0", code="import marimo as mo")])
- await k.run(
- [
- ExecutionRequest(
- cell_id="1", code="s = mo.ui.slider(0, 10, value=1); s"
- )
- ]
- )
- await k.run([ExecutionRequest(cell_id="2", code="x = s.value + 1")])
- assert k.globals["x"] == 2
+class TestExecution:
+ async def test_triangle(self, any_kernel: Kernel) -> None:
+ k = any_kernel
+ # x
+ # x --> y
+ # x, y --> z
+ await k.run(
+ [
+ ExecutionRequest(cell_id="0", code="x = 1"),
+ er1 := ExecutionRequest(cell_id="1", code="y = x + 1"),
+ er2 := ExecutionRequest(cell_id="2", code="z = x + y"),
+ ]
+ )
+ assert k.globals["x"] == 1
+ assert k.globals["y"] == 2
+ assert k.globals["z"] == 3
+
+ await k.run([ExecutionRequest(cell_id="0", code="x = 2")])
+ assert not k.graph.cells["0"].stale
+ assert k.globals["x"] == 2
+ if k.lazy():
+ assert k.graph.cells["1"].stale
+ assert k.graph.cells["2"].stale
+ await k.run([er1])
+
+ assert not k.graph.cells["0"].stale
+ assert not k.graph.cells["1"].stale
+ assert k.globals["x"] == 2
+ assert k.globals["y"] == 3
+ if k.lazy():
+ assert k.graph.cells["2"].stale
+ await k.run([er2])
+ assert k.globals["z"] == 5
+ assert not k.graph.cells["0"].stale
+ assert not k.graph.cells["1"].stale
+ assert not k.graph.cells["2"].stale
+
+ await k.run([ExecutionRequest(cell_id="1", code="y = 0")])
+ assert not k.graph.cells["0"].stale
+ assert not k.graph.cells["1"].stale
+ assert k.globals["x"] == 2
+ assert k.globals["y"] == 0
+ if k.lazy():
+ assert k.graph.cells["2"].stale
+ await k.run([er2])
+ assert k.globals["z"] == 2
+
+ await k.delete(DeleteRequest(cell_id="1"))
+ assert k.globals["x"] == 2
+ assert "y" not in k.globals
+ if k.lazy():
+ assert k.graph.cells["2"].stale
+ await k.run([er2])
+ assert "z" not in k.globals
+
+ await k.delete(DeleteRequest(cell_id="0"))
+ assert "x" not in k.globals
+ assert "y" not in k.globals
+ assert "z" not in k.globals
+
+ async def test_run_referrers_not_stale(self, any_kernel: Kernel) -> None:
+ k = any_kernel
+ graph = k.graph
+
+ # Tests that running cells doesn't spuriously mark other cells
+ # as stale
+ await k.run(
+ [
+ ExecutionRequest(cell_id="0", code="x = 1"),
+ er1 := ExecutionRequest(cell_id="1", code="x"),
+ er2 := ExecutionRequest(cell_id="2", code="x"),
+ ]
+ )
+ assert not graph.get_stale()
- element_id = k.globals["s"]._id
- await k.set_ui_element_value(SetUIElementValueRequest([(element_id, 5)]))
- assert k.globals["s"].value == 5
- assert k.globals["x"] == 6
+ await k.run([er1])
+ assert not graph.get_stale()
+ await k.run([er2])
+ assert not graph.get_stale()
-async def test_set_ui_element_value_not_found_doesnt_fail(k: Kernel) -> None:
- # smoke test -- this shouldn't raise an exception
- await k.set_ui_element_value(
- SetUIElementValueRequest([("does not exist", None)])
- )
+ async def test_set_ui_element_value(self, any_kernel: Kernel) -> None:
+ k = any_kernel
+ await k.run(
+ [ExecutionRequest(cell_id="0", code="import marimo as mo")]
+ )
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="1", code="s = mo.ui.slider(0, 10, value=1); s"
+ )
+ ]
+ )
+ await k.run(
+ [er2 := ExecutionRequest(cell_id="2", code="x = s.value + 1")]
+ )
+ assert k.globals["x"] == 2
+ element_id = k.globals["s"]._id
+ await k.set_ui_element_value(
+ SetUIElementValueRequest([(element_id, 5)])
+ )
+ assert k.globals["s"].value == 5
-async def test_set_ui_element_value_lensed(
- k: Kernel, exec_req: ExecReqProvider
-) -> None:
- """Test setting the value of a lensed element.
+ if k.reactive_execution_mode == "lazy":
+ assert k.graph.cells["2"].stale
+ await k.run([er2])
- Make sure reactivity flows through its parent, and that its on_change
- handler is called exactly once.
- """
- await k.run([exec_req.get(code="import marimo as mo")])
+ assert k.globals["x"] == 6
+ assert not k.graph.cells["2"].stale
- # Create an array and output it ...
- cell_one_code = """
- data = []
- def on_change(v):
- data.append(v)
+ async def test_set_ui_element_value_lensed(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ """Test setting the value of a lensed element.
- array = mo.ui.array([mo.ui.slider(0, 10, value=1, on_change=on_change)]);
- array
- """
- await k.run([exec_req.get(code=cell_one_code)])
+ Make sure reactivity flows through its parent, and that its on_change
+ handler is called exactly once.
+ """
+ k = any_kernel
+ await k.run([exec_req.get(code="import marimo as mo")])
+
+ # Create an array and output it ...
+ cell_one_code = """
+ data = []
+ def on_change(v):
+ data.append(v)
+
+ array = mo.ui.array(
+ [mo.ui.slider(0, 10, value=1, on_change=on_change)]);
+ array
+ """
+ await k.run([exec_req.get(code=cell_one_code)])
- # Reference the array's value
- await k.run([exec_req.get(code="x = array.value[0] + 1")])
- assert k.globals["x"] == 2
+ # Reference the array's value
+ await k.run([er := exec_req.get(code="x = array.value[0] + 1")])
+ assert k.globals["x"] == 2
- # Set a child of the array to 5 ...
- child_id = k.globals["array"][0]._id
- await k.set_ui_element_value(SetUIElementValueRequest([(child_id, 5)]))
+ # Set a child of the array to 5 ...
+ child_id = k.globals["array"][0]._id
+ await k.set_ui_element_value(SetUIElementValueRequest([(child_id, 5)]))
- # Make sure the array and its child are updated
- assert k.globals["array"].value == [5]
- assert k.globals["array"][0].value == 5
+ # Make sure the array and its child are updated
+ assert k.globals["array"].value == [5]
+ assert k.globals["array"][0].value == 5
- # Make sure the on_change handler got called exactly once
- assert k.globals["data"] == [5]
+ # Make sure the on_change handler got called exactly once
+ assert k.globals["data"] == [5]
- # Make sure setting array's child triggered execution of the second cell,
- # which references `array`
- assert k.globals["x"] == 6
+ if k.lazy():
+ assert k.graph.cells[er.cell_id].stale
+ await k.run([er])
+ # Make sure setting array's child triggered execution of the second
+ # cell, which references `array`
+ assert k.globals["x"] == 6
-async def test_set_ui_element_value_lensed_bound_child(
- k: Kernel, exec_req: ExecReqProvider
-) -> None:
- """Test setting the value of a lensed element.
+ async def test_set_ui_element_value_lensed_bound_child(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ """Test setting the value of a lensed element.
- Make sure reactivity flows through its parent and also to names bound
- to children.
- """
- await k.run([exec_req.get(code="import marimo as mo")])
+ Make sure reactivity flows through its parent and also to names bound
+ to children.
+ """
+ k = any_kernel
+ await k.run([exec_req.get(code="import marimo as mo")])
- cell_one_code = """
- array = mo.ui.array([mo.ui.slider(0, 10, value=1)])
- child = array[0]
- """
- await k.run([exec_req.get(code=cell_one_code)])
- await k.run([exec_req.get(code="x = child.value + 1")])
+ cell_one_code = """
+ array = mo.ui.array([mo.ui.slider(0, 10, value=1)])
+ child = array[0]
+ """
+ await k.run([exec_req.get(code=cell_one_code)])
+ await k.run([er := exec_req.get(code="x = child.value + 1")])
- array_id = k.globals["array"]._id
- await k.set_ui_element_value(
- SetUIElementValueRequest([(array_id, {"0": 5})])
- )
- assert k.globals["array"].value == [5]
- assert k.globals["x"] == 6
+ array_id = k.globals["array"]._id
+ await k.set_ui_element_value(
+ SetUIElementValueRequest([(array_id, {"0": 5})])
+ )
+ assert k.globals["array"].value == [5]
+ if k.lazy():
+ assert k.graph.cells[er.cell_id].stale
+ await k.run([er])
+ assert k.globals["x"] == 6
+
+ async def test_set_ui_element_value_lensed_with_state(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ """Test setting value of a lensed element with on_change set_state"""
+ k = any_kernel
+ await k.run([exec_req.get(code="import marimo as mo")])
+
+ # Create an array and output it ...
+ cell_one_code = """
+ get_state, set_state = mo.state(None)
+
+ array = mo.ui.array(
+ [mo.ui.slider(0, 10, value=1, on_change=set_state),
+ mo.ui.slider(0, 10, value=1, on_change=set_state)
+ ]);
+ """
+ await k.run([exec_req.get(code=cell_one_code)])
+ await k.run([er := exec_req.get(code="state = get_state()")])
+
+ # Set a child of the array and make sure its on_change handler is
+ # called
+ child_id = k.globals["array"][0]._id
+ await k.set_ui_element_value(SetUIElementValueRequest([(child_id, 5)]))
+ if k.lazy():
+ assert k.graph.cells[er.cell_id].stale
+ await k.run([er])
+
+ # Make sure the array and its child are updated
+ assert k.globals["state"] == 5
+
+ async def test_set_local_var_ui_element_value(
+ self, any_kernel: Kernel
+ ) -> None:
+ k = any_kernel
+ await k.run([ExecutionRequest("0", "import marimo as mo")])
+ await k.run(
+ [ExecutionRequest("1", "_s = mo.ui.slider(0, 10, value=1); _s")]
+ )
+ # _s's name is mangled to _cell_1_s because it is local
+ assert k.globals["_cell_1_s"].value == 1
+
+ element_id = k.globals["_cell_1_s"]._id
+ # This shouldn't crash the kernel, and s's value should still be
+ # updated
+ await k.set_ui_element_value(
+ SetUIElementValueRequest([(element_id, 5)])
+ )
+ assert k.globals["_cell_1_s"].value == 5
+ async def test_creation_with_ui_element_value(
+ self, any_kernel: Kernel
+ ) -> None:
+ k = any_kernel
+ id_provider = IDProvider(prefix="1")
+ await k.instantiate(
+ CreationRequest(
+ execution_requests=(
+ ExecutionRequest(cell_id="0", code="import marimo as mo"),
+ ExecutionRequest(
+ cell_id="1", code="s = mo.ui.slider(0, 10, value=1)"
+ ),
+ ),
+ set_ui_element_value_request=SetUIElementValueRequest(
+ [(id_provider.take_id(), 2)]
+ ),
+ )
+ )
+ assert k.globals["s"].value == 2
-async def test_set_ui_element_value_lensed_with_state(
- k: Kernel, exec_req: ExecReqProvider
-) -> None:
- """Test setting the value of a lensed element with on_change set_state"""
- await k.run([exec_req.get(code="import marimo as mo")])
+ # Test errors in marimo semantics
+ async def test_kernel_simultaneous_multiple_definition_error(
+ self,
+ any_kernel: Kernel,
+ ) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ ExecutionRequest(cell_id="0", code="x=0"),
+ ExecutionRequest(cell_id="1", code="x=1"),
+ ]
+ )
- # Create an array and output it ...
- cell_one_code = """
- get_state, set_state = mo.state(None)
+ assert "x" not in k.globals
+ assert set(k.errors.keys()) == {"0", "1"}
+ assert k.errors["0"] == (MultipleDefinitionError("x", ("1",)),)
+ assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
- array = mo.ui.array(
- [mo.ui.slider(0, 10, value=1, on_change=set_state),
- mo.ui.slider(0, 10, value=1, on_change=set_state)
- ]);
- """
- await k.run([exec_req.get(code=cell_one_code)])
- await k.run([exec_req.get(code="state = get_state()")])
+ async def test_kernel_new_multiple_definition_does_not_invalidate(
+ self,
+ any_kernel: Kernel,
+ ) -> None:
+ k = any_kernel
+ await k.run([ExecutionRequest(cell_id="0", code="x=0")])
+ assert k.globals["x"] == 0
+ assert not k.errors
- # Set a child of the array and make sure its on_change handler is called
- child_id = k.globals["array"][0]._id
- await k.set_ui_element_value(SetUIElementValueRequest([(child_id, 5)]))
+ # cell 0 should not be invalidated by the introduction of cell 1
+ await k.run([ExecutionRequest(cell_id="1", code="x=0")])
+ assert k.globals["x"] == 0
+ assert set(k.errors.keys()) == {"1"}
+ assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
+
+ # re-running cell 0 should invalidate it
+ await k.run([ExecutionRequest(cell_id="0", code="x=0")])
+ assert "x" not in k.globals
+ assert set(k.errors.keys()) == {"0", "1"}
+ assert k.errors["0"] == (MultipleDefinitionError("x", ("1",)),)
+ assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
+
+ async def test_clear_multiple_definition_error(
+ self, any_kernel: Kernel
+ ) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ er := ExecutionRequest(cell_id="0", code="x=0"),
+ ExecutionRequest(cell_id="1", code="x=1"),
+ ]
+ )
+ assert "x" not in k.globals
+ assert set(k.errors.keys()) == {"0", "1"}
+ assert k.errors["0"] == (MultipleDefinitionError("x", ("1",)),)
+ assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
+
+ # Rename second occurrence of x to y; should eliminate error and run
+ # both cells
+ await k.run([ExecutionRequest(cell_id="1", code="y=1")])
+ assert k.globals["y"] == 1
+ if k.lazy():
+ assert k.graph.cells["0"].stale
+ await k.run([er])
+ assert not k.graph.cells["0"].stale
+ assert k.globals["x"] == 0
+ assert not k.errors
+
+ async def test_clear_multiple_definition_error_with_delete(
+ self, any_kernel: Kernel
+ ) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ er := ExecutionRequest(cell_id="0", code="x=0"),
+ ExecutionRequest(cell_id="1", code="x=1"),
+ ]
+ )
+ assert "x" not in k.globals
+ assert set(k.errors.keys()) == {"0", "1"}
+ assert k.errors["0"] == (MultipleDefinitionError("x", ("1",)),)
+ assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
+
+ # issue delete request for cell 1 to clear error and run cell 0
+ await k.delete(DeleteRequest(cell_id="1"))
+ if k.lazy():
+ assert k.graph.cells[er.cell_id].stale
+ await k.run([er])
+ assert not k.graph.cells[er.cell_id].stale
+ assert k.globals["x"] == 0
+ assert not k.errors
- # Make sure the array and its child are updated
- assert k.globals["state"] == 5
+ async def test_new_errors_update_old_ones(
+ self, any_kernel: Kernel
+ ) -> None:
+ k = any_kernel
+ await k.run([ExecutionRequest(cell_id="0", code="x=0")])
+ await k.run([ExecutionRequest(cell_id="1", code="x, y = 1, 2")])
+ assert set(k.errors.keys()) == {"1"}
+ assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
+
+ # errors propagated back to cell 1, even though we are not running it
+ await k.run([ExecutionRequest(cell_id="2", code="x, y = 3, 4")])
+ assert set(k.errors.keys()) == {"1", "2"}
+ assert k.errors["1"] == (
+ MultipleDefinitionError("x", ("0", "2")),
+ MultipleDefinitionError("y", ("2",)),
+ )
+ assert k.errors["2"] == (
+ MultipleDefinitionError("x", ("0", "1")),
+ MultipleDefinitionError("y", ("1",)),
+ )
+ assert k.globals["x"] == 0
-async def test_set_local_var_ui_element_value(k: Kernel) -> None:
- await k.run([ExecutionRequest("0", "import marimo as mo")])
- await k.run(
- [ExecutionRequest("1", "_s = mo.ui.slider(0, 10, value=1); _s")]
- )
- # _s's name is mangled to _cell_1_s because it is local
- assert k.globals["_cell_1_s"].value == 1
+ async def test_cycle_error(self, any_kernel: Kernel) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ ExecutionRequest(cell_id="0", code="x=y"),
+ ExecutionRequest(cell_id="1", code="y=x"),
+ er := ExecutionRequest(cell_id="2", code="z = x + 1"),
+ ]
+ )
+ assert "x" not in k.globals
+ assert "y" not in k.globals
+ assert set(k.errors.keys()) == {"0", "1"}
+ assert len(k.errors["0"]) == 1
+ assert len(k.errors["1"]) == 1
+ _check_edges(k.errors["0"][0], [("0", ["x"], "1"), ("1", ["y"], "0")])
+ _check_edges(k.errors["1"][0], [("0", ["x"], "1"), ("1", ["y"], "0")])
+
+ # break cycle by modifying cell
+ await k.run([ExecutionRequest(cell_id="1", code="y=1")])
+ if k.lazy():
+ assert k.graph.cells["0"].stale
+ assert k.graph.cells["2"].stale
+ await k.run([er])
+
+ assert not k.graph.cells["0"].stale
+ assert not k.graph.cells["2"].stale
+ assert k.globals["x"] == 1
+ assert k.globals["y"] == 1
+ assert k.globals["z"] == 2
+ assert not k.errors
- element_id = k.globals["_cell_1_s"]._id
- # This shouldn't crash the kernel, and s's value should still be updated
- await k.set_ui_element_value(SetUIElementValueRequest([(element_id, 5)]))
- assert k.globals["_cell_1_s"].value == 5
+ async def test_break_cycle_error_with_delete(
+ self, any_kernel: Kernel
+ ) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ ExecutionRequest(cell_id="0", code="x=y"),
+ ExecutionRequest(cell_id="1", code="y=x"),
+ ]
+ )
+ assert "x" not in k.globals
+ assert "y" not in k.globals
+ assert set(k.errors.keys()) == {"0", "1"}
+ assert len(k.errors["0"]) == 1
+ assert len(k.errors["1"]) == 1
+ _check_edges(k.errors["0"][0], [("0", ["x"], "1"), ("1", ["y"], "0")])
+
+ # break cycle by deleting cell
+ await k.delete(DeleteRequest(cell_id="1"))
+ assert not k.errors
+ async def test_delete_nonlocal_error(self, any_kernel: Kernel) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ ExecutionRequest(cell_id="0", code="x=0"),
+ ExecutionRequest(cell_id="1", code="del x; y = 1"),
+ er := ExecutionRequest(cell_id="2", code="z = y + 1"),
+ ]
+ )
+ assert "y" not in k.globals
+ assert "z" not in k.globals
+ assert set(k.errors.keys()) == {"1"}
+ assert k.errors["1"] == (DeleteNonlocalError("x", ("0",)),)
+
+ # fix cell 1, should run cell 1 and 2
+ await k.run([ExecutionRequest(cell_id="1", code="y=1")])
+ if k.lazy():
+ assert k.graph.cells[er.cell_id].stale
+ await k.run([er])
+
+ assert not k.graph.cells[er.cell_id].stale
+ assert k.globals["y"] == 1
+ assert k.globals["z"] == 2
+ assert not k.errors
-async def test_creation_with_ui_element_value(k: Kernel) -> None:
- id_provider = IDProvider(prefix="1")
- await k.instantiate(
- CreationRequest(
- execution_requests=(
- ExecutionRequest(cell_id="0", code="import marimo as mo"),
- ExecutionRequest(
- cell_id="1", code="s = mo.ui.slider(0, 10, value=1)"
- ),
- ),
- set_ui_element_value_request=SetUIElementValueRequest(
- [(id_provider.take_id(), 2)]
- ),
+ async def test_defs_with_no_definers_are_removed_from_cell(
+ self, any_kernel: Kernel
+ ) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ ExecutionRequest(cell_id="0", code="x=0"),
+ ExecutionRequest(cell_id="1", code="del x"),
+ ]
)
- )
- assert k.globals["s"].value == 2
-
-
-# Test errors in marimo semantics
-async def test_kernel_simultaneous_multiple_definition_error(
- k: Kernel,
-) -> None:
- await k.run(
- [
- ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="x=1"),
- ]
- )
+ assert set(k.errors.keys()) == {"1"}
+ assert k.errors["1"] == (DeleteNonlocalError("x", ("0",)),)
- assert "x" not in k.globals
- assert set(k.errors.keys()) == {"0", "1"}
- assert k.errors["0"] == (MultipleDefinitionError("x", ("1",)),)
- assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
-
-
-async def test_kernel_new_multiple_definition_does_not_invalidate(
- k: Kernel,
-) -> None:
- await k.run([ExecutionRequest(cell_id="0", code="x=0")])
- assert k.globals["x"] == 0
- assert not k.errors
-
- # cell 0 should not be invalidated by the introduction of cell 1
- await k.run([ExecutionRequest(cell_id="1", code="x=0")])
- assert k.globals["x"] == 0
- assert set(k.errors.keys()) == {"1"}
- assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
-
- # re-running cell 0 should invalidate it
- await k.run([ExecutionRequest(cell_id="0", code="x=0")])
- assert "x" not in k.globals
- assert set(k.errors.keys()) == {"0", "1"}
- assert k.errors["0"] == (MultipleDefinitionError("x", ("1",)),)
- assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
-
-
-async def test_clear_multiple_definition_error(k: Kernel) -> None:
- await k.run(
- [
- ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="x=1"),
- ]
- )
- assert "x" not in k.globals
- assert set(k.errors.keys()) == {"0", "1"}
- assert k.errors["0"] == (MultipleDefinitionError("x", ("1",)),)
- assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
-
- # Rename second occurrence of x to y; should eliminate error and run both
- # cells
- await k.run([ExecutionRequest(cell_id="1", code="y=1")])
- assert k.globals["x"] == 0
- assert k.globals["y"] == 1
- assert not k.errors
-
-
-async def test_clear_multiple_definition_error_with_delete(k: Kernel) -> None:
- await k.run(
- [
- ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="x=1"),
- ]
- )
- assert "x" not in k.globals
- assert set(k.errors.keys()) == {"0", "1"}
- assert k.errors["0"] == (MultipleDefinitionError("x", ("1",)),)
- assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
-
- # issue delete request for cell 1 to clear error and run cell 0
- await k.delete(DeleteRequest(cell_id="1"))
- assert k.globals["x"] == 0
- assert not k.errors
-
-
-async def test_new_errors_update_old_ones(k: Kernel) -> None:
- await k.run([ExecutionRequest(cell_id="0", code="x=0")])
- await k.run([ExecutionRequest(cell_id="1", code="x, y =1, 2")])
- assert set(k.errors.keys()) == {"1"}
- assert k.errors["1"] == (MultipleDefinitionError("x", ("0",)),)
-
- # errors propagated back to cell 1, even though we are not running it
- await k.run([ExecutionRequest(cell_id="2", code="x, y = 3, 4")])
- assert set(k.errors.keys()) == {"1", "2"}
- assert k.errors["1"] == (
- MultipleDefinitionError("x", ("0", "2")),
- MultipleDefinitionError("y", ("2",)),
- )
- assert k.errors["2"] == (
- MultipleDefinitionError("x", ("0", "1")),
- MultipleDefinitionError("y", ("1",)),
- )
+ # Delete the cell that defines x. There shouldn't be any more errors
+ # because x no longer exists.
+ await k.delete(DeleteRequest(cell_id="0"))
+ assert not k.errors
- assert k.globals["x"] == 0
+ # Add x back in.
+ await k.run([ExecutionRequest(cell_id="2", code="x=0")])
+ assert set(k.errors.keys()) == {"1"}
+ assert k.errors["1"] == (DeleteNonlocalError("x", ("2",)),)
+ # Repair graph
+ await k.run([er := ExecutionRequest(cell_id="1", code="y = x + 1")])
+ assert not k.errors
+ assert k.globals["y"] == 1
-async def test_cycle_error(k: Kernel) -> None:
- await k.run(
- [
- ExecutionRequest(cell_id="0", code="x=y"),
- ExecutionRequest(cell_id="1", code="y=x"),
- ExecutionRequest(cell_id="2", code="z = x + 1"),
- ]
- )
- assert "x" not in k.globals
- assert "y" not in k.globals
- assert set(k.errors.keys()) == {"0", "1"}
- assert len(k.errors["0"]) == 1
- assert len(k.errors["1"]) == 1
- _check_edges(k.errors["0"][0], [("0", ["x"], "1"), ("1", ["y"], "0")])
- _check_edges(k.errors["1"][0], [("0", ["x"], "1"), ("1", ["y"], "0")])
-
- # break cycle by modifying cell
- await k.run([ExecutionRequest(cell_id="1", code="y=1")])
- assert k.globals["x"] == 1
- assert k.globals["y"] == 1
- assert k.globals["z"] == 2
- assert not k.errors
-
-
-async def test_break_cycle_error_with_delete(k: Kernel) -> None:
- await k.run(
- [
- ExecutionRequest(cell_id="0", code="x=y"),
- ExecutionRequest(cell_id="1", code="y=x"),
- ]
- )
- assert "x" not in k.globals
- assert "y" not in k.globals
- assert set(k.errors.keys()) == {"0", "1"}
- assert len(k.errors["0"]) == 1
- assert len(k.errors["1"]) == 1
- _check_edges(k.errors["0"][0], [("0", ["x"], "1"), ("1", ["y"], "0")])
-
- # break cycle by deleting cell
- await k.delete(DeleteRequest(cell_id="1"))
- assert not k.errors
-
-
-async def test_delete_nonlocal_error(k: Kernel) -> None:
- await k.run(
- [
- ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="del x; y = 1"),
- ExecutionRequest(cell_id="2", code="z = y + 1"),
- ]
- )
- assert "y" not in k.globals
- assert "z" not in k.globals
- assert set(k.errors.keys()) == {"1"}
- assert k.errors["1"] == (DeleteNonlocalError("x", ("0",)),)
-
- # fix cell 1, should run cell 1 and 2
- await k.run([ExecutionRequest(cell_id="1", code="y=1")])
- assert k.globals["y"] == 1
- assert k.globals["z"] == 2
- assert not k.errors
-
-
-async def test_defs_with_no_definers_are_removed_from_cell(k: Kernel) -> None:
- await k.run(
- [
- ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="del x"),
- ]
- )
- assert set(k.errors.keys()) == {"1"}
- assert k.errors["1"] == (DeleteNonlocalError("x", ("0",)),)
-
- # Delete the cell that defines x. There shouldn't be any more errors
- # because x no longer exists.
- await k.delete(DeleteRequest(cell_id="0"))
- assert not k.errors
-
- # Add x back in.
- await k.run([ExecutionRequest(cell_id="2", code="x=0")])
- assert set(k.errors.keys()) == {"1"}
- assert k.errors["1"] == (DeleteNonlocalError("x", ("2",)),)
-
- # Repair graph
- await k.run([ExecutionRequest(cell_id="1", code="y = x + 1")])
- assert not k.errors
- assert k.globals["y"] == 1
-
- # Make sure graph is tracking x again and update propagates
- await k.run([ExecutionRequest(cell_id="2", code="x = 1")])
- assert not k.errors
- assert k.globals["y"] == 2
-
-
-async def test_syntax_error(k: Kernel) -> None:
- await k.run(
- [
- ExecutionRequest(cell_id="0", code="x=0"),
- ExecutionRequest(cell_id="1", code="x; y = 1"),
- ]
- )
- assert k.globals["x"] == 0
- assert k.globals["y"] == 1
- assert not k.errors
-
- await k.run([ExecutionRequest(cell_id="0", code="x=")])
- assert "x" not in k.globals
- assert "y" not in k.globals
- assert "0" not in k.graph.cells
- assert "1" in k.graph.cells
-
- # fix syntax error
- await k.run([ExecutionRequest(cell_id="0", code="x=0")])
- assert k.globals["x"] == 0
- assert k.globals["y"] == 1
- assert "0" in k.graph.cells
- assert "1" in k.graph.cells
- assert not k.errors
-
-
-async def test_disable_and_reenable_not_stale(
- k: Kernel, exec_req: ExecReqProvider
-) -> None:
- await k.run(
- [
- (
- er_1 := exec_req.get(
- """
- class namespace:
+ # Make sure graph is tracking x again and update propagates
+ await k.run([ExecutionRequest(cell_id="2", code="x = 1")])
+ assert not k.errors
+ if k.lazy():
+ assert k.graph.cells[er.cell_id].stale
+ await k.run([er])
+ assert not k.graph.cells[er.cell_id].stale
+ assert k.globals["y"] == 2
+
+ async def test_syntax_error(self, any_kernel: Kernel) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ ExecutionRequest(cell_id="0", code="x=0"),
+ er := ExecutionRequest(cell_id="1", code="x; y = 1"),
+ ]
+ )
+ assert not k.graph.get_stale()
+ assert k.globals["x"] == 0
+ assert k.globals["y"] == 1
+ assert not k.errors
+
+ await k.run([ExecutionRequest(cell_id="0", code="x=")])
+ assert "0" not in k.graph.cells
+ assert "1" in k.graph.cells
+ assert "x" not in k.globals
+ if k.lazy():
+ assert k.graph.get_stale() == set([er.cell_id])
+ await k.run([er])
+ assert not k.graph.get_stale()
+ assert "y" not in k.globals
+
+ # fix syntax error
+ await k.run([ExecutionRequest(cell_id="0", code="x=0")])
+ assert k.globals["x"] == 0
+ assert "0" in k.graph.cells
+ assert "1" in k.graph.cells
+ assert not k.errors
+ if k.lazy():
+ assert k.graph.get_stale() == set([er.cell_id])
+ await k.run([er])
+ assert not k.graph.get_stale()
+ assert k.globals["y"] == 1
+
+ async def test_cell_state_invalidated(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ graph = k.graph
+ await k.run(
+ [
+ er_1 := exec_req.get("x = 0"),
+ er_2 := exec_req.get("x; y = 1"),
+ ]
+ )
+ assert k.globals["y"] == 1
+ assert not graph.get_stale()
+
+ # "y" should not be computed, and its global state should have been
+ # invalidated
+ await k.run(
+ [ExecutionRequest(er_1.cell_id, "x = 0; raise RuntimeError")]
+ )
+ if k.lazy():
+ assert graph.get_stale() == set([er_2.cell_id])
+ # running er_2 will redefine y; this is different from the
+ # behavior of a non-lazy kernel, which doesn't run er_2
+ # but instead invalidates it on exception raised
+ else:
+ assert not graph.get_stale()
+ assert "y" not in k.globals
+
+ async def test_set_ui_element_value_with_cell_run(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ graph = k.graph
+ # This test imports a cell from another notebook that defines a UI
+ # element It then sets a value on the UI element, and makes sure that
+ # reactivity flows through the defs mapping that is returned
+ await k.run(
+ [
+ exec_req.get(
+ "from runtime_data.cell_ui_element import make_slider"
+ ),
+ exec_req.get("_, defs = make_slider.run()"),
+ exec_req.get("_, second_defs = make_slider.run()"),
+ exec_req.get("counter = [0]"),
+ er := exec_req.get("slider_value = defs['slider'].value + 1"),
+ exec_req.get("second_defs; counter[0] += 1"),
+ ]
+ )
+ assert k.globals["defs"]["slider"].value == 0
+ assert k.globals["counter"][0] == 1
+ assert k.globals["slider_value"] == 1
+ element_id = k.globals["defs"]["slider"]._id
+
+ await k.set_ui_element_value(
+ SetUIElementValueRequest([(element_id, 5)])
+ )
+ assert k.globals["defs"]["slider"].value == 5
+ if k.lazy():
+ assert graph.get_stale() == set([er.cell_id])
+ await k.run([er])
+ assert not graph.get_stale()
+ 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
+
+ async def test_set_ui_element_value_not_found_doesnt_fail(
+ self,
+ any_kernel: Kernel,
+ ) -> None:
+ # smoke test -- this shouldn't raise an exception
+ k = any_kernel
+ await k.set_ui_element_value(
+ SetUIElementValueRequest([("does not exist", None)])
+ )
+
+ async def test_interrupt(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ er = exec_req.get(
+ """
+ from marimo._runtime.control_flow import MarimoInterrupt
+
+ tries = 0
+ while tries < 5:
+ try:
+ raise MarimoInterrupt
+ except Exception:
...
- ns = namespace()
- ns.count = 0
- """
+ tries += 1
+ """
+ )
+ await k.run([er])
+ # make sure the interrupt wasn't caught by the try/except
+ assert k.globals["tries"] == 0
+
+ async def test_running_in_notebook(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ exec_req.get(
+ "import marimo as mo; in_nb = mo.running_in_notebook()"
)
- ),
- (er_2 := exec_req.get("ns.count += 1")),
- ]
- )
- assert k.globals["ns"].count == 1
- assert not k.graph.cells[er_1.cell_id].stale
- assert not k.graph.cells[er_2.cell_id].stale
-
- # disable and re-enable cell 2: cell 2 should not re-run because it
- # shouldn't have passed through stale status
- # disable cell 2
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
- )
- assert k.globals["ns"].count == 1
- assert not k.graph.cells[er_1.cell_id].stale
- assert not k.graph.cells[er_2.cell_id].stale
+ ]
+ )
+ assert k.globals["in_nb"]
- # re-enable cell 2
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}})
- )
- # cell 2 should **not** have re-run
- assert k.globals["ns"].count == 1
- assert not k.graph.cells[er_1.cell_id].stale
- assert not k.graph.cells[er_2.cell_id].stale
-
-
-async def test_disable_and_reenable_stale(
- k: Kernel, exec_req: ExecReqProvider
-) -> None:
- await k.run(
- [
- (
- er_1 := exec_req.get(
+ async def test_file_path(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get("x = __file__"),
+ ]
+ )
+
+ assert "pytest" in k.globals["x"]
+
+ async def test_pickle(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ exec_req.get("import pickle"),
+ exec_req.get(
"""
- class namespace:
- ...
- ns = namespace()
- ns.count = 0
- """
- )
- ),
- (er_2 := exec_req.get("ns.count += 1")),
- ]
- )
- assert k.globals["ns"].count == 1
- assert not k.graph.cells[er_1.cell_id].stale
- assert not k.graph.cells[er_2.cell_id].stale
-
- # disable and re-enable cell 2, making it stale in between;
- # cell 2 should re-run on enable
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
- )
- await k.run(
- [
- exec_req.get_with_id(
- er_1.cell_id,
- """
- class namespace:
- ...
- ns = namespace()
- ns.count = 10
- """,
+ def foo():
+ ...
+
+ pickle_output = None
+ pickle_output = pickle.dumps(foo)
+ """
+ ),
+ ]
+ )
+ assert k.globals["pickle_output"] is not None
+
+ def test_sys_path_updated(self, tmp_path: pathlib.Path) -> None:
+ main: ModuleType | None = None
+ try:
+ filename = str(tmp_path / "notebook.py")
+ if "__main__" in sys.modules:
+ # kernel patches __main__; need to reset it after test
+ main = sys.modules["__main__"]
+ Kernel(
+ stream=NoopStream(),
+ stdout=None,
+ stderr=None,
+ stdin=None,
+ cell_configs={},
+ user_config=DEFAULT_CONFIG,
+ app_metadata=AppMetadata(
+ query_params={}, filename=filename, cli_args={}
+ ),
+ enqueue_control_request=lambda _: None,
)
- ]
- )
+ assert str(tmp_path) in sys.path
+ assert str(tmp_path) == sys.path[0]
+ finally:
+ if str(tmp_path) in sys.path:
+ sys.path.remove(str(tmp_path))
+ if main is not None:
+ sys.modules["__main__"] = main
+
+ async def test_set_config_before_registering_cell(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ er_1 = exec_req.get("x = 0")
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
+ )
+ await k.run([er_1])
+ assert k.graph.cells[er_1.cell_id].config.disabled
+ assert "x" not in k.globals
- assert k.globals["ns"].count == 10
- assert not k.graph.cells[er_1.cell_id].stale
- assert k.graph.cells[er_2.cell_id].stale
- # re-enable cell 2
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}})
- )
- # cell 2 should have re-run
- assert k.globals["ns"].count == 11
- assert not k.graph.cells[er_1.cell_id].stale
- assert not k.graph.cells[er_2.cell_id].stale
-
-
-async def test_disable_and_reenable_tree(
- k: Kernel, exec_req: ExecReqProvider
-) -> None:
- # x
- # x --> y
- # x, y --> z
- await k.run(
- [
- (er_1 := exec_req.get("x = 1")),
- (er_2 := exec_req.get("y = x + 1")),
- (er_3 := exec_req.get("z = x + y")),
- (er_4 := exec_req.get("zz = z + 1")),
- (er_5 := exec_req.get("zzz = x + 1")),
- ]
- )
- assert k.globals["x"] == 1
- assert k.globals["y"] == 2
- assert k.globals["z"] == 3
- assert k.globals["zz"] == 4
- assert k.globals["zzz"] == 2
-
- 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 not k.graph.cells[er_4.cell_id].stale
- assert not k.graph.cells[er_5.cell_id].stale
-
- # disable cell 2
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
- )
-
- await k.run([ExecutionRequest(cell_id=er_1.cell_id, code="x = 2")])
- assert k.globals["x"] == 2
- assert k.globals["zzz"] == 3
-
- # stale cells' state is gone
- assert "y" not in k.globals
- assert "z" not in k.globals
- assert "zz" not in k.globals
-
- # cell 1 is not disabled
- assert not k.graph.cells[er_1.cell_id].stale
- # cell 2 stale because disabled and cannot run
- assert k.graph.cells[er_2.cell_id].stale
- # cell 3 stale because its parent (cell 2) is disabled
- assert k.graph.cells[er_3.cell_id].stale
- # cell 4 stale because cell 2 (an ancestor) is disabled
- assert k.graph.cells[er_4.cell_id].stale
- # cell 5 is not disabled
- assert not k.graph.cells[er_5.cell_id].stale
-
- # enable cell 2: should run stale cells as a side-effect
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}})
- )
- assert k.globals["x"] == 2
- assert k.globals["zzz"] == 3
-
- # stale cells **should have** updated
- assert k.globals["y"] == 3
- assert k.globals["z"] == 5
- assert k.globals["zz"] == 6
-
- 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 not k.graph.cells[er_4.cell_id].stale
- assert not k.graph.cells[er_5.cell_id].stale
-
-
-async def test_disable_consecutive(
- k: Kernel, exec_req: ExecReqProvider
-) -> None:
- await k.run(
- [
- (er_1 := exec_req.get("x = 1")),
- (er_2 := exec_req.get("y = x + 1")),
- ]
- )
- assert k.globals["x"] == 1
- assert k.globals["y"] == 2
- assert not k.graph.cells[er_1.cell_id].stale
- assert not k.graph.cells[er_2.cell_id].stale
-
- # disable both cells
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
- )
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
- )
- # update the code of cell 1 -- both cells stale
- await k.run([exec_req.get_with_id(er_1.cell_id, "x = 2")])
- assert "x" not in k.globals
- assert "y" not in k.globals
- assert k.graph.cells[er_1.cell_id].stale
- assert k.graph.cells[er_2.cell_id].stale
-
- # enable cell 1, but 2 still disabled
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}})
- )
- assert k.globals["x"] == 2
- assert "y" not in k.globals
- assert not k.graph.cells[er_1.cell_id].stale
- assert k.graph.cells[er_2.cell_id].stale
-
- # enable cell 2
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}})
- )
- assert k.globals["x"] == 2
- assert k.globals["y"] == 3
- assert not k.graph.cells[er_1.cell_id].stale
- assert not k.graph.cells[er_2.cell_id].stale
-
-
-async def test_disable_syntax_error(
- k: Kernel, exec_req: ExecReqProvider
-) -> None:
- await k.run(
- [
- (er_1 := exec_req.get("x = 1")),
- ]
- )
- assert k.globals["x"] == 1
+class TestDisable:
+ async def test_disable_and_reenable_not_stale(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ graph = k.graph
+ await k.run(
+ [
+ exec_req.get(
+ """
+ class namespace:
+ ...
+ ns = namespace()
+ ns.count = 0
+ """
+ ),
+ (er_2 := exec_req.get("ns.count += 1")),
+ ]
+ )
+ assert k.globals["ns"].count == 1
+ assert not graph.get_stale()
+
+ # disable and re-enable cell 2: cell 2 should not re-run because it
+ # shouldn't have passed through stale status
+ # disable cell 2
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
+ )
+ assert k.globals["ns"].count == 1
+ assert not graph.get_stale()
- # disable cell
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
- )
+ # re-enable cell 2
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}})
+ )
+ # cell 2 should **not** have re-run
+ assert k.globals["ns"].count == 1
+ assert not graph.get_stale()
- # add a syntax error
- await k.run([exec_req.get_with_id(er_1.cell_id, "x 2")])
- assert "x" not in k.globals
+ async def test_disable_and_reenable_stale(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ graph = k.graph
+ await k.run(
+ [
+ (
+ er_1 := exec_req.get(
+ """
+ class namespace:
+ ...
+ ns = namespace()
+ ns.count = 0
+ """
+ )
+ ),
+ er_2 := exec_req.get("ns.count += 1"),
+ ]
+ )
+ assert k.globals["ns"].count == 1
+ assert not graph.get_stale()
- # repair syntax, cell should still be disabled
- await k.run([exec_req.get_with_id(er_1.cell_id, "x = 2")])
- assert "x" not in k.globals
- assert k.graph.cells[er_1.cell_id].stale
+ # disable and re-enable cell 2, making it stale in between;
+ # cell 2 should re-run on enable
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
+ )
+ await k.run(
+ [
+ exec_req.get_with_id(
+ er_1.cell_id,
+ """
+ class namespace:
+ ...
+ ns = namespace()
+ ns.count = 10
+ """,
+ )
+ ]
+ )
- # enable: should run
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}})
- )
- assert k.globals["x"] == 2
- assert not k.graph.cells[er_1.cell_id].stale
+ assert k.globals["ns"].count == 10
+ assert k.graph.get_stale() == set([er_2.cell_id])
+ # re-enable cell 2
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}})
+ )
+ if k.lazy():
+ assert k.graph.get_stale() == set([er_2.cell_id])
+ await k.run([er_2])
+ assert not k.graph.get_stale()
+ # cell 2 should have re-run
+ assert k.globals["ns"].count == 11
+
+ async def test_disable_and_reenable_tree(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ # x
+ # x --> y
+ # x, y --> z
+ k = any_kernel
+ graph = k.graph
+ await k.run(
+ [
+ (er_1 := exec_req.get("x = 1")),
+ (er_2 := exec_req.get("y = x + 1")),
+ (er_3 := exec_req.get("z = x + y")),
+ (er_4 := exec_req.get("zz = z + 1")),
+ (er_5 := exec_req.get("zzz = x + 1")),
+ ]
+ )
+ assert k.globals["x"] == 1
+ assert k.globals["y"] == 2
+ assert k.globals["z"] == 3
+ assert k.globals["zz"] == 4
+ assert k.globals["zzz"] == 2
+ assert not graph.get_stale()
+
+ # disable cell 2
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
+ )
-async def test_disable_cycle(k: Kernel, exec_req: ExecReqProvider) -> None:
- await k.run(
- [
- (er_1 := exec_req.get("a = b")),
- (er_2 := exec_req.get("b = a")),
- ]
- )
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
- )
- assert k.graph.cells[er_1.cell_id].config.disabled
- assert k.graph.cells[er_2.cell_id].disabled_transitively
+ await k.run([ExecutionRequest(cell_id=er_1.cell_id, code="x = 2")])
+ assert k.globals["x"] == 2
+ if k.lazy():
+ assert graph.get_stale() == set(
+ [er_2.cell_id, er_3.cell_id, er_4.cell_id, er_5.cell_id]
+ )
+ await k.run([er_5])
+ assert graph.get_stale() == set(
+ [er_2.cell_id, er_3.cell_id, er_4.cell_id]
+ )
+ assert k.globals["zzz"] == 3
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
- )
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}})
- )
- assert k.graph.cells[er_1.cell_id].disabled_transitively
- assert k.graph.cells[er_2.cell_id].config.disabled
-
- # adding a new cell shouldn't toggle disabled states of either
- await k.run([exec_req.get("c = 0")])
- assert k.graph.cells[er_1.cell_id].disabled_transitively
- assert k.graph.cells[er_2.cell_id].config.disabled
-
- # breaking the cycle should re-enable
- await k.run([ExecutionRequest(cell_id=er_1.cell_id, code="a = 0")])
- assert not k.graph.cells[er_1.cell_id].disabled_transitively
- assert not k.graph.cells[er_1.cell_id].stale
- assert not k.graph.cells[er_1.cell_id].config.disabled
- assert k.graph.cells[er_2.cell_id].config.disabled
-
-
-async def test_disable_cycle_incremental(
- k: Kernel, exec_req: ExecReqProvider
-) -> None:
- await k.run([er_1 := exec_req.get("a = b")])
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
- )
- assert k.graph.cells[er_1.cell_id].config.disabled
+ # enable cell 2: should run stale cells as a side-effect
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}})
+ )
+ assert k.globals["x"] == 2
+ assert k.globals["zzz"] == 3
+ if k.lazy():
+ assert graph.get_stale() == set(
+ [er_2.cell_id, er_3.cell_id, er_4.cell_id]
+ )
+ # runs er_3 and er_2, which are stale ancestors
+ await k.run([er_4])
+ # stale cells **should have** updated
+ assert not graph.get_stale()
+ assert k.globals["y"] == 3
+ assert k.globals["z"] == 5
+ assert k.globals["zz"] == 6
+
+ async def test_disable_consecutive(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ graph = k.graph
+ await k.run(
+ [
+ (er_1 := exec_req.get("x = 1")),
+ (er_2 := exec_req.get("y = x + 1")),
+ ]
+ )
+ assert k.globals["x"] == 1
+ assert k.globals["y"] == 2
+ assert not graph.get_stale()
- await k.run([er_2 := exec_req.get("b = a")])
- assert k.graph.cells[er_2.cell_id].disabled_transitively
+ # disable both cells
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
+ )
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
+ )
+ # update the code of cell 1 -- both cells stale
+ await k.run([er_1 := exec_req.get_with_id(er_1.cell_id, "x = 2")])
+ assert graph.get_stale() == set([er_1.cell_id, er_2.cell_id])
+ # enable cell 1, but 2 still disabled
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}})
+ )
+ if k.lazy():
+ assert graph.get_stale() == set([er_1.cell_id, er_2.cell_id])
+ await k.run([er_1])
-async def test_enable_cycle_incremental(
- k: Kernel, exec_req: ExecReqProvider
-) -> None:
- await k.run(
- [
- (er_1 := exec_req.get("a = b")),
- (er_2 := exec_req.get("b = a")),
- ]
- )
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
- )
- assert k.graph.cells[er_1.cell_id].config.disabled
- assert k.graph.cells[er_2.cell_id].disabled_transitively
+ assert k.globals["x"] == 2
+ assert graph.get_stale() == set([er_2.cell_id])
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}})
- )
- assert not k.graph.cells[er_1.cell_id].config.disabled
- assert k.graph.cells[er_2.cell_id].status == "idle"
+ # enable cell 2
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_2.cell_id: {"disabled": False}})
+ )
+ if k.lazy():
+ assert graph.get_stale() == set([er_2.cell_id])
+ await k.run([er_2])
+ assert not graph.get_stale()
+ assert k.globals["x"] == 2
+ assert k.globals["y"] == 3
-async def test_set_config_before_registering_cell(
- k: Kernel, exec_req: ExecReqProvider
-) -> None:
- er_1 = exec_req.get("x = 0")
- await k.set_cell_config(
- SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
- )
- await k.run([er_1])
- assert k.graph.cells[er_1.cell_id].config.disabled
- assert "x" not in k.globals
+ async def test_disable_syntax_error(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ graph = k.graph
+ await k.run(
+ [
+ er_1 := exec_req.get("x = 1"),
+ ]
+ )
+ assert k.globals["x"] == 1
+ # disable cell
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
+ )
-async def test_interrupt(k: Kernel, exec_req: ExecReqProvider) -> None:
- er = exec_req.get(
- """
- from marimo._runtime.control_flow import MarimoInterrupt
-
- tries = 0
- while tries < 5:
- try:
- raise MarimoInterrupt
- except Exception:
- ...
- tries += 1
- """
- )
- await k.run([er])
+ # add a syntax error
+ await k.run([exec_req.get_with_id(er_1.cell_id, "x 2")])
+ assert "x" not in k.globals
- # make sure the interrupt wasn't caught by the try/except
- assert k.globals["tries"] == 0
+ # repair syntax, cell should still be disabled
+ await k.run([er_1 := exec_req.get_with_id(er_1.cell_id, "x = 2")])
+ assert "x" not in k.globals
+ assert graph.cells[er_1.cell_id].stale
+ # enable: should run
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}})
+ )
+ if k.lazy():
+ assert graph.cells[er_1.cell_id].stale
+ await k.run([er_1])
-async def test_file_path(k: Kernel, exec_req: ExecReqProvider) -> None:
- await k.run(
- [
- exec_req.get("import marimo as mo"),
- exec_req.get("x = __file__"),
- ]
- )
+ assert not graph.cells[er_1.cell_id].stale
+ assert k.globals["x"] == 2
- assert "pytest" in k.globals["x"]
+ async def test_disable_cycle(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ (er_1 := exec_req.get("a = b")),
+ (er_2 := exec_req.get("b = a")),
+ ]
+ )
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
+ )
+ assert k.graph.cells[er_1.cell_id].config.disabled
+ assert k.graph.cells[er_2.cell_id].disabled_transitively
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_2.cell_id: {"disabled": True}})
+ )
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}})
+ )
+ assert k.graph.cells[er_1.cell_id].disabled_transitively
+ assert k.graph.cells[er_2.cell_id].config.disabled
-async def test_cell_state_invalidated(
- k: Kernel, exec_req: ExecReqProvider
-) -> None:
- await k.run(
- [
- (er_1 := exec_req.get("x = 0")),
- (exec_req.get("x; y = 1")),
- ]
- )
- assert k.globals["y"] == 1
+ # adding a new cell shouldn't toggle disabled states of either
+ await k.run([exec_req.get("c = 0")])
+ assert k.graph.cells[er_1.cell_id].disabled_transitively
+ assert k.graph.cells[er_2.cell_id].config.disabled
- # "y" should not have run, and its global state should have been
- # invalidated
- await k.run([ExecutionRequest(er_1.cell_id, "x = 0; raise RuntimeError")])
- assert "y" not in k.globals
+ # breaking the cycle should re-enable
+ await k.run([ExecutionRequest(cell_id=er_1.cell_id, code="a = 0")])
+ assert not k.graph.cells[er_1.cell_id].stale
+ assert not k.graph.cells[er_1.cell_id].disabled_transitively
+ assert not k.graph.cells[er_1.cell_id].config.disabled
-async def test_pickle(k: Kernel, exec_req: ExecReqProvider) -> None:
- await k.run(
- [
- exec_req.get("import pickle"),
- exec_req.get(
- """
- def foo():
- ...
+ assert k.graph.cells[er_2.cell_id].config.disabled
+ assert k.graph.cells[er_2.cell_id].stale
- pickle_output = None
- pickle_output = pickle.dumps(foo)
- """
- ),
- ]
- )
- assert k.globals["pickle_output"] is not None
-
-
-async def test_set_ui_element_value_with_cell_run(
- k: Kernel, exec_req: ExecReqProvider
-) -> None:
- # This test imports a cell from another notebook that defines a UI element
- # It then sets a value on the UI element, and makes sure that reactivity
- # flows through the defs mapping that is returned
- await k.run(
- [
- exec_req.get(
- "from runtime_data.cell_ui_element import make_slider"
- ),
- exec_req.get("_, defs = make_slider.run()"),
- exec_req.get("_, second_defs = make_slider.run()"),
- exec_req.get("counter = [0]"),
- exec_req.get("slider_value = defs['slider'].value + 1"),
- exec_req.get("second_defs; counter[0] += 1"),
- ]
- )
- assert k.globals["defs"]["slider"].value == 0
- assert k.globals["counter"][0] == 1
- element_id = k.globals["defs"]["slider"]._id
- await k.set_ui_element_value(SetUIElementValueRequest([(element_id, 5)]))
- assert k.globals["defs"]["slider"].value == 5
- 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
-
-
-def test_sys_path_updated(tmp_path: pathlib.Path) -> None:
- main: ModuleType | None = None
- try:
- filename = str(tmp_path / "notebook.py")
- if "__main__" in sys.modules:
- # kernel patches __main__; need to reset it after test
- main = sys.modules["__main__"]
- Kernel(
- stream=NoopStream(),
- stdout=None,
- stderr=None,
- stdin=None,
- cell_configs={},
- user_config=DEFAULT_CONFIG,
- app_metadata=AppMetadata(
- query_params={}, filename=filename, cli_args={}
- ),
- enqueue_control_request=lambda _: None,
- )
- assert str(tmp_path) in sys.path
- assert str(tmp_path) == sys.path[0]
- finally:
- if str(tmp_path) in sys.path:
- sys.path.remove(str(tmp_path))
- if main is not None:
- sys.modules["__main__"] = main
-
-
-async def test_running_in_notebook(
- k: Kernel, exec_req: ExecReqProvider
-) -> None:
- await k.run(
- [exec_req.get("import marimo as mo; in_nb = mo.running_in_notebook()")]
- )
- assert k.globals["in_nb"]
+ async def test_disable_cycle_incremental(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ await k.run([er_1 := exec_req.get("a = b")])
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
+ )
+ assert k.graph.cells[er_1.cell_id].config.disabled
+ await k.run([er_2 := exec_req.get("b = a")])
+ assert k.graph.cells[er_2.cell_id].disabled_transitively
-def test_not_running_in_notebook() -> None:
- from marimo._runtime.context.utils import running_in_notebook
+ async def test_enable_cycle_incremental(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ (er_1 := exec_req.get("a = b")),
+ (er_2 := exec_req.get("b = a")),
+ ]
+ )
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_1.cell_id: {"disabled": True}})
+ )
+ assert k.graph.cells[er_1.cell_id].config.disabled
+ assert k.graph.cells[er_2.cell_id].disabled_transitively
- assert not running_in_notebook()
+ await k.set_cell_config(
+ SetCellConfigRequest(configs={er_1.cell_id: {"disabled": False}})
+ )
+ 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"
class TestAsyncIO:
@staticmethod
async def test_toplevel_await_allowed(
- k: Kernel, exec_req: ExecReqProvider
+ any_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = any_kernel
await k.run(
[
exec_req.get(
@@ -929,8 +1076,9 @@ class TestAsyncIO:
@staticmethod
async def test_toplevel_gather(
- k: Kernel, exec_req: ExecReqProvider
+ any_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = any_kernel
await k.run(
[
exec_req.get(
@@ -950,9 +1098,13 @@ class TestAsyncIO:
assert k.globals["l"] == [1, 1, 2, 2]
@staticmethod
- async def test_wait_for(k: Kernel, exec_req: ExecReqProvider) -> None:
+ async def test_wait_for(
+ any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
import asyncio
+ k = any_kernel
+
await k.run(
[
exec_req.get(
@@ -974,7 +1126,10 @@ class TestAsyncIO:
assert isinstance(k.globals["e"], asyncio.exceptions.TimeoutError)
@staticmethod
- async def test_await_future(k: Kernel, exec_req: ExecReqProvider) -> None:
+ async def test_await_future(
+ any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
await k.run(
[
exec_req.get(
@@ -996,8 +1151,9 @@ class TestAsyncIO:
@staticmethod
async def test_await_future_complex(
- k: Kernel, exec_req: ExecReqProvider
+ any_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = any_kernel
await k.run(
[
exec_req.get(
@@ -1025,8 +1181,9 @@ class TestAsyncIO:
@staticmethod
async def test_run_in_default_executor(
- k: Kernel, exec_req: ExecReqProvider
+ any_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = any_kernel
await k.run(
[
exec_req.get(
@@ -1052,8 +1209,9 @@ class TestAsyncIO:
@staticmethod
async def test_run_in_threadpool_executor(
- k: Kernel, exec_req: ExecReqProvider
+ any_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = any_kernel
await k.run(
[
exec_req.get(
@@ -1088,8 +1246,9 @@ class TestAsyncIO:
),
)
async def test_run_in_processpool_executor(
- k: Kernel, exec_req: ExecReqProvider
+ any_kernel: Kernel, exec_req: ExecReqProvider
) -> None:
+ k = any_kernel
await k.run(
[
exec_req.get(
diff --git a/tests/_server/templates/snapshots/export1.txt b/tests/_server/templates/snapshots/export1.txt
index ac6aea047d..8ec77be19a 100644
--- a/tests/_server/templates/snapshots/export1.txt
+++ b/tests/_server/templates/snapshots/export1.txt
@@ -56,7 +56,7 @@
<marimo-filename hidden>notebook.py</marimo-filename>
<marimo-mode data-mode='read' hidden></marimo-mode>
<marimo-version data-version='0.0.0' hidden></marimo-version>
- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config>
+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config>
<marimo-app-config data-config='{"app_title": null, "layout_file": null, "width": "normal"}' hidden></marimo-app-config>
<marimo-server-token data-token='token' hidden></marimo-server-token>
<title>notebook</title>
diff --git a/tests/_server/templates/snapshots/export2.txt b/tests/_server/templates/snapshots/export2.txt
index 9fe1b34ad9..2e1cf523f3 100644
--- a/tests/_server/templates/snapshots/export2.txt
+++ b/tests/_server/templates/snapshots/export2.txt
@@ -56,7 +56,7 @@
<marimo-filename hidden></marimo-filename>
<marimo-mode data-mode='read' hidden></marimo-mode>
<marimo-version data-version='0.0.0' hidden></marimo-version>
- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config>
+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config>
<marimo-app-config data-config='{"app_title": null, "layout_file": null, "width": "normal"}' hidden></marimo-app-config>
<marimo-server-token data-token='token' hidden></marimo-server-token>
<title>marimo</title>
diff --git a/tests/_server/templates/snapshots/export3.txt b/tests/_server/templates/snapshots/export3.txt
index a8bc94c78f..c7642deaf9 100644
--- a/tests/_server/templates/snapshots/export3.txt
+++ b/tests/_server/templates/snapshots/export3.txt
@@ -56,7 +56,7 @@
<marimo-filename hidden>notebook.py</marimo-filename>
<marimo-mode data-mode='read' hidden></marimo-mode>
<marimo-version data-version='0.0.0' hidden></marimo-version>
- <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config>
+ <marimo-user-config data-config='{"completion": {"activate_on_typing": true, "copilot": false}, "display": {"cell_output": "above", "code_editor_font_size": 14, "theme": "light"}, "formatting": {"line_length": 79}, "keymap": {"preset": "default"}, "package_management": {"manager": "pip"}, "runtime": {"auto_instantiate": true, "auto_reload": "off", "on_cell_change": "autorun"}, "save": {"autosave": "after_delay", "autosave_delay": 1000, "format_on_save": false}, "server": {"browser": "default"}}' hidden></marimo-user-config>
<marimo-app-config data-config='{"app_title": null, "layout_file": null, "width": "normal"}' hidden></marimo-app-config>
<marimo-server-token data-token='token' hidden></marimo-server-token>
<title>notebook</title>
diff --git a/tests/conftest.py b/tests/conftest.py
index 96ea9e0d63..152729d3b2 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -127,6 +127,18 @@ def k() -> Generator[Kernel, None, None]:
mocked.teardown()
+# kernel configured with runtime=lazy
+def lazy_kernel(k: Kernel) -> Kernel:
+ k.reactive_execution_mode = "lazy"
+ return k
+
+
[email protected](params=["k", "lazy_kernel"])
+def any_kernel(request: Any) -> Kernel:
+ return request.getfixturevalue(request.param)
+
+
# fixture that wraps a kernel and other mocked objects
@pytest.fixture
def mocked_kernel() -> Generator[MockedKernel, None, None]: