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: handling of buffer paths in Anywidget (#2368)

Myles Scolnickc3712daba6ab
diff --git a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
index 865e74f7cc..22aa476ba7 100644
--- a/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
+++ b/frontend/src/plugins/impl/anywidget/AnyWidgetPlugin.tsx
@@ -3,7 +3,7 @@
import { z } from "zod";
import type { IPluginProps } from "@/plugins/types";
-import { useEffect, useRef } from "react";
+import { useEffect, useMemo, useRef } from "react";
import { useAsyncData } from "@/hooks/useAsyncData";
import { dequal } from "dequal";
import { useOnMount } from "@/hooks/useLifecycle";
@@ -15,10 +15,12 @@ import type { AnyModel, AnyWidget, EventHandler, Experimental } from "./types";
import { Logger } from "@/utils/Logger";
import { useEventListener } from "@/hooks/useEventListener";
import { MarimoIncomingMessageEvent } from "@/core/dom/events";
+import { updateBufferPaths } from "@/utils/date-views";
interface Data {
jsUrl: string;
css?: string | null;
+ bufferPaths?: Array<Array<string | number>> | null;
}
type T = Record<string, any>;
@@ -33,6 +35,9 @@ export const AnyWidgetPlugin = createPlugin<T>("marimo-anywidget")
z.object({
jsUrl: z.string(),
css: z.string().nullish(),
+ bufferPaths: z
+ .array(z.array(z.union([z.string(), z.number()])))
+ .nullish(),
}),
)
.withFunctions<PluginFunctions>({
@@ -45,7 +50,7 @@ export const AnyWidgetPlugin = createPlugin<T>("marimo-anywidget")
type Props = IPluginProps<T, Data, PluginFunctions>;
const AnyWidgetSlot = (props: Props) => {
- const { css, jsUrl } = props.data;
+ const { css, jsUrl, bufferPaths } = props.data;
// JS is an ESM file with a render function on it
// export function render({ model, el }) {
// ...
@@ -59,6 +64,10 @@ const AnyWidgetSlot = (props: Props) => {
return await import(/* @vite-ignore */ url);
}, []);
+ const valueWithBuffer = useMemo(() => {
+ return updateBufferPaths(props.value, bufferPaths);
+ }, [props.value, bufferPaths]);
+
// Mount the CSS
useEffect(() => {
if (!css || !props.host.shadowRoot) {
@@ -87,7 +96,9 @@ const AnyWidgetSlot = (props: Props) => {
return <ErrorBanner error={error} />;
}
- return <LoadedSlot {...props} widget={module.default} />;
+ return (
+ <LoadedSlot {...props} widget={module.default} value={valueWithBuffer} />
+ );
};
/**
diff --git a/frontend/src/utils/__tests__/date-views.test.ts b/frontend/src/utils/__tests__/date-views.test.ts
new file mode 100644
index 0000000000..dba1186f00
--- /dev/null
+++ b/frontend/src/utils/__tests__/date-views.test.ts
@@ -0,0 +1,61 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import { updateBufferPaths, base64ToDataView } from "../date-views";
+
+describe("updateBufferPaths", () => {
+ it("should return the original object if bufferPaths is null", () => {
+ const input = { a: 1, b: 2 };
+ const result = updateBufferPaths(input, null);
+ expect(result).toEqual(input);
+ });
+
+ it("should update buffer paths correctly", () => {
+ const input = {
+ a: 1,
+ b: {
+ c: "Hello",
+ d: "World",
+ },
+ };
+ const bufferPaths = [
+ ["b", "c"],
+ ["b", "d"],
+ ];
+ const result = updateBufferPaths(input, bufferPaths);
+
+ expect(result.a).toBe(1);
+ expect(result.b.c).toBeInstanceOf(DataView);
+ expect(result.b.d).toBeInstanceOf(DataView);
+ });
+
+ it("should handle non-existent paths", () => {
+ const input = { a: 1 };
+ const bufferPaths = [["b", "c"]];
+ const result = updateBufferPaths(input, bufferPaths);
+
+ expect(result).toEqual(input);
+ });
+});
+
+describe("base64ToDataView", () => {
+ it("should convert a base64 string to a DataView", () => {
+ const input = "Hello";
+ const result = base64ToDataView(input);
+
+ expect(result).toBeInstanceOf(DataView);
+ expect(result.byteLength).toBe(5);
+ expect(result.getUint8(0)).toBe(72); // 'H'
+ expect(result.getUint8(1)).toBe(101); // 'e'
+ expect(result.getUint8(2)).toBe(108); // 'l'
+ expect(result.getUint8(3)).toBe(108); // 'l'
+ expect(result.getUint8(4)).toBe(111); // 'o'
+ });
+
+ it("should handle empty string", () => {
+ const input = "";
+ const result = base64ToDataView(input);
+
+ expect(result).toBeInstanceOf(DataView);
+ expect(result.byteLength).toBe(0);
+ });
+});
diff --git a/frontend/src/utils/date-views.ts b/frontend/src/utils/date-views.ts
new file mode 100644
index 0000000000..af04eaa380
--- /dev/null
+++ b/frontend/src/utils/date-views.ts
@@ -0,0 +1,39 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { get, set } from "lodash-es";
+import { Logger } from "./Logger";
+
+/**
+ * Update the object with DataView buffers at the specified paths.
+ */
+export function updateBufferPaths<T extends object>(
+ inputObject: T,
+ bufferPaths: Array<Array<string | number>> | null | undefined,
+): T {
+ // If no buffer paths, return the original object
+ if (!bufferPaths || bufferPaths.length === 0) {
+ return inputObject;
+ }
+
+ let object = structuredClone(inputObject);
+
+ for (const bufferPath of bufferPaths) {
+ const bytes = get(object, bufferPath);
+ if (!bytes) {
+ Logger.warn("Could not find buffer at path", bufferPath);
+ continue;
+ }
+ const buffer = base64ToDataView(bytes);
+ object = set(object, bufferPath, buffer);
+ }
+
+ return object;
+}
+
+export const base64ToDataView = (bytes: string) => {
+ const buffer = new ArrayBuffer(bytes.length);
+ const view = new DataView(buffer);
+ for (let i = 0; i < bytes.length; i++) {
+ view.setUint8(i, bytes.charCodeAt(i));
+ }
+ return view;
+};
diff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.py
index ecbceb8e66..7bfaf6b8f9 100644
--- a/marimo/_plugins/ui/_impl/from_anywidget.py
+++ b/marimo/_plugins/ui/_impl/from_anywidget.py
@@ -128,6 +128,10 @@ class anywidget(UIElement[T, T]):
js: str = widget._esm if hasattr(widget, "_esm") else "" # type: ignore [unused-ignore] # noqa: E501
css: str = widget._css if hasattr(widget, "_css") else "" # type: ignore [unused-ignore] # noqa: E501
+ import ipywidgets # type: ignore
+
+ _remove_buffers = ipywidgets.widgets.widget._remove_buffers # type: ignore
+ _state, buffer_paths, _buffers = _remove_buffers(widget.get_state()) # type: ignore
super().__init__(
component_name="marimo-anywidget",
@@ -136,6 +140,7 @@ class anywidget(UIElement[T, T]):
args={
"js-url": mo_data.js(js).url if js else "", # type: ignore [unused-ignore] # noqa: E501
"css": css,
+ "buffer-paths": buffer_paths,
},
on_change=on_change,
functions=(
diff --git a/marimo/_smoke_tests/bugs/2366-anywidget-binary.py b/marimo/_smoke_tests/bugs/2366-anywidget-binary.py
new file mode 100644
index 0000000000..631c1b732e
--- /dev/null
+++ b/marimo/_smoke_tests/bugs/2366-anywidget-binary.py
@@ -0,0 +1,37 @@
+import marimo
+
+__generated_with = "0.8.17"
+app = marimo.App()
+
+
+def __():
+ import anywidget
+ import traitlets
+
+
+
+ class Widget(anywidget.AnyWidget):
+ _esm = """
+ function render({ model, el }) {
+ let arr = model.get("arr");
+ el.innerText = arr.bytes instanceof DataView;
+ }
+ export default { render };
+ """
+ arr = traitlets.Dict().tag(sync=True)
+
+ import numpy as np
+ arr = np.array([1, 2, 3])
+ Widget(
+ arr={
+ "bytes": arr.tobytes(),
+ "shape": arr.shape,
+ "dtype": str(arr.dtype),
+ }
+ )
+ return Widget, anywidget, arr, np, traitlets
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_plugins/ui/_impl/test_anywidget.py b/tests/_plugins/ui/_impl/test_anywidget.py
index 5faeee4b03..31d5cf685f 100644
--- a/tests/_plugins/ui/_impl/test_anywidget.py
+++ b/tests/_plugins/ui/_impl/test_anywidget.py
@@ -28,6 +28,10 @@ if HAS_DEPS:
_css = """button { padding: 5px !important; }"""
count = traitlets.Int(0).tag(sync=True)
+ class Widget(_anywidget.AnyWidget):
+ _esm = ""
+ arr = traitlets.Dict().tag(sync=True)
+
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
class TestAnywidget:
@@ -168,3 +172,29 @@ x = as_marimo_element.count
assert wrapped.value == {"count": 0}
wrapped._update({"count": 10})
assert wrapped.value == {"count": 10}
+
+ @staticmethod
+ async def test_initialization() -> None:
+ wrapped = anywidget(Widget(arr={"a": 1}))
+ assert wrapped._initial_value == {"arr": {"a": 1}}
+ assert wrapped._component_args == {
+ "buffer-paths": [],
+ "css": "",
+ "js-url": "",
+ }
+
+ @staticmethod
+ async def test_initialization_with_dataview() -> None:
+ # Create a simple array-like structure without numpy
+ arr = [1, 2, 3]
+ wrapped = anywidget(
+ Widget(arr={"bytes": bytes(arr), "shape": (len(arr),)})
+ )
+ assert wrapped._initial_value == {
+ "arr": {"bytes": bytes([1, 2, 3]), "shape": (3,)}
+ }
+ assert wrapped._component_args == {
+ "buffer-paths": [["arr", "bytes"]],
+ "css": "",
+ "js-url": "",
+ }