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: render dotted chart columns when data falls back to CSV (#10856)

Shahmir Varqha49b7b059d83b
diff --git a/frontend/src/components/data-table/charts/__tests__/chart-panel.test.tsx b/frontend/src/components/data-table/charts/__tests__/chart-panel.test.tsx
new file mode 100644
index 0000000000..32ac53d446
--- /dev/null
+++ b/frontend/src/components/data-table/charts/__tests__/chart-panel.test.tsx
@@ -0,0 +1,286 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { fireEvent, render, waitFor } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import { Tooltip } from "radix-ui";
+import type { ComponentProps } from "react";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+import { SetupMocks } from "@/__mocks__/common";
+import { cellId } from "@/__tests__/branded";
+import { LazyVegaEmbed } from "@/components/charts/lazy";
+import { vegaLoader } from "@/plugins/impl/vega/loader";
+import { ChartPanel, TablePanel, type TablePanelProps } from "../charts";
+import { getChartTabName, tabsStorageAtom } from "../storage";
+import { ChartType, NONE_VALUE } from "../types";
+
+vi.mock("@/components/charts/lazy", () => ({
+ LazyVegaEmbed: vi.fn(() => null),
+}));
+
+beforeAll(() => {
+ SetupMocks.resizeObserver();
+});
+
+describe("ChartPanel", () => {
+ it.each([undefined, null, []] as const)(
+ "infers the full CSV through TablePanel without backend metadata (%s)",
+ async (fieldTypes) => {
+ vi.spyOn(vegaLoader, "load").mockResolvedValue(
+ "value,index\n,0\n2.5,1\n",
+ );
+ const store = createStore();
+ const id = cellId("csv-inference");
+ const tabName = getChartTabName(0, ChartType.BAR);
+ store.set(
+ tabsStorageAtom,
+ new Map([
+ [
+ id,
+ [
+ {
+ tabName,
+ chartType: ChartType.BAR,
+ config: {
+ general: {
+ xColumn: { field: "value", type: "number" },
+ yColumn: {
+ field: "index",
+ type: "integer",
+ aggregate: NONE_VALUE,
+ },
+ },
+ },
+ },
+ ],
+ ],
+ ]),
+ );
+ const sample = [{ value: null }];
+ const SampleTable = (_props: { data: typeof sample }) => null;
+ const props: TablePanelProps = {
+ cellId: id,
+ data: sample,
+ dataTable: <SampleTable data={sample} />,
+ totalRows: 2,
+ columns: 1,
+ displayHeader: true,
+ fieldTypes: fieldTypes == null ? fieldTypes : [...fieldTypes],
+ rowHeaders: [["index", ["integer", "int64"]]],
+ getDataUrl: vi
+ .fn()
+ .mockResolvedValue({ data_url: "chart.csv", format: "csv" }),
+ };
+ const { getByRole } = render(
+ <Provider store={store}>
+ <Tooltip.Provider>
+ <TablePanel {...props} />
+ </Tooltip.Provider>
+ </Provider>,
+ );
+ fireEvent.click(getByRole("tab", { name: tabName }));
+ await waitFor(() => {
+ expect(vi.mocked(LazyVegaEmbed).mock.lastCall?.[0].spec).toEqual(
+ expect.objectContaining({
+ data: {
+ values: [
+ { value: null, index: 0 },
+ { value: 2.5, index: 1 },
+ ],
+ },
+ }),
+ );
+ });
+ },
+ );
+
+ it("reloads CSV only when column types change, not their array identity", async () => {
+ vi.spyOn(vegaLoader, "load").mockResolvedValue("value\n001\n");
+ const getDataUrl = vi.fn().mockResolvedValue({
+ data_url: "chart.csv",
+ format: "csv",
+ });
+ const props: ComponentProps<typeof ChartPanel> = {
+ tableData: [{ value: "001" }],
+ chartConfig: {
+ general: {
+ xColumn: { field: "value", type: "string" },
+ yColumn: { field: "value", type: "integer", aggregate: NONE_VALUE },
+ },
+ },
+ chartType: ChartType.BAR,
+ saveChart: vi.fn(),
+ saveChartType: vi.fn(),
+ getDataUrl,
+ isLargeDataset: false,
+ };
+ const panel = (
+ fieldTypes: ComponentProps<typeof ChartPanel>["fieldTypes"],
+ ) => (
+ <Tooltip.Provider>
+ <ChartPanel {...props} fieldTypes={fieldTypes} />
+ </Tooltip.Provider>
+ );
+ const expectValues = async (value: string | number) => {
+ await waitFor(() => {
+ expect(vi.mocked(LazyVegaEmbed).mock.lastCall?.[0].spec).toEqual(
+ expect.objectContaining({ data: { values: [{ value }] } }),
+ );
+ });
+ };
+
+ const { rerender } = render(panel([["value", ["string", "object"]]]));
+ await expectValues("001");
+ expect(getDataUrl).toHaveBeenCalledTimes(1);
+
+ rerender(panel([["value", ["string", "object"]]]));
+ await expectValues("001");
+ expect(getDataUrl).toHaveBeenCalledTimes(1);
+
+ rerender(panel([["value", ["integer", "int64"]]]));
+ await expectValues(1);
+ expect(getDataUrl).toHaveBeenCalledTimes(2);
+ });
+
+ it("uses column types to parse numeric CSV values without coercing text", async () => {
+ vi.spyOn(vegaLoader, "load").mockResolvedValue(
+ "a.b,n,label,day,timestamp,active,duration\ninf,1,inf,2024-01-01,2024-01-01T12:00:00Z,True,1 days\n-inf,2,001,2024-01-02,2024-01-02T12:00:00Z,False,2 days\n2.5,3,2024-01-03,2024-01-03,2024-01-03T12:00:00Z,True,3 days\n,4,,,,,\n",
+ );
+
+ render(
+ <Tooltip.Provider>
+ <ChartPanel
+ tableData={[{ "a.b": 1, n: 1 }]}
+ chartConfig={{
+ general: {
+ xColumn: { field: "a.b", type: "number" },
+ yColumn: { field: "n", type: "integer", aggregate: NONE_VALUE },
+ },
+ }}
+ chartType={ChartType.BAR}
+ saveChart={vi.fn()}
+ saveChartType={vi.fn()}
+ getDataUrl={vi.fn().mockResolvedValue({
+ data_url: "chart.csv",
+ format: "csv",
+ })}
+ fieldTypes={[
+ ["a.b", ["number", "float64"]],
+ ["n", ["integer", "int64"]],
+ ["label", ["string", "object"]],
+ ["day", ["date", "date"]],
+ ["timestamp", ["datetime", "datetime64[ns]"]],
+ ["active", ["boolean", "bool"]],
+ ["duration", ["unknown", "timedelta64[ns]"]],
+ ]}
+ isLargeDataset={false}
+ />
+ </Tooltip.Provider>,
+ );
+
+ await waitFor(() => {
+ expect(vi.mocked(LazyVegaEmbed).mock.lastCall?.[0].spec).toEqual(
+ expect.objectContaining({
+ data: {
+ values: [
+ {
+ "a.b": Infinity,
+ n: 1,
+ label: "inf",
+ day: new Date("2024-01-01"),
+ timestamp: new Date("2024-01-01T12:00:00Z"),
+ active: true,
+ duration: "1 days",
+ },
+ {
+ "a.b": -Infinity,
+ n: 2,
+ label: "001",
+ day: new Date("2024-01-02"),
+ timestamp: new Date("2024-01-02T12:00:00Z"),
+ active: false,
+ duration: "2 days",
+ },
+ {
+ "a.b": 2.5,
+ n: 3,
+ label: "2024-01-03",
+ day: new Date("2024-01-03"),
+ timestamp: new Date("2024-01-03T12:00:00Z"),
+ active: true,
+ duration: "3 days",
+ },
+ {
+ "a.b": null,
+ n: 4,
+ label: null,
+ day: "",
+ timestamp: "",
+ active: null,
+ duration: "",
+ },
+ ],
+ },
+ }),
+ );
+ });
+ });
+
+ it.each([true, false])(
+ "keeps dotted CSV columns aligned with the chart encodings (schema: %s)",
+ async (hasSchema) => {
+ vi.spyOn(vegaLoader, "load").mockResolvedValue("a.b,n\n1,1\n2,2\n3,3\n");
+
+ render(
+ <Tooltip.Provider>
+ <ChartPanel
+ tableData={[{ "a.b": 1, n: 1 }]}
+ chartConfig={{
+ general: {
+ xColumn: { field: "a.b", type: "number" },
+ yColumn: {
+ field: "n",
+ type: "number",
+ aggregate: NONE_VALUE,
+ },
+ },
+ }}
+ chartType={ChartType.BAR}
+ saveChart={vi.fn()}
+ saveChartType={vi.fn()}
+ getDataUrl={vi.fn().mockResolvedValue({
+ data_url: "chart.csv",
+ format: "csv",
+ })}
+ fieldTypes={
+ hasSchema
+ ? [
+ ["a.b", ["number", "float64"]],
+ ["n", ["integer", "int64"]],
+ ]
+ : undefined
+ }
+ isLargeDataset={false}
+ />
+ </Tooltip.Provider>,
+ );
+
+ await waitFor(() => {
+ expect(vi.mocked(LazyVegaEmbed).mock.lastCall?.[0].spec).toEqual(
+ expect.objectContaining({
+ data: {
+ values: [
+ { "a.b": 1, n: 1 },
+ { "a.b": 2, n: 2 },
+ { "a.b": 3, n: 3 },
+ ],
+ },
+ encoding: expect.objectContaining({
+ x: expect.objectContaining({ field: "a\\.b" }),
+ y: expect.objectContaining({ field: "n" }),
+ }),
+ }),
+ );
+ });
+ },
+ );
+});
diff --git a/frontend/src/components/data-table/charts/charts.tsx b/frontend/src/components/data-table/charts/charts.tsx
index 545fa1481d..2a878d73e1 100644
--- a/frontend/src/components/data-table/charts/charts.tsx
+++ b/frontend/src/components/data-table/charts/charts.tsx
@@ -23,9 +23,11 @@ import { Form } from "@/components/ui/form";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import type { CellId } from "@/core/cells/ids";
import { useAsyncData } from "@/hooks/useAsyncData";
+import { useDeepCompareMemoize } from "@/hooks/useDeepCompareMemoize";
import { useDebouncedCallback } from "@/hooks/useDebounce";
import type { GetDataUrl } from "@/plugins/impl/DataTablePlugin";
import { vegaLoadData } from "@/plugins/impl/vega/loader";
+import { getVegaFieldTypes } from "@/plugins/impl/vega/utils";
import { useTheme } from "@/theme/useTheme";
import { uniqueBy } from "@/utils/arrays";
import { inferFieldTypes } from "../columns";
@@ -284,6 +286,7 @@ export const TablePanel: React.FC<TablePanelProps> = ({
saveChart={saveChart}
saveChartType={saveChartType}
getDataUrl={getDataUrl}
+ hasSchema={Boolean(fieldTypes?.length)}
fieldTypes={mergeIndexFields(
fieldTypes ?? inferFieldTypes(dataTable.props.data),
rowHeaders,
@@ -307,6 +310,7 @@ export const ChartPanel: React.FC<{
saveChartType: (chartType: ChartType) => void;
getDataUrl?: GetDataUrl;
fieldTypes?: FieldTypesWithExternalType | null;
+ hasSchema?: boolean;
isLargeDataset: boolean;
}> = ({
tableData,
@@ -316,6 +320,7 @@ export const ChartPanel: React.FC<{
saveChartType,
getDataUrl,
fieldTypes,
+ hasSchema = Boolean(fieldTypes?.length),
isLargeDataset,
}) => {
const { theme } = useTheme();
@@ -331,6 +336,8 @@ export const ChartPanel: React.FC<{
const [renderLargeCharts, setRenderLargeCharts] = useState(!isLargeDataset);
const { ref: chartContainerRef } = useResizeObserver();
+ // Sample-inferred types are useful for controls, but not full CSV parsing.
+ const csvFieldTypes = useDeepCompareMemoize(hasSchema ? fieldTypes : null);
const { data, isPending, error } = useAsyncData(async () => {
if (!getDataUrl || tableData.length === 0 || !renderLargeCharts) {
@@ -342,20 +349,26 @@ export const ChartPanel: React.FC<{
return response.data_url;
}
- const chartData = await vegaLoadData(
- response.data_url,
- response.format === "arrow"
- ? { type: "arrow" }
- : response.format === "json"
- ? { type: "json" }
- : { type: "csv", parse: "auto" },
- {
- replacePeriod: true,
- },
- );
- return chartData;
+ let format: Parameters<typeof vegaLoadData>[1];
+ if (response.format === "arrow") {
+ format = { type: "arrow" };
+ } else if (response.format === "json") {
+ format = { type: "json" };
+ } else {
+ format = {
+ type: "csv",
+ parse: getVegaFieldTypes(
+ csvFieldTypes &&
+ Object.fromEntries(
+ csvFieldTypes.map(([name, [type]]) => [name, type]),
+ ),
+ { parseDates: true },
+ ),
+ };
+ }
+ return vegaLoadData(response.data_url, format);
// Re-run when the data table changes
- }, [tableData, renderLargeCharts]);
+ }, [tableData, renderLargeCharts, csvFieldTypes]);
const formValues = form.watch();
diff --git a/frontend/src/plugins/impl/vega/__tests__/utils.test.ts b/frontend/src/plugins/impl/vega/__tests__/utils.test.ts
index 7764fdaa79..8e2565e006 100644
--- a/frontend/src/plugins/impl/vega/__tests__/utils.test.ts
+++ b/frontend/src/plugins/impl/vega/__tests__/utils.test.ts
@@ -1,7 +1,22 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { describe, expect, it } from "vitest";
-import { getContainerWidth } from "../utils";
+import { getContainerWidth, getVegaFieldTypes } from "../utils";
+
+describe("getVegaFieldTypes", () => {
+ it("preserves date strings unless the caller requests date parsing", () => {
+ expect(getVegaFieldTypes({ day: "date", timestamp: "datetime" })).toEqual({
+ day: "string",
+ timestamp: "date",
+ });
+ expect(
+ getVegaFieldTypes(
+ { day: "date", timestamp: "datetime" },
+ { parseDates: true },
+ ),
+ ).toEqual({ day: "date", timestamp: "date" });
+ });
+});
describe("getContainerWidth", () => {
it('should return "container" when spec width is "container"', () => {
diff --git a/frontend/src/plugins/impl/vega/__tests__/vega.test.ts b/frontend/src/plugins/impl/vega/__tests__/vega.test.ts
index c3724e436d..154bb23481 100644
--- a/frontend/src/plugins/impl/vega/__tests__/vega.test.ts
+++ b/frontend/src/plugins/impl/vega/__tests__/vega.test.ts
@@ -13,6 +13,43 @@ const { ZERO_WIDTH_SPACE, replacePeriodsInColumnNames, uniquifyColumnNames } =
exportedForTesting;
describe("vega loader", () => {
+ it("parses infinities only in explicitly numeric CSV fields", async () => {
+ vi.spyOn(vegaLoader, "load").mockResolvedValue(
+ "value,label,id\ninf,inf,1\n-inf,-inf,2\n+inf,+inf,3\n2.5,002.5,4\n,,5\nNaN,NaN,6\n",
+ );
+
+ const data = await vegaLoadData("chart.csv", {
+ type: "csv",
+ parse: { value: "number", label: "string", id: "integer" },
+ });
+
+ expect(data).toEqual([
+ { value: Infinity, label: "inf", id: 1 },
+ { value: -Infinity, label: "-inf", id: 2 },
+ { value: Infinity, label: "+inf", id: 3 },
+ { value: 2.5, label: "002.5", id: 4 },
+ { value: null, label: null, id: 5 },
+ { value: Number.NaN, label: "NaN", id: 6 },
+ ]);
+ });
+
+ it("preserves the table's large integer and infinity handling", async () => {
+ vi.spyOn(vegaLoader, "load").mockResolvedValue(
+ "id,value\n9007199254740993,inf\n9007199254740995,-inf\n",
+ );
+
+ const data = await vegaLoadData(
+ "table.csv",
+ { type: "csv", parse: { id: "integer", value: "number" } },
+ { handleBigIntAndNumberLike: true },
+ );
+
+ expect(data).toEqual([
+ { id: BigInt("9007199254740993"), value: "inf" },
+ { id: BigInt("9007199254740995"), value: "-inf" },
+ ]);
+ });
+
it("should parse csv data with dates", async () => {
const csvData = `
active,username,id
diff --git a/frontend/src/plugins/impl/vega/loader.ts b/frontend/src/plugins/impl/vega/loader.ts
index 538c2b2cfe..df5aaabace 100644
--- a/frontend/src/plugins/impl/vega/loader.ts
+++ b/frontend/src/plugins/impl/vega/loader.ts
@@ -16,6 +16,26 @@ const previousNumberParser = typeParsers.number;
const previousDateParser = typeParsers.date;
const previousBooleanParser = typeParsers.boolean;
+const NUMBER_MIDDLEWARE: Middleware = () => {
+ const parseNumber = (value: string) => {
+ if (value === "inf" || value === "+inf") {
+ return Number.POSITIVE_INFINITY;
+ }
+ if (value === "-inf") {
+ return Number.NEGATIVE_INFINITY;
+ }
+ return previousNumberParser(value);
+ };
+
+ typeParsers.integer = parseNumber;
+ typeParsers.number = parseNumber;
+
+ return () => {
+ typeParsers.integer = previousIntegerParser;
+ typeParsers.number = previousNumberParser;
+ };
+};
+
const BIG_INT_MIDDLEWARE: Middleware = () => {
// Custom parser to:
// - handle BigInt
@@ -159,6 +179,8 @@ export async function vegaLoadData<T = object>(
const middleware: Middleware[] = [DATE_MIDDLEWARE];
if (handleBigIntAndNumberLike) {
middleware.push(BIG_INT_MIDDLEWARE);
+ } else {
+ middleware.push(NUMBER_MIDDLEWARE);
}
let unsubscribes: Unsubscribe[] = [];
@@ -216,7 +238,7 @@ export async function vegaLoadData<T = object>(
// Apply middleware
unsubscribes = middleware.map((m) => m());
- // Always set parse to auto for csv data, to be able to parse dates and floats
+ // CSV defaults to inference when no explicit column types are available.
const results = isCsv
? // csv -> json
read(csvOrJsonData, {
diff --git a/frontend/src/plugins/impl/vega/utils.ts b/frontend/src/plugins/impl/vega/utils.ts
index cc9d087fb9..7892d0cfa9 100644
--- a/frontend/src/plugins/impl/vega/utils.ts
+++ b/frontend/src/plugins/impl/vega/utils.ts
@@ -45,21 +45,22 @@ function toArray<T>(value: T | T[] | undefined): T[] {
export function getVegaFieldTypes(
types: Record<string, DataType> | undefined | null,
+ { parseDates = false }: { parseDates?: boolean } = {},
): FieldTypes | "auto" {
if (!types || Object.keys(types).length === 0) {
// If fieldTypes is provided, use it to parse the data
// Otherwise, infer the data types
return "auto";
}
- // Convert all 'date' to 'string', because dates don't format back to
- // the correct formatting. For example, a date like '2024-01-01' will
- // be formatted to '2024-01-01T00:00:00.000Z'.
+ // Preserve date-only strings for callers such as the data editor.
+ // Parsing creates Date objects that JSON serializes as full timestamps.
+ // Charts opt into date parsing for temporal axes.
return Objects.mapValues(types, (type): VegaDataType => {
if (type === "geometry") {
return "string";
}
if (type === "date") {
- return "string";
+ return parseDates ? "date" : "string";
}
if (type === "time") {
return "string";
diff --git a/marimo/_plugins/ui/_impl/charts/altair_transformer.py b/marimo/_plugins/ui/_impl/charts/altair_transformer.py
index 000b053f3b..7384f395c5 100644
--- a/marimo/_plugins/ui/_impl/charts/altair_transformer.py
+++ b/marimo/_plugins/ui/_impl/charts/altair_transformer.py
@@ -74,17 +74,23 @@ def _to_marimo_arrow(data: Data, **kwargs: Any) -> _TransformResult:
"""
del kwargs
data = _maybe_sanitize_dataframe(data)
+ manager = get_table_manager(data)
try:
- data_arrow = get_table_manager(data).to_arrow_ipc()
+ data_arrow = manager.to_arrow_ipc()
except NotImplementedError:
- return _to_marimo_csv(data)
+ pass
except Exception as e:
LOGGER.warning(
f"Failed to convert data to arrow format, falling back to CSV: {e}"
)
- return _to_marimo_csv(data)
- virtual_file = mo_data.arrow(data_arrow)
- return {"url": virtual_file.url, "format": {"type": "arrow"}}
+ else:
+ virtual_file = mo_data.arrow(data_arrow)
+ return {"url": virtual_file.url, "format": {"type": "arrow"}}
+
+ # Retrying sanitization on a native frame can raise for unsupported dtypes.
+ data_csv = manager.to_csv_str()
+ virtual_file = mo_data.csv(data_csv.encode("utf-8"))
+ return {"url": virtual_file.url, "format": {"type": "csv"}}
def _to_marimo_inline_csv(data: Data, **kwargs: Any) -> _TransformResult:
@@ -151,7 +157,7 @@ def _maybe_sanitize_dataframe(data: Any) -> Any:
return res.to_native() # type: ignore[return-value]
except Exception as e:
LOGGER.warning(f"Failed to sanitize narwhals dataframe: {e}")
- return data
+ return narwhals_data.to_native()
return data
diff --git a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py b/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
index 31fbdb0ed5..70fb55a299 100644
--- a/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
+++ b/tests/_plugins/ui/_impl/charts/test_altair_transformers.py
@@ -184,6 +184,36 @@ def test_data_to_json_string_with_special_characters(
assert parsed[2]["B"] == "e\nf" or parsed[2]["B"] == "ef"
+ not HAS_DEPS or not DependencyManager.pyarrow.has(),
+ reason="optional dependencies not installed",
+)
[email protected]("error", [ValueError, NotImplementedError])
+def test_to_marimo_arrow_with_duration_export_failure(error: type[Exception]):
+ import narwhals.stable.v2 as nw
+ import pandas as pd
+
+ df = pd.DataFrame({"a.b": [1.0, 2.0, 3.0], "n": [1, 2, 3]})
+ df["d"] = pd.to_timedelta([1, 2, 3], unit="D")
+
+ with (
+ patch(
+ "marimo._plugins.ui._impl.tables.pandas_table._dataframe_to_arrow_ipc",
+ side_effect=error("Arrow export failed"),
+ ),
+ patch(
+ "marimo._plugins.ui._impl.charts.altair_transformer.mo_data.csv"
+ ) as export_csv,
+ ):
+ export_csv.return_value.url = "test.csv"
+ result = _to_marimo_arrow(nw.from_native(df))
+
+ assert result == {"url": "test.csv", "format": {"type": "csv"}}
+ export_csv.assert_called_once_with(
+ b"a.b,n,d\n1.0,1,1 days\n2.0,2,2 days\n3.0,3,3 days\n"
+ )
+
+
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
@pytest.mark.parametrize(
"df",
@@ -293,6 +323,79 @@ def test_to_marimo_arrow_fallback(df: IntoDataFrame):
assert result["format"] == {"type": "csv"}
+ not HAS_DEPS or not DependencyManager.pyarrow.has(),
+ reason="optional dependencies not installed",
+)
+def test_to_marimo_arrow_with_duration():
+ import narwhals.stable.v2 as nw
+ import pandas as pd
+ import pyarrow as pa
+
+ df = pd.DataFrame({"a.b": [1.0, 2.0, 3.0], "n": [1, 2, 3]})
+ df["d"] = pd.to_timedelta([1, 2, 3], unit="D")
+
+ with patch(
+ "marimo._plugins.ui._impl.charts.altair_transformer.mo_data.arrow"
+ ) as export_arrow:
+ result = _to_marimo_arrow(nw.from_native(df))
+
+ assert result["format"] == {"type": "arrow"}
+ export_arrow.assert_called_once()
+ exported = pa.ipc.open_file(export_arrow.call_args.args[0]).read_all()
+ pd.testing.assert_frame_equal(exported.to_pandas(), df)
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_to_marimo_arrow_with_duration_without_pyarrow():
+ import narwhals.stable.v2 as nw
+ import pandas as pd
+
+ df = pd.DataFrame({"a.b": [1.0, 2.0, 3.0], "n": [1, 2, 3]})
+ df["d"] = pd.to_timedelta([1, 2, 3], unit="D")
+ wrapped = nw.from_native(df)
+
+ with (
+ patch.dict(sys.modules, {"pyarrow": None}),
+ patch(
+ "marimo._plugins.ui._impl.charts.altair_transformer.mo_data.csv"
+ ) as export_csv,
+ ):
+ export_csv.return_value.url = "test.csv"
+ result = _to_marimo_arrow(wrapped)
+
+ assert result == {"url": "test.csv", "format": {"type": "csv"}}
+ export_csv.assert_called_once_with(
+ b"a.b,n,d\n1.0,1,1 days\n2.0,2,2 days\n3.0,3,3 days\n"
+ )
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+def test_to_marimo_arrow_csv_fallback_preserves_infinities():
+ import narwhals.stable.v2 as nw
+ import pandas as pd
+
+ df = nw.from_native(
+ pd.DataFrame(
+ {
+ "a.b": [1.0, float("inf"), float("-inf"), None],
+ "n": [1, 2, 3, 4],
+ }
+ )
+ )
+ with (
+ patch.dict(sys.modules, {"pyarrow": None}),
+ patch(
+ "marimo._plugins.ui._impl.charts.altair_transformer.mo_data.csv"
+ ) as export_csv,
+ ):
+ export_csv.return_value.url = "test.csv"
+ result = _to_marimo_arrow(df)
+
+ assert result == {"url": "test.csv", "format": {"type": "csv"}}
+ export_csv.assert_called_once_with(b"a.b,n\n1.0,1\ninf,2\n-inf,3\n,4\n")
+
+
@pytest.mark.skipif(not HAS_DEPS, reason="optional dependencies not installed")
@pytest.mark.parametrize(
"df",