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
feat(table): allow hosts to size-gate downloads (#9510)
Kiran Gadhave8cb7debfe897
diff --git a/frontend/src/components/data-table/TableTopBar.tsx b/frontend/src/components/data-table/TableTopBar.tsxindex 9782ef8538..ba52e37350 100644--- a/frontend/src/components/data-table/TableTopBar.tsx+++ b/frontend/src/components/data-table/TableTopBar.tsx@@ -34,6 +34,7 @@ interface TableTopBarProps extends Partial<ExportActionProps> {showTableExplorer?: boolean;togglePanel?: (panelType: PanelType) => void;isAnyPanelOpen?: boolean;+ sizeBytes?: number | null;}export const TableTopBar: React.FC<TableTopBarProps> = ({@@ -48,6 +49,7 @@ export const TableTopBar: React.FC<TableTopBarProps> = ({togglePanel,isAnyPanelOpen,downloadAs,+ sizeBytes,}) => {const [internalValue, setInternalValue] = useState(searchQuery || "");const debouncedSearch = useDebounce(internalValue, 500);@@ -130,7 +132,9 @@ export const TableTopBar: React.FC<TableTopBarProps> = ({Explore</Button>)}- {downloadAs && <ExportMenu downloadAs={downloadAs} />}+ {downloadAs && (+ <ExportMenu downloadAs={downloadAs} sizeBytes={sizeBytes} />+ )}</div></div>);diff --git a/frontend/src/components/data-table/data-table.tsx b/frontend/src/components/data-table/data-table.tsxindex e95060f821..33f3e68a33 100644--- a/frontend/src/components/data-table/data-table.tsx+++ b/frontend/src/components/data-table/data-table.tsx@@ -70,6 +70,9 @@ interface DataTableProps<TData> extends Partial<ExportActionProps> {setSorting?: OnChangeFn<SortingState>; // controlled sorting// PaginationtotalRows: number | TooManyRows;+ // JSON-serialized size of the currently-rendered data. Forwarded to+ // ExportMenu so hosts can size-gate the Export button via downloadSizeLimitAtom.+ sizeBytes?: number | null;totalColumns: number;pagination?: boolean;manualPagination?: boolean; // server-side pagination@@ -121,6 +124,7 @@ const DataTableInternal = <TData,>({selection,totalColumns,totalRows,+ sizeBytes,manualSorting = false,sorting,setSorting,@@ -309,6 +313,7 @@ const DataTableInternal = <TData,>({togglePanel={togglePanel}isAnyPanelOpen={isAnyPanelOpen}downloadAs={downloadAs}+ sizeBytes={sizeBytes}/><TableclassName={cn(diff --git a/frontend/src/components/data-table/download-policy/atoms.ts b/frontend/src/components/data-table/download-policy/atoms.tsnew file mode 100644index 0000000000..1f4e3fe8fe--- /dev/null+++ b/frontend/src/components/data-table/download-policy/atoms.ts@@ -0,0 +1,10 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { atom } from "jotai";++export interface DownloadSizeLimit {+ limitBytes: number;+ unavailableMessage: string;+}++export const downloadSizeLimitAtom = atom<DownloadSizeLimit | null>(null);diff --git a/frontend/src/components/data-table/export-actions.tsx b/frontend/src/components/data-table/export-actions.tsxindex a058908397..a20f0c733c 100644--- a/frontend/src/components/data-table/export-actions.tsx+++ b/frontend/src/components/data-table/export-actions.tsx@@ -1,5 +1,6 @@/* Copyright 2026 Marimo. All rights reserved. */+import { useAtomValue } from "jotai";import {BracesIcon,BrickWallIcon,@@ -9,6 +10,7 @@ import {} from "lucide-react";import React from "react";import { useLocale } from "react-aria";+import { downloadSizeLimitAtom } from "./download-policy/atoms";import { logNever } from "@/utils/assertNever";import { cn } from "@/utils/cn";import { copyToClipboard } from "@/utils/copy";@@ -84,6 +86,11 @@ export interface ExportActionProps {error?: string | null;missing_packages?: string[] | null;}>;+ // JSON-serialized size of the currently-rendered data. Used together with+ // downloadSizeLimitAtom to disable the Export button when a host (e.g.,+ // marimo-lsp inside VS Code) declares a download size cap. Null/undefined+ // means "no info" and the gate stays disabled (fail-open).+ sizeBytes?: number | null;}const labelForDownloadFormat = (format: DownloadFormat): string =>@@ -94,12 +101,19 @@ const labelForCopyFormat = (format: CopyFormat): string =>export const ExportMenu: React.FC<ExportActionProps> = (props) => {const { locale } = useLocale();const [open, setOpen] = React.useState(false);+ const policy = useAtomValue(downloadSizeLimitAtom);+ const disabled = !!(+ policy &&+ props.sizeBytes != null &&+ props.sizeBytes > policy.limitBytes+ );const button = (<Buttondata-testid="export-button"size="xs"variant="text"+ disabled={disabled}className={cn("print:hidden text-xs gap-1",open ? "text-primary" : "text-muted-foreground",@@ -113,7 +127,10 @@ export const ExportMenu: React.FC<ExportActionProps> = (props) => {const resolveDownloadUrl = async (format: DownloadFormat,onRetry: () => void,- ): Promise<{ url: string; filename: string } | null> => {+ ): Promise<{+ url: string;+ filename: string;+ } | null> => {let response: Awaited<ReturnType<typeof props.downloadAs>>;try {response = await props.downloadAs({ format });@@ -143,7 +160,10 @@ export const ExportMenu: React.FC<ExportActionProps> = (props) => {return null;}- return { url: response.url, filename: response.filename };+ return {+ url: response.url,+ filename: response.filename,+ };};const handleDownload = async (format: DownloadFormat) => {@@ -229,8 +249,15 @@ export const ExportMenu: React.FC<ExportActionProps> = (props) => {return (<DropdownMenu modal={false} open={open} onOpenChange={setOpen}>- <Tooltip content="Export" open={open ? false : undefined}>- <DropdownMenuTrigger asChild={true}>{button}</DropdownMenuTrigger>+ <Tooltip+ content={disabled ? policy?.unavailableMessage : "Export"}+ open={open ? false : undefined}+ >+ <DropdownMenuTrigger asChild={true} disabled={disabled}>+ <span tabIndex={disabled ? 0 : -1} className="inline-flex">+ {button}+ </span>+ </DropdownMenuTrigger></Tooltip><DropdownMenuContent side="bottom" className="print:hidden"><DropdownMenuLabel className="text-xs text-muted-foreground">diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsxindex e2398ac683..ef09c9b733 100644--- a/frontend/src/plugins/impl/DataTablePlugin.tsx+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx@@ -194,6 +194,7 @@ interface Data<T> {wrappedColumns?: string[];headerTooltip?: Record<string, string>;totalColumns: number;+ sizeBytes?: number | null;maxColumns: number | "all";hasStableRowId: boolean;lazy: boolean;@@ -220,6 +221,7 @@ type DataTableFunctions = {cell_styles?: CellStyleState | null;cell_hover_texts?: Record<string, Record<string, string | null>> | null;raw_data?: TableData<T> | null;+ size_bytes?: number | null;}>;get_data_url?: GetDataUrl;get_row_ids?: GetRowIds;@@ -270,6 +272,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")headerTooltip: z.record(z.string(), z.string()).optional(),fieldTypes: columnToFieldTypesSchema.nullish(),totalColumns: z.number(),+ sizeBytes: z.number().nullish(),maxColumns: z.union([z.number(), z.literal("all")]).default("all"),hasStableRowId: z.boolean().default(false),maxHeight: z.number().optional(),@@ -327,6 +330,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table").nullable(),cell_hover_texts: cellHoverTextSchema.nullable(),raw_data: z.union([z.string(), z.array(z.looseObject({}))]).nullish(),+ size_bytes: z.number().nullish(),}),),get_row_ids: rpc.input(z.object({}).passthrough()).output(@@ -532,6 +536,7 @@ export const LoadingDataTableComponent = memo(rows: T[];rawRows?: T[];totalRows: number | TooManyRows;+ sizeBytes?: number | null;cellStyles: CellStyleState | undefined | null;cellHoverTexts?: Record<string, Record<string, string | null>> | null;}>(async () => {@@ -548,6 +553,7 @@ export const LoadingDataTableComponent = memo(let tableData = props.data;let rawTableData: TableData<T> | undefined | null = props.rawData;let totalRows = props.totalRows;+ let sizeBytes = props.sizeBytes ?? null;let cellStyles = props.cellStyles;let cellHoverTexts = props.cellHoverTexts;@@ -591,6 +597,7 @@ export const LoadingDataTableComponent = memo(tableData = searchResults.data;rawTableData = searchResults.raw_data;totalRows = searchResults.total_rows;+ sizeBytes = searchResults.size_bytes ?? null;cellStyles = searchResults.cell_styles || {};cellHoverTexts = searchResults.cell_hover_texts || {};}@@ -603,6 +610,7 @@ export const LoadingDataTableComponent = memo(rows: tableData,rawRows: rawData,totalRows: totalRows,+ sizeBytes,cellStyles,cellHoverTexts,};@@ -614,6 +622,7 @@ export const LoadingDataTableComponent = memo(useDeepCompareMemoize(props.fieldTypes),props.data,props.totalRows,+ props.sizeBytes,props.lazy,props.cellHoverTexts,props.cellStyles,@@ -728,6 +737,7 @@ export const LoadingDataTableComponent = memo(setFilters={setFilters}reloading={isFetching && !isPending}totalRows={data?.totalRows ?? props.totalRows}+ sizeBytes={data?.sizeBytes ?? props.sizeBytes ?? null}paginationState={paginationState}setPaginationState={setPaginationState}cellStyles={data?.cellStyles ?? props.cellStyles}@@ -774,6 +784,7 @@ const DataTableComponent = ({data,rawData,totalRows,+ sizeBytes,maxColumns,pagination,selection,@@ -1053,6 +1064,7 @@ const DataTableComponent = ({maxHeight={maxHeight}sorting={sorting}totalRows={totalRows}+ sizeBytes={sizeBytes}totalColumns={totalColumns}manualSorting={true}setSorting={setSorting}diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsxindex 890eeacfbb..18d138e635 100644--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx@@ -64,6 +64,7 @@ type PluginFunctions = {column_types_per_step: FieldTypesWithExternalType[];python_code?: string | null;sql_code?: string | null;+ size_bytes?: number | null;}>;get_column_values: (req: { column: string }) => Promise<{values: unknown[];@@ -81,6 +82,7 @@ type PluginFunctions = {}) => Promise<{data: TableData<T>;total_rows: number;+ size_bytes?: number | null;}>;download_as: DownloadAsArgs;};@@ -118,6 +120,7 @@ export const DataFramePlugin = createPlugin<S>("marimo-dataframe")column_types_per_step: z.array(columnToFieldTypesSchema),python_code: z.string().nullish(),sql_code: z.string().nullish(),+ size_bytes: z.number().nullish(),}),),get_column_values: rpc.input(z.object({ column: z.string() })).output(@@ -147,6 +150,7 @@ export const DataFramePlugin = createPlugin<S>("marimo-dataframe")z.object({data: z.union([z.string(), z.array(z.object({}).passthrough())]),total_rows: z.number(),+ size_bytes: z.number().nullish(),}),),download_as: DownloadAsSchema,@@ -203,6 +207,7 @@ export const DataFrameComponent = memo(column_types_per_step,python_code,sql_code,+ size_bytes,} = data || {};const totalColumns = field_types?.length;@@ -322,6 +327,7 @@ export const DataFrameComponent = memo(data={url || ""}hasStableRowId={false}totalRows={total_rows ?? 0}+ sizeBytes={size_bytes ?? null}totalColumns={totalColumns ?? 0}maxColumns="all"pageSize={pageSize}diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.pyindex 1c916d5c4f..fc6c4de117 100644--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py@@ -72,6 +72,9 @@ class GetDataFrameResponse:column_types_per_step: list[FieldTypes]python_code: str | None = Nonesql_code: str | None = None+ # JSON-serialized size of the current (post-transform) data; see+ # ``SearchTableResponse.size_bytes`` for usage.+ size_bytes: int | None = None@dataclass@@ -196,6 +199,7 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):"columns": self._get_column_types(),"dataframe-name": dataframe_name,"total": rows,+ "size-bytes": self._get_json_size_bytes(self._manager),"page-size": page_size,"show-download": show_download,"download-csv-encoding": download_csv_encoding,@@ -267,6 +271,7 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):sql_code=self._handler.as_sql_code(self._transform_container._snapshot_df),+ size_bytes=response.size_bytes,)def _get_column_values(@@ -333,6 +338,7 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):return SearchTableResponse(data=data,total_rows=result.get_num_rows(force=True) or 0,+ size_bytes=self._get_json_size_bytes(result),)def _download_as(self, args: DownloadAsArgs) -> DownloadAsResponse:@@ -391,3 +397,11 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):if limit is not None:tm = tm.take(limit, 0)return tm++ @memoize_last_value+ def _get_json_size_bytes(self, manager: TableManager[Any]) -> int | None:+ """JSON-serialized size of ``manager``; see table._get_json_size_bytes."""+ try:+ return len(manager.to_json(strict_json=True))+ except Exception:+ return Nonediff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.pyindex e5aecb80a1..a165e37596 100644--- a/marimo/_plugins/ui/_impl/table.py+++ b/marimo/_plugins/ui/_impl/table.py@@ -71,6 +71,7 @@ from marimo._runtime.context.types import (from marimo._runtime.context.utils import get_modefrom marimo._runtime.functions import EmptyArgs, Functionfrom marimo._utils.hashable import is_hashable+from marimo._utils.memoize import memoize_last_valuefrom marimo._utils.methods import getcallablefrom marimo._utils.narwhals_utils import (can_narwhalify_lazyframe,@@ -165,6 +166,8 @@ class SearchTableResponse:# Unformatted data mirroring the same shape/page as `data`,# provided when format_mapping is applied.raw_data: str | None = None+ # JSON-serialized size of the currently-rendered (searched/filtered) data.+ size_bytes: int | None = None@dataclass@@ -794,6 +797,11 @@ class table("data": search_result_data,"raw-data": search_result_raw_data,"total-rows": total_rows,+ "size-bytes": (+ self._get_json_size_bytes(self._manager)+ if not _internal_lazy+ else None+ ),"total-columns": num_columns,"max-columns": max_columns_arg,"banner-text": self._get_banner_text(),@@ -916,6 +924,20 @@ class table()return unwrap_narwhals_dataframe(self._selected_manager.data) # type: ignore[no-any-return]+ @memoize_last_value+ def _get_json_size_bytes(self, manager: TableManager[Any]) -> int | None:+ """Size in bytes of the manager's JSON serialization.++ JSON is the largest format we export, so this is a conservative size estimate:+ if the JSON fits under a host's download limit, CSV and Parquet will+ too. Memoized on manager identity — recomputed when filters/search+ produce a new ``_searched_manager``.+ """+ try:+ return len(manager.to_json(strict_json=True))+ except Exception:+ return None+def _download_as(self, args: DownloadAsArgs) -> DownloadAsResponse:"""Download the table data in the specified format.@@ -1619,6 +1641,7 @@ class table(offset, args.page_size, total_rows),raw_data=raw_data,+ size_bytes=self._get_json_size_bytes(self._manager),)filter_function = (@@ -1649,6 +1672,7 @@ class table(offset, args.page_size, total_rows),raw_data=raw_data,+ size_bytes=self._get_json_size_bytes(result),)def _get_row_ids(self, args: EmptyArgs) -> GetRowIdsResponse:diff --git a/marimo/_plugins/ui/_impl/utils/dataframe.py b/marimo/_plugins/ui/_impl/utils/dataframe.pyindex f44a40b7a3..68ba9008d7 100644--- a/marimo/_plugins/ui/_impl/utils/dataframe.py+++ b/marimo/_plugins/ui/_impl/utils/dataframe.py@@ -116,18 +116,17 @@ def download_as(if csv_encoding is not Noneelse get_default_csv_encoding())- vfile = mo_data.csv(- manager.to_csv(encoding=encoding, separator=csv_separator)- )+ payload = manager.to_csv(encoding=encoding, separator=csv_separator)+ vfile = mo_data.csv(payload)elif ext == "json":# Use strict JSON to ensure compliance with JSON spec- vfile = mo_data.json(- manager.to_json(- encoding=None, ensure_ascii=json_ensure_ascii, strict_json=True- )+ payload = manager.to_json(+ encoding=None, ensure_ascii=json_ensure_ascii, strict_json=True)+ vfile = mo_data.json(payload)elif ext == "parquet":- vfile = mo_data.parquet(manager.to_parquet())+ payload = manager.to_parquet()+ vfile = mo_data.parquet(payload)else:raise ValueError("format must be one of 'csv', 'json', or 'parquet'.")diff --git a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py b/tests/_plugins/ui/_impl/dataframes/test_dataframe.pyindex 2f459dc111..8d24d694ac 100644--- a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py+++ b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py@@ -883,3 +883,40 @@ def test_base_exception_handling():assert "to json panic" in str(exc_info.value)assert exc_info.value.error == str(exc_info.value)assert type(table.value) is type(df)++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_dataframe_render_args_carry_size_bytes() -> None:+ import pandas as pd++ df = pd.DataFrame({"a": [1, 2, 3]})+ subject = ui.dataframe(df)+ args = subject._component_args # type: ignore[attr-defined]+ assert args["size-bytes"] == len(+ subject._manager.to_json(strict_json=True)+ )++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_dataframe_get_dataframe_response_carries_size_bytes() -> None:+ import pandas as pd++ df = pd.DataFrame({"a": [1, 2, 3]})+ subject = ui.dataframe(df)+ response = subject._get_dataframe(EmptyArgs())+ assert response.size_bytes == len(+ subject._manager.to_json(strict_json=True)+ )++[email protected](not HAS_DEPS, reason="optional dependencies not installed")+def test_dataframe_get_json_size_bytes_fails_open() -> None:+ import pandas as pd++ subject = ui.dataframe(pd.DataFrame({"a": [1]}))++ class _Boom:+ def to_json(self, **_: object) -> str:+ raise RuntimeError("boom")++ assert subject._get_json_size_bytes(_Boom()) is None # type: ignore[arg-type]diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.pyindex b71a77b3db..8894545592 100644--- a/tests/_plugins/ui/_impl/test_table.py+++ b/tests/_plugins/ui/_impl/test_table.py@@ -1370,6 +1370,72 @@ def test_download_as(df: Any) -> None:assert selected_nw["cities"][0] == "New York"+def test_json_size_bytes_matches_payload() -> None:+ data = [{"a": 1, "b": "x"}, {"a": 2, "b": "y"}]+ table = ui.table(data)+ expected = len(table._manager.to_json(strict_json=True))+ assert table._get_json_size_bytes(table._manager) == expected+ assert expected > 0+++def test_json_size_bytes_cached_per_manager_identity() -> None:+ table = ui.table([{"a": 1}, {"a": 2}])+ # The constructor already primed the cache with table._manager; verify+ # that asking again does not re-serialize, while a fresh manager does.+ call_count = 0+ original_to_json = type(table._manager).to_json++ def counting_to_json(self: Any, **kwargs: Any) -> Any:+ nonlocal call_count+ call_count += 1+ return original_to_json(self, **kwargs)++ other_manager = ui.table([{"a": 3, "b": 4}])._manager+ # other_manager's construction primed the cache with a different key,+ # so the next call on table._manager will be a fresh miss.+ with patch.object(type(table._manager), "to_json", counting_to_json):+ table._get_json_size_bytes(table._manager)+ table._get_json_size_bytes(table._manager)+ assert call_count == 1, (+ "second call with same manager identity should hit cache"+ )+ table._get_json_size_bytes(other_manager)+ assert call_count == 2, "different manager identity should recompute"+++def test_json_size_bytes_fails_open() -> None:+ table = ui.table([{"a": 1}])++ class _Boom:+ def to_json(self, **_: Any) -> str:+ raise RuntimeError("boom")++ assert table._get_json_size_bytes(_Boom()) is None # type: ignore[arg-type]+++def test_render_args_carry_size_bytes() -> None:+ table = ui.table([{"a": 1}, {"a": 2}])+ args = table._component_args # type: ignore[attr-defined]+ assert args["size-bytes"] == len(table._manager.to_json(strict_json=True))+++def test_search_response_carries_size_bytes() -> None:+ data = [{"a": i} for i in range(10)]+ table = ui.table(data)+ # Unfiltered branch — should report _manager's size.+ unfiltered = table._search(SearchTableArgs(page_size=5, page_number=0))+ assert unfiltered.size_bytes == len(+ table._manager.to_json(strict_json=True)+ )+ # Filtered branch — should report the searched manager's size, which+ # differs from the full manager.+ filtered = table._search(+ SearchTableArgs(query="1", page_size=5, page_number=0)+ )+ assert filtered.size_bytes is not None+ assert filtered.size_bytes < unfiltered.size_bytes++def test_download_as_ignores_cell_selection() -> None:# Download should ignore selection when in cell selection modesdata = {"a": [1, 2, 3]}