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: altair data deserialization (#2703)

Myles Scolnickc423d5188e1d
diff --git a/frontend/package.json b/frontend/package.json
index 638fbd313c..381ba7c812 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -135,7 +135,7 @@
"timestring": "^7.0.0",
"typescript-memoize": "^1.1.1",
"use-resize-observer": "^9.1.0",
- "vega-lite": "^5.20.1",
+ "vega-lite": "^5.21.0",
"vega-loader": "^4.5.2",
"vscode-languageserver-protocol": "^3.17.5",
"web-vitals": "^4.2.3",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index db4b2b34a6..f384406779 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -347,7 +347,7 @@ importers:
version: 0.9.6([email protected])
react-vega:
specifier: ^7.6.0
react-virtuoso:
specifier: ^4.10.1
@@ -382,8 +382,8 @@ importers:
specifier: ^9.1.0
vega-lite:
- specifier: ^5.20.1
- version: 5.20.1([email protected])
+ specifier: ^5.21.0
+ version: 5.21.0([email protected])
vega-loader:
specifier: ^4.5.2
version: 4.5.2
@@ -8082,8 +8082,8 @@ packages:
peerDependencies:
vega: ^5.4.0
- resolution: {integrity: sha512-rpw6aT3NXR4bIdctPpK/V+FZAt1VNHMEnfF/TxaZDc4PDOzfYXiYOFf0zOMURUq/EyzFCkhBvtkf1MzmqlAz9g==}
+ resolution: {integrity: sha512-hNxM9nuMqpI1vkUOhEx6ewEf23WWLmJxSFJ4TA86AW43ixJyqcLV+iSCO0NipuVTE0rlDcc2e8joSewWyOlEwA==}
engines: {node: '>=18'}
hasBin: true
peerDependencies:
@@ -16432,15 +16432,15 @@ snapshots:
dependencies:
react: 18.3.1
dependencies:
'@types/react': 18.3.7
fast-deep-equal: 3.1.3
prop-types: 15.8.1
react: 18.3.1
vega: 5.30.0
- vega-lite: 5.20.1([email protected])
+ vega-lite: 5.21.0([email protected])
dependencies:
@@ -17653,7 +17653,7 @@ snapshots:
transitivePeerDependencies:
- encoding
dependencies:
fast-json-patch: 3.1.1
json-stringify-pretty-compact: 3.0.0
@@ -17661,9 +17661,9 @@ snapshots:
tslib: 2.7.0
vega: 5.30.0
vega-interpreter: 1.0.5
- vega-lite: 5.20.1([email protected])
+ vega-lite: 5.21.0([email protected])
vega-schema-url-parser: 2.2.0
vega-tooltip: 0.33.0
@@ -17769,7 +17769,7 @@ snapshots:
vega-util: 1.10.0
yargs: 13.3.2
dependencies:
json-stringify-pretty-compact: 3.0.0
tslib: 2.6.3
@@ -17853,10 +17853,10 @@ snapshots:
dependencies:
d3-array: 3.2.4
dependencies:
vega: 5.30.0
- vega-lite: 5.20.1([email protected])
+ vega-lite: 5.21.0([email protected])
dependencies:
diff --git a/frontend/src/plugins/impl/vega/__tests__/vega.test.ts b/frontend/src/plugins/impl/vega/__tests__/vega.test.ts
index 64131a45ee..9a8ad7be61 100644
--- a/frontend/src/plugins/impl/vega/__tests__/vega.test.ts
+++ b/frontend/src/plugins/impl/vega/__tests__/vega.test.ts
@@ -1,6 +1,11 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { describe, expect, it, vi } from "vitest";
-import { vegaLoadData, vegaLoader, exportedForTesting } from "../loader";
+import {
+ vegaLoadData,
+ vegaLoader,
+ exportedForTesting,
+ parseCsvData,
+} from "../loader";
const { ZERO_WIDTH_SPACE, replacePeriodsInColumnNames, uniquifyColumnNames } =
exportedForTesting;
@@ -151,6 +156,191 @@ yield_error,yield_center
]
`);
});
+
+ it("should parse csv data with boolean values", async () => {
+ const csvData = `
+is_active,username
+True,user1
+False,user2
+true,user3
+false,user4
+`.trim();
+
+ vi.spyOn(vegaLoader, "load").mockReturnValue(Promise.resolve(csvData));
+
+ const data = await vegaLoadData(csvData, { type: "csv", parse: "auto" });
+
+ expect(data).toMatchInlineSnapshot(`
+ [
+ {
+ "is_active": "True",
+ "username": "user1",
+ },
+ {
+ "is_active": "False",
+ "username": "user2",
+ },
+ {
+ "is_active": "true",
+ "username": "user3",
+ },
+ {
+ "is_active": "false",
+ "username": "user4",
+ },
+ ]
+ `);
+ });
+
+ it("should handle inf and -inf values", async () => {
+ const csvData = `
+value,name
+inf,positive_infinity
+-inf,negative_infinity
+100,regular_number
+`.trim();
+
+ vi.spyOn(vegaLoader, "load").mockReturnValue(Promise.resolve(csvData));
+
+ const data = await vegaLoadData(csvData, { type: "csv", parse: "auto" });
+
+ expect(data).toMatchInlineSnapshot(`
+ [
+ {
+ "name": "positive_infinity",
+ "value": "inf",
+ },
+ {
+ "name": "negative_infinity",
+ "value": "-inf",
+ },
+ {
+ "name": "regular_number",
+ "value": "100",
+ },
+ ]
+ `);
+ });
+
+ it("should handle BigInt values with and without the handleBigInt option", async () => {
+ const csvData = `
+id,name
+9007199254740991,max_safe_integer
+9007199254740992,above_max_safe_integer
+`.trim();
+
+ vi.spyOn(vegaLoader, "load").mockReturnValue(Promise.resolve(csvData));
+
+ const dataWithBigInt = await vegaLoadData(
+ csvData,
+ { type: "csv", parse: "auto" },
+ { handleBigInt: true },
+ );
+
+ expect(dataWithBigInt).toMatchInlineSnapshot(`
+ [
+ {
+ "id": 9007199254740991,
+ "name": "max_safe_integer",
+ },
+ {
+ "id": 9007199254740992n,
+ "name": "above_max_safe_integer",
+ },
+ ]
+ `);
+
+ const dataWithoutBigInt = await vegaLoadData(
+ csvData,
+ { type: "csv", parse: "auto" },
+ { handleBigInt: false },
+ );
+
+ expect(dataWithoutBigInt).toMatchInlineSnapshot(`
+ [
+ {
+ "id": 9007199254740991,
+ "name": "max_safe_integer",
+ },
+ {
+ "id": 9007199254740992,
+ "name": "above_max_safe_integer",
+ },
+ ]
+ `);
+ });
+
+ it("should handle JSON data", async () => {
+ const jsonData = JSON.stringify([
+ { name: "Alice", age: 30 },
+ { name: "Bob", age: 25 },
+ ]);
+
+ vi.spyOn(vegaLoader, "load").mockReturnValue(Promise.resolve(jsonData));
+
+ const data = await vegaLoadData(jsonData, { type: "json" });
+
+ expect(data).toMatchInlineSnapshot(`
+ [
+ {
+ "age": 30,
+ "name": "Alice",
+ },
+ {
+ "age": 25,
+ "name": "Bob",
+ },
+ ]
+ `);
+ });
+
+ it("should handle the replacePeriod option", async () => {
+ const csvData = `
+user.name,user.age
+Alice.Smith,30
+Bob.Jones,25
+`.trim();
+
+ vi.spyOn(vegaLoader, "load").mockReturnValue(Promise.resolve(csvData));
+
+ const dataWithReplacePeriod = await vegaLoadData(
+ csvData,
+ { type: "csv", parse: "auto" },
+ { replacePeriod: true },
+ );
+
+ expect(dataWithReplacePeriod).toMatchInlineSnapshot(`
+ [
+ {
+ "user․age": 30,
+ "user․name": "Alice.Smith",
+ },
+ {
+ "user․age": 25,
+ "user․name": "Bob.Jones",
+ },
+ ]
+ `);
+
+ const dataWithoutReplacePeriod = await vegaLoadData(
+ csvData,
+ { type: "csv", parse: "auto" },
+ { replacePeriod: false },
+ );
+
+ expect(dataWithoutReplacePeriod).toMatchInlineSnapshot(`
+ [
+ {
+ "user.age": 30,
+ "user.name": "Alice.Smith",
+ },
+ {
+ "user.age": 25,
+ "user.name": "Bob.Jones",
+ },
+ ]
+ `);
+ });
});
describe("uniquifyColumnNames", () => {
@@ -233,3 +423,46 @@ describe("replacePeriodsInColumnNames", () => {
expect(result).toBe(expectedResult);
});
});
+
+describe("parseCsvData", () => {
+ it("should parse CSV data with and without handleBigInt option", () => {
+ const csvData = `
+id,name,value
+9007199254740992,big_int,1.5
+100,regular,2.0
+`.trim();
+
+ const dataWithBigInt = parseCsvData(csvData, true);
+ const dataWithoutBigInt = parseCsvData(csvData, false);
+
+ expect(dataWithBigInt).toMatchInlineSnapshot(`
+ [
+ {
+ "id": 9007199254740992n,
+ "name": "big_int",
+ "value": 1.5,
+ },
+ {
+ "id": 100,
+ "name": "regular",
+ "value": 2,
+ },
+ ]
+ `);
+
+ expect(dataWithoutBigInt).toMatchInlineSnapshot(`
+ [
+ {
+ "id": 9007199254740992,
+ "name": "big_int",
+ "value": 1.5,
+ },
+ {
+ "id": 100,
+ "name": "regular",
+ "value": 2,
+ },
+ ]
+ `);
+ });
+});
diff --git a/frontend/src/plugins/impl/vega/loader.ts b/frontend/src/plugins/impl/vega/loader.ts
index cbb9d06c47..8e2de9aed2 100644
--- a/frontend/src/plugins/impl/vega/loader.ts
+++ b/frontend/src/plugins/impl/vega/loader.ts
@@ -8,54 +8,68 @@ import {
type FieldTypes,
} from "./vega-loader";
-// Augment the typeParsers to support Date
-typeParsers.date = (value: string) => new Date(value).toISOString();
-const previousBooleanParser = typeParsers.boolean;
-const previousNumberParser = typeParsers.number;
+type Unsubscribe = () => void;
+type Middleware = () => Unsubscribe;
+
+// Store all the previous type parsers so we can restore them later
const previousIntegerParser = typeParsers.integer;
+const previousNumberParser = typeParsers.number;
+const previousDateParser = typeParsers.date;
+const previousBooleanParser = typeParsers.boolean;
-// Custom parser to:
-// - handle BigInt
-// - handle inf and -inf
-const customIntegerParser = (v: string) => {
- if (v === "") {
- return "";
- }
- if (v === "-inf") {
- return v;
- }
- if (v === "inf") {
- return v;
- }
+const BIG_INT_MIDDLEWARE: Middleware = () => {
+ // Custom parser to:
+ // - handle BigInt
+ // - handle inf and -inf
+ typeParsers.integer = (v: string) => {
+ if (v === "") {
+ return "";
+ }
+ if (v === "-inf") {
+ return v;
+ }
+ if (v === "inf") {
+ return v;
+ }
- const parsedInt = Number.parseInt(v);
- if (isNumber(parsedInt)) {
- const needsBigInt = Math.abs(parsedInt) > Number.MAX_SAFE_INTEGER;
- if (!needsBigInt) {
- return previousIntegerParser(v);
+ const parsedInt = Number.parseInt(v);
+ if (isNumber(parsedInt)) {
+ const needsBigInt = Math.abs(parsedInt) > Number.MAX_SAFE_INTEGER;
+ if (!needsBigInt) {
+ return previousIntegerParser(v);
+ }
+ try {
+ return BigInt(v);
+ } catch {
+ // Floats like 2.0 are parseable as ints but not
+ // as BigInt
+ return previousIntegerParser(v);
+ }
+ } else {
+ return "";
}
- try {
- return BigInt(v);
- } catch {
- // Floats like 2.0 are parseable as ints but not
- // as BigInt
- return previousIntegerParser(v);
+ };
+ typeParsers.number = (v: string) => {
+ if (v === "-inf") {
+ return v;
}
- } else {
- return "";
- }
+ if (v === "inf") {
+ return v;
+ }
+ return previousNumberParser(v);
+ };
+
+ return () => {
+ typeParsers.integer = previousIntegerParser;
+ typeParsers.number = previousNumberParser;
+ };
};
-// Custom number parser to:
-// - handle inf and -inf
-const customNumberParser = (v: string) => {
- if (v === "-inf") {
- return v;
- }
- if (v === "inf") {
- return v;
- }
- return previousNumberParser(v);
+const DATE_MIDDLEWARE: Middleware = () => {
+ typeParsers.date = (value: string) => new Date(value).toISOString();
+ return () => {
+ typeParsers.date = previousDateParser;
+ };
};
// Custom boolean parser:
@@ -74,16 +88,6 @@ const customBooleanParser = (v: string) => {
typeParsers.boolean = customBooleanParser;
-function enableBigInt() {
- typeParsers.integer = customIntegerParser;
- typeParsers.number = customNumberParser;
-}
-
-function disableBigInt() {
- typeParsers.integer = previousIntegerParser;
- typeParsers.number = previousNumberParser;
-}
-
export const vegaLoader = createLoader();
/**
@@ -91,17 +95,29 @@ export const vegaLoader = createLoader();
*
* This resolves to an array of objects, where each object represents a row.
*/
-export function vegaLoadData<T = object>(
+export async function vegaLoadData<T = object>(
url: string,
format: DataFormat | undefined | { type: "csv"; parse: "auto" },
opts: {
+ // We support enabling/disabling since the Table enables it
+ // but Vega does not support BigInts
handleBigInt?: boolean;
replacePeriod?: boolean;
} = {},
): Promise<T[]> {
const { handleBigInt = false, replacePeriod = false } = opts;
- return vegaLoader.load(url).then((csvOrJsonData) => {
+ const middleware: Middleware[] = [DATE_MIDDLEWARE];
+ if (handleBigInt) {
+ middleware.push(BIG_INT_MIDDLEWARE);
+ }
+
+ // Apply middleware
+ const unsubscribes = middleware.map((m) => m());
+
+ // Load the data
+ try {
+ let csvOrJsonData = await vegaLoader.load(url);
if (!format) {
// Infer by trying to parse
if (typeof csvOrJsonData === "string") {
@@ -134,12 +150,6 @@ export function vegaLoadData<T = object>(
csvOrJsonData = replacePeriodsInColumnNames(csvOrJsonData);
}
- // We support enabling/disabling since the Table enables it
- // but Vega does not support BigInts
- if (handleBigInt) {
- enableBigInt();
- }
-
// Always set parse to auto for csv data, to be able to parse dates and floats
const results = isCsv
? // csv -> json
@@ -149,22 +159,27 @@ export function vegaLoadData<T = object>(
})
: read(csvOrJsonData, format);
- if (handleBigInt) {
- disableBigInt();
- }
-
return results as T[];
- });
+ } finally {
+ // Unsubscribe from middleware
+ unsubscribes.forEach((u) => u());
+ }
}
export function parseCsvData(csvData: string, handleBigInt = true): object[] {
+ const middleware: Middleware[] = [DATE_MIDDLEWARE];
if (handleBigInt) {
- enableBigInt();
+ middleware.push(BIG_INT_MIDDLEWARE);
}
+
+ // Apply middleware
+ const unsubscribes = middleware.map((m) => m());
+
const data = read(csvData, { type: "csv", parse: "auto" });
- if (handleBigInt) {
- disableBigInt();
- }
+
+ // Unsubscribe from middleware
+ unsubscribes.forEach((u) => u());
+
return data;
}
diff --git a/marimo/_smoke_tests/issues/2702-altair-deserialization.py b/marimo/_smoke_tests/issues/2702-altair-deserialization.py
new file mode 100644
index 0000000000..09356e2530
--- /dev/null
+++ b/marimo/_smoke_tests/issues/2702-altair-deserialization.py
@@ -0,0 +1,52 @@
+import marimo
+
+__generated_with = "0.9.12"
+app = marimo.App(width="medium")
+
+
+def __():
+ from datetime import date
+ import marimo as mo
+ import polars as pl
+ import altair as alt
+
+ df = pl.DataFrame(
+ {
+ "date": [date(2020, 1, 2), date(2020, 1, 3), date(2020, 1, 4)] * 2,
+ "price": [1, 4, 6, 1, 5, 2],
+ "stock": ["a", "a", "a", "b", "b", "b"],
+ }
+ )
+ return alt, date, df, mo, pl
+
+
+def __(alt, df):
+ alt.data_transformers.enable("marimo_csv")
+ df.plot.line(x="date", y="price", color="stock")
+ return
+
+
+def __(alt, df):
+ alt.data_transformers.enable("marimo_json")
+ df.plot.line(x="date", y="price", color="stock")
+ return
+
+
+def __(alt, df):
+ alt.data_transformers.enable("default")
+ df.plot.line(x="date", y="price", color="stock")
+ return
+
+
+def __(df, mo):
+ mo.ui.altair_chart(df.plot.line(x="date", y="price", color="stock"))
+ return
+
+
+if __name__ == "__main__":
+ app.run()