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.

mo.stop; interrupt => state invalidation (#11)

Akshay Agrawal1850f178f89b
diff --git a/docs/api/misc.md b/docs/api/misc.md
index 28ff2e66ae..2748d34282 100644
--- a/docs/api/misc.md
+++ b/docs/api/misc.md
@@ -1,5 +1,18 @@
# Misc
+## Control flow
+Use `mo.stop` to halt execution of a cell, and optionally output an object.
+This function is useful for validating user input.
+
+```{eval-rst}
+.. autofunction:: marimo.stop
+```
+
+```{eval-rst}
+.. autoclass:: marimo.MarimoStopError
+```
+
+## Debugging
Use `mo.defs` and `mo.refs` to get the global definitions and references of
a cell.
diff --git a/frontend/src/core/kernel/messages.tsx b/frontend/src/core/kernel/messages.tsx
index 618399ddf5..732518fdf6 100644
--- a/frontend/src/core/kernel/messages.tsx
+++ b/frontend/src/core/kernel/messages.tsx
@@ -5,10 +5,16 @@ import { CellId } from "../model/ids";
export type MarimoError =
| { type: "syntax"; msg?: string }
| { type: "interruption"; msg?: string }
- | { type: "exception"; msg: string; raising_cell?: number }
- | { type: "cycle"; edges: Array<[number, number]> }
- | { type: "multiple-defs"; name: string; cells: number[] }
- | { type: "delete-nonlocal"; name: string; cells: number[] }
+ | {
+ type: "exception";
+ exception_type: string;
+ msg: string;
+ raising_cell?: CellId;
+ }
+ | { type: "ancestor-stopped"; msg: string; raising_cell: CellId }
+ | { type: "cycle"; edges: Array<[CellId, CellId]> }
+ | { type: "multiple-defs"; name: string; cells: CellId[] }
+ | { type: "delete-nonlocal"; name: string; cells: CellId[] }
| { type: "unknown"; msg?: string };
export type OutputMessage =
diff --git a/frontend/src/core/model/cells.ts b/frontend/src/core/model/cells.ts
index 02360a425d..82c2ba3146 100644
--- a/frontend/src/core/model/cells.ts
+++ b/frontend/src/core/model/cells.ts
@@ -31,6 +31,7 @@ export function createCell({
edited = false,
interrupted = false,
errored = false,
+ stopped = false,
runElapsedTimeMs = null,
runStartTimestamp = null,
lastCodeRun = null,
@@ -47,6 +48,7 @@ export function createCell({
edited: edited,
interrupted: interrupted,
errored: errored,
+ stopped: stopped,
runElapsedTimeMs: runElapsedTimeMs,
runStartTimestamp: runStartTimestamp,
lastCodeRun: lastCodeRun,
@@ -74,6 +76,8 @@ export interface CellState {
edited: boolean;
/** whether this cell has been interrupted since its last run */
interrupted: boolean;
+ /** whether this cell was stopped with mo.stop */
+ stopped: boolean;
/** snapshot of code that was last run */
lastCodeRun: string | null;
/**
diff --git a/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap b/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap
index d07b37b49f..d4fd96938f 100644
--- a/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap
+++ b/frontend/src/core/state/__tests__/__snapshots__/cells.test.ts.snap
@@ -19,6 +19,7 @@ exports[`cell reducer > can run cell and receive cell messages 1`] = `
"runStartTimestamp": null,
"serializedEditorState": null,
"status": "idle",
+ "stopped": false,
}
`;
@@ -41,6 +42,7 @@ exports[`cell reducer > can run cell and receive cell messages 2`] = `
"runStartTimestamp": null,
"serializedEditorState": null,
"status": "idle",
+ "stopped": false,
}
`;
@@ -63,6 +65,7 @@ exports[`cell reducer > can run cell and receive cell messages 3`] = `
"runStartTimestamp": null,
"serializedEditorState": null,
"status": "idle",
+ "stopped": false,
}
`;
@@ -85,6 +88,7 @@ exports[`cell reducer > can run cell and receive cell messages 4`] = `
"runStartTimestamp": null,
"serializedEditorState": null,
"status": "queued",
+ "stopped": false,
}
`;
@@ -107,6 +111,7 @@ exports[`cell reducer > can run cell and receive cell messages 5`] = `
"runStartTimestamp": 20,
"serializedEditorState": null,
"status": "running",
+ "stopped": false,
}
`;
@@ -136,6 +141,7 @@ exports[`cell reducer > can run cell and receive cell messages 6`] = `
"runStartTimestamp": 20,
"serializedEditorState": null,
"status": "running",
+ "stopped": false,
}
`;
@@ -170,6 +176,7 @@ exports[`cell reducer > can run cell and receive cell messages 7`] = `
"runStartTimestamp": null,
"serializedEditorState": null,
"status": "idle",
+ "stopped": false,
}
`;
@@ -205,6 +212,7 @@ import numpy",
"runStartTimestamp": null,
"serializedEditorState": null,
"status": "idle",
+ "stopped": false,
}
`;
@@ -239,6 +247,7 @@ exports[`cell reducer > can run cell and receive cell messages 9`] = `
"runStartTimestamp": null,
"serializedEditorState": null,
"status": "idle",
+ "stopped": false,
}
`;
@@ -274,6 +283,7 @@ import numpy",
"runStartTimestamp": null,
"serializedEditorState": null,
"status": "idle",
+ "stopped": false,
}
`;
@@ -301,6 +311,7 @@ import numpy",
"channel": "marimo-error",
"data": [
{
+ "exception_type": "ValueError",
"msg": "Oh no!",
"type": "exception",
},
@@ -315,6 +326,7 @@ import numpy",
"runStartTimestamp": null,
"serializedEditorState": null,
"status": "idle",
+ "stopped": false,
}
`;
@@ -354,5 +366,6 @@ import numpy",
"runStartTimestamp": null,
"serializedEditorState": null,
"status": "idle",
+ "stopped": false,
}
`;
diff --git a/frontend/src/core/state/__tests__/cells.test.ts b/frontend/src/core/state/__tests__/cells.test.ts
index 7596f6c718..0c43c556e6 100644
--- a/frontend/src/core/state/__tests__/cells.test.ts
+++ b/frontend/src/core/state/__tests__/cells.test.ts
@@ -415,7 +415,9 @@ describe("cell reducer", () => {
output: {
channel: "marimo-error",
mimetype: "application/vnd.marimo+error",
- data: [{ type: "exception", msg: "Oh no!" }],
+ data: [
+ { type: "exception", exception_type: "ValueError", msg: "Oh no!" },
+ ],
timestamp: "",
},
console: null,
diff --git a/frontend/src/core/state/cell.ts b/frontend/src/core/state/cell.ts
index 907c818d04..99d319ed22 100644
--- a/frontend/src/core/state/cell.ts
+++ b/frontend/src/core/state/cell.ts
@@ -13,6 +13,7 @@ export function transitionCell(
// implies a status transition
switch (message.status) {
case "queued":
+ nextCell.stopped = false;
nextCell.interrupted = false;
nextCell.errored = false;
// We intentionally don't update lastCodeRun, since the kernel queues
@@ -45,6 +46,13 @@ export function transitionCell(
// its lastCodeRun
nextCell.lastCodeRun = null;
nextCell.interrupted = true;
+ } else if (
+ message.output.data.some((error) => error["type"] === "ancestor-stopped")
+ ) {
+ // The cell didn't run, but it was intentional, so don't count as
+ // errored.
+ nextCell.stopped = true;
+ nextCell.runElapsedTimeMs = null;
} else {
nextCell.errored = true;
// The cell didn't actually run.
diff --git a/frontend/src/editor/Cell.tsx b/frontend/src/editor/Cell.tsx
index 661252e2c6..a37aa77c49 100644
--- a/frontend/src/editor/Cell.tsx
+++ b/frontend/src/editor/Cell.tsx
@@ -80,6 +80,7 @@ export interface CellProps
| "edited"
| "errored"
| "interrupted"
+ | "stopped"
| "runElapsedTimeMs"
> {
theme: Theme;
@@ -124,6 +125,7 @@ const CellComponent = (
edited,
interrupted,
errored,
+ stopped,
registerRunStart,
serializedEditorState,
editing,
@@ -540,11 +542,13 @@ const CellComponent = (
published: !editing,
"needs-run": needsRun,
"has-error": errored,
+ stopped: stopped,
});
const HTMLId = HTMLCellId.create(cellId);
if (!editing) {
- return errored || interrupted ? null : (
+ const hidden = errored || interrupted || stopped;
+ return hidden ? null : (
<div tabIndex={-1} id={HTMLId} ref={cellRef} className={className}>
{outputArea}
</div>
diff --git a/frontend/src/editor/output/MarimoErrorOutput.tsx b/frontend/src/editor/output/MarimoErrorOutput.tsx
index 12f4e47617..758b2c65df 100644
--- a/frontend/src/editor/output/MarimoErrorOutput.tsx
+++ b/frontend/src/editor/output/MarimoErrorOutput.tsx
@@ -5,6 +5,7 @@ import { logNever } from "../../utils/assertNever";
import { MarimoError } from "../../core/kernel/messages";
import { Alert } from "../../components/ui/alert";
import { AlertTitle } from "../../components/ui/alert";
+import { CellId } from "@/core/model/ids";
import {
Accordion,
@@ -37,7 +38,7 @@ const Tip = (props: {
};
/* Component that adds a link to a cell, for use in a MarimoError. */
-const CellLink = (props: { cellId: number }): JSX.Element => {
+const CellLink = (props: { cellId: CellId }): JSX.Element => {
const cellName = `cell-${props.cellId}`;
return (
<div
@@ -74,7 +75,9 @@ export const MarimoErrorOutput = ({
errors,
className,
}: Props): JSX.Element => {
- let runtimeError = false;
+ let titleContents = "This cell wasn't run because it has errors";
+ let alertVariant: "destructive" | "default" = "destructive";
+ let textColor = "text-error";
const liStyle = "my-0.5 ml-8 text-muted-foreground/40";
const msgs = errors.map((error, idx) => {
switch (error.type) {
@@ -137,13 +140,13 @@ export const MarimoErrorOutput = ({
);
case "interruption":
- runtimeError = true;
+ titleContents = "Interrupted";
return (
<p key={idx}>{"This cell was interrupted and needs to be re-run."}</p>
);
case "exception":
- runtimeError = true;
+ titleContents = error.exception_type;
return error.raising_cell == null ? (
<Fragment key={idx}>
<p>{error.msg}</p>
@@ -159,6 +162,16 @@ export const MarimoErrorOutput = ({
</Tip>
</p>
);
+ case "ancestor-stopped":
+ titleContents = "Ancestor stopped";
+ alertVariant = "default";
+ textColor = "text-secondary-foreground";
+ return (
+ <p key={idx}>
+ {error.msg}
+ <CellLink cellId={error.raising_cell} />
+ </p>
+ );
default:
logNever(error);
@@ -166,19 +179,17 @@ export const MarimoErrorOutput = ({
}
});
- const title = runtimeError ? (
- <AlertTitle className="font-code font-bold mb-4">Runtime error</AlertTitle>
- ) : (
+ const title = (
<AlertTitle className="font-code font-bold mb-4">
- This cell wasn't run because it has errors
+ {titleContents}
</AlertTitle>
);
return (
<Alert
- variant="destructive"
+ variant={alertVariant}
className={cn(
- "border-none font-code text-sm text-[0.84375rem] px-0 text-error [&:has(svg)]:pl-0",
+ `border-none font-code text-sm text-[0.84375rem] px-0 ${textColor} normal [&:has(svg)]:pl-0`,
className
)}
>
diff --git a/frontend/src/editor/renderers/CellArray.tsx b/frontend/src/editor/renderers/CellArray.tsx
index f96d847d99..3cfbe49c04 100644
--- a/frontend/src/editor/renderers/CellArray.tsx
+++ b/frontend/src/editor/renderers/CellArray.tsx
@@ -121,6 +121,7 @@ export const CellArray: React.FC<CellArrayProps> = ({
edited={cell.edited}
interrupted={cell.interrupted}
errored={cell.errored}
+ stopped={cell.stopped}
runElapsedTimeMs={cell.runElapsedTimeMs}
registerRunStart={registerRunStart}
serializedEditorState={cell.serializedEditorState}
diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsx
index 5055acd4cc..3c409ead3c 100644
--- a/frontend/src/stories/cell.stories.tsx
+++ b/frontend/src/stories/cell.stories.tsx
@@ -23,6 +23,7 @@ const props: CellProps = {
edited: false,
interrupted: false,
errored: false,
+ stopped: false,
updateCellCode: console.log,
prepareCellForRun: console.log,
registerRunStart: console.log,
diff --git a/marimo/__init__.py b/marimo/__init__.py
index 8d6210fbbe..c7a17332cb 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -14,6 +14,7 @@ marimo is designed to be:
__all__ = [
"App",
+ "MarimoStopError",
"accordion",
"as_html",
"callout",
@@ -24,6 +25,7 @@ __all__ = [
"Html",
"md",
"refs",
+ "stop",
"tabs",
"tree",
"ui",
@@ -43,4 +45,5 @@ from marimo._plugins.stateless.callout_output import callout
from marimo._plugins.stateless.flex import hstack, vstack
from marimo._plugins.stateless.tabs import tabs
from marimo._plugins.stateless.tree import tree
+from marimo._runtime.control_flow import MarimoStopError, stop
from marimo._runtime.runtime import defs, refs
diff --git a/marimo/_messaging/errors.py b/marimo/_messaging/errors.py
index 71c865a0f8..299623397a 100644
--- a/marimo/_messaging/errors.py
+++ b/marimo/_messaging/errors.py
@@ -33,9 +33,17 @@ class MarimoInterruptionError:
type: str = "interruption"
+@dataclass
+class MarimoAncestorStoppedError:
+ msg: str
+ raising_cell: CellId_t
+ type: str = "ancestor-stopped"
+
+
@dataclass
class MarimoExceptionRaisedError:
msg: str
+ exception_type: str
# None for if raising_cell is the current cell
raising_cell: Optional[CellId_t]
type: str = "exception"
@@ -57,6 +65,7 @@ Error = Union[
CycleError,
MultipleDefinitionError,
DeleteNonlocalError,
+ MarimoAncestorStoppedError,
MarimoExceptionRaisedError,
MarimoInterruptionError,
MarimoSyntaxError,
diff --git a/marimo/_runtime/cell_runner.py b/marimo/_runtime/cell_runner.py
new file mode 100644
index 0000000000..28ba164e43
--- /dev/null
+++ b/marimo/_runtime/cell_runner.py
@@ -0,0 +1,208 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+import io
+import pprint
+import re
+import sys
+import traceback
+from dataclasses import dataclass
+from typing import Any, Optional
+
+from marimo._ast.cell import CellId_t, execute_cell
+from marimo._output import formatting
+from marimo._runtime import dataflow
+from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
+
+
+def cell_filename(cell_id: CellId_t) -> str:
+ """Filename to use when running cells through exec."""
+ return f"<cell-{cell_id}>"
+
+
+def cell_id_from_filename(filename: str) -> Optional[CellId_t]:
+ """Parses cell id from filename."""
+ matches = re.findall(r"<cell-([0-9]+)>", filename)
+ if matches:
+ return str(matches[0])
+ return None
+
+
+def format_traceback(graph: dataflow.DirectedGraph) -> str:
+ """Formats the current exception on the stack."""
+ # all three values are guaranteed to be non-None because an
+ # exception is on the stack:
+ # https://docs.python.org/3/library/sys.html#sys.exc_info
+ exc_type, exc_value, tb = sys.exc_info()
+ # custom traceback formatting strips out marimo internals
+ # and adds source code from cells
+ frames = traceback.extract_tb(tb)
+ error_msg_lines = []
+ found_cell_frame = False
+ for filename, lineno, fn_name, text in frames:
+ filename_cell_id = cell_id_from_filename(filename)
+ in_cell = filename_cell_id is not None
+ if in_cell:
+ found_cell_frame = True
+ if not found_cell_frame:
+ continue
+
+ line = " "
+ if in_cell:
+ # TODO: hyperlink to cell ... should the traceback
+ # be assembled in the frontend?
+ line += f"Cell {filename}, "
+ else:
+ line += f"File {filename}, "
+ line += f"line {lineno}"
+
+ if fn_name != "<module>":
+ line += f", in {fn_name}"
+ error_msg_lines.append(line)
+
+ if filename_cell_id is not None:
+ lines = graph.cells[filename_cell_id].code.split("\n")
+ error_msg_lines.append(" " + lines[lineno - 1].strip())
+ else:
+ error_msg_lines.append(" " + text.strip())
+
+ return (
+ "Traceback (most recent call last):\n"
+ + "\n".join(error_msg_lines)
+ + "\n"
+ + exc_type.__name__ # type: ignore
+ + ": "
+ + str(exc_value)
+ )
+
+
+@dataclass
+class FormattedOutput:
+ """Cell output transformed to wire format."""
+
+ channel: str
+ mimetype: str
+ data: str
+ # non-None if there was an error in formatting the cell output.
+ traceback: Optional[str] = None
+
+
+@dataclass
+class RunResult:
+ # Raw output of cell
+ output: Any
+ # Exception raised by cell, if any
+ exception: Optional[Exception]
+
+ def success(self) -> bool:
+ """Whether the cell exected successfully"""
+ return self.exception is None
+
+ def format_output(self) -> FormattedOutput:
+ """Formats raw output to wire format."""
+ return_value = "" if self.output is None else self.output
+ if (formatter := formatting.get_formatter(return_value)) is not None:
+ try:
+ mimetype, data = formatter(return_value)
+ return FormattedOutput(
+ channel="output", mimetype=mimetype, data=data
+ )
+ except Exception: # noqa: E722
+ return FormattedOutput(
+ channel="output",
+ mimetype="text/plain",
+ data="",
+ traceback=traceback.format_exc(),
+ )
+ else:
+ tmpio = io.StringIO()
+ tb = None
+ if isinstance(return_value, str):
+ tmpio.write(return_value)
+ else:
+ try:
+ pprint.pprint(return_value, stream=tmpio)
+ except Exception: # noqa: E722
+ tmpio.write("")
+ tb = traceback.format_exc()
+ tmpio.seek(0)
+ return FormattedOutput(
+ channel="output",
+ mimetype="text/plain",
+ data=tmpio.read(),
+ traceback=tb,
+ )
+
+
+class Runner:
+ """Runner for a collection of cells."""
+
+ def __init__(
+ self,
+ cell_ids: set[CellId_t],
+ graph: dataflow.DirectedGraph,
+ glbls: dict[Any, Any],
+ ):
+ self.graph = graph
+ self.glbls = glbls
+ self.cells_to_run = dataflow.topological_sort(graph, cell_ids)
+ self.cells_cancelled: dict[CellId_t, set[CellId_t]] = {}
+ self.interrupted = False
+ self.exceptions: dict[CellId_t, Exception] = {}
+
+ def cancel(self, cell_id: CellId_t) -> None:
+ """Mark a cell (and its descendants) as cancelled."""
+ self.cells_cancelled[cell_id] = set(
+ cid
+ for cid in dataflow.transitive_closure(self.graph, set([cell_id]))
+ if cid in self.cells_to_run
+ )
+
+ def cancelled(self, cell_id: CellId_t) -> bool:
+ """Return whether a cell has been cancelled."""
+ return any(
+ cell_id in cancelled for cancelled in self.cells_cancelled.values()
+ )
+
+ def pending(self) -> bool:
+ """Whether there are more cells to run."""
+ return not self.interrupted and len(self.cells_to_run) > 0
+
+ def pop_cell(self) -> CellId_t:
+ """Get the next cell to run."""
+ return self.cells_to_run.pop(0)
+
+ def print_traceback(self) -> None:
+ """Print a traceback to stderr.
+
+ Must be called when there is an exception on the stack.
+ """
+ error_msg = format_traceback(self.graph)
+ sys.stderr.write(error_msg)
+
+ def run(self, cell_id: CellId_t) -> RunResult:
+ """Run a cell."""
+ cell = self.graph.cells[cell_id]
+ try:
+ return_value = execute_cell(cell, self.glbls)
+ run_result = RunResult(output=return_value, exception=None)
+ except MarimoInterrupt as e:
+ # interrupt the entire runner
+ self.interrupted = True
+ run_result = RunResult(output=None, exception=e)
+ self.print_traceback()
+ except MarimoStopError as e:
+ # cancel only the descendants of this cell
+ self.cancel(cell_id)
+ run_result = RunResult(output=e.output, exception=e)
+ self.print_traceback()
+ except Exception as e: # noqa: E722
+ # cancel only the descendants of this cell
+ self.cancel(cell_id)
+ run_result = RunResult(output=None, exception=e)
+ self.print_traceback()
+
+ if run_result.exception is not None:
+ self.exceptions[cell_id] = run_result.exception
+
+ return run_result
diff --git a/marimo/_runtime/control_flow.py b/marimo/_runtime/control_flow.py
new file mode 100644
index 0000000000..5e9484b0db
--- /dev/null
+++ b/marimo/_runtime/control_flow.py
@@ -0,0 +1,40 @@
+# Copyright 2023 Marimo. All rights reserved.
+from typing import Optional
+
+from marimo._output.rich_help import mddoc
+
+
+class MarimoInterrupt(Exception):
+ """User stops execution of entire program with interrupt."""
+
+ pass
+
+
+class MarimoStopError(Exception):
+ """Raised by `marimo.stop` to stop execution of a cell and descendants."""
+
+ def __init__(self, output: Optional[object]) -> None:
+ self.output = output
+
+
+@mddoc
+def stop(predicate: bool, output: Optional[object] = None) -> None:
+ """Stops execution of a cell when `predicate` is `False`
+
+ When `predicate` is `True`, this function stops execution of the
+ current cell and makes `output` its output. Any descendants of this cell
+ that were previously scheduled to run will not be run, and their defs will
+ be removed from program memory.
+
+ **Example:**
+
+ ```python
+ mo.stop(form.value is None, mo.md("**Submit the form to continue.**"))
+ ```
+
+ **Raises:**
+
+ When `predicate` is `True`, raises a `MarimoStopError`.
+ """
+ if predicate:
+ raise MarimoStopError(output)
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index b919a23ebf..02e951ff1e 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -6,9 +6,7 @@ import contextlib
import io
import itertools
import multiprocessing as mp
-import pprint
import queue
-import re
import signal
import sys
import threading
@@ -19,9 +17,10 @@ from queue import Empty as QueueEmpty
from typing import Any, Iterator, Optional
from marimo import _loggers
-from marimo._ast.cell import CellId_t, execute_cell, parse_cell
+from marimo._ast.cell import CellId_t, parse_cell
from marimo._messaging.errors import (
Error,
+ MarimoAncestorStoppedError,
MarimoExceptionRaisedError,
MarimoInterruptionError,
MarimoSyntaxError,
@@ -37,16 +36,16 @@ from marimo._messaging.messages import (
write_remove_ui_elements,
)
from marimo._messaging.streams import Stderr, Stdout, Stream, redirect_streams
-from marimo._output.formatting import get_formatter
from marimo._output.rich_help import mddoc
from marimo._plugins.ui._core.registry import UIElementRegistry
-from marimo._runtime import dataflow
+from marimo._runtime import cell_runner, dataflow
from marimo._runtime.complete import complete
from marimo._runtime.context import (
get_context,
get_global_context,
initialize_context,
)
+from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
from marimo._runtime.requests import (
CompletionRequest,
ConfigurationRequest,
@@ -64,21 +63,6 @@ from marimo.config._config import configure
LOGGER = _loggers.marimo_logger()
-class MarimoInterrupt(Exception):
- pass
-
-
-def cell_filename(cell_id: CellId_t) -> str:
- return f"<cell-{cell_id}>"
-
-
-def cell_id_from_filename(filename: str) -> Optional[CellId_t]:
- matches = re.findall(r"<cell-([0-9]+)>", filename)
- if matches:
- return str(matches[0])
- return None
-
-
@mddoc
def defs() -> tuple[str, ...]:
"""Get the definitions of the currently executing cell.
@@ -167,7 +151,9 @@ class Kernel:
"""
error: Optional[Error] = None
try:
- cell = parse_cell(code, cell_filename(cell_id), cell_id)
+ cell = parse_cell(
+ code, cell_runner.cell_filename(cell_id), cell_id
+ )
except Exception as e:
cell = None
if isinstance(e, SyntaxError):
@@ -448,8 +434,9 @@ class Kernel:
for cid in cell_ids:
write_queued(cell_id=cid)
- cells_to_run = dataflow.topological_sort(self.graph, cell_ids)
- cells_cancelled: dict[CellId_t, set[CellId_t]] = {}
+ runner = cell_runner.Runner(
+ cell_ids=cell_ids, graph=self.graph, glbls=self.globals
+ )
# I/O
#
@@ -461,173 +448,88 @@ class Kernel:
# redirected to frontend (it's printed to console),
# which is incorrect
# TODO(akshayka): pdb support
- LOGGER.debug("final set of cells to run %s", cells_to_run)
- interrupted = False
- while not interrupted and cells_to_run:
- curr_cell_id = cells_to_run.pop(0)
- if any(
- curr_cell_id in cancelled
- for cancelled in cells_cancelled.values()
- ):
+ 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
- LOGGER.debug("running cell %s", curr_cell_id)
- write_new_run(curr_cell_id)
- curr_cell = self.graph.cells[curr_cell_id]
-
+ LOGGER.debug("running cell %s", cell_id)
+ write_new_run(cell_id)
# State clean-up: don't leak names, UI elements, ...
- self._invalidate_cell_state(curr_cell_id)
+ self._invalidate_cell_state(cell_id)
- return_value = None
- raised_exception = None
- with self._execution_ctx(curr_cell_id):
- try:
- return_value = execute_cell(curr_cell, self.globals)
- except Exception as e: # noqa: E722
- raised_exception = e
- # all three values are guaranteed to be non-None because an
- # exception is on the stack:
- # https://docs.python.org/3/library/sys.html#sys.exc_info
- exc_type, exc_value, tb = sys.exc_info()
- # custom traceback formatting strips out marimo internals
- # and adds source code from cells
- frames = traceback.extract_tb(tb)
- error_msg_lines = []
- found_cell_frame = False
- for filename, lineno, fn_name, text in frames:
- filename_cell_id = cell_id_from_filename(filename)
- in_cell = filename_cell_id is not None
- if in_cell:
- found_cell_frame = True
- if not found_cell_frame:
- continue
-
- line = " "
- if in_cell:
- # TODO: hyperlink to cell ... should the traceback
- # be assembled in the frontend?
- line += f"Cell {filename}, "
- else:
- line += f"File {filename}, "
- line += f"line {lineno}"
-
- if fn_name != "<module>":
- line += f", in {fn_name}"
- error_msg_lines.append(line)
-
- if filename_cell_id is not None:
- lines = self.graph.cells[
- filename_cell_id
- ].code.split("\n")
- error_msg_lines.append(
- " " + lines[lineno - 1].strip()
- )
- else:
- error_msg_lines.append(" " + text.strip())
-
- error_msg = (
- "Traceback (most recent call last):\n"
- + "\n".join(error_msg_lines)
- + "\n"
- + exc_type.__name__ # type: ignore
- + ": "
- + str(exc_value)
- )
- sys.stderr.write(error_msg)
-
- if raised_exception is None:
- return_value = "" if return_value is None else return_value
- if (formatter := get_formatter(return_value)) is not None:
- try:
- mimetype, data = formatter(return_value)
- write_output(
- channel="output",
- mimetype=mimetype,
- data=data,
- cell_id=curr_cell_id,
- )
- except Exception: # noqa: E722
- with self._execution_ctx(curr_cell_id):
- sys.stderr.write(traceback.format_exc())
- write_output(
- channel="output",
- mimetype="text/plain",
- data="",
- cell_id=curr_cell_id,
- )
- else:
- tmpio = io.StringIO()
- if isinstance(return_value, str):
- tmpio.write(return_value)
- else:
- try:
- pprint.pprint(return_value, stream=tmpio)
- except Exception: # noqa: E722
- tmpio.write("")
- with self._execution_ctx(curr_cell_id):
- sys.stderr.write(traceback.format_exc())
- tmpio.seek(0)
- write_output(
- channel="output",
- mimetype="text/plain",
- data=tmpio.read(),
- cell_id=curr_cell_id,
- )
- elif isinstance(raised_exception, MarimoInterrupt):
- # We don't cleanup the cell: users may want to
- # access variables/state that was computed before interruption
- # happened
- LOGGER.debug("Cell %s was interrupted", curr_cell_id)
+ with self._execution_ctx(cell_id):
+ run_result = runner.run(cell_id)
+
+ if run_result.success():
+ formatted_output = run_result.format_output()
+ if formatted_output.traceback is not None:
+ with self._execution_ctx(cell_id):
+ sys.stderr.write(formatted_output.traceback)
+ write_output(
+ channel=formatted_output.channel,
+ mimetype=formatted_output.mimetype,
+ data=formatted_output.data,
+ cell_id=cell_id,
+ )
+ elif isinstance(run_result.exception, MarimoStopError):
+ LOGGER.debug("Cell %s was stopped via mo.stop()", cell_id)
+ formatted_output = run_result.format_output()
+ if formatted_output.traceback is not None:
+ with self._execution_ctx(cell_id):
+ sys.stderr.write(formatted_output.traceback)
+ write_output(
+ channel=formatted_output.channel,
+ mimetype=formatted_output.mimetype,
+ data=formatted_output.data,
+ cell_id=cell_id,
+ )
+ 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
write_marimo_error(
data=[MarimoInterruptionError()],
clear_console=False,
- cell_id=curr_cell_id,
+ cell_id=cell_id,
)
- interrupted = True
- else:
+ elif run_result.exception is not None:
LOGGER.debug(
"Cell %s raised %s",
- curr_cell_id,
- type(raised_exception).__name__,
+ 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__
write_marimo_error(
data=[
MarimoExceptionRaisedError(
msg="This cell raised an exception: %s%s"
% (
- type(raised_exception).__name__,
- f"('{str(raised_exception)}')"
- if str(raised_exception)
+ 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=curr_cell_id,
- )
- cells_cancelled[curr_cell_id] = set(
- cid
- for cid in dataflow.transitive_closure(
- self.graph, set([curr_cell_id])
- )
- if cid in cells_to_run
+ cell_id=cell_id,
)
if get_global_context().mpl_installed:
# ensures that every cell gets a fresh axis.
exec("__marimo__._output.mpl.close_figures()", self.globals)
- if cells_to_run:
- assert interrupted
- for cid in cells_to_run:
- # once again, we don't cleanup the cell's definitions, because
- # the user may want to inspect state that was computed
- # on a previous run
+ if runner.cells_to_run:
+ assert runner.interrupted
+ for cid in runner.cells_to_run:
+ # `cid` was not run. Its defs should be deleted.
+ self._invalidate_cell_state(cid)
write_marimo_error(
data=[MarimoInterruptionError()],
# these cells are transitioning from queued to stopped
@@ -637,17 +539,34 @@ class Kernel:
cell_id=cid,
)
- for raising_cell in cells_cancelled:
- for cid in cells_cancelled[raising_cell]:
+ for raising_cell in runner.cells_cancelled:
+ for cid in runner.cells_cancelled[raising_cell]:
# `cid` was not run. Its defs should be deleted.
self._invalidate_cell_state(cid)
+ 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,
+ )
write_marimo_error(
- data=[
- MarimoExceptionRaisedError(
- msg="The following ancestor raised an exception: ",
- raising_cell=raising_cell,
- )
- ],
+ 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
diff --git a/marimo/_runtime/test_control_flow.py b/marimo/_runtime/test_control_flow.py
new file mode 100644
index 0000000000..b1dac0d4a1
--- /dev/null
+++ b/marimo/_runtime/test_control_flow.py
@@ -0,0 +1,99 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Any, Generator
+
+import pytest
+
+from marimo._plugins.ui._core.registry import UIElementRegistry
+from marimo._runtime import cell_runner, control_flow
+from marimo._runtime.context import get_context
+from marimo._runtime.requests import (
+ ExecutionRequest,
+)
+from marimo._runtime.runtime import Kernel
+
+
+class _MockStream:
+ def write(self, op: str, data: dict[Any, Any]) -> None:
+ del op
+ del data
+ pass
+
+
+# fixture that provides a kernel (and tears it down)
+def k() -> Generator[Kernel, None, None]:
+ k = Kernel()
+ get_context().initialize(
+ kernel=k,
+ ui_element_registry=UIElementRegistry(),
+ stream=_MockStream(), # type: ignore
+ stdout=None,
+ stderr=None,
+ )
+ yield k
+ get_context()._kernel = None
+ get_context()._ui_element_registry = None
+ get_context()._stream = None
+ get_context()._initialized = False
+
+
+def test_stop_false(k: Kernel) -> None:
+ k.run(
+ [
+ ExecutionRequest(
+ "0", "import marimo as mo; x = 0; mo.stop(False); y = 1"
+ ),
+ ExecutionRequest("1", "z = y + 1"),
+ ]
+ )
+ assert k.globals["x"] == 0
+ assert k.globals["y"] == 1
+ assert k.globals["z"] == 2
+
+
+def test_stop_true(k: Kernel) -> None:
+ # Populate the kernel and its globals
+ k.run(
+ [
+ ExecutionRequest("0", "x = 0; y = 1"),
+ ExecutionRequest("1", "z = y + 1"),
+ ]
+ )
+ assert k.globals["x"] == 0
+ assert k.globals["y"] == 1
+ assert k.globals["z"] == 2
+
+ # Force cell 0 to stop
+ k.run(
+ [
+ ExecutionRequest(
+ "0", "import marimo as mo; x = 0; mo.stop(True); y = 1"
+ ),
+ ]
+ )
+ # stop happened after x was assigned, so it should still exist
+ assert k.globals["x"] == 0
+ # y is assigned after stop, so it should not exist
+ assert "y" not in k.globals
+ # cell 1's defs should be invalidated
+ assert "z" not in k.globals
+
+
+def test_stop_output(k: Kernel) -> None:
+ # Run a cell through the kernel to populate graph
+ k.run(
+ [
+ ExecutionRequest(
+ "0",
+ "import marimo as mo; x = 0; mo.stop(True, 'stopped!'); y = 1",
+ ),
+ ]
+ )
+ # Run the cell through the runner to get the output
+ runner = cell_runner.Runner(set(["0"]), k.graph, k.globals)
+ run_result = runner.run("0")
+ # Check that the cell was stopped and its output is the stop output
+ assert run_result.output == "stopped!"
+ assert isinstance(run_result.exception, control_flow.MarimoStopError)
diff --git a/marimo/_smoke_tests/stop.py b/marimo/_smoke_tests/stop.py
new file mode 100644
index 0000000000..4ae501dfb0
--- /dev/null
+++ b/marimo/_smoke_tests/stop.py
@@ -0,0 +1,70 @@
+# Copyright 2023 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.1.1"
+app = marimo.App()
+
+
+def __():
+ import marimo as mo
+ import time
+ return mo, time
+
+
+def __(mo):
+ secret = mo.ui.text(label="Type a valid password: ")
+ secret
+ return secret,
+
+
+def __(mo, secret):
+ # Validation 1
+ # This cell just depends on the secret
+ mo.stop(
+ len(secret.value) < 8, mo.md("Must have length 8").callout(kind="warn")
+ )
+
+ success_1 = True
+ return success_1,
+
+
+def __(mo, secret):
+ # Validation 2
+ # This cell just depends on the secret
+ mo.stop(
+ "$" not in secret.value, mo.md("Must contain a **$**").callout(kind="warn")
+ )
+
+ success_2 = True
+ return success_2,
+
+
+def __(mo, secret, success_1):
+ # Validation 3
+ # This cell depends on the secret and first validation
+ mo.stop(
+ "7" not in secret.value and success_1,
+ mo.md("Must contain the number 7").callout(kind="warn"),
+ )
+
+ success_3 = True
+ return success_3,
+
+
+def __(mo, success_1, success_2, success_3):
+ # This depends on all the validations, and not the secret
+ _success = success_1 and success_2 and success_3
+ mo.stop(not _success)
+
+ mo.md("Secret is correct!").callout(kind="success")
+ return
+
+
+if __name__ == "__main__":
+ app.run()