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
fix: rpc serialization and gracefully handle errors (#1595)
Myles Scolnickf556e02ea73e
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.pyindex d657a06aff..f7f6448375 100644--- a/marimo/_messaging/ops.py+++ b/marimo/_messaging/ops.py@@ -6,6 +6,7 @@ Messages that the kernel sends to the frontend.from __future__ import annotations+import jsonimport sysimport timefrom dataclasses import asdict, dataclass, field@@ -34,6 +35,7 @@ from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._messaging.streams import OUTPUT_MAX_BYTESfrom marimo._messaging.types import Streamfrom marimo._output.hypertext import Html+from marimo._plugins.core.json_encoder import WebComponentEncoderfrom marimo._plugins.core.web_component import JSONTypefrom marimo._plugins.ui._core.ui_element import UIElementfrom marimo._runtime.context import get_context@@ -42,8 +44,19 @@ from marimo._runtime.layout.layout import LayoutConfigLOGGER = loggers.marimo_logger()-def serialize(datacls: Any) -> dict[str, JSONType]:- return cast(Dict[str, JSONType], asdict(datacls))+def serialize(datacls: Any) -> Dict[str, JSONType]:+ try:+ # Try to serialize as a dataclass+ return cast(+ Dict[str, JSONType],+ asdict(datacls),+ )+ except Exception:+ # If that fails, try to serialize using the WebComponentEncoder+ return cast(+ Dict[str, JSONType],+ json.loads(json.dumps(datacls, cls=WebComponentEncoder)),+ )@dataclass@@ -63,8 +76,18 @@ class Op:else:stream = ctx.stream- LOGGER.debug("Broadcasting op: %s", self)- stream.write(op=self.name, data=serialize(self))+ try:+ stream.write(op=self.name, data=self.serialize())+ except Exception as e:+ LOGGER.exception(+ "Error serializing op %s: %s",+ self.__class__.__name__,+ e,+ )+ return++ def serialize(self) -> dict[str, Any]:+ return serialize(self)@dataclass@@ -255,6 +278,27 @@ class FunctionCallResult(Op):return_value: JSONTypestatus: HumanReadableStatus+ def serialize(self) -> dict[str, Any]:+ try:+ return serialize(self)+ except Exception as e:+ LOGGER.exception(+ "Error serializing function call result %s: %s",+ self.__class__.__name__,+ e,+ )+ return serialize(+ FunctionCallResult(+ function_call_id=self.function_call_id,+ return_value=None,+ status=HumanReadableStatus(+ code="error",+ title="Error calling function",+ message="Failed to serialize function call result",+ ),+ )+ )+@dataclassclass RemoveUIElements(Op):diff --git a/marimo/_plugins/core/json_encoder.py b/marimo/_plugins/core/json_encoder.pyindex 0bb521dfb6..36a4bc8999 100644--- a/marimo/_plugins/core/json_encoder.py+++ b/marimo/_plugins/core/json_encoder.py@@ -1,6 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import dataclassesimport datetimeimport jsonfrom json import JSONEncoder@@ -12,7 +13,11 @@ from marimo._dependencies.dependencies import DependencyManagerclass WebComponentEncoder(JSONEncoder):"""Custom JSON encoder for WebComponents"""- def default(self, obj: Any) -> Any:+ def default(self, o: Any) -> Any:+ obj = o+ if dataclasses.is_dataclass(obj):+ return dataclasses.asdict(obj)+# Handle numpy objectsif DependencyManager.has_numpy():import numpy as np