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.

improvement: patch polars I/O in wasm (#9413)

Myles Scolnick2fdba9d4fcf7
diff --git a/marimo/_output/formatters/df_formatters.py b/marimo/_output/formatters/df_formatters.py
index dda837bef3..71a17705cc 100644
--- a/marimo/_output/formatters/df_formatters.py
+++ b/marimo/_output/formatters/df_formatters.py
@@ -19,7 +19,7 @@ from marimo._plugins.stateless.mermaid import mermaid
from marimo._plugins.stateless.plain_text import plain_text
from marimo._plugins.ui._impl import tabs
from marimo._plugins.ui._impl.table import get_default_table_page_size, table
-from marimo._runtime.patches import patch_polars_write_json
+from marimo._runtime._wasm._polars import patch_polars_for_wasm
LOGGER = _loggers.marimo_logger()
@@ -89,7 +89,7 @@ class PolarsFormatter(FormatterFactory):
if not include_opinionated():
return None
- unpatch_polars_write_json = patch_polars_write_json()
+ unpatch_polars = patch_polars_for_wasm()
@formatting.opinionated_formatter(pl.DataFrame)
def _show_marimo_dataframe(
@@ -137,7 +137,7 @@ class PolarsFormatter(FormatterFactory):
}
)._mime_()
- return unpatch_polars_write_json
+ return unpatch_polars
class PyArrowFormatter(FormatterFactory):
diff --git a/marimo/_runtime/_wasm/__init__.py b/marimo/_runtime/_wasm/__init__.py
new file mode 100644
index 0000000000..fe2d2e388e
--- /dev/null
+++ b/marimo/_runtime/_wasm/__init__.py
@@ -0,0 +1 @@
+# Copyright 2026 Marimo. All rights reserved.
diff --git a/marimo/_runtime/_wasm/_patches.py b/marimo/_runtime/_wasm/_patches.py
new file mode 100644
index 0000000000..a726d45d7f
--- /dev/null
+++ b/marimo/_runtime/_wasm/_patches.py
@@ -0,0 +1,95 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""WASM-only monkey-patch framework.
+
+`WasmPatchSet` wraps a target so that when the original raises a caught
+exception, a fallback runs instead. Returns one unpatch handle for all
+patches. No-op outside pyodide.
+"""
+
+from __future__ import annotations
+
+import functools
+from collections.abc import Callable
+from typing import Any
+
+from marimo import _loggers
+from marimo._utils.platform import is_pyodide
+
+LOGGER = _loggers.marimo_logger()
+
+Unpatch = Callable[[], None]
+Fallback = Callable[..., Any]
+
+
+class WasmPatchSet:
+ """Collects WASM-only monkey-patches with a single unpatch handle.
+
+ `patch` replaces ``owner.attr`` with a wrapper: calls original; on
+ ``catch`` exception, runs ``fallback(original, *args, **kwargs)``. If the
+ fallback also raises, re-raises the original with the fallback chained so
+ users see the real underlying error.
+ """
+
+ def __init__(self) -> None:
+ self._unpatches: list[Unpatch] = []
+ self._active = is_pyodide()
+
+ def patch(
+ self,
+ owner: Any,
+ attr: str,
+ fallback: Fallback,
+ *,
+ catch: tuple[type[BaseException], ...] = (NameError, Exception),
+ ) -> None:
+ """Register a patch on ``owner.attr``.
+
+ No-op outside pyodide or if ``attr`` is missing (e.g. renamed across
+ polars versions).
+ """
+ if not self._active:
+ return
+
+ original = getattr(owner, attr, None)
+ if original is None:
+ return
+
+ @functools.wraps(original)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ try:
+ return original(*args, **kwargs)
+ except catch as original_exc:
+ original_tb = original_exc.__traceback__
+ try:
+ return fallback(original, *args, **kwargs)
+ except ModuleNotFoundError:
+ # Let missing-dependency errors bubble up so marimo can
+ # prompt the user to install the package.
+ raise
+ except Exception as fallback_exc:
+ raise original_exc.with_traceback(
+ original_tb
+ ) from fallback_exc
+
+ setattr(owner, attr, wrapper)
+
+ def _unpatch() -> None:
+ # Only restore if we're still the active wrapper.
+ if getattr(owner, attr, None) is wrapper:
+ setattr(owner, attr, original)
+
+ self._unpatches.append(_unpatch)
+
+ def unpatch_all(self) -> Unpatch:
+ """Return a callable that restores all originals (idempotent)."""
+ unpatches = self._unpatches
+ self._unpatches = []
+
+ def _run() -> None:
+ for u in reversed(unpatches):
+ try:
+ u()
+ except Exception as e:
+ LOGGER.warning("Failed to unpatch: %s", e)
+
+ return _run
diff --git a/marimo/_runtime/_wasm/_polars.py b/marimo/_runtime/_wasm/_polars.py
new file mode 100644
index 0000000000..36571c6f06
--- /dev/null
+++ b/marimo/_runtime/_wasm/_polars.py
@@ -0,0 +1,267 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""WASM-only fallback patches for polars.
+
+Two flavors of fallback live here, both built on :class:`WasmPatchSet`:
+
+* **Read/scan I/O** — in pyodide, polars' Rust core can't reach the network
+ and its Python fallbacks reference missing modules (fsspec/aiohttp),
+ surfacing as :class:`NameError` and friends. On failure we resolve the
+ source to bytes, decode via pyarrow, and convert with
+ :func:`polars.from_arrow`.
+
+* **DataFrame.write_json** — file system / native JSON writers can fail in
+ WASM. On failure we round-trip via CSV and emit JSON manually.
+
+Read/scan path is best-effort: polars-only kwargs (``n_rows``,
+``try_parse_dates``, ...) are ignored; common kwargs with a pyarrow
+equivalent (``columns``, csv ``separator``, ``has_header``) are honored.
+All patches are no-ops outside pyodide.
+"""
+
+from __future__ import annotations
+
+import io
+import pathlib
+from typing import TYPE_CHECKING, Any
+
+from marimo import _loggers
+from marimo._runtime._wasm._patches import Unpatch, WasmPatchSet
+from marimo._utils.platform import is_pyodide
+
+if TYPE_CHECKING:
+ from collections.abc import Callable
+
+ import polars as pl
+
+LOGGER = _loggers.marimo_logger()
+
+
+# ---------------------------------------------------------------------------
+# Source resolution
+# ---------------------------------------------------------------------------
+
+
+def _is_url(source: Any) -> bool:
+ return isinstance(source, str) and source.startswith(
+ ("http://", "https://")
+ )
+
+
+def _fetch_url_bytes(url: str) -> bytes:
+ """Sync fetch via urllib — works in pyodide thanks to pyodide_http's
+ patch_all (installed at marimo startup), which routes urllib through JS
+ fetch. Single sync path for text and binary.
+ """
+ import urllib.request
+
+ with urllib.request.urlopen(url) as response:
+ return response.read() # type: ignore[no-any-return]
+
+
+def _resolve_to_bytes(source: Any) -> bytes:
+ """Coerce a polars I/O source into raw bytes."""
+ if isinstance(source, bytes):
+ return source
+ if isinstance(source, bytearray):
+ return bytes(source)
+ if isinstance(source, io.IOBase):
+ data = source.read()
+ if isinstance(data, str):
+ return data.encode("utf-8")
+ return data # type: ignore[no-any-return]
+ if isinstance(source, pathlib.Path):
+ return source.read_bytes()
+ if isinstance(source, str):
+ if _is_url(source):
+ return _fetch_url_bytes(source)
+ return pathlib.Path(source).read_bytes()
+ raise TypeError(
+ f"Unsupported source type for WASM polars fallback: {type(source)!r}"
+ )
+
+
+# ---------------------------------------------------------------------------
+# pyarrow decoders
+# ---------------------------------------------------------------------------
+
+
+def _read_csv_arrow(buf: io.BytesIO, **kwargs: Any) -> Any:
+ import pyarrow.csv as pa_csv # type: ignore[import-not-found]
+
+ read_options = pa_csv.ReadOptions(
+ autogenerate_column_names=not kwargs.get("has_header", True),
+ )
+ parse_options_kwargs: dict[str, Any] = {}
+ if "separator" in kwargs:
+ parse_options_kwargs["delimiter"] = kwargs["separator"]
+ parse_options = pa_csv.ParseOptions(**parse_options_kwargs)
+ convert_options_kwargs: dict[str, Any] = {}
+ if "columns" in kwargs and kwargs["columns"] is not None:
+ convert_options_kwargs["include_columns"] = list(kwargs["columns"])
+ convert_options = pa_csv.ConvertOptions(**convert_options_kwargs)
+ return pa_csv.read_csv(
+ buf,
+ read_options=read_options,
+ parse_options=parse_options,
+ convert_options=convert_options,
+ )
+
+
+def _read_parquet_arrow(buf: io.BytesIO, **kwargs: Any) -> Any:
+ import pyarrow.parquet as pa_parquet # type: ignore[import-not-found]
+
+ read_kwargs: dict[str, Any] = {}
+ if "columns" in kwargs and kwargs["columns"] is not None:
+ read_kwargs["columns"] = list(kwargs["columns"])
+ return pa_parquet.read_table(buf, **read_kwargs)
+
+
+def _read_ipc_arrow(buf: io.BytesIO, **kwargs: Any) -> Any:
+ import pyarrow.feather as pa_feather # type: ignore[import-not-found]
+
+ read_kwargs: dict[str, Any] = {}
+ if "columns" in kwargs and kwargs["columns"] is not None:
+ read_kwargs["columns"] = list(kwargs["columns"])
+ return pa_feather.read_table(buf, **read_kwargs)
+
+
+def _read_json_arrow(buf: io.BytesIO, **kwargs: Any) -> Any:
+ del kwargs
+ import pyarrow.json as pa_json # type: ignore[import-not-found]
+
+ return pa_json.read_json(buf)
+
+
+_ARROW_READERS: dict[str, Callable[..., Any]] = {
+ "csv": _read_csv_arrow,
+ "parquet": _read_parquet_arrow,
+ "ipc": _read_ipc_arrow,
+ "ndjson": _read_json_arrow,
+ "json": _read_json_arrow,
+}
+
+
+# ---------------------------------------------------------------------------
+# Fallback factory
+# ---------------------------------------------------------------------------
+
+
+def _make_fallback(fmt: str, lazy: bool) -> Callable[..., Any]:
+ """Decode ``source`` via pyarrow and return polars."""
+ import polars as pl
+
+ from marimo._dependencies.dependencies import DependencyManager
+
+ reader = _ARROW_READERS[fmt]
+
+ def _fallback(
+ original: Callable[..., Any], *args: Any, **kwargs: Any
+ ) -> Any:
+ DependencyManager.pyarrow.require(
+ f"to read polars {fmt} sources in WASM"
+ )
+ del original
+ if not args:
+ source = kwargs.pop("source", None)
+ if source is None:
+ # polars renames the first arg across versions.
+ for alt in ("file", "path"):
+ if alt in kwargs:
+ source = kwargs.pop(alt)
+ break
+ if source is None:
+ raise TypeError("Missing source argument")
+ rest_args: tuple[Any, ...] = ()
+ else:
+ source, rest_args = args[0], args[1:]
+ del rest_args # polars-specific positional args aren't forwarded
+
+ data = _resolve_to_bytes(source)
+ table = reader(io.BytesIO(data), **kwargs)
+ df: pl.DataFrame = pl.from_arrow(table) # type: ignore[assignment]
+ # scan_* materializes eagerly; true streaming wouldn't work in WASM.
+ return df.lazy() if lazy else df
+
+ return _fallback
+
+
+# ---------------------------------------------------------------------------
+# write_json fallback
+# ---------------------------------------------------------------------------
+
+
+def _write_json_fallback(
+ _original: Callable[..., Any],
+ self: pl.DataFrame,
+ file: Any = None,
+ *_args: Any,
+ **_kwargs: Any,
+) -> str | None:
+ """Convert the frame to dicts and emit JSON.
+
+ ``to_dicts`` preserves types and handles quoting/embedded delimiters
+ correctly (unlike a naive CSV split), and avoids I/O so it works in WASM.
+ ``default=str`` covers temporal/decimal types that aren't JSON-native.
+ """
+ import json
+
+ json_data = self.to_dicts()
+
+ if file is None:
+ return json.dumps(json_data, default=str)
+ if isinstance(file, io.IOBase):
+ json.dump(json_data, file, default=str)
+ elif isinstance(file, pathlib.Path):
+ file.write_text(json.dumps(json_data, default=str))
+ else:
+ with open(file, "w", encoding="utf-8") as f:
+ json.dump(json_data, f, default=str)
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Public entry point
+# ---------------------------------------------------------------------------
+
+
+# (polars attr, format key, lazy)
+_IO_TARGETS: tuple[tuple[str, str, bool], ...] = (
+ ("read_csv", "csv", False),
+ ("scan_csv", "csv", True),
+ ("read_parquet", "parquet", False),
+ ("scan_parquet", "parquet", True),
+ ("read_ipc", "ipc", False),
+ ("scan_ipc", "ipc", True),
+ ("read_ndjson", "ndjson", False),
+ ("scan_ndjson", "ndjson", True),
+ ("read_json", "json", False),
+)
+
+
+def patch_polars_for_wasm() -> Unpatch:
+ """Install all WASM fallbacks for polars (read/scan I/O + write_json)."""
+ if not is_pyodide():
+ return lambda: None
+
+ try:
+ import polars as pl
+ except ImportError:
+ return lambda: None
+
+ patches = WasmPatchSet()
+
+ for attr, fmt, lazy in _IO_TARGETS:
+ if not hasattr(pl, attr):
+ continue
+ try:
+ fallback = _make_fallback(fmt, lazy)
+ except Exception as e:
+ LOGGER.warning(
+ "Failed to build WASM fallback for polars.%s: %s", attr, e
+ )
+ continue
+ patches.patch(pl, attr, fallback)
+
+ patches.patch(pl.DataFrame, "write_json", _write_json_fallback)
+
+ return patches.unpatch_all()
diff --git a/marimo/_runtime/patches.py b/marimo/_runtime/patches.py
index e37c5ccfe7..23eeda3414 100644
--- a/marimo/_runtime/patches.py
+++ b/marimo/_runtime/patches.py
@@ -7,18 +7,14 @@ import functools
import sys
import textwrap
import types
-from collections.abc import Callable
from typing import TYPE_CHECKING, Any
from marimo._ast.parse import ast_parse
from marimo._dependencies.dependencies import DependencyManager
from marimo._runtime import marimo_browser, marimo_pdb
-from marimo._utils.platform import is_pyodide
-
-Unpatch = Callable[[], None]
if TYPE_CHECKING:
- from collections.abc import Iterator
+ from collections.abc import Callable, Iterator
from jedi.inference.base_value import ( # type: ignore[import-untyped]
ValueSet,
@@ -458,72 +454,3 @@ def patch_jedi_parameter_completion() -> None:
SignatureParamName.infer = wrap_infer(original_dynamic_infer)
if not getattr(SignatureParamName.__init__, "patched", False):
SignatureParamName.__init__ = enhanced_init
-
-
-def patch_polars_write_json() -> Unpatch:
- """Patch polars.DataFrame.write_json to work in WASM environments.
-
- In WASM, file system operations may fail. This patch attempts to use
- write_json first, and if it fails, falls back to write_csv and then
- converts the CSV to JSON.
- """
- if not is_pyodide():
- return lambda: None
-
- import io
- import pathlib
-
- import polars
-
- original_write_json = polars.DataFrame.write_json
-
- def patched_write_json(
- self: polars.DataFrame,
- file: io.IOBase | str | pathlib.Path | None = None,
- *args: Any,
- **kwargs: Any,
- ) -> str | None:
- try:
- # First try the original method
- return original_write_json(self, file, *args, **kwargs)
- except Exception:
- # Fallback to CSV
- import json
-
- buffer = io.BytesIO()
-
- # Write to CSV
- self.write_csv(buffer)
-
- # Read CSV as text
- buffer.seek(0)
- csv_content = buffer.read().decode("utf-8")
-
- # Parse CSV to create JSON
- lines = csv_content.strip().split("\n")
- json_data: list[dict[str, str]] = []
- if lines:
- headers: list[str] = lines[0].split(",")
- for line in lines[1:]:
- values: list[str] = line.split(",")
- json_data.append(dict(zip(headers, values, strict=False)))
-
- if file is None:
- return json.dumps(json_data)
- elif isinstance(file, io.IOBase):
- json.dump(json_data, file)
- elif isinstance(file, pathlib.Path):
- file.write_text(json.dumps(json_data))
- else:
- with open(file, "w", encoding="utf-8") as f:
- json.dump(json_data, f)
-
- return None
-
- # Apply the patch
- polars.DataFrame.write_json = patched_write_json # type: ignore
-
- def unpatch_polars_write_json() -> None:
- polars.DataFrame.write_json = original_write_json # type: ignore
-
- return unpatch_polars_write_json
diff --git a/tests/_pyodide/test_pyodide_acceptance.mjs b/tests/_pyodide/test_pyodide_acceptance.mjs
index 249b4cfd94..528f2574b7 100644
--- a/tests/_pyodide/test_pyodide_acceptance.mjs
+++ b/tests/_pyodide/test_pyodide_acceptance.mjs
@@ -17,11 +17,13 @@ import path from "node:path";
/**
- * Start a CORS-enabled HTTP server to serve the wheel file
+ * Start a CORS-enabled HTTP server to serve the wheel file plus any extra
+ * files registered at runtime via `addFile(name, buffer, contentType)`.
*/
function startWheelServer(wheelPath) {
const wheelDir = path.dirname(wheelPath);
const wheelFilename = path.basename(wheelPath);
+ const extraFiles = new Map(); // name -> { data: Buffer, contentType: string }
return new Promise((resolve, reject) => {
const server = http.createServer((req, res) => {
@@ -49,10 +51,19 @@ function startWheelServer(wheelPath) {
res.writeHead(200);
res.end(data);
});
- } else {
- res.writeHead(404);
- res.end("Not found");
+ return;
+ }
+
+ const extra = extraFiles.get(requestedFile);
+ if (extra) {
+ res.setHeader("Content-Type", extra.contentType);
+ res.writeHead(200);
+ res.end(extra.data);
+ return;
}
+
+ res.writeHead(404);
+ res.end("Not found");
});
// Listen on a random available port
@@ -60,7 +71,14 @@ function startWheelServer(wheelPath) {
const address = server.address();
const port = typeof address === 'object' && address !== null && 'port' in address ? address.port : 0;
console.log(`Wheel server started at http://127.0.0.1:${port}`);
- resolve({ server, port, wheelFilename });
+ resolve({
+ server,
+ port,
+ wheelFilename,
+ addFile: (name, data, contentType = "application/octet-stream") => {
+ extraFiles.set(name, { data, contentType });
+ },
+ });
});
server.on("error", reject);
@@ -320,6 +338,69 @@ print(f"Final file content verified: '{final_content}' - OK")
print("\\nmo.watch.file works correctly in Pyodide execution context!")
`);
+ // Step 7: Test polars WASM I/O patches (read_csv / read_parquet / scan_csv)
+ //
+ // Sync HTTP isn't available in Node.js pyodide (no XHR shim, no
+ // SharedArrayBuffer/Atomics setup), so we can't exercise the URL fetch
+ // end-to-end through the wrapper here — that's covered by unit tests.
+ // Instead, verify two things in a real pyodide runtime: (1) the polars
+ // formatter actually wrapped pl.read_csv on import, and (2) the pyarrow
+ // fallback decoders return a polars DataFrame when called with bytes.
+ console.log("Step 7: Testing polars WASM I/O patches...");
+
+ // Load polars + pyarrow (pyarrow is the patch's fallback decoder).
+ await pyodide.loadPackage(["polars", "pyarrow"]);
+
+ await pyodide.runPythonAsync(`
+import io
+import polars as pl
+from marimo._runtime._wasm._polars import _make_fallback, _write_json_fallback
+
+# Importing polars triggers the formatter's register(), which calls
+# patch_polars_for_wasm() and wraps pl.read_csv etc. functools.wraps copies
+# __wrapped__, so we can confirm the wrapper is in place.
+assert hasattr(pl.read_csv, "__wrapped__"), "pl.read_csv should be wrapped in pyodide"
+assert hasattr(pl.scan_csv, "__wrapped__"), "pl.scan_csv should be wrapped in pyodide"
+assert hasattr(pl.read_parquet, "__wrapped__"), "pl.read_parquet should be wrapped in pyodide"
+print(" - polars I/O wrappers installed: OK")
+
+# Exercise the fallback decoders directly with bytes.
+csv_bytes = b"a,b\\n1,x\\n2,y\\n"
+df = _make_fallback("csv", lazy=False)(None, io.BytesIO(csv_bytes))
+assert df.shape == (2, 2), f"unexpected csv shape: {df.shape}"
+assert df.columns == ["a", "b"], f"unexpected csv columns: {df.columns}"
+assert df["b"].to_list() == ["x", "y"], f"unexpected csv values: {df['b'].to_list()}"
+print(f" - csv fallback: {df.shape} OK")
+
+lf = _make_fallback("csv", lazy=True)(None, io.BytesIO(csv_bytes))
+assert isinstance(lf, pl.LazyFrame), f"expected LazyFrame, got {type(lf).__name__}"
+assert lf.collect().shape == (2, 2)
+print(f" - scan_csv fallback returns LazyFrame: OK")
+
+import pyarrow as pa
+import pyarrow.parquet as pq
+table = pa.table({"a": [1, 2], "b": ["x", "y"]})
+parquet_buf = io.BytesIO()
+pq.write_table(table, parquet_buf)
+df2 = _make_fallback("parquet", lazy=False)(None, io.BytesIO(parquet_buf.getvalue()))
+assert df2.shape == (2, 2), f"unexpected parquet shape: {df2.shape}"
+assert df2["b"].to_list() == ["x", "y"], f"unexpected parquet values: {df2['b'].to_list()}"
+print(f" - parquet fallback: {df2.shape} OK")
+
+# write_json fallback handles temporal types (default=str).
+import datetime
+df3 = pl.DataFrame({
+ "a": [1, 2],
+ "d": [datetime.date(2026, 1, 1), datetime.date(2026, 1, 2)],
+})
+out = _write_json_fallback(None, df3)
+assert "2026-01-01" in out, f"expected serialized date in output: {out}"
+print(f" - write_json fallback handles dates: OK")
+
+print("polars WASM I/O patches verified")
+`);
+ console.log("");
+
console.log("");
console.log("Verification results:", result);
console.log("");
diff --git a/tests/_runtime/test_patches.py b/tests/_runtime/test_patches.py
index a7a4d17001..abd42633c9 100644
--- a/tests/_runtime/test_patches.py
+++ b/tests/_runtime/test_patches.py
@@ -7,15 +7,16 @@ from unittest.mock import patch
import pytest
-from marimo._dependencies.dependencies import DependencyManager
+from marimo._runtime._wasm._patches import WasmPatchSet
+from marimo._runtime._wasm._polars import patch_polars_for_wasm
from marimo._runtime.capture import capture_stderr
-from marimo._runtime.patches import patch_polars_write_json
from marimo._runtime.runtime import Kernel
from marimo._utils.platform import is_pyodide
from tests._messaging.mocks import MockStream
from tests.conftest import ExecReqProvider, mock_pyodide
if TYPE_CHECKING:
+ from collections.abc import Callable
from pathlib import Path
@@ -206,10 +207,7 @@ async def test_webbrowser_easter_egg(
assert "<img" in outputs[-1]
- not DependencyManager.polars.has(),
- reason="Polars is not installed",
-)
@mock_pyodide()
def test_polars_write_json_patch(tmp_path: Path):
import polars as pl
@@ -227,9 +225,9 @@ def test_polars_write_json_patch(tmp_path: Path):
df.write_json(file_path)
# Patch to fallback to write_csv
- unpatch_polars_write_json = patch_polars_write_json()
+ unpatch = patch_polars_for_wasm()
- expected_json = '[{"a": "1", "b": "x"}, {"a": "2", "b": "y"}]'
+ expected_json = '[{"a": 1, "b": "x"}, {"a": 2, "b": "y"}]'
# Test it succeeds with file path
df.write_json(file_path)
@@ -247,9 +245,239 @@ def test_polars_write_json_patch(tmp_path: Path):
# Test it succeeds with None
assert df.write_json() == expected_json
- # Patch the patch
- unpatch_polars_write_json()
+ # Unpatch
+ unpatch()
# Test it fails again
with pytest.raises(ValueError, match="Test error"):
df.write_json(file_path)
+
+
+def _const_fallback(value: object) -> Callable[..., object]:
+ """Build a fallback that ignores its arguments and returns ``value``."""
+
+ def _fb(*_args: object, **_kwargs: object) -> object:
+ return value
+
+ return _fb
+
+
+class TestWasmPatchSet:
+ @staticmethod
+ def test_noop_outside_pyodide() -> None:
+ import types
+
+ mod = types.SimpleNamespace(fn=lambda x: x + 1)
+ original = mod.fn
+ patches = WasmPatchSet()
+ patches.patch(mod, "fn", _const_fallback(999))
+ # Outside pyodide, no patch is installed.
+ assert mod.fn is original
+ assert mod.fn(1) == 2
+ patches.unpatch_all()()
+
+ @staticmethod
+ @mock_pyodide()
+ def test_fallback_on_caught_exception() -> None:
+ import types
+
+ def divide_by_zero(_x: int) -> float:
+ return 1 / 0
+
+ mod = types.SimpleNamespace(fn=divide_by_zero)
+ patches = WasmPatchSet()
+ patches.patch(
+ mod,
+ "fn",
+ _const_fallback("fallback"),
+ catch=(ZeroDivisionError,),
+ )
+ assert mod.fn(0) == "fallback"
+
+ unpatch = patches.unpatch_all()
+ unpatch()
+ with pytest.raises(ZeroDivisionError):
+ mod.fn(0)
+
+ @staticmethod
+ @mock_pyodide()
+ def test_fallback_failure_chains_original_error() -> None:
+ import types
+
+ def boom(*_: object, **__: object) -> object:
+ raise NameError("primary boom")
+
+ def fallback_fail(*_: object, **__: object) -> object:
+ raise RuntimeError("fallback boom")
+
+ mod = types.SimpleNamespace(fn=boom)
+ patches = WasmPatchSet()
+ patches.patch(mod, "fn", fallback_fail)
+
+ with pytest.raises(NameError, match="primary boom") as exc_info:
+ mod.fn()
+ assert isinstance(exc_info.value.__cause__, RuntimeError)
+ patches.unpatch_all()()
+
+ @staticmethod
+ @mock_pyodide()
+ def test_skips_missing_attr() -> None:
+ import types
+
+ mod = types.SimpleNamespace()
+ patches = WasmPatchSet()
+ # Should silently skip without raising.
+ patches.patch(mod, "missing", _const_fallback(None))
+ assert not hasattr(mod, "missing")
+ patches.unpatch_all()()
+
+
[email protected]("polars", "pyarrow")
+class TestPolarsIoWasmPatch:
+ @staticmethod
+ def test_noop_outside_pyodide() -> None:
+ import polars as pl
+
+ original = pl.read_csv
+ unpatch = patch_polars_for_wasm()
+ assert pl.read_csv is original
+ unpatch()
+ assert pl.read_csv is original
+
+ @staticmethod
+ @mock_pyodide()
+ def test_read_csv_falls_back_on_name_error() -> None:
+ import polars as pl
+
+ csv_bytes = b"a,b\n1,x\n2,y\n"
+ with patch(
+ "polars.read_csv",
+ side_effect=NameError("simulated wasm failure"),
+ ):
+ unpatch = patch_polars_for_wasm()
+ try:
+ df = pl.read_csv(io.BytesIO(csv_bytes))
+ assert df.shape == (2, 2)
+ assert df.columns == ["a", "b"]
+ assert df["b"].to_list() == ["x", "y"]
+ finally:
+ unpatch()
+
+ @staticmethod
+ @mock_pyodide()
+ def test_read_csv_falls_back_on_generic_exception() -> None:
+ import polars as pl
+
+ csv_bytes = b"a,b\n1,x\n"
+ with patch(
+ "polars.read_csv",
+ side_effect=RuntimeError("network unavailable"),
+ ):
+ unpatch = patch_polars_for_wasm()
+ try:
+ df = pl.read_csv(io.BytesIO(csv_bytes))
+ assert df.shape == (1, 2)
+ finally:
+ unpatch()
+
+ @staticmethod
+ @mock_pyodide()
+ def test_scan_csv_returns_lazyframe() -> None:
+ import polars as pl
+
+ csv_bytes = b"a,b\n1,x\n2,y\n"
+ with patch(
+ "polars.scan_csv",
+ side_effect=NameError("simulated wasm failure"),
+ ):
+ unpatch = patch_polars_for_wasm()
+ try:
+ lf = pl.scan_csv(io.BytesIO(csv_bytes))
+ assert isinstance(lf, pl.LazyFrame)
+ assert lf.collect().shape == (2, 2)
+ finally:
+ unpatch()
+
+ @staticmethod
+ @mock_pyodide()
+ def test_read_parquet_falls_back(tmp_path: Path) -> None:
+ import polars as pl
+
+ df_in = pl.DataFrame({"a": [1, 2, 3], "b": ["x", "y", "z"]})
+ path = tmp_path / "test.parquet"
+ df_in.write_parquet(path)
+ parquet_bytes = path.read_bytes()
+
+ with patch(
+ "polars.read_parquet",
+ side_effect=NameError("simulated wasm failure"),
+ ):
+ unpatch = patch_polars_for_wasm()
+ try:
+ df = pl.read_parquet(io.BytesIO(parquet_bytes))
+ assert df.shape == (3, 2)
+ assert df["a"].to_list() == [1, 2, 3]
+ finally:
+ unpatch()
+
+ @staticmethod
+ @mock_pyodide()
+ def test_unpatch_restores_original() -> None:
+ import polars as pl
+
+ unpatch = patch_polars_for_wasm()
+ try:
+ assert pl.read_csv is not None
+ patched = pl.read_csv
+ unpatch()
+ assert pl.read_csv is not patched
+ finally:
+ # idempotent — calling again should be safe
+ unpatch()
+
+ @staticmethod
+ @mock_pyodide()
+ def test_unpatch_is_idempotent() -> None:
+ unpatch = patch_polars_for_wasm()
+ unpatch()
+ unpatch() # second call must not raise
+
+ @staticmethod
+ @mock_pyodide()
+ def test_fallback_propagates_original_error_when_fallback_fails() -> None:
+ import polars as pl
+
+ with patch(
+ "polars.read_csv",
+ side_effect=NameError("simulated wasm failure"),
+ ):
+ unpatch = patch_polars_for_wasm()
+ try:
+ # Pass an unsupported source type so the fallback raises.
+ with pytest.raises(NameError, match="simulated wasm failure"):
+ pl.read_csv(12345) # type: ignore[arg-type]
+ finally:
+ unpatch()
+
+ @staticmethod
+ @mock_pyodide()
+ def test_missing_pyarrow_bubbles_module_not_found_error() -> None:
+ """ModuleNotFoundError must propagate so marimo can prompt to install."""
+ import polars as pl
+
+ from marimo._dependencies.dependencies import DependencyManager
+
+ with (
+ patch(
+ "polars.read_csv",
+ side_effect=NameError("simulated wasm failure"),
+ ),
+ patch.object(DependencyManager.pyarrow, "has", return_value=False),
+ ):
+ unpatch = patch_polars_for_wasm()
+ try:
+ with pytest.raises(ModuleNotFoundError) as exc_info:
+ pl.read_csv(io.BytesIO(b"a,b\n1,x\n"))
+ assert exc_info.value.name == "pyarrow"
+ finally:
+ unpatch()