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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: don't crash the table on 1 million rows (#1314)
Myles Scolnickb86a05da7cca
diff --git a/frontend/.storybook/preview.tsx b/frontend/.storybook/preview.tsxindex 8432060c2d..2bedcbac7d 100644--- a/frontend/.storybook/preview.tsx+++ b/frontend/.storybook/preview.tsx@@ -7,7 +7,7 @@ import React, { useEffect } from "react";import { cn } from "../src/utils/cn";import { TooltipProvider } from "../src/components/ui/tooltip";import { Toaster } from "../src/components/ui/toaster";-import { TailwindIndicator } from "../src/components/ui/tailwind-indicator";+import { TailwindIndicator } from "../src/components/indicator";const withTheme: Decorator = (Story, context) => {const theme = context.globals.theme || "light";diff --git a/frontend/src/components/data-table/__test__/columns.test.ts b/frontend/src/components/data-table/__test__/columns.test.tsnew file mode 100644index 0000000000..03f61714f7--- /dev/null+++ b/frontend/src/components/data-table/__test__/columns.test.ts@@ -0,0 +1,23 @@+/* Copyright 2024 Marimo. All rights reserved. */+import { expect, test } from "vitest";+import { uniformSample } from "../columns";++test("uniformSample", () => {+ const items = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];++ expect(uniformSample(items, 2)).toMatchInlineSnapshot(`+ [+ "A",+ "J",+ ]+ `);+ expect(uniformSample(items, 4)).toMatchInlineSnapshot(`+ [+ "A",+ "C",+ "F",+ "J",+ ]+ `);+ expect(uniformSample(items, 100)).toBe(items);+});diff --git a/frontend/src/components/data-table/columns.tsx b/frontend/src/components/data-table/columns.tsxindex 3c3b7f46e6..61bc3559df 100644--- a/frontend/src/components/data-table/columns.tsx+++ b/frontend/src/components/data-table/columns.tsx@@ -9,7 +9,7 @@ interface ColumnInfo {type: "primitive" | "mime";}-export function getColumnInfo<T>(items: T[]): ColumnInfo[] {+function getColumnInfo<T>(items: T[]): ColumnInfo[] {// No itemsif (items.length === 0) {return [];@@ -21,7 +21,10 @@ export function getColumnInfo<T>(items: T[]): ColumnInfo[] {}const keys = new Map<string, ColumnInfo>();- items.forEach((item) => {++ // This can be slow for large datasets,+ // so only sample 10 evenly distributed rows+ uniformSample(items, 10).forEach((item) => {if (typeof item !== "object") {return;}@@ -153,3 +156,21 @@ function isPrimitiveOrNullish(value: unknown): boolean {const isObject = typeof value === "object";return !isObject;}++/**+ * Uniformly sample n items from an array+ */+export function uniformSample<T>(items: T[], n: number): T[] {+ if (items.length <= n) {+ return items;+ }+ const sample: T[] = [];+ const step = items.length / n;+ for (let i = 0; i < n - 1; i++) {+ const idx = Math.floor(i * step);+ sample.push(items[idx]);+ }+ const last = items.at(-1) as T;+ sample.push(last);+ return sample;+}diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsxindex 064e6ec166..cd12868148 100644--- a/frontend/src/components/data-table/data-table.tsx+++ b/frontend/src/components/data-table/data-table.tsx@@ -1,5 +1,5 @@/* Copyright 2024 Marimo. All rights reserved. */-import React from "react";+import React, { memo } from "react";import {ColumnDef,OnChangeFn,@@ -25,10 +25,10 @@ import { DataTablePagination } from "./pagination";import { DownloadActionProps, DownloadAs } from "./download-actions";import { cn } from "@/utils/cn";-interface DataTableProps<TData, TValue> extends Partial<DownloadActionProps> {+interface DataTableProps<TData> extends Partial<DownloadActionProps> {wrapperClassName?: string;className?: string;- columns: Array<ColumnDef<TData, TValue>>;+ columns: Array<ColumnDef<TData>>;data: TData[];pagination?: boolean;pageSize?: number;@@ -37,7 +37,7 @@ interface DataTableProps<TData, TValue> extends Partial<DownloadActionProps> {onRowSelectionChange?: OnChangeFn<RowSelectionState>;}-export const DataTable = <TData, TValue>({+const DataTableInternal = <TData,>({wrapperClassName,className,columns,@@ -47,7 +47,7 @@ export const DataTable = <TData, TValue>({downloadAs,pagination = false,onRowSelectionChange,-}: DataTableProps<TData, TValue>) => {+}: DataTableProps<TData>) => {const [sorting, setSorting] = React.useState<SortingState>([]);const [paginationState, setPaginationState] = React.useState<PaginationState>({ pageSize: pageSize, pageIndex: 0 },@@ -133,3 +133,5 @@ export const DataTable = <TData, TValue>({</div>);};++export const DataTable = memo(DataTableInternal) as typeof DataTableInternal;diff --git a/frontend/src/components/data-table/pagination.tsx b/frontend/src/components/data-table/pagination.tsxindex 43fefbecf6..4b4c45119f 100644--- a/frontend/src/components/data-table/pagination.tsx+++ b/frontend/src/components/data-table/pagination.tsx@@ -25,14 +25,14 @@ export const DataTablePagination = <TData,>({if (isAllPageSelected && !isAllSelected) {return (<span>- {selected} selected+ {prettyNumber(selected)} selected<Buttonsize="xs"data-testid="select-all-button"variant="link"onClick={() => table.toggleAllRowsSelected(true)}>- Select all {count}+ Select all {prettyNumber(count)}</Button></span>);@@ -41,7 +41,7 @@ export const DataTablePagination = <TData,>({if (selected) {return (<span>- {selected} selected+ {prettyNumber(selected)} selected<Buttonsize="xs"data-testid="clear-selection-button"@@ -54,7 +54,7 @@ export const DataTablePagination = <TData,>({);}- return `${count} items`;+ return `${prettyNumber(count)} items`;};const currentPage = Math.min(table.getState().pagination.pageIndex + 1,diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex d127a0f8ea..a767b2d90e 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -14,6 +14,9 @@ import { createPlugin } from "../core/builder";import { vegaLoadData } from "./vega/loader";import { VegaType } from "./vega/vega-loader";import { getVegaFieldTypes } from "./vega/utils";+import { Arrays } from "@/utils/arrays";+import { Banner } from "./common/error-banner";+import { prettyNumber } from "@/utils/numbers";/*** Arguments for a data table@@ -24,6 +27,8 @@ import { getVegaFieldTypes } from "./vega/utils";interface Data<T> {label: string | null;data: T[] | string;+ hasMore: boolean;+ totalRows: number;pagination: boolean;pageSize: number;selection: "single" | "multi" | null;@@ -45,6 +50,8 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")initialValue: z.array(z.number()),label: z.string().nullable(),data: z.union([z.string(), z.array(z.object({}).passthrough())]),+ hasMore: z.boolean().default(false),+ totalRows: z.number(),pagination: z.boolean().default(false),pageSize: z.number().default(10),selection: z.enum(["single", "multi"]).nullable().default(null),@@ -120,12 +127,14 @@ export const LoadingDataTableComponent = ();}- return <DataTableComponent {...props} data={data || []} />;+ return <DataTableComponent {...props} data={data || Arrays.EMPTY} />;};const DataTableComponent = ({label,data,+ hasMore,+ totalRows,pagination,pageSize,selection,@@ -146,29 +155,36 @@ const DataTableComponent = ({const rowSelection = Object.fromEntries((value || []).map((v) => [v, true]));return (- <Labeled label={label} align="top" fullWidth={true}>- <DataTable- data={data}- columns={columns}- className={className}- pagination={pagination}- pageSize={pageSize}- rowSelection={rowSelection}- downloadAs={showDownload ? downloadAs : undefined}- onRowSelectionChange={(updater) => {- if (selection === "single") {- const nextValue =- typeof updater === "function" ? updater({}) : updater;- setValue(Object.keys(nextValue).slice(0, 1));- }+ <>+ {hasMore && totalRows && (+ <Banner className="mb-2 rounded">+ Result clipped. Total rows {prettyNumber(totalRows)}.+ </Banner>+ )}+ <Labeled label={label} align="top" fullWidth={true}>+ <DataTable+ data={data}+ columns={columns}+ className={className}+ pagination={pagination}+ pageSize={pageSize}+ rowSelection={rowSelection}+ downloadAs={showDownload ? downloadAs : undefined}+ onRowSelectionChange={(updater) => {+ if (selection === "single") {+ const nextValue =+ typeof updater === "function" ? updater({}) : updater;+ setValue(Object.keys(nextValue).slice(0, 1));+ }- if (selection === "multi") {- const nextValue =- typeof updater === "function" ? updater(rowSelection) : updater;- setValue(Object.keys(nextValue));- }- }}- />- </Labeled>+ if (selection === "multi") {+ const nextValue =+ typeof updater === "function" ? updater(rowSelection) : updater;+ setValue(Object.keys(nextValue));+ }+ }}+ />+ </Labeled>+ </>);};diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsxindex 4372eab7c2..c58202b5c3 100644--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx@@ -159,6 +159,8 @@ export const DataFrameComponent = ({label={null}className="rounded-b border-x border-b"data={url || ""}+ hasMore={false} // Handled above+ totalRows={total_rows || 0}pageSize={pageSize}pagination={true}rowHeaders={row_headers || Arrays.EMPTY}diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex 6f188b69f6..0355e59283 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -159,6 +159,11 @@ class table(self._manager = get_table_manager(data)self._filtered_manager: Optional[TableManager[Any]] = None+ totalRows = len(self._manager.data)+ hasMore = totalRows > TableManager.DEFAULT_LIMIT+ if hasMore:+ self._manager = self._manager.limit(TableManager.DEFAULT_LIMIT)+# pagination defaults to True if there are more than 10 rowsif pagination is None:pagination = len(self._data) > 10@@ -174,6 +179,8 @@ class table(initial_value=[],args={"data": self._manager.to_data(),+ "has-more": hasMore,+ "total-rows": totalRows,"pagination": pagination,"page-size": page_size,"field-types": field_types if field_types else None,diff --git a/marimo/_plugins/ui/_impl/tables/default_table.py b/marimo/_plugins/ui/_impl/tables/default_table.pyindex f6b23db8e8..21fba6e5bb 100644--- a/marimo/_plugins/ui/_impl/tables/default_table.py+++ b/marimo/_plugins/ui/_impl/tables/default_table.py@@ -53,6 +53,15 @@ class DefaultTableManager(TableManager[JsonTableData]):# Row major datareturn DefaultTableManager([self.data[i] for i in indices])+ def limit(self, num: int) -> DefaultTableManager:+ if num < 0:+ raise ValueError("Limit must be a positive integer")+ if isinstance(self.data, dict):+ return DefaultTableManager(+ {key: value[:num] for key, value in self.data.items()}+ )+ return DefaultTableManager(self.data[:num])+def get_row_headers(self) -> list[tuple[str, list[str | int | float]]]:return []diff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.pyindex 4642c0474c..8cb94fd7ce 100644--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py@@ -114,6 +114,11 @@ class PandasTableManagerFactory(TableManagerFactory):for column in self.data.columns}+ def limit(self, num: int) -> PandasTableManager:+ if num < 0:+ raise ValueError("Limit must be a positive integer")+ return PandasTableManager(self.data.head(num))+@staticmethoddef _get_field_type(series: pd.Series[Any] | pd.DataFrame,diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.pyindex 35d52d45cb..116edf6273 100644--- a/marimo/_plugins/ui/_impl/tables/polars_table.py+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py@@ -49,6 +49,11 @@ class PolarsTableManagerFactory(TableManagerFactory):for column in self.data.columns}+ def limit(self, num: int) -> PolarsTableManager:+ if num < 0:+ raise ValueError("Limit must be a positive integer")+ return PolarsTableManager(self.data.head(num))+@staticmethoddef _get_field_type(column: pl.Series) -> FieldType:if column.is_utf8():diff --git a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py b/marimo/_plugins/ui/_impl/tables/pyarrow_table.pyindex f99581870f..a42b93411e 100644--- a/marimo/_plugins/ui/_impl/tables/pyarrow_table.py+++ b/marimo/_plugins/ui/_impl/tables/pyarrow_table.py@@ -67,6 +67,11 @@ class PyArrowTableManagerFactory(TableManagerFactory):for idx, column in enumerate(self.data.schema.names)}+ def limit(self, num: int) -> PyArrowTableManager:+ if num < 0:+ raise ValueError("Limit must be a positive integer")+ return PyArrowTableManager(self.data.take(list(range(num))))+@staticmethoddef _get_field_type(column: pa.Array[Any, Any]) -> FieldType:if isinstance(column, pa.NullArray):diff --git a/marimo/_plugins/ui/_impl/tables/table_manager.py b/marimo/_plugins/ui/_impl/tables/table_manager.pyindex 9d1d1dffdb..7bda07f2d5 100644--- a/marimo/_plugins/ui/_impl/tables/table_manager.py+++ b/marimo/_plugins/ui/_impl/tables/table_manager.py@@ -18,6 +18,8 @@ FieldTypes = Dict[str, FieldType]class TableManager(abc.ABC, Generic[T]):+ DEFAULT_LIMIT = 10_000+def __init__(self, data: T) -> None:self.data = data@@ -51,6 +53,10 @@ class TableManager(abc.ABC, Generic[T]):# so the frontend can infer themreturn {}+ @abc.abstractmethod+ def limit(self, num: int) -> TableManager[T]:+ raise NotImplementedError+@staticmethod@abc.abstractmethoddef is_type(value: Any) -> bool:diff --git a/marimo/_smoke_tests/bugs/1311.py b/marimo/_smoke_tests/bugs/1311.pynew file mode 100644index 0000000000..f0076281a8--- /dev/null+++ b/marimo/_smoke_tests/bugs/1311.py@@ -0,0 +1,36 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.4.11"+app = marimo.App()+++def __():+ import marimo as mo+ import pandas as pd+ return mo, pd+++def __(pd):+ all_flights = pd.read_parquet(+ "https://vegafusion-datasets.s3.amazonaws.com/vega/flights_1m.parquet"+ )+ return all_flights,+++def __(all_flights, mo):+ mo.ui.table(all_flights)+ return+++def __(all_flights, mo):+ mo.ui.table(all_flights[0:10])+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/bugs/1312.py b/marimo/_smoke_tests/bugs/1312.pyindex 80f6ed973c..91ac04c172 100644--- a/marimo/_smoke_tests/bugs/1312.py+++ b/marimo/_smoke_tests/bugs/1312.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.4.11"diff --git a/tests/_plugins/ui/_impl/tables/test_default_table.py b/tests/_plugins/ui/_impl/tables/test_default_table.pyindex db14c5c25d..cce5b527b9 100644--- a/tests/_plugins/ui/_impl/tables/test_default_table.py+++ b/tests/_plugins/ui/_impl/tables/test_default_table.py@@ -36,6 +36,13 @@ class TestDefaultTable(unittest.TestCase):assert self.manager.is_type(self.data)assert not self.manager.is_type("not a dataframe")+ def test_limit(self) -> None:+ limited_manager = self.manager.limit(1)+ expected_data = [+ {"A": 1, "B": "a"},+ ]+ assert limited_manager.data == expected_data+class TestColumnarDefaultTable(unittest.TestCase):def setUp(self) -> None:@@ -68,3 +75,11 @@ class TestColumnarDefaultTable(unittest.TestCase):def test_get_field_types(self) -> None:assert self.manager.get_field_types() == {}++ def test_limit(self) -> None:+ limited_manager = self.manager.limit(1)+ expected_data = {+ "A": [1],+ "B": ["a"],+ }+ assert limited_manager.data == expected_datadiff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.pyindex 113c295c6a..7b21636698 100644--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py@@ -208,3 +208,11 @@ class TestPandasTableManager(unittest.TestCase):self.factory.create()(data).get_field_types()== expected_field_types)++ def test_limit(self) -> None:+ import pandas as pd++ limit = 2+ limited_manager = self.manager.limit(limit)+ expected_data = self.data.head(limit)+ pd.testing.assert_frame_equal(limited_manager.data, expected_data)diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.pyindex d6ead0e469..d78e24354a 100644--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py@@ -100,3 +100,8 @@ class TestPolarsTableManagerFactory(unittest.TestCase):self.factory.create()(complex_data).get_field_types()== expected_field_types)++ def test_limit(self) -> None:+ limited_manager = self.manager.limit(1)+ expected_data = self.data.head(1)+ assert limited_manager.data.frame_equal(expected_data)diff --git a/tests/_plugins/ui/_impl/tables/test_pyarrow.py b/tests/_plugins/ui/_impl/tables/test_pyarrow.pyindex 9ef032fbd4..55709206d5 100644--- a/tests/_plugins/ui/_impl/tables/test_pyarrow.py+++ b/tests/_plugins/ui/_impl/tables/test_pyarrow.py@@ -77,3 +77,8 @@ class TestPyArrowTableManagerFactory(unittest.TestCase):self.factory.create()(complex_data).get_field_types()== expected_field_types)++ def test_limit(self) -> None:+ limited_manager = self.manager.limit(1)+ expected_data = self.data.take([0])+ assert limited_manager.data == expected_data