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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
refactor: pull out notification utils (#7585)
Myles Scolnick90a291874d26
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex e579bc78a1..8d942986b2 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -348,7 +348,7 @@ class CellImpl:status (RuntimeStateType): New runtime state to setstream (Stream | None, optional): Stream to broadcast on. Defaults to None."""- from marimo._messaging.ops import CellOp+ from marimo._messaging.notification_utils import CellNotificationUtilsfrom marimo._runtime.context import (ContextNotInitializedError,get_context,@@ -361,7 +361,7 @@ class CellImpl:returnassert self.cell_id is not None- CellOp.broadcast_status(+ CellNotificationUtils.broadcast_status(cell_id=self.cell_id, status=status, stream=stream)@@ -376,11 +376,11 @@ class CellImpl:def set_stale(self, stale: bool, stream: Stream | None = None, broadcast: bool = True) -> None:- from marimo._messaging.ops import CellOp+ from marimo._messaging.notification_utils import CellNotificationUtilsself._stale.state = staleif broadcast:- CellOp.broadcast_stale(+ CellNotificationUtils.broadcast_stale(cell_id=self.cell_id, stale=stale, stream=stream)diff --git a/marimo/_messaging/console_output_worker.py b/marimo/_messaging/console_output_worker.pyindex f357e1bbc5..6e40090e26 100644--- a/marimo/_messaging/console_output_worker.py+++ b/marimo/_messaging/console_output_worker.py@@ -37,16 +37,20 @@ def _write_console_output(data: str,mimetype: ConsoleMimeType,) -> None:+ from marimo._messaging.notification_utils import broadcast_opfrom marimo._messaging.ops import CellOp- CellOp(- cell_id=cell_id,- console=CellOutput(- channel=stream_type,- mimetype=mimetype,- data=data,+ broadcast_op(+ CellOp(+ cell_id=cell_id,+ console=CellOutput(+ channel=stream_type,+ mimetype=mimetype,+ data=data,+ ),),- ).broadcast(stream)+ stream,+ )def _can_merge_outputs(first: ConsoleMsg, second: ConsoleMsg) -> bool:diff --git a/marimo/_messaging/notification_utils.py b/marimo/_messaging/notification_utils.pynew file mode 100644index 0000000000..fca1973a80--- /dev/null+++ b/marimo/_messaging/notification_utils.py@@ -0,0 +1,271 @@+# Copyright 2024 Marimo. All rights reserved.+"""Notification utilities for kernel messages.++CellNotificationUtils for cell-related broadcasts.+"""++from __future__ import annotations++import sys+from typing import TYPE_CHECKING, Optional+from uuid import uuid4++from marimo import _loggers as loggers++if TYPE_CHECKING:+ from collections.abc import Sequence++ import msgspec++from marimo._ast.cell import RuntimeStateType+from marimo._ast.toplevel import TopLevelHints, TopLevelStatus+from marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._messaging.errors import (+ Error,+ MarimoInternalError,+ is_sensitive_error,+)+from marimo._messaging.mimetypes import KnownMimeType+from marimo._messaging.serde import serialize_kernel_message+from marimo._messaging.streams import output_max_bytes+from marimo._messaging.types import Stream+from marimo._runtime.context import get_context+from marimo._runtime.context.types import ContextNotInitializedError+from marimo._runtime.context.utils import get_mode+from marimo._types.ids import CellId_t++LOGGER = loggers.marimo_logger()+++def broadcast_op(op: msgspec.Struct, stream: Optional[Stream] = None) -> None:+ """Broadcast an operation to the stream."""+ if stream is None:+ try:+ ctx = get_context()+ except ContextNotInitializedError:+ LOGGER.debug("No context initialized.")+ return+ else:+ stream = ctx.stream++ try:+ stream.write(serialize_kernel_message(op))+ except Exception as e:+ LOGGER.exception(+ "Error serializing op %s: %s",+ op.__class__.__name__,+ e,+ )+ return+++class CellNotificationUtils:+ """Utilities for broadcasting cell notifications."""++ @staticmethod+ def maybe_truncate_output(+ mimetype: KnownMimeType, data: str+ ) -> tuple[KnownMimeType, str]:+ if (size := sys.getsizeof(data)) > output_max_bytes():+ from marimo._output.md import md+ from marimo._plugins.stateless.callout 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, you can configure+ the max output size by adding (eg)++ ```+ [tool.marimo.runtime]+ output_max_bytes = 10_000_000+ ```++ to your pyproject.toml, or with the environment variable+ `MARIMO_OUTPUT_MAX_BYTES`:++ ```+ export MARIMO_OUTPUT_MAX_BYTES=10_000_000+ ```++ Increasing the max output size may cause performance issues.+ If you run into problems, please reach out+ to us on [Discord](https://marimo.io/discord?ref=app) 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: CellChannel,+ mimetype: KnownMimeType,+ data: str,+ cell_id: Optional[CellId_t],+ status: Optional[RuntimeStateType],+ stream: Stream | None = None,+ ) -> None:+ # Import here to avoid circular dependency+ from marimo._messaging.ops import CellOp++ mimetype, data = CellNotificationUtils.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+ broadcast_op(+ CellOp(+ cell_id=cell_id,+ output=CellOutput(+ channel=channel,+ mimetype=mimetype,+ data=data,+ ),+ status=status,+ ),+ stream=stream,+ )++ @staticmethod+ def broadcast_empty_output(+ cell_id: Optional[CellId_t],+ status: Optional[RuntimeStateType],+ stream: Stream | None = None,+ ) -> None:+ # Import here to avoid circular dependency+ from marimo._messaging.ops import CellOp++ cell_id = (+ cell_id if cell_id is not None else get_context().stream.cell_id+ )+ assert cell_id is not None+ broadcast_op(+ CellOp(+ cell_id=cell_id,+ output=CellOutput.empty(),+ status=status,+ ),+ stream=stream,+ )++ @staticmethod+ def broadcast_console_output(+ channel: CellChannel,+ mimetype: KnownMimeType,+ data: str,+ cell_id: Optional[CellId_t],+ status: Optional[RuntimeStateType],+ stream: Stream | None = None,+ ) -> None:+ # Import here to avoid circular dependency+ from marimo._messaging.ops import CellOp++ mimetype, data = CellNotificationUtils.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+ broadcast_op(+ CellOp(+ cell_id=cell_id,+ console=CellOutput(+ channel=channel,+ mimetype=mimetype,+ data=data,+ ),+ status=status,+ ),+ stream=stream,+ )++ @staticmethod+ def broadcast_status(+ cell_id: CellId_t,+ status: RuntimeStateType,+ stream: Stream | None = None,+ ) -> None:+ # Import here to avoid circular dependency+ from marimo._messaging.ops import CellOp++ if status != "running":+ broadcast_op(CellOp(cell_id=cell_id, status=status), stream)+ else:+ # Console gets cleared on "running"+ broadcast_op(+ CellOp(cell_id=cell_id, console=[], status=status),+ stream=stream,+ )++ @staticmethod+ def broadcast_error(+ data: Sequence[Error],+ clear_console: bool,+ cell_id: CellId_t,+ ) -> None:+ # Import here to avoid circular dependency+ from marimo._messaging.ops import CellOp++ console: Optional[list[CellOutput]] = [] if clear_console else None++ # In run mode, we don't want to broadcast the error. Instead we want to print the error to the console+ # and then broadcast a new error such that the data is hidden.+ safe_errors: list[Error] = []+ if get_mode() == "run":+ for error in data:+ # Skip non-sensitive errors+ if not is_sensitive_error(error):+ safe_errors.append(error)+ continue++ error_id = uuid4()+ LOGGER.error(+ f"(error_id={error_id}) {error.describe()}",+ extra={"error_id": error_id},+ )+ safe_errors.append(MarimoInternalError(error_id=str(error_id)))+ else:+ safe_errors = list(data)++ broadcast_op(+ CellOp(+ cell_id=cell_id,+ output=CellOutput.errors(safe_errors),+ console=console,+ status=None,+ )+ )++ @staticmethod+ def broadcast_stale(+ cell_id: CellId_t, stale: bool, stream: Stream | None = None+ ) -> None:+ # Import here to avoid circular dependency+ from marimo._messaging.ops import CellOp++ broadcast_op(CellOp(cell_id=cell_id, stale_inputs=stale), stream)++ @staticmethod+ def broadcast_serialization(+ cell_id: CellId_t,+ serialization: TopLevelStatus,+ stream: Stream | None = None,+ ) -> None:+ # Import here to avoid circular dependency+ from marimo._messaging.ops import CellOp++ status: Optional[TopLevelHints] = serialization.hint+ broadcast_op(+ CellOp(cell_id=cell_id, serialization=str(status)), stream+ )diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex f27ab16d07..0e1f2111c4 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -6,9 +6,7 @@ Messages that the kernel sends to the frontend.from __future__ import annotations-import sysimport time-from collections.abc import Sequence # noqa: TC003from types import ModuleTypefrom typing import (Any,@@ -17,14 +15,12 @@ from typing import (Optional,Union,)-from uuid import uuid4import msgspecfrom marimo import _loggers as loggersfrom marimo._ast.app_config import _AppConfigfrom marimo._ast.cell import CellConfig, RuntimeStateType-from marimo._ast.toplevel import TopLevelHints, TopLevelStatusfrom marimo._data.models import (ColumnStats,DataSourceConnection,@@ -32,25 +28,15 @@ from marimo._data.models import (DataTableSource,)from marimo._dependencies.dependencies import DependencyManager-from marimo._messaging.cell_output import CellChannel, CellOutput+from marimo._messaging.cell_output import CellOutputfrom marimo._messaging.completion_option import CompletionOptionfrom marimo._messaging.context import RUN_ID_CTX, RunId_t-from marimo._messaging.errors import (- Error,- MarimoInternalError,- is_sensitive_error,-)-from marimo._messaging.mimetypes import KnownMimeType-from marimo._messaging.msgspec_encoder import encode_json_bytes-from marimo._messaging.streams import output_max_bytes-from marimo._messaging.types import KernelMessage, Stream+from marimo._messaging.serde import serialize_kernel_message+from marimo._messaging.types import KernelMessagefrom marimo._messaging.variables import get_variable_previewfrom marimo._output.hypertext import Htmlfrom marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import UIElement-from marimo._runtime.context import get_context-from marimo._runtime.context.types import ContextNotInitializedError-from marimo._runtime.context.utils import get_modefrom marimo._runtime.layout.layout import LayoutConfigfrom marimo._secrets.models import SecretKeysWithProviderfrom marimo._sql.parse import SqlCatalogCheckResult, SqlParseResult@@ -61,55 +47,9 @@ from marimo._utils.platform import is_pyodide, is_windowsLOGGER = loggers.marimo_logger()-def serialize_kernel_message(message: Op) -> KernelMessage:- """- Serialize a MessageOperation to a KernelMessage.- """- return KernelMessage(encode_json_bytes(message))---def deserialize_kernel_message(message: KernelMessage) -> MessageOperation:- """- Deserialize a KernelMessage to a MessageOperation.- """- return msgspec.json.decode(message, strict=True, type=MessageOperation) # type: ignore[no-any-return]---class _OpName(msgspec.Struct):- op: str---def deserialize_kernel_operation_name(message: KernelMessage) -> str:- """- Deserialize a KernelMessage to a MessageOperation name.- """- # We use the Op type to deserialize the message because it is slimmer than MessageOperation- return msgspec.json.decode(message, strict=True, type=_OpName).op--class Op(msgspec.Struct, tag_field="op"):name: ClassVar[str]- def broadcast(self, stream: Optional[Stream] = None) -> None:- if stream is None:- try:- ctx = get_context()- except ContextNotInitializedError:- LOGGER.debug("No context initialized.")- return- else:- stream = ctx.stream-- try:- stream.write(serialize_kernel_message(self))- except Exception as e:- LOGGER.exception(- "Error serializing op %s: %s",- self.__class__.__name__,- e,- )- return-class CellOp(Op, tag="cell-op"):"""Op to transition a cell.@@ -160,175 +100,6 @@ class CellOp(Op, tag="cell-op"):LOGGER.error("Error getting run id: %s", str(e))self.run_id = None- @staticmethod- def maybe_truncate_output(- mimetype: KnownMimeType, data: str- ) -> tuple[KnownMimeType, str]:- if (size := sys.getsizeof(data)) > output_max_bytes():- from marimo._output.md import md- from marimo._plugins.stateless.callout 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, you can configure- the max output size by adding (eg)-- ```- [tool.marimo.runtime]- output_max_bytes = 10_000_000- ```-- to your pyproject.toml, or with the environment variable- `MARIMO_OUTPUT_MAX_BYTES`:-- ```- export MARIMO_OUTPUT_MAX_BYTES=10_000_000- ```-- Increasing the max output size may cause performance issues.- If you run into problems, please reach out- to us on [Discord](https://marimo.io/discord?ref=app) 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: CellChannel,- mimetype: KnownMimeType,- data: str,- cell_id: Optional[CellId_t],- status: Optional[RuntimeStateType],- stream: Stream | None = None,- ) -> 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(stream=stream)-- @staticmethod- def broadcast_empty_output(- cell_id: Optional[CellId_t],- status: Optional[RuntimeStateType],- stream: Stream | None = None,- ) -> None:- 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.empty(),- status=status,- ).broadcast(stream=stream)-- @staticmethod- def broadcast_console_output(- channel: CellChannel,- mimetype: KnownMimeType,- data: str,- cell_id: Optional[CellId_t],- status: Optional[RuntimeStateType],- stream: Stream | None = None,- ) -> 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(stream=stream)-- @staticmethod- def broadcast_status(- cell_id: CellId_t,- status: RuntimeStateType,- stream: Stream | None = None,- ) -> 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(- stream=stream- )-- @staticmethod- def broadcast_error(- data: Sequence[Error],- clear_console: bool,- cell_id: CellId_t,- ) -> None:- console: Optional[list[CellOutput]] = [] if clear_console else None-- # In run mode, we don't want to broadcast the error. Instead we want to print the error to the console- # and then broadcast a new error such that the data is hidden.- safe_errors: list[Error] = []- if get_mode() == "run":- for error in data:- # Skip non-sensitive errors- if not is_sensitive_error(error):- safe_errors.append(error)- continue-- error_id = uuid4()- LOGGER.error(- f"(error_id={error_id}) {error.describe()}",- extra={"error_id": error_id},- )- safe_errors.append(MarimoInternalError(error_id=str(error_id)))- else:- safe_errors = list(data)-- CellOp(- cell_id=cell_id,- output=CellOutput.errors(safe_errors),- console=console,- status=None,- ).broadcast()-- @staticmethod- def broadcast_stale(- cell_id: CellId_t, stale: bool, stream: Stream | None = None- ) -> None:- CellOp(cell_id=cell_id, stale_inputs=stale).broadcast(stream)-- @staticmethod- def broadcast_serialization(- cell_id: CellId_t,- serialization: TopLevelStatus,- stream: Stream | None = None,- ) -> None:- status: Optional[TopLevelHints] = serialization.hint- CellOp(cell_id=cell_id, serialization=str(status)).broadcast(stream)-class HumanReadableStatus(msgspec.Struct):"""Human-readable status."""diff --git a/marimo/_messaging/print_override.py b/marimo/_messaging/print_override.pyindex ab9430d23e..fe2a8f28b0 100644--- a/marimo/_messaging/print_override.py+++ b/marimo/_messaging/print_override.py@@ -6,6 +6,7 @@ import threadingfrom typing import Anyfrom marimo._messaging.cell_output import CellOutput+from marimo._messaging.notification_utils import broadcast_opfrom marimo._messaging.ops import CellOpfrom marimo._runtime.context.types import (ContextNotInitializedError,@@ -50,7 +51,10 @@ def print_override(*args: Any, **kwargs: Any) -> None:end = kwargs.get("end", "\n")msg = sep.join([str(arg) for arg in args]) + end- CellOp(- cell_id=cell_id,- console=CellOutput.stdout(msg),- ).broadcast(ctx.stream)+ broadcast_op(+ CellOp(+ cell_id=cell_id,+ console=CellOutput.stdout(msg),+ ),+ ctx.stream,+ )diff --git a/marimo/_messaging/serde.py b/marimo/_messaging/serde.pynew file mode 100644index 0000000000..1fa672f549--- /dev/null+++ b/marimo/_messaging/serde.py@@ -0,0 +1,43 @@+# Copyright 2024 Marimo. All rights reserved.+"""Serialization and deserialization utilities for kernel messages."""++from __future__ import annotations++from typing import TYPE_CHECKING++import msgspec++from marimo._messaging.msgspec_encoder import encode_json_bytes+from marimo._messaging.types import KernelMessage++if TYPE_CHECKING:+ from marimo._messaging.ops import MessageOperation+++def serialize_kernel_message(message: msgspec.Struct) -> KernelMessage:+ """+ Serialize a MessageOperation to a KernelMessage.+ """+ return KernelMessage(encode_json_bytes(message))+++def deserialize_kernel_message(message: KernelMessage) -> MessageOperation:+ """+ Deserialize a KernelMessage to a MessageOperation.+ """+ # Import here to avoid circular dependency+ from marimo._messaging.ops import MessageOperation++ return msgspec.json.decode(message, strict=True, type=MessageOperation) # type: ignore[no-any-return]+++class _OpName(msgspec.Struct):+ op: str+++def deserialize_kernel_operation_name(message: KernelMessage) -> str:+ """+ Deserialize a KernelMessage to a MessageOperation name.+ """+ # We use the _OpName type to deserialize the message because it is slimmer than MessageOperation+ return msgspec.json.decode(message, strict=True, type=_OpName).opdiff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.pyindex a027ff5841..5ea65bc72b 100644--- a/marimo/_messaging/streams.py+++ b/marimo/_messaging/streams.py@@ -122,7 +122,7 @@ class ThreadSafeStream(Stream):try:self.pipe.send(data)except OSError as e:- from marimo._messaging.ops import (+ from marimo._messaging.serde import (deserialize_kernel_operation_name,)diff --git a/marimo/_output/formatters/plotly_formatters.py b/marimo/_output/formatters/plotly_formatters.pyindex f505dd5306..fd5f43ac13 100644--- a/marimo/_output/formatters/plotly_formatters.py+++ b/marimo/_output/formatters/plotly_formatters.py@@ -7,7 +7,7 @@ from typing import Anyfrom marimo._config.config import Themefrom marimo._messaging.cell_output import CellChannelfrom marimo._messaging.mimetypes import KnownMimeType-from marimo._messaging.ops import CellOp+from marimo._messaging.notification_utils import CellNotificationUtilsfrom marimo._output.formatters.formatter_factory import FormatterFactoryfrom marimo._output.hypertext import Htmlfrom marimo._plugins.core.web_component import build_stateless_plugin@@ -58,7 +58,7 @@ class PlotlyFormatter(FormatterFactory):# Extract config if providedconfig = kwargs.get("config")mimetype, data = _show_plotly_figure(self, config=config)- CellOp.broadcast_console_output(+ CellNotificationUtils.broadcast_console_output(channel=CellChannel.MEDIA,mimetype=mimetype,data=data,diff --git a/marimo/_output/mpl.py b/marimo/_output/mpl.pyindex c9ebe0a656..5c13c62bd2 100644--- a/marimo/_output/mpl.py+++ b/marimo/_output/mpl.py@@ -28,7 +28,7 @@ from matplotlib.backends.backend_agg import FigureCanvasAggfrom marimo._messaging.cell_output import CellChannelfrom marimo._messaging.mimetypes import KnownMimeType-from marimo._messaging.ops import CellOp+from marimo._messaging.notification_utils import CellNotificationUtilsfrom marimo._utils.data_uri import build_data_urlFigureCanvas = FigureCanvasAgg@@ -107,7 +107,7 @@ def _render_figure_mimebundle(def _internal_show(canvas: FigureCanvasBase) -> None:mimetype, data = _render_figure_mimebundle(canvas)plt.close(canvas.figure)- CellOp.broadcast_console_output(+ CellNotificationUtils.broadcast_console_output(channel=CellChannel.MEDIA,mimetype=mimetype,data=data,diff --git a/marimo/_plugins/stateless/status/_progress.py b/marimo/_plugins/stateless/status/_progress.pyindex 9c3b8bc0d8..27f4e981db 100644--- a/marimo/_plugins/stateless/status/_progress.py+++ b/marimo/_plugins/stateless/status/_progress.py@@ -16,6 +16,7 @@ from typing import (import marimo._runtime.output._output as outputfrom marimo._messaging.mimetypes import KnownMimeType+from marimo._messaging.notification_utils import broadcast_opfrom marimo._messaging.ops import Alertfrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddoc@@ -500,4 +501,6 @@ def toast(kind (Literal["danger"], optional): Optional kind, use "danger" for error toasts.Defaults to None."""- Alert(title=title, description=description, variant=kind).broadcast()+ broadcast_op(+ Alert(title=title, description=description, variant=kind),+ )diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.pyindex 11cd52a2e6..4acbc22569 100644--- a/marimo/_plugins/ui/_core/ui_element.py+++ b/marimo/_plugins/ui/_core/ui_element.py@@ -433,14 +433,17 @@ class UIElement(Html, Generic[S, T]):from the backend."""+ from marimo._messaging.notification_utils import broadcast_opfrom marimo._messaging.ops import SendUIElementMessage- SendUIElementMessage(- ui_element=self._id,- model_id=None,- message=message,- buffers=list(buffers or []),- ).broadcast()+ broadcast_op(+ SendUIElementMessage(+ ui_element=self._id,+ model_id=None,+ message=message,+ buffers=list(buffers or []),+ ),+ )def _update(self, value: S) -> None:"""Update value, given a value from the frontenddiff --git a/marimo/_plugins/ui/_impl/comm.py b/marimo/_plugins/ui/_impl/comm.pyindex baf74cf2fd..8cdfcbf9be 100644--- a/marimo/_plugins/ui/_impl/comm.py+++ b/marimo/_plugins/ui/_impl/comm.py@@ -218,18 +218,22 @@ class MarimoComm:)def flush(self) -> None:+ from marimo._messaging.notification_utils import broadcast_opfrom marimo._messaging.ops import SendUIElementMessagewhile self._publish_message_buffer:item = self._publish_message_buffer.pop(0)- SendUIElementMessage(- # ui_element_id can be None. In this case, we are creating a model- # not tied to a specific UI element- ui_element=self.ui_element_id,- model_id=item.model_id,- message=item.data,- buffers=item.buffers,- ).broadcast()++ broadcast_op(+ SendUIElementMessage(+ # ui_element_id can be None. In this case, we are creating a model+ # not tied to a specific UI element+ ui_element=self.ui_element_id,+ model_id=item.model_id,+ message=item.data,+ buffers=item.buffers,+ ),+ )# This is the method that ipywidgets.widgets.Widget uses to respond to# client-side changesdiff --git a/marimo/_pyodide/bootstrap.py b/marimo/_pyodide/bootstrap.pyindex 1f506c3785..522a3eecc9 100644--- a/marimo/_pyodide/bootstrap.py+++ b/marimo/_pyodide/bootstrap.py@@ -8,6 +8,8 @@ from marimo._config.config import merge_configfrom marimo._messaging.ops import (KernelCapabilities,KernelReady,+)+from marimo._messaging.serde import (deserialize_kernel_message,serialize_kernel_message,)diff --git a/marimo/_pyodide/streams.py b/marimo/_pyodide/streams.pyindex c3d125afe5..17aa72ac7f 100644--- a/marimo/_pyodide/streams.py+++ b/marimo/_pyodide/streams.py@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Callable, Optionalfrom marimo import _loggersfrom marimo._messaging.cell_output import CellOutputfrom marimo._messaging.mimetypes import ConsoleMimeType+from marimo._messaging.notification_utils import broadcast_opfrom marimo._messaging.ops import CellOpfrom marimo._messaging.streams import std_stream_max_bytesfrom marimo._messaging.types import (@@ -73,10 +74,13 @@ class PyodideStdout(Stdout):"Warning: marimo truncated a very large console output.\n")data = data[: int(max_bytes)] + " ... "- CellOp(- cell_id=self.stream.cell_id,- console=CellOutput.stdout(data, mimetype),- ).broadcast(self.stream)+ broadcast_op(+ CellOp(+ cell_id=self.stream.cell_id,+ console=CellOutput.stdout(data, mimetype),+ ),+ self.stream,+ )return len(data)# Buffer type not available python < 3.12, hence type ignore@@ -118,10 +122,13 @@ class PyodideStderr(Stderr):+ " ... ")- CellOp(- cell_id=self.stream.cell_id,- console=CellOutput.stderr(data, mimetype),- ).broadcast(self.stream)+ broadcast_op(+ CellOp(+ cell_id=self.stream.cell_id,+ console=CellOutput.stderr(data, mimetype),+ ),+ self.stream,+ )return len(data)def writelines(self, sequence: Iterable[str]) -> None: # type: ignore[override] # noqa: E501@@ -157,10 +164,13 @@ class PyodideStdin(Stdin):+ " ... ")- CellOp(- cell_id=self.stream.cell_id,- console=CellOutput.stdin(prompt),- ).broadcast(self.stream)+ broadcast_op(+ CellOp(+ cell_id=self.stream.cell_id,+ console=CellOutput.stdin(prompt),+ ),+ self.stream,+ )return self._get_response()diff --git a/marimo/_runtime/complete.py b/marimo/_runtime/complete.pyindex 39c225943d..203293d0a3 100644--- a/marimo/_runtime/complete.py+++ b/marimo/_runtime/complete.py@@ -16,6 +16,7 @@ import jedi.api # type: ignore # noqa: F401from marimo import _loggers as loggersfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.completion_option import CompletionOption+from marimo._messaging.notification_utils import broadcast_opfrom marimo._messaging.ops import CompletionResultfrom marimo._messaging.types import Streamfrom marimo._output.md import _md@@ -298,11 +299,14 @@ def _write_completion_result(prefix_length: int,options: list[CompletionOption],) -> None:- CompletionResult(- completion_id=completion_id,- prefix_length=prefix_length,- options=options,- ).broadcast(stream=stream)+ broadcast_op(+ CompletionResult(+ completion_id=completion_id,+ prefix_length=prefix_length,+ options=options,+ ),+ stream,+ )def _write_no_completions(stream: Stream, completion_id: str) -> None:diff --git a/marimo/_runtime/handlers.py b/marimo/_runtime/handlers.pyindex cb676d6c10..2997348f03 100644--- a/marimo/_runtime/handlers.py+++ b/marimo/_runtime/handlers.py@@ -6,6 +6,7 @@ from dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Callablefrom marimo import _loggers+from marimo._messaging.notification_utils import broadcast_opfrom marimo._messaging.ops import Interruptedfrom marimo._runtime.context import get_contextfrom marimo._runtime.context.kernel_context import KernelRuntimeContext@@ -30,7 +31,7 @@ def construct_interrupt_handler(# it won't be interrupted, which isn't right ... but the# probability of that happening is low.if context.execution_context is not None:- Interrupted().broadcast()+ broadcast_op(Interrupted())# DuckDB connections are sometimes left in an inconsistent# state when interrupted by a SIGINT. Manually interrupting# duckdb through its own API seems to be safer.diff --git a/marimo/_runtime/output/_output.py b/marimo/_runtime/output/_output.pyindex 15773a1286..142c77f01b 100644--- a/marimo/_runtime/output/_output.py+++ b/marimo/_runtime/output/_output.py@@ -2,7 +2,7 @@from __future__ import annotationsfrom marimo._messaging.cell_output import CellChannel-from marimo._messaging.ops import CellOp+from marimo._messaging.notification_utils import CellNotificationUtilsfrom marimo._messaging.tracebacks import write_tracebackfrom marimo._output import formattingfrom marimo._output.rich_help import mddoc@@ -16,7 +16,7 @@ def write_internal(cell_id: CellId_t, value: object) -> None:output = formatting.try_format(value)if output.traceback is not None:write_traceback(output.traceback)- CellOp.broadcast_output(+ CellNotificationUtils.broadcast_output(channel=CellChannel.OUTPUT,mimetype=output.mimetype,data=output.data,diff --git a/marimo/_runtime/packages/package_manager.py b/marimo/_runtime/packages/package_manager.pyindex c43620693b..f5c7e36e23 100644--- a/marimo/_runtime/packages/package_manager.py+++ b/marimo/_runtime/packages/package_manager.py@@ -10,6 +10,7 @@ import msgspecfrom marimo import _loggersfrom marimo._dependencies.dependencies import DependencyManager+from marimo._messaging.notification_utils import broadcast_opfrom marimo._messaging.ops import Alertfrom marimo._runtime.packages.utils import append_version@@ -220,11 +221,13 @@ class PackageManager(abc.ABC):def alert_not_installed(self) -> None:"""Alert the user that the package manager is not installed."""- Alert(- title="Package manager not installed",- description=(f"{self.name} is not available on your machine."),- variant="danger",- ).broadcast()+ broadcast_op(+ Alert(+ title="Package manager not installed",+ description=(f"{self.name} is not available on your machine."),+ variant="danger",+ ),+ )class CanonicalizingPackageManager(PackageManager):diff --git a/marimo/_runtime/params.py b/marimo/_runtime/params.pyindex 53af28d5c5..4df7353090 100644--- a/marimo/_runtime/params.py+++ b/marimo/_runtime/params.py@@ -10,6 +10,7 @@ from typing import ()from marimo._messaging.mimetypes import KnownMimeType+from marimo._messaging.notification_utils import broadcast_opfrom marimo._messaging.ops import (QueryParamsAppend,QueryParamsClear,@@ -104,12 +105,12 @@ class QueryParams(State[SerializedQueryParams]):return# We always overwrite the valueself._params[key] = value- QueryParamsSet(key, value).broadcast(self._stream)+ broadcast_op(QueryParamsSet(key, value), self._stream)self._set_value(self._params)def __delitem__(self, key: str) -> None:del self._params[key]- QueryParamsDelete(key, None).broadcast(self._stream)+ broadcast_op(QueryParamsDelete(key, None), self._stream)self._set_value(self._params)def set(self, key: str, value: Union[str, list[str]]) -> None:@@ -125,7 +126,7 @@ class QueryParams(State[SerializedQueryParams]):"""if key not in self._params:self._params[key] = value- QueryParamsAppend(key, value).broadcast(self._stream)+ broadcast_op(QueryParamsAppend(key, value), self._stream)self._set_value(self._params)return@@ -135,7 +136,7 @@ class QueryParams(State[SerializedQueryParams]):else:self._params[key] = [current_value, value]- QueryParamsAppend(key, value).broadcast(self._stream)+ broadcast_op(QueryParamsAppend(key, value), self._stream)self._set_value(self._params)def remove(self, key: str, value: Optional[str] = None) -> None:@@ -150,7 +151,7 @@ class QueryParams(State[SerializedQueryParams]):# If value is None, remove the keyif value is None:del self._params[key]- QueryParamsDelete(key, value).broadcast(self._stream)+ broadcast_op(QueryParamsDelete(key, value), self._stream)self._set_value(self._params)return@@ -160,7 +161,7 @@ class QueryParams(State[SerializedQueryParams]):elif current_value == value:del self._params[key]- QueryParamsDelete(key, value).broadcast(self._stream)+ broadcast_op(QueryParamsDelete(key, value), self._stream)self._set_value(self._params)def _mime_(self) -> tuple[KnownMimeType, str]:@@ -171,7 +172,7 @@ class QueryParams(State[SerializedQueryParams]):def clear(self) -> None:"""Clear all query params."""self._params.clear()- QueryParamsClear().broadcast(self._stream)+ broadcast_op(QueryParamsClear(), self._stream)self._set_value(self._params)def to_dict(self) -> dict[str, Union[str, list[str]]]:diff --git a/marimo/_runtime/runner/hooks_on_finish.py b/marimo/_runtime/runner/hooks_on_finish.pyindex 7ef07ac45e..34269ebe1a 100644--- a/marimo/_runtime/runner/hooks_on_finish.py+++ b/marimo/_runtime/runner/hooks_on_finish.py@@ -12,7 +12,7 @@ from marimo._messaging.errors import (MarimoInterruptionError,MarimoStrictExecutionError,)-from marimo._messaging.ops import CellOp+from marimo._messaging.notification_utils import CellNotificationUtilsfrom marimo._runtime.control_flow import MarimoStopErrorfrom marimo._runtime.runner import cell_runnerfrom marimo._tracer import kernel_tracer@@ -29,7 +29,7 @@ def _send_interrupt_errors(runner: cell_runner.Runner) -> None:for cid in runner.cells_to_run:# `cid` was not runrunner.graph.cells[cid].set_runtime_state("idle")- CellOp.broadcast_error(+ CellNotificationUtils.broadcast_error(data=[MarimoInterruptionError()],# these cells are transitioning from queued to stopped# (interrupted); they didn't get to run, so their consoles@@ -79,7 +79,7 @@ def _send_cancellation_errors(runner: cell_runner.Runner) -> None:exception_type="Ancestor raised",raising_cell=raising_cell,)- CellOp.broadcast_error(+ CellNotificationUtils.broadcast_error(data=[data],# these cells are transitioning from queued to stopped# (interrupted); they didn't get to run, so their consolesdiff --git a/marimo/_runtime/runner/hooks_post_execution.py b/marimo/_runtime/runner/hooks_post_execution.pyindex 9dcad99869..2b2e691ff3 100644--- a/marimo/_runtime/runner/hooks_post_execution.py+++ b/marimo/_runtime/runner/hooks_post_execution.py@@ -19,8 +19,11 @@ from marimo._messaging.errors import (MarimoSQLError,MarimoStrictExecutionError,)+from marimo._messaging.notification_utils import (+ CellNotificationUtils,+ broadcast_op,+)from marimo._messaging.ops import (- CellOp,Datasets,DataSourceConnections,VariableValue,@@ -129,7 +132,7 @@ def _broadcast_variables(for variable in cell.defs]if values:- VariableValues(variables=values).broadcast()+ broadcast_op(VariableValues(variables=values))@kernel_tracer.start_as_current_span("broadcast_datasets")@@ -152,7 +155,7 @@ def _broadcast_datasets()if tables:LOGGER.debug("Broadcasting data tables")- Datasets(tables=tables).broadcast()+ broadcast_op(Datasets(tables=tables))@kernel_tracer.start_as_current_span("broadcast_data_source_connection")@@ -178,12 +181,14 @@ def _broadcast_data_source_connection(returnLOGGER.debug("Broadcasting data source connections")- DataSourceConnections(- connections=[- engine_to_data_source_connection(variable, engine)- for variable, engine in engines- ]- ).broadcast()+ broadcast_op(+ DataSourceConnections(+ connections=[+ engine_to_data_source_connection(variable, engine)+ for variable, engine in engines+ ]+ )+ )@kernel_tracer.start_as_current_span("broadcast_duckdb_datasource")@@ -212,13 +217,15 @@ def _broadcast_duckdb_datasource(returnLOGGER.debug("Broadcasting internal duckdb datasource")- DataSourceConnections(- connections=[- engine_to_data_source_connection(- INTERNAL_DUCKDB_ENGINE, DuckDBEngine()- )- ]- ).broadcast()+ broadcast_op(+ DataSourceConnections(+ connections=[+ engine_to_data_source_connection(+ INTERNAL_DUCKDB_ENGINE, DuckDBEngine()+ )+ ]+ )+ )except Exception:return@@ -320,7 +327,7 @@ def _broadcast_outputs(if formatted_output.traceback is not None:write_traceback(formatted_output.traceback)- CellOp.broadcast_output(+ CellNotificationUtils.broadcast_output(channel=CellChannel.OUTPUT,mimetype=formatted_output.mimetype,data=formatted_output.data,@@ -330,7 +337,7 @@ def _broadcast_outputs(elif isinstance(run_result.exception, MarimoStrictExecutionError):LOGGER.debug("Cell %s raised a strict error", cell.cell_id)# Cell never runs, so clear console- CellOp.broadcast_error(+ CellNotificationUtils.broadcast_error(data=[run_result.output],clear_console=True,cell_id=cell.cell_id,@@ -339,20 +346,20 @@ def _broadcast_outputs(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(+ CellNotificationUtils.broadcast_error(data=[MarimoInterruptionError()],clear_console=False,cell_id=cell.cell_id,)elif isinstance(run_result.exception, MarimoExceptionRaisedError):- CellOp.broadcast_error(+ CellNotificationUtils.broadcast_error(data=[run_result.exception],clear_console=False,cell_id=cell.cell_id,)elif isinstance(run_result.exception, MarimoSQLError):LOGGER.debug("Cell %s raised a SQL error", cell.cell_id)- CellOp.broadcast_error(+ CellNotificationUtils.broadcast_error(data=[run_result.exception],clear_console=True,cell_id=cell.cell_id,@@ -369,7 +376,7 @@ def _broadcast_outputs(msg = str(run_result.exception)if not msg:msg = f"This cell raised an exception: {exception_type}"- CellOp.broadcast_error(+ CellNotificationUtils.broadcast_error(data=[MarimoExceptionRaisedError(msg=msg,@@ -393,7 +400,7 @@ def render_toplevel_defs(if variable is not None:extractor = TopLevelExtraction.from_graph(runner.graph, cell=cell)serialization = list(iter(extractor))[-1]- CellOp.broadcast_serialization(+ CellNotificationUtils.broadcast_serialization(serialization=serialization,cell_id=cell.cell_id,)diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 3e17d3d840..27be9d188b 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -53,10 +53,13 @@ from marimo._messaging.errors import (MarimoSyntaxError,UnknownError,)+from marimo._messaging.notification_utils import (+ CellNotificationUtils,+ broadcast_op,+)from marimo._messaging.ops import (CacheCleared,CacheInfoFetched,- CellOp,CompletedRun,DataColumnPreview,DataSourceConnections,@@ -1101,7 +1104,7 @@ class Kernel:get_context().cell_lifecycle_registry.dispose(descendent, deletion=deletion)- RemoveUIElements(cell_id=cell_id).broadcast()+ broadcast_op(RemoveUIElements(cell_id=cell_id))def _deactivate_cell(self, cell_id: CellId_t) -> set[CellId_t]:"""Deactivate: remove from graph, invalidate state, but keep metadata@@ -1265,7 +1268,7 @@ class Kernel:if self.reactive_execution_mode == "autorun":for cid in cells_that_no_longer_have_errors:# clear error outputs before running- CellOp.broadcast_output(+ CellNotificationUtils.broadcast_output(channel=CellChannel.OUTPUT,mimetype="text/plain",data="",@@ -1315,9 +1318,9 @@ class Kernel:cell.set_stale(False)else:# On syntax errors, we don't have a cell object.- CellOp.broadcast_stale(cell_id=cid, stale=False)+ CellNotificationUtils.broadcast_stale(cell_id=cid, stale=False)- CellOp.broadcast_error(+ CellNotificationUtils.broadcast_error(data=self.errors[cid],clear_console=True,cell_id=cid,@@ -1325,20 +1328,22 @@ class Kernel:# Always broadcast Variables message after graph mutation to ensure# frontend has the latest dependency information- Variables(- variables=[- VariableDeclaration(- name=variable,- declared_by=list(declared_by),- used_by=list(- self.graph.get_referring_cells(- variable, language="python"- )- ),- )- for variable, declared_by in self.graph.definitions.items()- ]- ).broadcast()+ broadcast_op(+ Variables(+ variables=[+ VariableDeclaration(+ name=variable,+ declared_by=list(declared_by),+ used_by=list(+ self.graph.get_referring_cells(+ variable, language="python"+ )+ ),+ )+ for variable, declared_by in self.graph.definitions.items()+ ]+ ),+ )stale_cells = (set(@@ -1652,7 +1657,7 @@ class Kernel:filtered_requests: list[ExecutionRequest] = []for request in execution_requests:if request.timestamp < self.last_interrupt_timestamp:- CellOp.broadcast_error(+ CellNotificationUtils.broadcast_error(data=[MarimoInterruptionError()],clear_console=False,cell_id=request.cell_id,@@ -1664,7 +1669,7 @@ class Kernel:# to backend (which will require moving execution requests to# a dedicated multiprocessing queue and processing execution# requests in a background thread).- CellOp.broadcast_status(+ CellNotificationUtils.broadcast_status(cell_id=request.cell_id,status="idle",)@@ -1703,7 +1708,7 @@ class Kernel:# If cannot compile, don't runcell, error = self._try_compiling_cell(SCRATCH_CELL_ID, code, [])if error:- CellOp.broadcast_error(+ CellNotificationUtils.broadcast_error(data=[error],clear_console=True,cell_id=SCRATCH_CELL_ID,@@ -1937,7 +1942,9 @@ class Kernel:continueif variable_values:- VariableValues(variables=variable_values).broadcast()+ broadcast_op(+ VariableValues(variables=variable_values), self.stream+ )if self.reactive_execution_mode == "autorun":await self._run_cells(referring_cells)@@ -2122,7 +2129,9 @@ class Kernel:) in self._uninstantiated_execution_requests.items():# Only mark non-empty cells as staleif cell_request.code.strip():- CellOp.broadcast_stale(cell_id=cell_id, stale=True)+ CellNotificationUtils.broadcast_stale(+ cell_id=cell_id, stale=True+ )def _handle_markdown_cells_on_instantiate(self, execution_requests: dict[CellId_t, ExecutionRequest]@@ -2180,7 +2189,7 @@ class Kernel:mimetype, html_content = html_obj._mime_()# Broadcast the markdown output- CellOp.broadcast_output(+ CellNotificationUtils.broadcast_output(channel=CellChannel.OUTPUT,mimetype=mimetype,data=html_content,@@ -2189,7 +2198,7 @@ class Kernel:)# Mark the cell as not stale (already "run")- CellOp.broadcast_stale(cell_id=cell_id, stale=False)+ CellNotificationUtils.broadcast_stale(cell_id=cell_id, stale=False)del execution_requests[cell_id]def load_dotenv(self) -> None:@@ -2214,14 +2223,14 @@ class Kernel:async def handle_instantiate(request: CreationRequest) -> None:with http_request_context(request.request):await self.instantiate(request)- CompletedRun().broadcast()+ broadcast_op(CompletedRun())async def handle_execute_multiple(request: ExecuteMultipleRequest,) -> None:with http_request_context(request.request):await self.run(request.execution_requests)- CompletedRun().broadcast()+ broadcast_op(CompletedRun())async def handle_sync_graph(request: SyncGraphRequest,@@ -2230,26 +2239,26 @@ class Kernel:await self.sync_graph(request.cells, request.run_ids, request.delete_ids)- CompletedRun().broadcast()+ broadcast_op(CompletedRun())async def handle_execute_scratchpad(request: ExecuteScratchpadRequest,) -> None:with http_request_context(request.request):await self.run_scratchpad(request.code)- CompletedRun().broadcast()+ broadcast_op(CompletedRun())async def handle_execute_stale(request: ExecuteStaleRequest) -> None:with http_request_context(request.request):await self.run_stale_cells()- CompletedRun().broadcast()+ broadcast_op(CompletedRun())async def handle_set_ui_element_value(request: SetUIElementValueRequest,) -> None:with http_request_context(request.request):await self.set_ui_element_value(request)- CompletedRun().broadcast()+ broadcast_op(CompletedRun())async def handle_pdb_request(request: PdbRequest) -> None:await self.pdb_request(request.cell_id)@@ -2269,11 +2278,13 @@ class Kernel:async def handle_function_call(request: FunctionCallRequest) -> None:status, ret, _ = await self.function_call_request(request)LOGGER.debug("Function returned with status %s", status)- FunctionCallResult(- function_call_id=request.function_call_id,- return_value=ret,- status=status,- ).broadcast()+ broadcast_op(+ FunctionCallResult(+ function_call_id=request.function_call_id,+ return_value=ret,+ status=status,+ ),+ )async def handle_set_user_config(request: SetUserConfigRequest,@@ -2284,7 +2295,7 @@ class Kernel:request: InstallMissingPackagesRequest,) -> None:await self.packages_callbacks.install_missing_packages(request)- CompletedRun().broadcast()+ broadcast_op(CompletedRun())async def handle_stop(request: StopRequest) -> None:del request@@ -2435,30 +2446,36 @@ class DatasetCallbacks:dataset, request)elif source_type == "connection":- DataColumnPreview(- error="Column preview for connection data sources is not supported",- column_name=column_name,- table_name=table_name,- ).broadcast()+ broadcast_op(+ DataColumnPreview(+ error="Column preview for connection data sources is not supported",+ column_name=column_name,+ table_name=table_name,+ ),+ )returnelif source_type == "catalog":- DataColumnPreview(- error="Column preview for catalog data sources is not supported",- column_name=column_name,- table_name=table_name,- ).broadcast()+ broadcast_op(+ DataColumnPreview(+ error="Column preview for catalog data sources is not supported",+ column_name=column_name,+ table_name=table_name,+ ),+ )returnelse:assert_never(source_type)if column_preview is None:- DataColumnPreview(- error=f"Column {column_name} not found",- column_name=column_name,- table_name=table_name,- ).broadcast()+ broadcast_op(+ DataColumnPreview(+ error=f"Column {column_name} not found",+ column_name=column_name,+ table_name=table_name,+ ),+ )else:- column_preview.broadcast()+ broadcast_op(column_preview)except Exception as e:LOGGER.warning("Failed to get preview for column %s in table %s",@@ -2466,11 +2483,13 @@ class DatasetCallbacks:table_name,exc_info=e,)- DataColumnPreview(- error=str(e),- column_name=column_name,- table_name=table_name,- ).broadcast()+ broadcast_op(+ DataColumnPreview(+ error=str(e),+ column_name=column_name,+ table_name=table_name,+ ),+ )return@kernel_tracer.start_as_current_span("preview_sql_table")@@ -2496,12 +2515,14 @@ class DatasetCallbacks:engine, error = self.get_engine_catalog(variable_name)if error is not None or engine is None:- SQLTablePreview(- request_id=request.request_id,- table=None,- error=error,- metadata=sql_metadata,- ).broadcast()+ broadcast_op(+ SQLTablePreview(+ request_id=request.request_id,+ table=None,+ error=error,+ metadata=sql_metadata,+ ),+ )returntry:@@ -2511,23 +2532,27 @@ class DatasetCallbacks:database_name=database_name,)- SQLTablePreview(- request_id=request.request_id,- table=table,- metadata=sql_metadata,- ).broadcast()+ broadcast_op(+ SQLTablePreview(+ request_id=request.request_id,+ table=table,+ metadata=sql_metadata,+ ),+ )except Exception as e:LOGGER.exception("Failed to get preview for table %s in schema %s",table_name,schema_name,)- SQLTablePreview(- request_id=request.request_id,- table=None,- error="Failed to get table details: " + str(e),- metadata=sql_metadata,- ).broadcast()+ broadcast_op(+ SQLTablePreview(+ request_id=request.request_id,+ table=None,+ error="Failed to get table details: " + str(e),+ metadata=sql_metadata,+ ),+ )@kernel_tracer.start_as_current_span("preview_sql_table_list")async def preview_sql_table_list(@@ -2552,12 +2577,14 @@ class DatasetCallbacks:engine, error = self.get_engine_catalog(variable_name)if error is not None or engine is None:- SQLTableListPreview(- request_id=request.request_id,- tables=[],- error=error,- metadata=sql_metadata,- ).broadcast()+ broadcast_op(+ SQLTableListPreview(+ request_id=request.request_id,+ tables=[],+ error=error,+ metadata=sql_metadata,+ ),+ )returntry:@@ -2566,21 +2593,25 @@ class DatasetCallbacks:database=database_name,include_table_details=False,)- SQLTableListPreview(- request_id=request.request_id,- tables=table_list,- metadata=sql_metadata,- ).broadcast()+ broadcast_op(+ SQLTableListPreview(+ request_id=request.request_id,+ tables=table_list,+ metadata=sql_metadata,+ ),+ )except Exception as e:LOGGER.exception("Failed to get table list for schema %s", schema_name)- SQLTableListPreview(- request_id=request.request_id,- tables=[],- error="Failed to get table list: " + str(e),- metadata=sql_metadata,- ).broadcast()+ broadcast_op(+ SQLTableListPreview(+ request_id=request.request_id,+ tables=[],+ error="Failed to get table list: " + str(e),+ metadata=sql_metadata,+ ),+ )@kernel_tracer.start_as_current_span("preview_datasource_connection")async def preview_datasource_connection(@@ -2600,9 +2631,11 @@ class DatasetCallbacks:LOGGER.debug("Broadcasting datasource connection for %s engine", variable_name)- DataSourceConnections(- connections=[data_source_connection],- ).broadcast()+ broadcast_op(+ DataSourceConnections(+ connections=[data_source_connection],+ ),+ )class SqlCallbacks:@@ -2620,19 +2653,23 @@ class SqlCallbacks:if request.only_parse:if request.dialect is None:- ValidateSQLResult(- request_id=request_id,- error="Dialect is required when only parsing",- ).broadcast()+ broadcast_op(+ ValidateSQLResult(+ request_id=request_id,+ error="Dialect is required when only parsing",+ ),+ )return# Just parse the query (no DB connection required)parse_result, error = parse_sql(request.query, request.dialect)- ValidateSQLResult(- request_id=request_id,- parse_result=parse_result,- error=error,- ).broadcast()+ broadcast_op(+ ValidateSQLResult(+ request_id=request_id,+ parse_result=parse_result,+ error=error,+ ),+ )return# Validate against the database@@ -2641,10 +2678,12 @@ class SqlCallbacks:# For failed connections, we should not raise an errorif request.engine is None:- ValidateSQLResult(- request_id=request_id,- error="Engine is required for validating catalog",- ).broadcast()+ broadcast_op(+ ValidateSQLResult(+ request_id=request_id,+ error="Engine is required for validating catalog",+ ),+ )returnvariable_name = cast(VariableName, request.engine)@@ -2656,10 +2695,12 @@ class SqlCallbacks:engine, error = self._kernel.get_sql_connection(variable_name)if error is not None or engine is None:- ValidateSQLResult(- request_id=request_id,- error="Failed to get engine " + variable_name,- ).broadcast()+ broadcast_op(+ ValidateSQLResult(+ request_id=request_id,+ error="Failed to get engine " + variable_name,+ ),+ )return# Get the parse error for linting@@ -2669,11 +2710,13 @@ class SqlCallbacks:LOGGER.debug("Parse error: %s", parse_error)if not isinstance(engine, QueryEngine):- ValidateSQLResult(- request_id=request_id,- error=f"Engine {variable_name} does not support catalog validation.",- parse_result=parse_result,- ).broadcast()+ broadcast_op(+ ValidateSQLResult(+ request_id=request_id,+ error=f"Engine {variable_name} does not support catalog validation.",+ parse_result=parse_result,+ ),+ )return_, error_message = engine.execute_in_explain_mode(request.query) # type: ignore@@ -2681,12 +2724,14 @@ class SqlCallbacks:success=True if error_message is None else False,error_message=error_message,)- ValidateSQLResult(- request_id=request_id,- validate_result=validate_result,- parse_result=parse_result,- error=None,- ).broadcast()+ broadcast_op(+ ValidateSQLResult(+ request_id=request_id,+ validate_result=validate_result,+ parse_result=parse_result,+ error=None,+ ),+ )@kernel_tracer.start_as_current_span("validate_sql")async def validate_sql(self, request: ValidateSQLRequest) -> None:@@ -2696,10 +2741,12 @@ class SqlCallbacks:await self._validate_sql_query(request)except Exception as e:LOGGER.exception("Failed to validate SQL query")- ValidateSQLResult(- request_id=request.request_id,- error="Failed to validate SQL query: " + str(e),- ).broadcast()+ broadcast_op(+ ValidateSQLResult(+ request_id=request.request_id,+ error="Failed to validate SQL query: " + str(e),+ ),+ )class SecretsCallbacks:@@ -2710,9 +2757,9 @@ class SecretsCallbacks:secrets = get_secret_keys(self._kernel.user_config, self._kernel._original_environ)- SecretKeysResult(- request_id=request.request_id, secrets=secrets- ).broadcast()+ broadcast_op(+ SecretKeysResult(request_id=request.request_id, secrets=secrets),+ )async def refresh_secrets(self, request: RefreshSecretsRequest) -> None:del request@@ -2751,10 +2798,12 @@ class PackagesCallbacks:))# Deleting a cell can make the set of missing packages smaller- MissingPackageAlert(- packages=packages,- isolated=is_python_isolated(),- ).broadcast()+ broadcast_op(+ MissingPackageAlert(+ packages=packages,+ isolated=is_python_isolated(),+ ),+ )def missing_packages_hook(self, runner: cell_runner.Runner) -> None:module_not_found_errors = [@@ -2828,10 +2877,12 @@ class PackagesCallbacks:))else:- MissingPackageAlert(- packages=packages,- isolated=is_python_isolated(),- ).broadcast()+ broadcast_op(+ MissingPackageAlert(+ packages=packages,+ isolated=is_python_isolated(),+ ),+ )async def install_missing_packages(self, request: InstallMissingPackagesRequest@@ -2876,15 +2927,17 @@ class PackagesCallbacks:package_statuses: PackageStatusType = {pkg: "queued" for pkg in missing_packages}- InstallingPackageAlert(packages=package_statuses).broadcast()+ broadcast_op(InstallingPackageAlert(packages=package_statuses))def create_log_callback(pkg: str) -> LogCallback:def log_callback(log_line: str) -> None:- InstallingPackageAlert(- packages=package_statuses,- logs={pkg: log_line},- log_status="append",- ).broadcast()+ broadcast_op(+ InstallingPackageAlert(+ packages=package_statuses,+ logs={pkg: log_line},+ log_status="append",+ ),+ )return log_callback@@ -2894,14 +2947,16 @@ class PackagesCallbacks:# Skip the installation.continuepackage_statuses[pkg] = "installing"- InstallingPackageAlert(packages=package_statuses).broadcast()+ broadcast_op(InstallingPackageAlert(packages=package_statuses))# Send initial "start" log- InstallingPackageAlert(- packages=package_statuses,- logs={pkg: f"Installing {pkg}...\n"},- log_status="start",- ).broadcast()+ broadcast_op(+ InstallingPackageAlert(+ packages=package_statuses,+ logs={pkg: f"Installing {pkg}...\n"},+ log_status="start",+ )+ )version = request.versions.get(pkg)if await self.package_manager.install(@@ -2909,21 +2964,25 @@ class PackagesCallbacks:):package_statuses[pkg] = "installed"# Send final "done" log- InstallingPackageAlert(- packages=package_statuses,- logs={pkg: f"Successfully installed {pkg}\n"},- log_status="done",- ).broadcast()+ broadcast_op(+ InstallingPackageAlert(+ packages=package_statuses,+ logs={pkg: f"Successfully installed {pkg}\n"},+ log_status="done",+ ),+ )else:package_statuses[pkg] = "failed"mod = self.package_manager.package_to_module(pkg)self._kernel.module_registry.excluded_modules.add(mod)# Send final "done" log with error- InstallingPackageAlert(- packages=package_statuses,- logs={pkg: f"Failed to install {pkg}\n"},- log_status="done",- ).broadcast()+ broadcast_op(+ InstallingPackageAlert(+ packages=package_statuses,+ logs={pkg: f"Failed to install {pkg}\n"},+ log_status="done",+ ),+ )installed_modules = [self.package_manager.package_to_module(pkg)@@ -3008,7 +3067,7 @@ class CacheCallbacks:if isinstance(obj.loader, BasePersistenceLoader):obj.loader.clear()- CacheCleared(bytes_freed=saved).broadcast()+ broadcast_op(CacheCleared(bytes_freed=saved))async def get_cache_info(self, request: GetCacheInfoRequest) -> None:del request@@ -3028,13 +3087,15 @@ class CacheCallbacks:total_misses += missestotal_time += time# d2f, dt = obj.loader.disk_usage()- CacheInfoFetched(- hits=total_hits,- misses=total_misses,- time=total_time,- disk_to_free=disk_to_free,- disk_total=disk_total,- ).broadcast()+ broadcast_op(+ CacheInfoFetched(+ hits=total_hits,+ misses=total_misses,+ time=total_time,+ disk_to_free=disk_to_free,+ disk_total=disk_total,+ ),+ )class RequestHandler:diff --git a/marimo/_server/api/endpoints/ws.py b/marimo/_server/api/endpoints/ws.pyindex ebf094349d..42c1c9938d 100644--- a/marimo/_server/api/endpoints/ws.py+++ b/marimo/_server/api/endpoints/ws.py@@ -22,6 +22,8 @@ from marimo._messaging.ops import (KernelReady,MessageOperation,Reconnected,+)+from marimo._messaging.serde import (deserialize_kernel_operation_name,serialize_kernel_message,)diff --git a/marimo/_server/export/__init__.py b/marimo/_server/export/__init__.pyindex fc2b61c212..e41789b18f 100644--- a/marimo/_server/export/__init__.py+++ b/marimo/_server/export/__init__.py@@ -18,8 +18,8 @@ from marimo._messaging.errors import Error, is_unexpected_errorfrom marimo._messaging.ops import (CellOp,CompletedRun,- deserialize_kernel_message,)+from marimo._messaging.serde import deserialize_kernel_messagefrom marimo._messaging.types import KernelMessagefrom marimo._output.hypertext import patch_html_for_non_interactive_outputfrom marimo._runtime.requests import AppMetadata, SerializedCLIArgsdiff --git a/marimo/_server/session/session_view.py b/marimo/_server/session/session_view.pyindex fd8e86b4ef..5390503544 100644--- a/marimo/_server/session/session_view.py+++ b/marimo/_server/session/session_view.py@@ -23,8 +23,8 @@ from marimo._messaging.ops import (Variables,VariableValue,VariableValues,- deserialize_kernel_message,)+from marimo._messaging.serde import deserialize_kernel_messagefrom marimo._messaging.types import KernelMessagefrom marimo._runtime.requests import (ControlRequest,diff --git a/marimo/_server/sessions/session.py b/marimo/_server/sessions/session.pyindex c216571984..20887465a7 100644--- a/marimo/_server/sessions/session.py+++ b/marimo/_server/sessions/session.py@@ -16,8 +16,8 @@ from marimo._messaging.ops import (FocusCell,MessageOperation,UpdateCellCodes,- serialize_kernel_message,)+from marimo._messaging.serde import serialize_kernel_messagefrom marimo._messaging.types import KernelMessagefrom marimo._runtime import requestsfrom marimo._runtime.requests import (diff --git a/marimo/_server/sessions/utils.py b/marimo/_server/sessions/utils.pyindex da9d1addd7..60718b513a 100644--- a/marimo/_server/sessions/utils.py+++ b/marimo/_server/sessions/utils.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Optional-from marimo._messaging.ops import serialize_kernel_message+from marimo._messaging.serde import serialize_kernel_messagefrom marimo._server.model import ConnectionStatefrom marimo._types.ids import ConsumerIddiff --git a/tests/_messaging/mocks.py b/tests/_messaging/mocks.pyindex 1a76784f98..db4d676631 100644--- a/tests/_messaging/mocks.py+++ b/tests/_messaging/mocks.py@@ -6,8 +6,8 @@ from marimo._messaging.mimetypes import ConsoleMimeTypefrom marimo._messaging.ops import (CellOp,MessageOperation,- deserialize_kernel_message,)+from marimo._messaging.serde import deserialize_kernel_messagefrom marimo._messaging.types import KernelMessage, Stderr, Streamdiff --git a/tests/_messaging/test_ops.py b/tests/_messaging/test_ops.pyindex 096fb2f445..9e1dd31c30 100644--- a/tests/_messaging/test_ops.py+++ b/tests/_messaging/test_ops.py@@ -4,6 +4,10 @@ from __future__ import annotationsfrom unittest.mock import MagicMockfrom marimo._ast.toplevel import HINT_UNPARSABLE, TopLevelStatus+from marimo._messaging.notification_utils import (+ CellNotificationUtils,+ broadcast_op,+)from marimo._messaging.ops import (CellOp,InstallingPackageAlert,@@ -51,7 +55,7 @@ def test_broadcast_serialization() -> None:status = MagicMock(TopLevelStatus)status.hint = HINT_UNPARSABLE- CellOp.broadcast_serialization(+ CellNotificationUtils.broadcast_serialization(cell_id=cell_id, serialization=status, stream=stream)@@ -113,7 +117,7 @@ def test_send_ui_element_message_broadcast() -> None:buffers=[b"buffer1", b"buffer2"],)- msg.broadcast(stream=stream)+ broadcast_op(msg, stream)assert len(stream.messages) == 1diff --git a/tests/_messaging/test_serde.py b/tests/_messaging/test_serde.pyindex 807031c661..1863527767 100644--- a/tests/_messaging/test_serde.py+++ b/tests/_messaging/test_serde.py@@ -10,6 +10,8 @@ from marimo._messaging.ops import (Alert,CompletedRun,Interrupted,+)+from marimo._messaging.serde import (deserialize_kernel_message,deserialize_kernel_operation_name,serialize_kernel_message,diff --git a/tests/_runtime/test_complete.py b/tests/_runtime/test_complete.pyindex 087c38c7ba..5e1027320d 100644--- a/tests/_runtime/test_complete.py+++ b/tests/_runtime/test_complete.py@@ -13,7 +13,8 @@ import pytestimport marimofrom marimo._dependencies.dependencies import DependencyManager-from marimo._messaging.ops import CompletionResult, deserialize_kernel_message+from marimo._messaging.ops import CompletionResult+from marimo._messaging.serde import deserialize_kernel_messagefrom marimo._messaging.types import KernelMessage, Streamfrom marimo._runtime.complete import (_build_docstring_cached,diff --git a/tests/_runtime/test_manage_script_metadata.py b/tests/_runtime/test_manage_script_metadata.pyindex e03a8846e3..8d1ca32edd 100644--- a/tests/_runtime/test_manage_script_metadata.py+++ b/tests/_runtime/test_manage_script_metadata.py@@ -302,7 +302,9 @@ async def test_missing_packages_hook(def mock_broadcast(msg: InstallingPackageAlert | MissingPackageAlert,+ stream: Any = None,) -> None:+ del streambroadcast_messages.append(msg)k.enqueue_control_request = mock_enqueue@@ -329,8 +331,7 @@ async def test_missing_packages_hook(}with (- patch.object(InstallingPackageAlert, "broadcast", mock_broadcast),- patch.object(MissingPackageAlert, "broadcast", mock_broadcast),+ patch("marimo._runtime.runtime.broadcast_op", mock_broadcast),patch("micropip.install", new_callable=AsyncMock),):# Case 1: Auto-install enabled@@ -434,7 +435,9 @@ def test_missing_packages_hook_pip(def mock_broadcast(msg: InstallingPackageAlert | MissingPackageAlert,+ stream: Any = None,) -> None:+ del streambroadcast_messages.append(msg)k.enqueue_control_request = mock_enqueue@@ -457,8 +460,7 @@ def test_missing_packages_hook_pip(}with (- patch.object(InstallingPackageAlert, "broadcast", mock_broadcast),- patch.object(MissingPackageAlert, "broadcast", mock_broadcast),+ patch("marimo._runtime.runtime.broadcast_op", mock_broadcast),):k.packages_callbacks.package_manager = create_package_manager("pip")package_manager = k.packages_callbacks.package_manager@@ -511,9 +513,11 @@ async def test_install_missing_packages_with_streaming_logs(k = mocked_kernel.kbroadcast_messages: list[InstallingPackageAlert] = []- def mock_broadcast(self):- """Mock the broadcast method to capture alerts"""- broadcast_messages.append(self)+ def mock_broadcast(msg, stream=None):+ """Mock the broadcast_op function to capture alerts"""+ del stream+ if isinstance(msg, InstallingPackageAlert):+ broadcast_messages.append(msg)# Mock package managermock_package_manager = Mock(spec=PipPackageManager)@@ -538,7 +542,7 @@ async def test_install_missing_packages_with_streaming_logs(k.packages_callbacks.package_manager = mock_package_managerwith (- patch.object(InstallingPackageAlert, "broadcast", mock_broadcast),+ patch("marimo._runtime.runtime.broadcast_op", mock_broadcast),):# Create install requestrequest = InstallMissingPackagesRequest(@@ -587,8 +591,10 @@ async def test_install_missing_packages_streaming_logs_failure(k = mocked_kernel.kbroadcast_messages: list[InstallingPackageAlert] = []- def mock_broadcast(self):- broadcast_messages.append(self)+ def mock_broadcast(msg, stream=None):+ del stream+ if isinstance(msg, InstallingPackageAlert):+ broadcast_messages.append(msg)# Mock package managermock_package_manager = Mock(spec=PipPackageManager)@@ -609,7 +615,7 @@ async def test_install_missing_packages_streaming_logs_failure(k.packages_callbacks.package_manager = mock_package_managerwith (- patch.object(InstallingPackageAlert, "broadcast", mock_broadcast),+ patch("marimo._runtime.runtime.broadcast_op", mock_broadcast),):request = InstallMissingPackagesRequest(manager="pip", versions={"nonexistent-package": ""}@@ -641,8 +647,10 @@ async def test_install_missing_packages_streaming_logs_multiple_packages(k = mocked_kernel.kbroadcast_messages: list[InstallingPackageAlert] = []- def mock_broadcast(self):- broadcast_messages.append(self)+ def mock_broadcast(msg, stream=None):+ del stream+ if isinstance(msg, InstallingPackageAlert):+ broadcast_messages.append(msg)# Mock package managermock_package_manager = Mock(spec=PipPackageManager)@@ -668,7 +676,7 @@ async def test_install_missing_packages_streaming_logs_multiple_packages(k.packages_callbacks.package_manager = mock_package_managerwith (- patch.object(InstallingPackageAlert, "broadcast", mock_broadcast),+ patch("marimo._runtime.runtime.broadcast_op", mock_broadcast),):request = InstallMissingPackagesRequest(manager="pip", versions={"numpy": "", "pandas": "", "scipy": ""}@@ -716,8 +724,10 @@ async def test_install_missing_packages_no_logs_backward_compatibility(k = mocked_kernel.kbroadcast_messages: list[InstallingPackageAlert] = []- def mock_broadcast(self):- broadcast_messages.append(self)+ def mock_broadcast(msg, stream=None):+ del stream+ if isinstance(msg, InstallingPackageAlert):+ broadcast_messages.append(msg)# Mock package manager that doesn't use log callbacksmock_package_manager = Mock(spec=PipPackageManager)@@ -738,7 +748,7 @@ async def test_install_missing_packages_no_logs_backward_compatibility(k.packages_callbacks.package_manager = mock_package_managerwith (- patch.object(InstallingPackageAlert, "broadcast", mock_broadcast),+ patch("marimo._runtime.runtime.broadcast_op", mock_broadcast),):request = InstallMissingPackagesRequest(manager="pip", versions={"requests": ""}diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex 7fbb81c51a..672c9e3496 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -26,8 +26,8 @@ from marimo._messaging.errors import (from marimo._messaging.ops import (CellOp,Variables,- deserialize_kernel_message,)+from marimo._messaging.serde import deserialize_kernel_messagefrom marimo._messaging.types import NoopStreamfrom marimo._plugins.ui._core.ids import IDProviderfrom marimo._plugins.ui._core.ui_element import UIElementdiff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex 07725d2b39..4ae0863383 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -26,8 +26,8 @@ from marimo._config.manager import (from marimo._messaging.ops import (MessageOperation,UpdateCellCodes,- deserialize_kernel_message,)+from marimo._messaging.serde import deserialize_kernel_messagefrom marimo._messaging.types import KernelMessagefrom marimo._runtime.requests import (AppMetadata,diff --git a/tests/conftest.py b/tests/conftest.pyindex d4b6c34e98..b811a1bf51 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -21,9 +21,9 @@ from marimo._messaging.mimetypes import ConsoleMimeTypefrom marimo._messaging.ops import (CellOp,MessageOperation,- deserialize_kernel_message,)from marimo._messaging.print_override import print_override+from marimo._messaging.serde import deserialize_kernel_messagefrom marimo._messaging.streams import (ThreadSafeStderr,ThreadSafeStdin,