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: stable row id (#3875)

Myles Scolnickcfdf9c3f6747
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index 0bfe6b2dd3..8a2a2157c0 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -18,7 +18,6 @@ import { ColumnChartContext } from "@/components/data-table/column-summary";
import { Logger } from "@/utils/Logger";
import {
- INDEX_COLUMN_NAME,
toFieldTypes,
type ColumnHeaderSummary,
type FieldTypesWithExternalType,
@@ -78,6 +77,7 @@ interface Data<T> {
textJustifyColumns?: Record<string, "left" | "center" | "right">;
wrappedColumns?: string[];
totalColumns: number;
+ hasStableRowId: boolean;
}
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
@@ -132,6 +132,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
)
.nullish(),
totalColumns: z.number(),
+ hasStableRowId: z.boolean().default(false),
}),
)
.withFunctions<Functions>({
@@ -216,6 +217,7 @@ interface DataTableSearchProps {
// Filters
filters?: ColumnFiltersState;
setFilters?: OnChangeFn<ColumnFiltersState>;
+ hasStableRowId: boolean;
}
export const LoadingDataTableComponent = memo(
@@ -237,14 +239,11 @@ export const LoadingDataTableComponent = memo(
// We need to clear the selection when sort, query, or filters change
// if we don't have a stable ID for each row, which is determined by
// _marimo_row_id.
- const hasStableRowId = props.fieldTypes?.some(
- (fieldType) => fieldType[0] === INDEX_COLUMN_NAME,
- );
useEffectSkipFirstRender(() => {
- if (!hasStableRowId) {
+ if (!props.hasStableRowId) {
setValue([]);
}
- }, [setValue, filters, searchQuery, sorting, hasStableRowId]);
+ }, [setValue, filters, searchQuery, sorting, props.hasStableRowId]);
// If pageSize changes, reset pagination state
useEffect(() => {
diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
index f67ecad2d3..0d89cd7a2e 100644
--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
@@ -262,6 +262,7 @@ export const DataFrameComponent = memo(
label={null}
className="rounded-b border-x border-b"
data={url || ""}
+ hasStableRowId={false}
totalRows={total_rows ?? 0}
totalColumns={Object.keys(columns).length}
pageSize={pageSize}
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 5db974bc4d..d5b8a16c89 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -270,8 +270,10 @@ class table(
validate_no_integer_columns(data)
validate_page_size(page_size)
+ has_stable_row_id = False
if selection is not None:
- data = add_selection_column(data)
+ data, has_stable_row_id = add_selection_column(data)
+ self._has_stable_row_id = has_stable_row_id
# The original data passed in
self._data = data
@@ -395,6 +397,7 @@ class table(
"freeze-columns-right": freeze_columns_right,
"text-justify-columns": text_justify_columns,
"wrapped-columns": wrapped_columns,
+ "has-stable-row-id": self._has_stable_row_id,
},
on_change=on_change,
functions=(
@@ -440,7 +443,13 @@ class table(
self, value: Union[List[int], List[str]]
) -> Union[List[JSONType], "IntoDataFrame"]:
indices = [int(v) for v in value]
- self._selected_manager = self._searched_manager.select_rows(indices)
+ if self._has_stable_row_id:
+ # Search across the original data
+ self._selected_manager = self._manager.select_rows(indices)
+ else:
+ self._selected_manager = self._searched_manager.select_rows(
+ indices
+ )
self._has_any_selection = len(indices) > 0
return unwrap_narwhals_dataframe(self._selected_manager.data) # type: ignore[no-any-return]
diff --git a/marimo/_plugins/ui/_impl/tables/selection.py b/marimo/_plugins/ui/_impl/tables/selection.py
index 74b2209fe3..72b66c2c85 100644
--- a/marimo/_plugins/ui/_impl/tables/selection.py
+++ b/marimo/_plugins/ui/_impl/tables/selection.py
@@ -11,12 +11,13 @@ INDEX_COLUMN_NAME = "_marimo_row_id"
T = TypeVar("T")
-def add_selection_column(data: T) -> T:
+def add_selection_column(data: T) -> tuple[T, bool]:
if nw.dependencies.is_into_dataframe(data):
df = nw.from_native(cast(IntoDataFrame, data), strict=True)
if INDEX_COLUMN_NAME not in df.columns:
- return df.with_row_index(name=INDEX_COLUMN_NAME).to_native() # type: ignore[return-value]
- return data
+ return df.with_row_index(name=INDEX_COLUMN_NAME).to_native(), True # type: ignore[return-value]
+ return data, True # already has a row index
+ return data, False
def remove_selection_column(data: T) -> T:
diff --git a/tests/_plugins/ui/_impl/tables/test_selection.py b/tests/_plugins/ui/_impl/tables/test_selection.py
index aa76b367a9..97fc35b4f0 100644
--- a/tests/_plugins/ui/_impl/tables/test_selection.py
+++ b/tests/_plugins/ui/_impl/tables/test_selection.py
@@ -164,7 +164,9 @@ def test_add_selection_to_dataframe(backend: Any):
{"name": ["Alice", "Bob", "Charlie"], "age": [30, 25, 35]},
native_namespace=backend,
)
- with_selection = add_selection_column(data.to_native())
+ with_selection, has_stable_row_id = add_selection_column(data.to_native())
+
+ assert has_stable_row_id is True
# Convert back to Narwhals to assert
nw_df = nw.from_native(with_selection)
@@ -183,7 +185,9 @@ def test_add_selection_to_dataframe_already_has_index(backend: Any):
},
native_namespace=backend,
)
- with_selection = add_selection_column(data.to_native())
+ with_selection, has_stable_row_id = add_selection_column(data.to_native())
+
+ assert has_stable_row_id is True
# Convert back to Narwhals to assert
nw_df = nw.from_native(with_selection)
@@ -198,7 +202,9 @@ def test_remove_selection_column(backend: Any):
{"name": ["Alice", "Bob", "Charlie"], "age": [30, 25, 35]},
native_namespace=backend,
)
- with_selection = add_selection_column(data.to_native())
+ with_selection, has_stable_row_id = add_selection_column(data.to_native())
+ assert has_stable_row_id is True
+
without_selection = remove_selection_column(with_selection)
nw_df = nw.from_native(without_selection)
assert nw_df.columns == ["name", "age"]
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index c4de494692..9f8eb12862 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -331,6 +331,10 @@ def test_value_with_search_then_selection() -> None:
{"value": "banana"},
]
+ # Rows not in the search are not selected
+ with pytest.raises(IndexError):
+ table._convert_value(["2"])
+
# empty search
table._search(
SearchTableArgs(
@@ -369,10 +373,11 @@ def test_value_with_search_then_selection_dfs(df: Any) -> None:
page_number=0,
)
)
- value = table._convert_value(["0"])
+ # Can still select rows not in the search
+ value = table._convert_value(["0", "1"])
assert not isinstance(value, nw.DataFrame)
assert nw.from_native(value)["a"][0] == "foo"
-
+ assert nw.from_native(value)["a"][1] == "bar"
# empty search
table._search(
SearchTableArgs(