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.

fix: rpc serialization and gracefully handle errors (#1595)

Myles Scolnickf556e02ea73e
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
index 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 json
import sys
import time
from dataclasses import asdict, dataclass, field
@@ -34,6 +35,7 @@ from marimo._messaging.mimetypes import KnownMimeType
from marimo._messaging.streams import OUTPUT_MAX_BYTES
from marimo._messaging.types import Stream
from marimo._output.hypertext import Html
+from marimo._plugins.core.json_encoder import WebComponentEncoder
from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._core.ui_element import UIElement
from marimo._runtime.context import get_context
@@ -42,8 +44,19 @@ from marimo._runtime.layout.layout import LayoutConfig
LOGGER = 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: JSONType
status: 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",
+ ),
+ )
+ )
+
@dataclass
class RemoveUIElements(Op):
diff --git a/marimo/_plugins/core/json_encoder.py b/marimo/_plugins/core/json_encoder.py
index 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 dataclasses
import datetime
import json
from json import JSONEncoder
@@ -12,7 +13,11 @@ from marimo._dependencies.dependencies import DependencyManager
class 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 objects
if DependencyManager.has_numpy():
import numpy as np