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.

Refactor websocket ops in backend (#145)

Akshay Agrawal540d02913fa9
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index 2bb4332fb7..819d383777 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -81,15 +81,17 @@ class CellStatus:
@dataclasses.dataclass(frozen=True)
class Cell:
+ # hash of code
key: int
code: str
mod: ast.Module
defs: set[Name]
refs: set[Name]
deleted_refs: set[Name]
-
body: Optional[CodeType]
last_expr: Optional[CodeType]
+ # unique id
+ cell_id: Optional[CellId_t]
# Mutable fields
# config: explicit configuration of cell
@@ -117,8 +119,15 @@ class Cell:
def disabled_transitively(self) -> bool:
return self.status == "disabled-transitively"
- def set_status(self, status: Optional[CellStatusType]) -> None:
+ def set_status(self, status: CellStatusType) -> None:
+ from marimo._runtime.context import get_context
+
self._status.state = status
+ if get_context().initialized:
+ from marimo._messaging.ops import CellOp
+
+ assert self.cell_id is not None
+ CellOp.broadcast_status(cell_id=self.cell_id, status=status)
CellFuncType = Callable[..., Optional[Tuple[Any, ...]]]
@@ -220,6 +229,7 @@ def parse_cell(
deleted_refs=set(),
body=None,
last_expr=None,
+ cell_id=cell_id,
)
v = ScopedVisitor("cell_" + str(cell_id) if cell_id is not None else None)
@@ -244,6 +254,7 @@ def parse_cell(
deleted_refs=v.deleted_refs,
body=body,
last_expr=last_expr,
+ cell_id=cell_id,
)
diff --git a/marimo/_messaging/console_output_worker.py b/marimo/_messaging/console_output_worker.py
index 6cdaecaf49..b918476734 100644
--- a/marimo/_messaging/console_output_worker.py
+++ b/marimo/_messaging/console_output_worker.py
@@ -3,13 +3,12 @@ from __future__ import annotations
import time
from collections import deque
-from dataclasses import asdict, dataclass
+from dataclasses import dataclass
from threading import Condition
from typing import TYPE_CHECKING, Literal, Optional
from marimo._ast.cell import CellId_t
from marimo._messaging.cell_output import CellOutput
-from marimo._messaging.message_types import CellOp
if TYPE_CHECKING:
from marimo._messaging.streams import Stream
@@ -30,19 +29,16 @@ class ConsoleMsg:
def _write_console_output(
stream: Stream, stream_type: StreamT, cell_id: CellId_t, data: str
) -> None:
- return stream.write(
- op=CellOp.name,
- data=asdict(
- CellOp(
- cell_id=cell_id,
- console=CellOutput(
- channel=stream_type,
- mimetype="text/plain",
- data=data,
- ),
- )
+ from marimo._messaging.ops import CellOp
+
+ CellOp(
+ cell_id=cell_id,
+ console=CellOutput(
+ channel=stream_type,
+ mimetype="text/plain",
+ data=data,
),
- )
+ ).broadcast(stream)
def _add_output_to_buffer(
diff --git a/marimo/_messaging/message_types.py b/marimo/_messaging/message_types.py
deleted file mode 100644
index 35c696bd5b..0000000000
--- a/marimo/_messaging/message_types.py
+++ /dev/null
@@ -1,148 +0,0 @@
-# Copyright 2023 Marimo. All rights reserved.
-"""Message Types
-
-Messages that the kernel sends to the frontend.
-"""
-
-from __future__ import annotations
-
-import time
-from dataclasses import asdict, dataclass, field
-from typing import ClassVar, Dict, Literal, Optional, Union, cast
-
-from marimo._ast.cell import CellConfig, CellId_t, CellStatusType
-from marimo._messaging.cell_output import CellOutput
-from marimo._messaging.completion_option import CompletionOption
-from marimo._output.hypertext import Html
-from marimo._plugins.core.web_component import JSONType
-from marimo._plugins.ui._core.ui_element import UIElement
-from marimo._server.layout import LayoutConfig
-
-
-# A cell-op's data has three optional fields:
-#
-# output - a CellOutput
-# console - a CellOutput (console message to append), or a list of CellOutputs
-# status - execution status
-#
-# NB: omitting a field means that its value should be unchanged
-#
-# and one required field:
-#
-# cell_id - the cell id
-@dataclass
-class CellOp:
- name: ClassVar[str] = "cell-op"
- cell_id: CellId_t
- output: Optional[CellOutput] = None
- console: Optional[Union[CellOutput, list[CellOutput]]] = None
- status: Optional[CellStatusType] = None
- timestamp: float = field(default_factory=lambda: time.time())
-
-
-@dataclass
-class RemoveUIElements:
- name: ClassVar[str] = "remove-ui-elements"
- cell_id: CellId_t
-
-
-@dataclass
-class Interrupted:
- name: ClassVar[str] = "interrupted"
-
-
-@dataclass
-class CompletedRun:
- name: ClassVar[str] = "completed-run"
-
-
-@dataclass
-class KernelReady:
- name: ClassVar[str] = "kernel-ready"
- codes: tuple[str, ...]
- names: tuple[str, ...]
- layout: Optional[LayoutConfig]
- configs: tuple[CellConfig, ...]
-
-
-@dataclass
-class CompletionResult:
- name: ClassVar[str] = "completion-result"
- completion_id: str
- prefix_length: int
- options: list[CompletionOption]
-
-
-@dataclass
-class Alert:
- name: ClassVar[str] = "alert"
- title: str
- description: str
- variant: Optional[Literal["danger"]] = None
-
-
-@dataclass
-class VariableDeclaration:
- name: str
- declared_by: list[CellId_t]
- used_by: list[CellId_t]
-
-
-@dataclass
-class VariableValue:
- name: str
- datatype: Optional[str]
- value: Optional[str]
-
- def __init__(self, name: str, value: object):
- self.name = name
- try:
- self.datatype = type(value).__name__ if value is not None else None
- except Exception:
- self.datatype = None
- try:
- self.value = self._format_value(value)
- except Exception:
- self.value = None
-
- def _stringify(self, value: object) -> str:
- return str(value)[:50]
-
- def _format_value(self, value: object) -> str:
- if isinstance(value, UIElement):
- return self._stringify(value.value)
- elif isinstance(value, Html):
- return self._stringify(value.text)
- else:
- return self._stringify(value)
-
-
-@dataclass
-class Variables:
- name: ClassVar[str] = "variables"
- variables: list[VariableDeclaration]
-
-
-@dataclass
-class VariableValues:
- name: ClassVar[str] = "variable-values"
- variables: list[VariableValue]
-
-
-MessageType = Union[
- Alert,
- CellOp,
- RemoveUIElements,
- Interrupted,
- CompletedRun,
- KernelReady,
- CompletionResult,
- Variables,
- VariableValues,
-]
-
-
-# TODO(akshayka): fix typing once mypy/dataclasses has stricter
-# typing for asdict
-def serialize(message: MessageType) -> dict[str, JSONType]:
- return cast(Dict[str, JSONType], asdict(message))
diff --git a/marimo/_messaging/messages.py b/marimo/_messaging/messages.py
deleted file mode 100644
index ddd9c4aeaa..0000000000
--- a/marimo/_messaging/messages.py
+++ /dev/null
@@ -1,208 +0,0 @@
-# Copyright 2023 Marimo. All rights reserved.
-from __future__ import annotations
-
-import sys
-from typing import Any, Optional, Sequence
-
-from marimo._ast.cell import CellId_t, CellStatusType
-from marimo._messaging.cell_output import CellOutput
-from marimo._messaging.errors import Error
-from marimo._messaging.message_types import (
- CellOp,
- CompletedRun,
- Interrupted,
- MessageType,
- RemoveUIElements,
- VariableDeclaration,
- Variables,
- VariableValue,
- VariableValues,
- serialize,
-)
-from marimo._messaging.streams import OUTPUT_MAX_BYTES
-from marimo._output.formatting import get_formatter
-from marimo._runtime.context import get_context
-
-
-def write_output(
- channel: str,
- mimetype: str,
- data: str,
- cell_id: CellId_t,
- status: Optional[CellStatusType],
-) -> None:
- if (size := sys.getsizeof(data)) > OUTPUT_MAX_BYTES:
- from marimo._output.md import md
- from marimo._plugins.stateless.callout_output import callout
-
- warning = callout(
- md(
- f"""
- <span class="text-error">**Your output is too large**</span>
-
- Your output is too large for marimo to show. It has a size
- of {size} bytes. Did you output this object by accident?
-
- If this limitation is a problem for you, please reach out
- to us on [Discord](https://discord.gg/JE7nhX6mD8) or
- [Github](https://github.com/marimo-team/marimo/issues).
- """
- ),
- kind="warn",
- )
- mimetype, data = warning._mime_()
-
- get_context().stream.write(
- op=CellOp.name,
- data=serialize(
- CellOp(
- cell_id=cell_id,
- output=CellOutput(
- channel=channel,
- mimetype=mimetype,
- data=data,
- ),
- status=status,
- )
- ),
- )
-
-
-def write_stale(cell_id: CellId_t) -> None:
- get_context().stream.write(
- op=CellOp.name,
- data=serialize(CellOp(cell_id=cell_id, status="stale")),
- )
-
-
-def write_idle(cell_id: CellId_t) -> None:
- get_context().stream.write(
- op=CellOp.name,
- data=serialize(CellOp(cell_id=cell_id, status="idle")),
- )
-
-
-def write_disabled_transitively(cell_id: CellId_t) -> None:
- get_context().stream.write(
- op=CellOp.name,
- data=serialize(
- CellOp(cell_id=cell_id, status="disabled-transitively")
- ),
- )
-
-
-def write_queued(cell_id: CellId_t) -> None:
- get_context().stream.write(
- op=CellOp.name,
- data=serialize(CellOp(cell_id=cell_id, status="queued")),
- )
-
-
-def write_new_run(cell_id: CellId_t) -> None:
- get_context().stream.write(
- op=CellOp.name,
- data=serialize(CellOp(cell_id=cell_id, console=[], status="running")),
- )
-
-
-def write_marimo_error(
- data: Sequence[Error],
- clear_console: bool,
- cell_id: CellId_t,
- status: Optional[CellStatusType],
-) -> None:
- console: Optional[list[CellOutput]] = [] if clear_console else None
- get_context().stream.write(
- op=CellOp.name,
- data=serialize(
- CellOp(
- cell_id=cell_id,
- output=CellOutput(
- channel="marimo-error",
- mimetype="application/vnd.marimo+error",
- data=data,
- ),
- console=console,
- status=status,
- )
- ),
- )
-
-
-def write_variables(data: list[VariableDeclaration]) -> None:
- get_context().stream.write(
- op=Variables.name,
- data=serialize(Variables(variables=data)),
- )
-
-
-def write_variable_values(data: list[VariableValue]) -> None:
- get_context().stream.write(
- op=VariableValues.name,
- data=serialize(VariableValues(variables=data)),
- )
-
-
-def write_interrupted() -> None:
- get_context().stream.write(op=Interrupted.name, data={})
-
-
-def write_completed_run() -> None:
- get_context().stream.write(op=CompletedRun.name, data={})
-
-
-def write_remove_ui_elements(cell_id: CellId_t) -> None:
- get_context().stream.write(
- op=RemoveUIElements.name,
- data=serialize(RemoveUIElements(cell_id=cell_id)),
- )
-
-
-# TODO: refactor messaging code to use this function instead of
-# write_* for specific ops ...
-def write_message(op: MessageType) -> None:
- get_context().stream.write(op=op.name, data=serialize(op))
-
-
-def write_output_to_global_stream(
- channel: str, mimetype: str, data: str
-) -> None:
- stream = get_context().stream
- assert stream.cell_id is not None
- write_output(channel, mimetype, data, stream.cell_id, status=None)
-
-
-def write_to_global_console_stream(
- channel: str, mimetype: str, data: str
-) -> None:
- stream = get_context().stream
- assert stream.cell_id is not None
- stream.write(
- op=CellOp.name,
- data=serialize(
- CellOp(
- cell_id=stream.cell_id,
- console=CellOutput(
- channel=channel,
- mimetype=mimetype,
- data=data,
- ),
- )
- ),
- )
-
-
-def _show(value: Any, mimetype: Optional[str] = None) -> None:
- """Shows a value in the current cell's console area
-
- Uses the media protocol to instantiate a displayable element
- for `value`.
- """
- if (formatter := get_formatter(value)) is not None:
- mimetype, data = formatter(value)
- else:
- mimetype, data = ("text/plain", value)
-
- write_to_global_console_stream(
- channel="output", mimetype=mimetype, data=data
- )
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
new file mode 100644
index 0000000000..fa6d2e4e0a
--- /dev/null
+++ b/marimo/_messaging/ops.py
@@ -0,0 +1,272 @@
+# Copyright 2023 Marimo. All rights reserved.
+"""Message Types
+
+Messages that the kernel sends to the frontend.
+"""
+
+from __future__ import annotations
+
+import sys
+import time
+from dataclasses import asdict, dataclass, field
+from typing import (
+ Any,
+ ClassVar,
+ Dict,
+ Literal,
+ Optional,
+ Sequence,
+ Union,
+ cast,
+)
+
+from marimo._ast.cell import CellConfig, CellId_t, CellStatusType
+from marimo._messaging.cell_output import CellOutput
+from marimo._messaging.completion_option import CompletionOption
+from marimo._messaging.errors import Error
+from marimo._messaging.streams import OUTPUT_MAX_BYTES, Stream
+from marimo._output.hypertext import Html
+from marimo._plugins.core.web_component import JSONType
+from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._runtime.context import get_context
+from marimo._server.layout import LayoutConfig
+
+
+def serialize(datacls: Any) -> dict[str, JSONType]:
+ return cast(Dict[str, JSONType], asdict(datacls))
+
+
+@dataclass
+class Op:
+ name: ClassVar[str]
+
+ # 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
+ stream.write(op=self.name, data=serialize(self))
+
+
+@dataclass
+class CellOp(Op):
+ """Op to transition a cell.
+
+ A CellOp's data has three optional fields:
+
+ output - a CellOutput
+ console - a CellOutput (console msg to append), or a list of CellOutputs
+ status - execution status
+
+ Omitting a field means that its value should be unchanged!
+
+ And one required field:
+
+ cell_id - the cell id
+ """
+
+ name: ClassVar[str] = "cell-op"
+ cell_id: CellId_t
+ output: Optional[CellOutput] = None
+ console: Optional[Union[CellOutput, list[CellOutput]]] = None
+ status: Optional[CellStatusType] = None
+ timestamp: float = field(default_factory=lambda: time.time())
+
+ @staticmethod
+ def maybe_truncate_output(mimetype: str, data: str) -> tuple[str, str]:
+ if (size := sys.getsizeof(data)) > OUTPUT_MAX_BYTES:
+ from marimo._output.md import md
+ from marimo._plugins.stateless.callout_output import callout
+
+ text = f"""
+ <span class="text-error">**Your output is too large**</span>
+
+ Your output is too large for marimo to show. It has a size
+ of {size} bytes. Did you output this object by accident?
+
+ If this limitation is a problem for you, please reach out
+ to us on [Discord](https://discord.gg/JE7nhX6mD8) or
+ [Github](https://github.com/marimo-team/marimo/issues).
+ """
+
+ warning = callout(
+ md(text),
+ kind="warn",
+ )
+ mimetype, data = warning._mime_()
+ return mimetype, data
+
+ @staticmethod
+ def broadcast_output(
+ channel: str,
+ mimetype: str,
+ data: str,
+ cell_id: Optional[CellId_t],
+ status: Optional[CellStatusType],
+ ) -> None:
+ mimetype, data = CellOp.maybe_truncate_output(mimetype, data)
+ cell_id = (
+ cell_id if cell_id is not None else get_context().stream.cell_id
+ )
+ assert cell_id is not None
+ CellOp(
+ cell_id=cell_id,
+ output=CellOutput(
+ channel=channel,
+ mimetype=mimetype,
+ data=data,
+ ),
+ status=status,
+ ).broadcast()
+
+ @staticmethod
+ def broadcast_console_output(
+ channel: str,
+ mimetype: str,
+ data: str,
+ cell_id: Optional[CellId_t],
+ status: Optional[CellStatusType],
+ ) -> None:
+ mimetype, data = CellOp.maybe_truncate_output(mimetype, data)
+ cell_id = (
+ cell_id if cell_id is not None else get_context().stream.cell_id
+ )
+ assert cell_id is not None
+ CellOp(
+ cell_id=cell_id,
+ console=CellOutput(
+ channel=channel,
+ mimetype=mimetype,
+ data=data,
+ ),
+ status=status,
+ ).broadcast()
+
+ @staticmethod
+ def broadcast_status(cell_id: CellId_t, status: CellStatusType) -> None:
+ if status != "running":
+ CellOp(cell_id=cell_id, status=status).broadcast()
+ else:
+ # Console gets cleared on "running"
+ CellOp(cell_id=cell_id, console=[], status=status).broadcast()
+
+ @staticmethod
+ def broadcast_error(
+ data: Sequence[Error],
+ clear_console: bool,
+ cell_id: CellId_t,
+ status: Optional[CellStatusType],
+ ) -> None:
+ console: Optional[list[CellOutput]] = [] if clear_console else None
+ CellOp(
+ cell_id=cell_id,
+ output=CellOutput(
+ channel="marimo-error",
+ mimetype="application/vnd.marimo+error",
+ data=data,
+ ),
+ console=console,
+ status=status,
+ ).broadcast()
+
+
+@dataclass
+class RemoveUIElements(Op):
+ """Invalidate UI elements for a given cell."""
+
+ name: ClassVar[str] = "remove-ui-elements"
+ cell_id: CellId_t
+
+
+@dataclass
+class Interrupted(Op):
+ """Written when the kernel is interrupted by the user."""
+
+ name: ClassVar[str] = "interrupted"
+
+
+@dataclass
+class CompletedRun(Op):
+ """Written on run completion (of submitted cells and their descendants."""
+
+ name: ClassVar[str] = "completed-run"
+
+
+@dataclass
+class KernelReady(Op):
+ """Kernel is ready for execution."""
+
+ name: ClassVar[str] = "kernel-ready"
+ codes: tuple[str, ...]
+ names: tuple[str, ...]
+ layout: Optional[LayoutConfig]
+ configs: tuple[CellConfig, ...]
+
+
+@dataclass
+class CompletionResult(Op):
+ """Code completion result."""
+
+ name: ClassVar[str] = "completion-result"
+ completion_id: str
+ prefix_length: int
+ options: list[CompletionOption]
+
+
+@dataclass
+class Alert(Op):
+ name: ClassVar[str] = "alert"
+ title: str
+ # description may be HTML
+ description: str
+ variant: Optional[Literal["danger"]] = None
+
+
+@dataclass
+class VariableDeclaration:
+ name: str
+ declared_by: list[CellId_t]
+ used_by: list[CellId_t]
+
+
+@dataclass
+class VariableValue:
+ name: str
+ datatype: Optional[str]
+ value: Optional[str]
+
+ def __init__(self, name: str, value: object):
+ self.name = name
+ try:
+ self.datatype = type(value).__name__ if value is not None else None
+ except Exception:
+ self.datatype = None
+ try:
+ self.value = self._format_value(value)
+ except Exception:
+ self.value = None
+
+ def _stringify(self, value: object) -> str:
+ return str(value)[:50]
+
+ def _format_value(self, value: object) -> str:
+ if isinstance(value, UIElement):
+ return self._stringify(value.value)
+ elif isinstance(value, Html):
+ return self._stringify(value.text)
+ else:
+ return self._stringify(value)
+
+
+@dataclass
+class Variables(Op):
+ """List of variable declarations."""
+
+ name: ClassVar[str] = "variables"
+ variables: list[VariableDeclaration]
+
+
+@dataclass
+class VariableValues(Op):
+ """List of variables and their types/values."""
+
+ name: ClassVar[str] = "variable-values"
+ variables: list[VariableValue]
diff --git a/marimo/_messaging/test_message_types.py b/marimo/_messaging/test_ops.py
similarity index 90%
rename from marimo/_messaging/test_message_types.py
rename to marimo/_messaging/test_ops.py
index 05e285d6fc..09265e0e02 100644
--- a/marimo/_messaging/test_message_types.py
+++ b/marimo/_messaging/test_ops.py
@@ -1,5 +1,5 @@
# Copyright 2023 Marimo. All rights reserved.
-from marimo._messaging.message_types import VariableValue
+from marimo._messaging.ops import VariableValue
from marimo._output.hypertext import Html
from marimo._plugins.ui._impl.input import slider
diff --git a/marimo/_output/mpl.py b/marimo/_output/mpl.py
index 65387b284a..f9f3c25111 100644
--- a/marimo/_output/mpl.py
+++ b/marimo/_output/mpl.py
@@ -19,7 +19,7 @@ import matplotlib.pyplot as plt # type: ignore
from matplotlib.backend_bases import FigureManagerBase, Gcf # type: ignore
from matplotlib.backends.backend_agg import FigureCanvasAgg # type: ignore
-from marimo._messaging.messages import write_to_global_console_stream
+from marimo._messaging.ops import CellOp
from marimo._output.utils import build_data_url
FigureCanvas = FigureCanvasAgg
@@ -37,10 +37,12 @@ def _internal_show(canvas: FigureCanvasAgg) -> None:
plt.close(canvas.figure)
mimetype = "image/png"
plot_bytes = base64.b64encode(buf.getvalue())
- write_to_global_console_stream(
- data=build_data_url(mimetype=mimetype, data=plot_bytes),
+ CellOp.broadcast_console_output(
channel="media",
mimetype=mimetype,
+ data=build_data_url(mimetype=mimetype, data=plot_bytes),
+ cell_id=None,
+ status=None,
)
diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.py
index 3e4f122862..2c6437be6c 100644
--- a/marimo/_runtime/complete.py
+++ b/marimo/_runtime/complete.py
@@ -10,7 +10,7 @@ import jedi.api # type: ignore # noqa: F401
from marimo import _loggers as loggers
from marimo._messaging.completion_option import CompletionOption
-from marimo._messaging.message_types import CompletionResult, serialize
+from marimo._messaging.ops import CompletionResult
from marimo._messaging.streams import Stream
from marimo._output.md import _md
from marimo._runtime import dataflow
@@ -155,16 +155,11 @@ def _write_completion_result(
prefix_length: int,
options: list[CompletionOption],
) -> None:
- stream.write(
- op=CompletionResult.name,
- data=serialize(
- CompletionResult(
- completion_id=completion_id,
- prefix_length=prefix_length,
- options=options,
- )
- ),
- )
+ CompletionResult(
+ completion_id=completion_id,
+ prefix_length=prefix_length,
+ options=options,
+ ).broadcast(stream=stream)
def _write_no_completions(stream: Stream, completion_id: str) -> None:
diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.py
index 5aa2288699..8464b82e2c 100644
--- a/marimo/_runtime/dataflow.py
+++ b/marimo/_runtime/dataflow.py
@@ -142,7 +142,7 @@ class DirectedGraph:
self.cycles.add(tuple([(other_id, cell_id)] + path))
self.children[other_id].add(cell_id)
- def disable_cell(self, cell_id: CellId_t) -> set[CellId_t]:
+ def disable_cell(self, cell_id: CellId_t) -> None:
"""
Disables a cell in the graph.
@@ -153,17 +153,12 @@ class DirectedGraph:
if cell_id not in self.cells:
raise ValueError(f"Cell {cell_id} not found")
- disabled_transitively: set[CellId_t] = set()
for cid in transitive_closure(self, set([cell_id])) - set([cell_id]):
cell = self.cells[cid]
if not cell.stale:
cell.set_status(status="disabled-transitively")
- disabled_transitively.add(cid)
- return disabled_transitively
- def enable_cell(
- self, cell_id: CellId_t
- ) -> tuple[set[CellId_t], set[CellId_t]]:
+ def enable_cell(self, cell_id: CellId_t) -> set[CellId_t]:
"""
Enables a cell in the graph.
@@ -171,13 +166,11 @@ class DirectedGraph:
Returns:
- set of cells that were stale and should be re-run
- - set of cells that were disabled transitively and now idle
"""
if cell_id not in self.cells:
raise ValueError(f"Cell {cell_id} not found")
cells_to_run: set[CellId_t] = set()
- cells_idle: set[CellId_t] = set()
for cid in transitive_closure(self, set([cell_id])):
if not self.is_disabled(cid):
child = self.cells[cid]
@@ -187,9 +180,8 @@ class DirectedGraph:
cells_to_run.add(cid)
elif child.disabled_transitively:
# cell is no longer disabled: status -> idle
- cells_idle.add(cid)
child.set_status("idle")
- return cells_to_run, cells_idle
+ return cells_to_run
def delete_cell(self, cell_id: CellId_t) -> set[CellId_t]:
"""Removes a cell from the graph.
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 5a5771e859..3df115b274 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -27,20 +27,15 @@ from marimo._messaging.errors import (
MarimoSyntaxError,
UnknownError,
)
-from marimo._messaging.message_types import VariableDeclaration, VariableValue
-from marimo._messaging.messages import (
- write_completed_run,
- write_disabled_transitively,
- write_idle,
- write_interrupted,
- write_marimo_error,
- write_new_run,
- write_output,
- write_queued,
- write_remove_ui_elements,
- write_stale,
- write_variable_values,
- write_variables,
+from marimo._messaging.ops import (
+ CellOp,
+ CompletedRun,
+ Interrupted,
+ RemoveUIElements,
+ VariableDeclaration,
+ Variables,
+ VariableValue,
+ VariableValues,
)
from marimo._messaging.streams import Stderr, Stdout, Stream, redirect_streams
from marimo._output.rich_help import mddoc
@@ -290,7 +285,7 @@ class Kernel:
self._delete_names(
defs_to_delete, exclude_defs if exclude_defs is not None else set()
)
- write_remove_ui_elements(cell_id)
+ RemoveUIElements(cell_id=cell_id).broadcast()
def _deactivate_cell(self, cell_id: CellId_t) -> set[CellId_t]:
"""Deactivate: remove from graph, invalidate state, but keep metadata
@@ -440,8 +435,8 @@ class Kernel:
) & cells_in_graph
for cid in cells_that_no_longer_have_errors:
# clear error outputs before running
- write_output(
- "output",
+ CellOp.broadcast_output(
+ channel="output",
mimetype="text/plain",
data="",
cell_id=cid,
@@ -502,16 +497,15 @@ class Kernel:
# this may be the first time we're seeing the cell: set its
# status
self.graph.cells[cid].set_status("disabled-transitively")
- write_disabled_transitively(cid)
- write_marimo_error(
+ CellOp.broadcast_error(
data=self.errors[cid],
clear_console=True,
cell_id=cid,
status=None,
)
- write_variables(
- [
+ Variables(
+ variables=[
VariableDeclaration(
name=variable,
declared_by=list(declared_by),
@@ -519,7 +513,7 @@ class Kernel:
)
for variable, declared_by in self.graph.definitions.items()
]
- )
+ ).broadcast()
return descendants
def _run_cells(self, cell_ids: set[CellId_t]) -> None:
@@ -543,10 +537,8 @@ class Kernel:
for cid in cell_ids:
if self.graph.is_disabled(cid):
self.graph.cells[cid].set_status(status="stale")
- write_stale(cell_id=cid)
else:
self.graph.cells[cid].set_status(status="queued")
- write_queued(cell_id=cid)
runner = cell_runner.Runner(
cell_ids=cell_ids,
graph=self.graph,
@@ -576,7 +568,6 @@ class Kernel:
LOGGER.debug("running cell %s", cell_id)
cell.set_status(status="running")
- write_new_run(cell_id)
with self._install_execution_context(cell_id):
run_result = runner.run(cell_id)
@@ -594,7 +585,7 @@ class Kernel:
]
if values:
- write_variable_values(values)
+ VariableValues(variables=values).broadcast()
cell.set_status(status="idle")
if run_result.success():
@@ -602,7 +593,7 @@ class Kernel:
if formatted_output.traceback is not None:
with self._install_execution_context(cell_id):
sys.stderr.write(formatted_output.traceback)
- write_output(
+ CellOp.broadcast_output(
channel=formatted_output.channel,
mimetype=formatted_output.mimetype,
data=formatted_output.data,
@@ -615,7 +606,7 @@ class Kernel:
if formatted_output.traceback is not None:
with self._install_execution_context(cell_id):
sys.stderr.write(formatted_output.traceback)
- write_output(
+ CellOp.broadcast_output(
channel=formatted_output.channel,
mimetype=formatted_output.mimetype,
data=formatted_output.data,
@@ -626,7 +617,7 @@ class Kernel:
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(
+ CellOp.broadcast_error(
data=[MarimoInterruptionError()],
clear_console=False,
cell_id=cell_id,
@@ -641,7 +632,7 @@ class Kernel:
# 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(
+ CellOp.broadcast_error(
data=[
MarimoExceptionRaisedError(
msg="This cell raised an exception: %s%s"
@@ -670,7 +661,7 @@ class Kernel:
# `cid` was not run. Its defs should be deleted.
self.graph.cells[cid].set_status("idle")
self._invalidate_cell_state(cid)
- write_marimo_error(
+ CellOp.broadcast_error(
data=[MarimoInterruptionError()],
# these cells are transitioning from queued to stopped
# (interrupted); they didn't get to run, so their consoles
@@ -707,7 +698,7 @@ class Kernel:
exception_type=exception_type,
raising_cell=raising_cell,
)
- write_marimo_error(
+ CellOp.broadcast_error(
data=[data],
# these cells are transitioning from queued to stopped
# (interrupted); they didn't get to run, so their consoles
@@ -775,12 +766,9 @@ class Kernel:
continue
cell.configure(config)
if not cell.config.disabled:
- cells_to_run, cells_idle = self.graph.enable_cell(cell_id)
- for cid in cells_idle:
- write_idle(cid)
+ cells_to_run = self.graph.enable_cell(cell_id)
elif cell.config.disabled:
- for cid in self.graph.disable_cell(cell_id):
- write_disabled_transitively(cid)
+ self.graph.disable_cell(cell_id)
if cells_to_run:
self._run_cells(
@@ -858,7 +846,7 @@ class Kernel:
- self.graph.definitions[name]
)
if variable_values:
- write_variable_values(variable_values)
+ VariableValues(variables=variable_values).broadcast()
self._run_cells(
dataflow.transitive_closure(self.graph, referring_cells)
)
@@ -970,7 +958,7 @@ def launch_kernel(
# it won't be interrupted, which isn't right ... but the
# probability of that happening is low.
if kernel.execution_context is not None:
- write_interrupted()
+ Interrupted().broadcast()
raise MarimoInterrupt
signal.signal(signal.SIGINT, interrupt_handler)
@@ -985,15 +973,15 @@ def launch_kernel(
LOGGER.debug("received request %s", request)
if isinstance(request, CreationRequest):
kernel.instantiate(request)
- write_completed_run()
+ CompletedRun().broadcast()
elif isinstance(request, ExecuteMultipleRequest):
kernel.run(request.execution_requests)
- write_completed_run()
+ CompletedRun().broadcast()
elif isinstance(request, SetCellConfigRequest):
kernel.set_cell_config(request)
elif isinstance(request, SetUIElementValueRequest):
kernel.set_ui_element_value(request)
- write_completed_run()
+ CompletedRun().broadcast()
elif isinstance(request, DeleteRequest):
kernel.delete(request)
elif isinstance(request, CompletionRequest):
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index f4d7bb3f2e..2ecc9ae3d4 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -37,7 +37,7 @@ from marimo import _loggers
from marimo._ast import codegen
from marimo._ast.app import App, _AppConfig
from marimo._ast.cell import CellConfig
-from marimo._messaging.message_types import Alert, KernelReady, serialize
+from marimo._messaging.ops import Alert, KernelReady, serialize
from marimo._output.formatters.formatters import register_formatters
from marimo._runtime import requests, runtime
from marimo._server.api.status import HTTPStatus