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: use Arrow IPC for mo.ui.altair_chart to preserve field types (#3902)

Myles Scolnick4194855bb7a9
diff --git a/frontend/package.json b/frontend/package.json
index 5e44fa4fdd..23c457cfba 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -81,6 +81,7 @@
"@uidotdev/usehooks": "^2.4.1",
"@uiw/codemirror-extensions-langs": "^4.23.8",
"@uiw/react-codemirror": "^4.23.7",
+ "@uwdata/flechette": "^1.1.2",
"@valtown/codemirror-codeium": "^1.1.1",
"@xterm/addon-attach": "^0.11.0",
"@xterm/addon-fit": "^0.10.0",
@@ -139,6 +140,7 @@
"timestring": "^7.0.0",
"typescript-memoize": "^1.1.1",
"use-resize-observer": "^9.1.0",
+ "vega": "^5.31.0",
"vega-lite": "^5.23.0",
"vega-loader": "^4.5.3",
"vscode-languageserver-protocol": "^3.17.5",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index 16013ccc25..3bf2a8b9f8 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -219,6 +219,9 @@ importers:
'@uiw/react-codemirror':
specifier: ^4.23.7
+ '@uwdata/flechette':
+ specifier: ^1.1.2
+ version: 1.1.2
'@valtown/codemirror-codeium':
specifier: ^1.1.1
version: 1.1.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
@@ -260,7 +263,7 @@ importers:
version: 1.12.1
compassql:
specifier: ^0.21.2
- version: 0.21.2([email protected])
+ version: 0.21.2([email protected])
cssnano:
specifier: ^7.0.6
version: 7.0.6([email protected])
@@ -359,7 +362,7 @@ importers:
version: 0.9.6([email protected])
react-vega:
specifier: ^7.6.0
react-virtuoso:
specifier: ^4.12.3
@@ -393,9 +396,12 @@ importers:
use-resize-observer:
specifier: ^9.1.0
+ vega:
+ specifier: ^5.31.0
+ version: 5.31.0
vega-lite:
specifier: ^5.23.0
- version: 5.23.0([email protected])
+ version: 5.23.0([email protected])
vega-loader:
specifier: ^4.5.3
version: 4.5.3
@@ -3712,6 +3718,9 @@ packages:
resolution: {integrity: sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==}
+ '@uwdata/[email protected]':
+ resolution: {integrity: sha512-hhtAgXlJbibLIHHIyFJ2fcPQ/hAK43HtEirRgrb/v2xEQv4It/KcUOyMklaVPUv2Z7+agKjSWLAXGyAQglRPvQ==}
+
'@valtown/[email protected]':
resolution: {integrity: sha512-J/LcCiHAhqcqTFjxAFYtUIxSPXY1cdhANsJ8HWqb4wIRengcigBC0r8psZOaVdFHrky4p56q+sJL1Wnsd0Xsug==}
peerDependencies:
@@ -8516,9 +8525,6 @@ packages:
resolution: {integrity: sha512-wQhw7KR46wKJAip28FF/CicW+oiJaPAwMKdrxlnTA0Nv8Bf7bloRlc+O3kON4b4H1iALLr9KgRcYTOeXNs2MOA==}
- resolution: {integrity: sha512-pCqmm5efd+3M65jrJGxEy3UGuRksmK6DnWijoSNocnxdCBxez+yqUUVX9o2pN8VxMe3648vZnR9/Vk5CXqRvIQ==}
-
resolution: {integrity: sha512-uXjSDbbGcFLCQTZZI+OiZK0U+2dLWC26ONdO0g9RhPzXXzR3niPcFOA0bc/OeiHdTexqsLjOiXxR/K2BckB8gQ==}
@@ -8595,8 +8601,8 @@ packages:
resolution: {integrity: sha512-BReB2qRERA/Ke+QoxKDQ7fES25A9Q3qKRm1CJxwvpLGhAl4k5cGDORx6yW+J3rFHMzpJlmdRM+kb489EuphxZQ==}
- resolution: {integrity: sha512-j9Sdgmvowz09jkMgTFGVfiv7ycuRP/TQkdHRPXIYwt3RDgPQn7inyFcJ8C8ABFt4MiMWdjOwbneF6KWW8TRXIw==}
+ resolution: {integrity: sha512-UTXjuasq0Q8uMuzz/qow4moVHFJ5atYdQu871QZJ/zgWY3Po4du3dIGBVQN4fYEv6seKhDvxpEFke2rqx81Wqw==}
resolution: {integrity: sha512-fTGnTG7FhtTG9tiYDL3k5s8YHqB71Ml5+aC9B7eaBygeB8GKXBrcbTXLOzoCRxT3Jr5cRhr99PMBu0AkqmhBog==}
@@ -8607,8 +8613,8 @@ packages:
resolution: {integrity: sha512-RYlyMJu5kZV4XXjmyTQKADJWDB25SMHsiF+B1rbE1p+pmdQPlp5tGdPl9r5dUJOp3p8mSt/NGI8GPGucmPMxtw==}
- resolution: {integrity: sha512-ZPAAQ3iYz6YrQjJoDT+0bcxJkXt9PKF5v4OO7Omw8PFhkIv++jFXeKlQTW1bBtyQ92dkdGGHv5lYY67Djqjf3A==}
+ resolution: {integrity: sha512-gg2ukCviKG6Nofmr0Y6hFbr9romRMzmXHe3ljNJ5QyRnkwmQ7HbTvXOyS9cZZ0VtuhSRw+uiyd0Pg+nep0IhwA==}
resolution: {integrity: sha512-lWNimgJAXGeRFu2Pz8axOUqVf1moYhD+5yhBzDSmckE9I5jLOyZc/XvgFTXwFnsVkMd1QW1vxJa+y9yfUblzYw==}
@@ -8616,8 +8622,8 @@ packages:
resolution: {integrity: sha512-lFmF3u9/ozU0P+WqPjeThQfZm0PigdbXDwpIUCxczrCXKYJLYFmZuZLZR7cxtmpZ0/yuvRvAJ4g123LXbSZF8A==}
- resolution: {integrity: sha512-ZGoC8LdfEUV0LlXIuz7hup9jxuQYhSaWek2M7r9dEHAPbPrzSQvKXZ0BbsJbrarM100TGRpTVN/l1AFxCwDkWw==}
+ resolution: {integrity: sha512-ZZ+8kcKqCeRi7pBdS7kfBpfhV2gDpa6N950GKGWFw0QL4fH319A9o8FAJzdY8zK0WW0PKrivZSoRmK9fWUxnhg==}
resolution: {integrity: sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==}
@@ -13047,6 +13053,8 @@ snapshots:
'@ungap/[email protected]': {}
+ '@uwdata/[email protected]': {}
+
'@valtown/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':
dependencies:
'@bufbuild/protobuf': 1.10.0
@@ -13846,11 +13854,11 @@ snapshots:
dependencies:
datalib: 1.7.3
typescript-json-schema: 0.9.2
- vega-lite: 3.4.0([email protected])
+ vega-lite: 3.4.0([email protected])
yargs: 13.3.2
transitivePeerDependencies:
- vega
@@ -17574,15 +17582,15 @@ snapshots:
dependencies:
react: 18.3.1
dependencies:
'@types/react': 18.3.18
fast-deep-equal: 3.1.3
prop-types: 15.8.1
react: 18.3.1
- vega: 5.30.0
- vega-lite: 5.23.0([email protected])
+ vega: 5.31.0
+ vega-lite: 5.23.0([email protected])
dependencies:
@@ -18807,17 +18815,17 @@ snapshots:
transitivePeerDependencies:
- encoding
dependencies:
fast-json-patch: 3.1.1
json-stringify-pretty-compact: 3.0.0
semver: 7.6.3
tslib: 2.8.1
- vega: 5.30.0
+ vega: 5.31.0
vega-interpreter: 1.0.5
- vega-lite: 5.23.0([email protected])
+ vega-lite: 5.23.0([email protected])
vega-schema-url-parser: 2.2.0
vega-tooltip: 0.33.0
@@ -18859,22 +18867,6 @@ snapshots:
vega-time: 2.1.3
vega-util: 1.17.3
- dependencies:
- d3-array: 3.2.4
- d3-color: 3.1.0
- d3-geo: 3.1.1
- vega-dataflow: 5.7.7
- vega-expression: 5.1.2
- vega-scale: 7.4.2
- vega-scenegraph: 4.13.1
- vega-selections: 5.5.0
- vega-statistics: 1.9.0
- vega-time: 2.1.3
- vega-util: 1.17.3
- transitivePeerDependencies:
- - encoding
-
dependencies:
d3-array: 3.2.4
@@ -18923,7 +18915,7 @@ snapshots:
transitivePeerDependencies:
- encoding
dependencies:
'@types/clone': 0.1.30
'@types/fast-json-stable-stringify': 2.1.0
@@ -18932,18 +18924,18 @@ snapshots:
fast-json-stable-stringify: 2.0.0
json-stringify-pretty-compact: 2.0.0
tslib: 1.10.0
- vega: 5.30.0
+ vega: 5.31.0
vega-event-selector: 2.0.6
vega-expression: 2.6.6
vega-typings: 0.7.2
vega-util: 1.10.0
yargs: 13.3.2
dependencies:
json-stringify-pretty-compact: 4.0.0
tslib: 2.8.1
- vega: 5.30.0
+ vega: 5.31.0
vega-event-selector: 3.0.1
vega-expression: 5.1.2
vega-util: 1.17.3
@@ -19023,10 +19015,10 @@ snapshots:
dependencies:
d3-array: 3.2.4
dependencies:
- vega: 5.30.0
- vega-lite: 5.23.0([email protected])
+ vega: 5.31.0
+ vega-lite: 5.23.0([email protected])
dependencies:
@@ -19052,7 +19044,7 @@ snapshots:
dependencies:
vega-util: 1.17.3
dependencies:
'@types/geojson': 7946.0.4
vega-event-selector: 3.0.1
@@ -19071,7 +19063,7 @@ snapshots:
transitivePeerDependencies:
- encoding
dependencies:
d3-array: 3.2.4
d3-timer: 3.0.1
@@ -19102,7 +19094,7 @@ snapshots:
transitivePeerDependencies:
- encoding
dependencies:
vega-crossfilter: 4.1.3
vega-dataflow: 5.7.7
@@ -19111,7 +19103,7 @@ snapshots:
vega-expression: 5.1.2
vega-force: 4.2.2
vega-format: 1.1.3
- vega-functions: 5.15.0
+ vega-functions: 5.16.0
vega-geo: 4.4.3
vega-hierarchy: 4.1.3
vega-label: 1.3.1
@@ -19125,9 +19117,9 @@ snapshots:
vega-statistics: 1.9.0
vega-time: 2.1.3
vega-transforms: 4.12.1
- vega-typings: 1.3.1
+ vega-typings: 1.4.0
vega-util: 1.17.3
- vega-view: 5.13.0
+ vega-view: 5.14.0
vega-view-transforms: 4.6.1
vega-voronoi: 4.2.4
vega-wordcloud: 4.1.6
diff --git a/frontend/src/plugins/impl/vega/__tests__/vega.test.ts b/frontend/src/plugins/impl/vega/__tests__/vega.test.ts
index c58b0fba17..ce7e5b1717 100644
--- a/frontend/src/plugins/impl/vega/__tests__/vega.test.ts
+++ b/frontend/src/plugins/impl/vega/__tests__/vega.test.ts
@@ -451,6 +451,31 @@ Bob.Jones,25
]
`);
});
+
+ it.skip("should handle arrow files", async () => {
+ // Create a small arrow file with schema and one empty record batch
+ const arrowData = new Uint8Array([
+ 0x41,
+ 0x52,
+ 0x52,
+ 0x4f,
+ 0x57,
+ 0x31,
+ 0x00,
+ 0x00, // "ARROW1\0\0"
+ ]);
+ global.fetch = vi.fn().mockResolvedValue({
+ arrayBuffer: () => Promise.resolve(arrowData.buffer),
+ });
+ const data = await vegaLoadData(
+ "data.arrow",
+ {
+ type: "arrow",
+ },
+ { handleBigIntAndNumberLike: true },
+ );
+ expect(data).toBe([]);
+ });
});
describe("uniquifyColumnNames", () => {
diff --git a/frontend/src/plugins/impl/vega/formats.ts b/frontend/src/plugins/impl/vega/formats.ts
new file mode 100644
index 0000000000..ea82e5f055
--- /dev/null
+++ b/frontend/src/plugins/impl/vega/formats.ts
@@ -0,0 +1,25 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { tableFromIPC, type Table as ArrowTable } from "@uwdata/flechette";
+
+// Adapted from https://github.com/vega/vega-loader-arrow/blob/main/src/index.js
+// but this avoids bundling flechette which causes code duplication
+
+interface IPCOptions {
+ useProxy?: boolean;
+}
+
+export function arrow(data: ArrowTable): unknown[] {
+ function isArrowTable(data: unknown): data is ArrowTable {
+ return (
+ !!(data as ArrowTable)?.schema &&
+ Array.isArray((data as ArrowTable).schema.fields) &&
+ typeof (data as ArrowTable).toArray === "function"
+ );
+ }
+ return (isArrowTable(data) ? data : decodeIPC(data)).toArray();
+}
+arrow.responseType = "arrayBuffer";
+
+function decodeIPC(data: ArrayBuffer, options?: IPCOptions): ArrowTable {
+ return tableFromIPC(data, options ?? { useProxy: true });
+}
diff --git a/frontend/src/plugins/impl/vega/loader.ts b/frontend/src/plugins/impl/vega/loader.ts
index d33dddbad5..b12773b1a2 100644
--- a/frontend/src/plugins/impl/vega/loader.ts
+++ b/frontend/src/plugins/impl/vega/loader.ts
@@ -1,9 +1,12 @@
/* Copyright 2024 Marimo. All rights reserved. */
import type { DataFormat } from "./types";
import { isNumber } from "lodash-es";
-import { typeParsers, createLoader, read, type DataType } from "./vega-loader";
+import { typeParsers, read, type DataType } from "./vega-loader";
import { Objects } from "@/utils/objects";
import { Logger } from "@/utils/Logger";
+import { tableFromIPC } from "@uwdata/flechette";
+import { batch } from "@/utils/batch-requests";
+import { createBatchedLoader } from "./batched";
type Unsubscribe = () => void;
type Middleware = () => Unsubscribe;
@@ -121,7 +124,15 @@ const customBooleanParser = (v: string) => {
typeParsers.boolean = customBooleanParser;
-export const vegaLoader = createLoader();
+export const vegaLoader = createBatchedLoader();
+
+/**
+ * Batch requests to the same URL returning the same promise for all calls with the same key.
+ */
+export const batchedArrowLoader = batch(
+ (url: string) => fetch(url).then((r) => r.arrayBuffer()),
+ (url: string) => url,
+);
/**
* Load data from a URL and parse it according to the given format.
@@ -130,7 +141,11 @@ export const vegaLoader = createLoader();
*/
export async function vegaLoadData<T = object>(
url: string,
- format: DataFormat | undefined | { type: "csv"; parse: "auto" },
+ format:
+ | DataFormat
+ | undefined
+ | { type: "csv"; parse: "auto" }
+ | { type: "arrow" },
opts: {
// We support enabling/disabling since the Table enables it
// but Vega does not support BigInts
@@ -140,6 +155,16 @@ export async function vegaLoadData<T = object>(
): Promise<T[]> {
const { handleBigIntAndNumberLike = false, replacePeriod = false } = opts;
+ // Handle arrow data
+ if (url.endsWith(".arrow") || format?.type === "arrow") {
+ const arrow = await batchedArrowLoader(url);
+ return tableFromIPC(arrow, {
+ useProxy: true,
+ useDate: true,
+ useBigInt: handleBigIntAndNumberLike,
+ }).toArray() as T[];
+ }
+
const middleware: Middleware[] = [DATE_MIDDLEWARE];
if (handleBigIntAndNumberLike) {
middleware.push(BIG_INT_MIDDLEWARE);
diff --git a/frontend/src/plugins/impl/vega/vega-component.tsx b/frontend/src/plugins/impl/vega/vega-component.tsx
index 6118e8605e..cee24fa14d 100644
--- a/frontend/src/plugins/impl/vega/vega-component.tsx
+++ b/frontend/src/plugins/impl/vega/vega-component.tsx
@@ -19,6 +19,12 @@ import { ErrorBanner } from "../common/error-banner";
import { Tooltip } from "@/components/ui/tooltip";
import { HelpCircleIcon } from "lucide-react";
import { isValid } from "date-fns";
+// @ts-expect-error vega-typings does not include formats
+import { formats } from "vega";
+import { arrow } from "./formats";
+
+// register arrow reader under type 'arrow'
+formats("arrow", arrow);
export interface Data {
spec: VegaLiteSpec;
diff --git a/marimo/_output/data/data.py b/marimo/_output/data/data.py
index 4d358f979d..1c47da928f 100644
--- a/marimo/_output/data/data.py
+++ b/marimo/_output/data/data.py
@@ -70,6 +70,18 @@ def csv(data: Union[str, bytes, io.BytesIO]) -> VirtualFile:
return any_data(data, ext="csv") # type: ignore
+def arrow(data: bytes) -> VirtualFile:
+ """Create a virtual file for Arrow data.
+
+ Args:
+ data: Arrow data in bytes
+
+ Returns:
+ A `VirtualFile` object.
+ """
+ return any_data(data, ext="arrow") # type: ignore
+
+
def json(data: Union[str, bytes, io.BytesIO]) -> VirtualFile:
"""Create a virtual file for JSON data.
diff --git a/marimo/_output/formatters/altair_formatters.py b/marimo/_output/formatters/altair_formatters.py
index f5dae64685..19f584bff3 100644
--- a/marimo/_output/formatters/altair_formatters.py
+++ b/marimo/_output/formatters/altair_formatters.py
@@ -83,7 +83,10 @@ class AltairFormatter(FormatterFactory):
chart = _apply_embed_options(chart)
# Return the chart as a vega-lite chart with embed options
- return ("application/vnd.vegalite.v5+json", chart.to_json())
+ return (
+ "application/vnd.vegalite.v5+json",
+ chart.to_json(validate=False),
+ )
def apply_theme(self, theme: Theme) -> None:
del theme
diff --git a/marimo/_plugins/ui/_impl/altair_chart.py b/marimo/_plugins/ui/_impl/altair_chart.py
index 7e5e3e01b6..150b12fecf 100644
--- a/marimo/_plugins/ui/_impl/altair_chart.py
+++ b/marimo/_plugins/ui/_impl/altair_chart.py
@@ -222,8 +222,8 @@ def _parse_spec(spec: altair.TopLevelMixin) -> VegaSpec:
with altair.data_transformers.enable("default"):
return spec.to_dict() # type: ignore
- with altair.data_transformers.enable("marimo"):
- return spec.to_dict() # type: ignore
+ with altair.data_transformers.enable("marimo_arrow"):
+ return spec.to_dict(validate=False) # type: ignore
def _has_transforms(spec: VegaSpec) -> bool:
diff --git a/marimo/_plugins/ui/_impl/charts/altair_transformer.py b/marimo/_plugins/ui/_impl/charts/altair_transformer.py
index 87899eedf1..06fa76b20a 100644
--- a/marimo/_plugins/ui/_impl/charts/altair_transformer.py
+++ b/marimo/_plugins/ui/_impl/charts/altair_transformer.py
@@ -27,17 +27,16 @@ class _CsvFormatDict(TypedDict):
type: Literal["csv"]
-class _ToJsonReturnUrlDict(TypedDict):
- url: str
- format: _JsonFormatDict
+class _ArrowFormatDict(TypedDict):
+ type: Literal["arrow"]
-class _ToCsvReturnUrlDict(TypedDict):
+class _TransformResult(TypedDict):
url: str
- format: _CsvFormatDict
+ format: Union[_CsvFormatDict, _JsonFormatDict, _ArrowFormatDict]
-def _to_marimo_json(data: Data, **kwargs: Any) -> _ToJsonReturnUrlDict:
+def _to_marimo_json(data: Data, **kwargs: Any) -> _TransformResult:
"""
Custom implementation of altair.utils.data.to_json that
returns a VirtualFile URL instead of writing to disk.
@@ -48,7 +47,7 @@ def _to_marimo_json(data: Data, **kwargs: Any) -> _ToJsonReturnUrlDict:
return {"url": virtual_file.url, "format": {"type": "json"}}
-def _to_marimo_csv(data: Data, **kwargs: Any) -> _ToCsvReturnUrlDict:
+def _to_marimo_csv(data: Data, **kwargs: Any) -> _TransformResult:
"""
Custom implementation of altair.utils.data.to_csv that
returns a VirtualFile URL instead of writing to disk.
@@ -59,7 +58,20 @@ def _to_marimo_csv(data: Data, **kwargs: Any) -> _ToCsvReturnUrlDict:
return {"url": virtual_file.url, "format": {"type": "csv"}}
-def _to_marimo_inline_csv(data: Data, **kwargs: Any) -> _ToCsvReturnUrlDict:
+def _to_marimo_arrow(data: Data, **kwargs: Any) -> _TransformResult:
+ """
+ Convert data to arrow format, falls back to CSV if not possible.
+ """
+ del kwargs
+ try:
+ data_arrow = get_table_manager(data).to_arrow_ipc()
+ except Exception:
+ return _to_marimo_csv(data)
+ virtual_file = mo_data.arrow(data_arrow)
+ return {"url": virtual_file.url, "format": {"type": "arrow"}}
+
+
+def _to_marimo_inline_csv(data: Data, **kwargs: Any) -> _TransformResult:
"""
Custom implementation of altair.utils.data.to_csv that
inlines the CSV data in the URL.
@@ -136,3 +148,4 @@ def register_transformers() -> None:
alt.data_transformers.register("marimo_inline_csv", _to_marimo_inline_csv)
alt.data_transformers.register("marimo_json", _to_marimo_json)
alt.data_transformers.register("marimo_csv", _to_marimo_csv)
+ alt.data_transformers.register("marimo_arrow", _to_marimo_arrow)
diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.py
index 1e18158ba6..74289740cf 100644
--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py
+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import io
from functools import cached_property
from typing import Any, Optional, Tuple
@@ -65,6 +66,11 @@ class PandasTableManagerFactory(TableManagerFactory):
"utf-8"
)
+ def to_arrow_ipc(self) -> bytes:
+ out = io.BytesIO()
+ self._original_data.to_feather(out, compression="uncompressed")
+ return out.getvalue()
+
def apply_formatting(
self, format_mapping: Optional[FormatMapping]
) -> PandasTableManager:
diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.py
index 56710a4e04..272be98aae 100644
--- a/marimo/_plugins/ui/_impl/tables/polars_table.py
+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import io
from functools import cached_property
from typing import Any, Optional, Tuple, Union
@@ -53,6 +54,11 @@ class PolarsTableManagerFactory(TableManagerFactory):
def schema(self) -> dict[str, pl.DataType]:
return self._original_data.schema
+ def to_arrow_ipc(self) -> bytes:
+ out = io.BytesIO()
+ self.collect().write_ipc(out)
+ return out.getvalue()
+
# We override narwhals's to_csv to handle polars
# nested data types.
def to_csv(
diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.py
index a25be9243f..5e27e5b9e5 100644
--- a/marimo/_plugins/ui/_impl/tables/table_manager.py
+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py
@@ -83,6 +83,9 @@ class TableManager(abc.ABC, Generic[T]):
) -> bytes:
pass
+ def to_arrow_ipc(self) -> bytes:
+ raise NotImplementedError("Arrow format not supported")
+
@abc.abstractmethod
def to_json(self) -> bytes:
pass
diff --git a/marimo/_smoke_tests/altair/binary_values.py b/marimo/_smoke_tests/altair/binary_values.py
new file mode 100644
index 0000000000..ee80c98e81
--- /dev/null
+++ b/marimo/_smoke_tests/altair/binary_values.py
@@ -0,0 +1,84 @@
+import marimo
+
+__generated_with = "0.11.8"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+ import altair as alt
+ import pandas as pd
+ import polars as pl
+
+ df = pd.DataFrame(
+ {
+ "state": ["000", "010", "100", "111"],
+ "count": [1, 2, 3, 4],
+ "date": ["2023-01-01", "2023-01-02", "2023-01-03", "2023-01-04"],
+ }
+ )
+ pl_df = pl.DataFrame(df)
+
+ pd_chart = (
+ alt.Chart(df)
+ .mark_line()
+ .encode(x="state:O", y="date:T")
+ .properties(width=200)
+ )
+ pl_chart = (
+ alt.Chart(pl_df)
+ .mark_line()
+ .encode(x="state:O", y="date:T")
+ .properties(width=200)
+ )
+
+
+ mo.hstack([pd_chart, pl_chart])
+ return alt, df, mo, pd, pd_chart, pl, pl_chart, pl_df
+
+
+def _(alt, mo, pd_chart, pl_chart):
+ with alt.data_transformers.enable("marimo_csv"):
+ mo.output.append(mo.hstack([pd_chart, pl_chart]))
+ return
+
+
+def _(alt, mo, pd_chart, pl_chart):
+ with alt.data_transformers.enable("marimo_json"):
+ mo.output.append(mo.hstack([pd_chart, pl_chart]))
+ return
+
+
+def _(alt, mo, pd_chart, pl_chart):
+ with alt.data_transformers.enable("marimo_inline_csv"):
+ mo.output.append(mo.hstack([pd_chart, pl_chart]))
+ return
+
+
+def _(alt, mo, pd_chart, pl_chart):
+ with alt.data_transformers.enable("marimo"):
+ mo.output.append(mo.hstack([pd_chart, pl_chart]))
+ return
+
+
+def _(alt, mo, pd_chart, pl_chart):
+ # This currently errors since Altair does internal validation, and 'arrow' is not a supported "type"
+ with alt.data_transformers.enable("marimo_arrow"):
+ mo.output.append(mo.hstack([pd_chart, pl_chart]))
+ return
+
+
+def _(mo, pd_chart, pl_chart):
+ mo.hstack([mo.ui.altair_chart(pd_chart), mo.ui.altair_chart(pl_chart)])
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_smoke_tests/altair/map_selection.py b/marimo/_smoke_tests/altair/map_selection.py
index 8d41dd6e29..0f6ffcedb2 100644
--- a/marimo/_smoke_tests/altair/map_selection.py
+++ b/marimo/_smoke_tests/altair/map_selection.py
@@ -1,6 +1,6 @@
import marimo
-__generated_with = "0.10.17"
+__generated_with = "0.11.8"
app = marimo.App(width="columns")
@@ -147,7 +147,7 @@ def _():
@app.cell(column=2)
def _(mo):
- mo.md("""## Example 2: """)
+ mo.md("""## Example 2:""")
return
diff --git a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py b/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
index a48f2d0dc4..6a4b046580 100644
--- a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
+++ b/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
@@ -12,6 +12,7 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.ui._impl.charts.altair_transformer import (
_data_to_csv_string,
_data_to_json_string,
+ _to_marimo_arrow,
_to_marimo_csv,
_to_marimo_inline_csv,
_to_marimo_json,
@@ -223,7 +224,7 @@ def test_data_to_csv_string_with_different_dtypes(df: IntoDataFrame):
def test_register_transformers(mock_data_transformers: MagicMock):
register_transformers()
- assert mock_data_transformers.register.call_count == 4
+ assert mock_data_transformers.register.call_count == 5
mock_data_transformers.register.assert_any_call("marimo", _to_marimo_csv)
mock_data_transformers.register.assert_any_call(
"marimo_inline_csv", _to_marimo_inline_csv
@@ -234,3 +235,70 @@ def test_register_transformers(mock_data_transformers: MagicMock):
mock_data_transformers.register.assert_any_call(
"marimo_csv", _to_marimo_csv
)
+ mock_data_transformers.register.assert_any_call(
+ "marimo_arrow", _to_marimo_arrow
+ )
+
+
+SUPPORTS_ARROW_IPC = ["pandas", "polars"]
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {"A": [1, 2, 3], "B": ["a", "b", "c"]}, include=SUPPORTS_ARROW_IPC
+ ),
+)
+def test_to_marimo_arrow(df: IntoDataFrame):
+ result = _to_marimo_arrow(df)
+
+ assert isinstance(result, dict)
+ assert "url" in result
+ assert "format" in result
+ print(type(df))
+ assert result["format"] == {"type": "arrow"}
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {"A": [1, 2, 3], "B": ["a", "b", "c"]}, exclude=SUPPORTS_ARROW_IPC
+ ),
+)
+def test_to_marimo_arrow_fallback(df: IntoDataFrame):
+ result = _to_marimo_arrow(df)
+
+ # Should fallback to CSV format
+ assert isinstance(result, dict)
+ assert "url" in result
+ assert "format" in result
+ assert result["format"] == {"type": "csv"}
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+ "df",
+ create_dataframes(
+ {
+ "int": [1, 2, 3],
+ "float": [1.1, 2.2, 3.3],
+ "bool": [True, False, True],
+ "datetime": [
+ datetime.datetime(2023, 1, 1, 1),
+ datetime.datetime(2023, 1, 2, 1),
+ datetime.datetime(2023, 1, 3, 1),
+ ],
+ "category": ["a", "b", "c"],
+ },
+ include=SUPPORTS_ARROW_IPC,
+ ),
+)
+def test_to_marimo_arrow_different_dtypes(df: IntoDataFrame):
+ result = _to_marimo_arrow(df)
+
+ assert isinstance(result, dict)
+ assert "url" in result
+ assert "format" in result
+ assert result["format"] == {"type": "arrow"}
diff --git a/tests/_plugins/ui/_impl/snapshots/parse_spec_duckdb.txt b/tests/_plugins/ui/_impl/snapshots/parse_spec_duckdb.txt
new file mode 100644
index 0000000000..5cc1f539e5
--- /dev/null
+++ b/tests/_plugins/ui/_impl/snapshots/parse_spec_duckdb.txt
@@ -0,0 +1,24 @@
+{
+ "config": {
+ "view": {
+ "continuousWidth": 300,
+ "continuousHeight": 300
+ }
+ },
+ "data": {
+ "url": "data:text/csv;base64,InZhbHVlcyIKMQoyCjMK",
+ "format": {
+ "type": "csv"
+ }
+ },
+ "mark": {
+ "type": "point"
+ },
+ "encoding": {
+ "x": {
+ "field": "values",
+ "type": "quantitative"
+ }
+ },
+ "$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json"
+}
\ No newline at end of file
diff --git a/tests/_plugins/ui/_impl/snapshots/parse_spec_narwhal.txt b/tests/_plugins/ui/_impl/snapshots/parse_spec_narwhal.txt
index 5098349ddb..257f6fbbea 100644
--- a/tests/_plugins/ui/_impl/snapshots/parse_spec_narwhal.txt
+++ b/tests/_plugins/ui/_impl/snapshots/parse_spec_narwhal.txt
@@ -6,9 +6,9 @@
}
},
"data": {
- "url": "data:text/csv;base64,dmFsdWVzCjEKMgozCg==",
+ "url": "_placeholder_",
"format": {
- "type": "csv"
+ "type": "arrow"
}
},
"mark": {
diff --git a/tests/_plugins/ui/_impl/snapshots/parse_spec_pandas.txt b/tests/_plugins/ui/_impl/snapshots/parse_spec_pandas.txt
index 5098349ddb..257f6fbbea 100644
--- a/tests/_plugins/ui/_impl/snapshots/parse_spec_pandas.txt
+++ b/tests/_plugins/ui/_impl/snapshots/parse_spec_pandas.txt
@@ -6,9 +6,9 @@
}
},
"data": {
- "url": "data:text/csv;base64,dmFsdWVzCjEKMgozCg==",
+ "url": "_placeholder_",
"format": {
- "type": "csv"
+ "type": "arrow"
}
},
"mark": {
diff --git a/tests/_plugins/ui/_impl/snapshots/parse_spec_polars.txt b/tests/_plugins/ui/_impl/snapshots/parse_spec_polars.txt
new file mode 100644
index 0000000000..257f6fbbea
--- /dev/null
+++ b/tests/_plugins/ui/_impl/snapshots/parse_spec_polars.txt
@@ -0,0 +1,24 @@
+{
+ "config": {
+ "view": {
+ "continuousWidth": 300,
+ "continuousHeight": 300
+ }
+ },
+ "data": {
+ "url": "_placeholder_",
+ "format": {
+ "type": "arrow"
+ }
+ },
+ "mark": {
+ "type": "point"
+ },
+ "encoding": {
+ "x": {
+ "field": "values",
+ "type": "quantitative"
+ }
+ },
+ "$schema": "https://vega.github.io/schema/vega-lite/v5.20.1.json"
+}
\ No newline at end of file
diff --git a/tests/_plugins/ui/_impl/test_altair_chart.py b/tests/_plugins/ui/_impl/test_altair_chart.py
index eed1456063..681864df1b 100644
--- a/tests/_plugins/ui/_impl/test_altair_chart.py
+++ b/tests/_plugins/ui/_impl/test_altair_chart.py
@@ -38,6 +38,8 @@ HAS_DEPS = (
and DependencyManager.altair.has()
# altair produces different output on windows
and sys.platform != "win32"
+ # skip 3.9
+ and sys.version_info >= (3, 10)
)
if HAS_DEPS:
@@ -659,6 +661,8 @@ def test_parse_spec_pandas() -> None:
data = pd.DataFrame({"values": [1, 2, 3]})
chart = alt.Chart(data).mark_point().encode(x="values:Q")
spec = _parse_spec(chart)
+ # Replace data.url with a placeholder
+ spec["data"]["url"] = "_placeholder_"
snapshot("parse_spec_pandas.txt", json.dumps(spec, indent=2))
@@ -669,9 +673,38 @@ def test_parse_spec_narwhal() -> None:
data = nw.from_native(pd.DataFrame({"values": [1, 2, 3]}))
chart = alt.Chart(data).mark_point().encode(x="values:Q")
spec = _parse_spec(chart)
+ # Replace data.url with a placeholder
+ spec["data"]["url"] = "_placeholder_"
snapshot("parse_spec_narwhal.txt", json.dumps(spec, indent=2))
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_parse_spec_polars() -> None:
+ import altair as alt
+ import polars as pl
+
+ data = pl.DataFrame({"values": [1, 2, 3]})
+ chart = alt.Chart(data).mark_point().encode(x="values:Q")
+ spec = _parse_spec(chart)
+ # Replace data.url with a placeholder
+ spec["data"]["url"] = "_placeholder_"
+ snapshot("parse_spec_polars.txt", json.dumps(spec, indent=2))
+
+
+ not HAS_DEPS or not DependencyManager.duckdb.has(),
+ reason="optional dependencies not installed",
+)
+def test_parse_spec_duckdb() -> None:
+ import altair as alt
+ import duckdb
+
+ data = duckdb.from_df(pd.DataFrame({"values": [1, 2, 3]}))
+ chart = alt.Chart(data).mark_point().encode(x="values:Q")
+ spec = _parse_spec(chart)
+ snapshot("parse_spec_duckdb.txt", json.dumps(spec, indent=2))
+
+
@pytest.mark.skipif(
not HAS_DEPS or not DependencyManager.geopandas.has(),
reason="optional dependencies not installed",