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: gracefully handle BaseExceptions from downstream df libraries (#5576)

Myles Scolnickde028e45861b
diff --git a/frontend/src/components/editor/documentation.css b/frontend/src/components/editor/documentation.css
index d45f8ceb02..767aeed089 100644
--- a/frontend/src/components/editor/documentation.css
+++ b/frontend/src/components/editor/documentation.css
@@ -53,6 +53,10 @@
@apply border px-1 rounded font-mono bg-[var(--slate-2)] text-sm mb-4 mt-2;
}
+ code:empty {
+ display: none;
+ }
+
h1,
h2 {
font-weight: 600;
diff --git a/frontend/src/plugins/impl/common/error-banner.tsx b/frontend/src/plugins/impl/common/error-banner.tsx
index 107accb440..ed6659da35 100644
--- a/frontend/src/plugins/impl/common/error-banner.tsx
+++ b/frontend/src/plugins/impl/common/error-banner.tsx
@@ -45,7 +45,7 @@ export const ErrorBanner = ({
<AlertDialogHeader>
<AlertDialogTitle className="text-error">Error</AlertDialogTitle>
</AlertDialogHeader>
- <pre className="text-error text-sm p-2 font-mono overflow-auto">
+ <pre className="text-error text-sm p-2 font-mono overflow-auto whitespace-pre-wrap">
{message}
</pre>
<AlertDialogFooter>
diff --git a/marimo/_output/formatters/df_formatters.py b/marimo/_output/formatters/df_formatters.py
index 16a03c283c..7c8b4b706f 100644
--- a/marimo/_output/formatters/df_formatters.py
+++ b/marimo/_output/formatters/df_formatters.py
@@ -93,7 +93,9 @@ class PolarsFormatter(FormatterFactory):
) -> tuple[KnownMimeType, str]:
try:
return table(df, selection=None, pagination=True)._mime_()
- except Exception as e:
+ except BaseException as e:
+ # Catch-all: some libraries like Polars have bugs and raise
+ # BaseExceptions, which shouldn't crash the kernel
LOGGER.warning("Failed to format DataFrame: %s", e)
return ("text/html", df._repr_html_())
@@ -108,7 +110,9 @@ class PolarsFormatter(FormatterFactory):
else:
df = series.to_frame()
return table(df, selection=None, pagination=True)._mime_()
- except Exception as e:
+ except BaseException as e:
+ # Catch-all: some libraries like Polars have bugs and raise
+ # BaseExceptions, which shouldn't crash the kernel
LOGGER.warning("Failed to format Series: %s", e)
return ("text/html", series._repr_html_())
diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
index 373f0347a1..a79771c487 100644
--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py
+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
@@ -27,6 +27,7 @@ from marimo._plugins.ui._impl.table import (
SearchTableArgs,
SearchTableResponse,
SortArgs,
+ TableSearchError,
)
from marimo._plugins.ui._impl.tables.table_manager import (
FieldTypes,
@@ -256,7 +257,13 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):
)
# Save the manager to be used for selection
- data = result.take(args.page_size, offset).to_json_str()
+ try:
+ data = result.take(args.page_size, offset).to_json_str()
+ except BaseException as e:
+ # Catch and re-raise the error as a non-BaseException
+ # to avoid crashing the kernel
+ raise TableSearchError(str(e)) from e
+
return SearchTableResponse(
data=data,
total_rows=result.get_num_rows(force=True) or 0,
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 478e4e7b54..7c0d431445 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -73,6 +73,12 @@ if TYPE_CHECKING:
LOGGER = _loggers.marimo_logger()
+class TableSearchError(Exception):
+ def __init__(self, error: str):
+ self.error = error
+ super().__init__(error)
+
+
@dataclass
class DownloadAsArgs:
format: Literal["csv", "json", "parquet"]
@@ -1003,7 +1009,13 @@ class table(
# Do not clamp if max_columns is None
if max_columns is not None and len(column_names) > max_columns:
data = data.select_columns(column_names[:max_columns])
- return data.to_json_str(self._format_mapping)
+
+ try:
+ return data.to_json_str(self._format_mapping)
+ except BaseException as e:
+ # Catch and re-raise the error as a non-BaseException
+ # to avoid crashing the kernel
+ raise TableSearchError(str(e)) from e
# If no query or sort, return nothing
# The frontend will just show the original data
diff --git a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
index a80a056efe..3cb3fcd403 100644
--- a/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
+++ b/tests/_plugins/ui/_impl/dataframes/test_dataframe.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from typing import Any
-from unittest.mock import Mock
+from unittest.mock import Mock, patch
import pytest
@@ -12,7 +12,7 @@ from marimo._plugins.ui._impl.dataframes.dataframe import (
GetColumnValuesArgs,
GetColumnValuesResponse,
)
-from marimo._plugins.ui._impl.table import SearchTableArgs
+from marimo._plugins.ui._impl.table import SearchTableArgs, TableSearchError
from marimo._runtime.functions import EmptyArgs
from marimo._utils.platform import is_windows
from tests._data.mocks import create_dataframes
@@ -486,3 +486,41 @@ def test_dataframe_with_int_column_names():
assert "DataFrame has integer column names" in str(w[0].message)
assert dataframe.value is not None
+
+
+ not HAS_IBIS or not HAS_POLARS,
+ reason="optional dependencies not installed",
+)
+def test_base_exception_handling():
+ """Test that BaseException is caught and re-raised as TableSearchError."""
+ import polars as pl
+
+ df = pl.DataFrame({"col": [1]})
+ table = ui.dataframe(df)
+
+ search_args = SearchTableArgs(
+ page_size=10,
+ page_number=0,
+ query="test",
+ sort=None,
+ filters=None,
+ )
+
+ table_manager = table._get_cached_table_manager(df, None)
+
+ with patch.object(table_manager, "take") as take:
+ take.side_effect = BaseException("to json panic")
+
+ with patch.object(
+ table, "_apply_filters_query_sort"
+ ) as _apply_filters_query_sort:
+ _apply_filters_query_sort.return_value = table_manager
+
+ # Should catch BaseException and re-raise as TableSearchError
+ with pytest.raises(TableSearchError) as exc_info:
+ table._search(search_args)
+
+ # Verify the error message is preserved
+ assert "to json panic" in str(exc_info.value)
+ assert exc_info.value.error == str(exc_info.value)
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index 1a7bed7d4e..8060bd66be 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -19,6 +19,7 @@ from marimo._plugins.ui._impl.table import (
DownloadAsArgs,
SearchTableArgs,
SortArgs,
+ TableSearchError,
get_default_table_page_size,
)
from marimo._plugins.ui._impl.tables.default_table import DefaultTableManager
@@ -1984,3 +1985,29 @@ def test_show_toggles_app_mode():
table_default = ui.table(data)
assert table_default._component_args["show-column-explorer"] is False
assert table_default._component_args["show-chart-builder"] is False
+
+
+def test_base_exception_handling():
+ """Test that BaseException is caught and re-raised as TableSearchError."""
+ table = ui.table({"col": [1]})
+
+ search_args = SearchTableArgs(
+ page_size=10,
+ page_number=0,
+ query="test",
+ sort=None,
+ filters=None,
+ )
+
+ with patch(
+ "marimo._plugins.ui._impl.tables.default_table.DefaultTableManager.to_json_str"
+ ) as mock_to_json_str:
+ mock_to_json_str.side_effect = BaseException("to json panic")
+
+ # Should catch BaseException and re-raise as TableSearchError
+ with pytest.raises(TableSearchError) as exc_info:
+ table._search(search_args)
+
+ # Verify the error message is preserved
+ assert "to json panic" in str(exc_info.value)
+ assert exc_info.value.error == str(exc_info.value)