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: style_cell and hover_template lost when sorting in descending order (#8915)

Manas Vardhanfce3c66f00fc
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index 5aed70b628..91261e86a3 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -1244,12 +1244,61 @@ class table(
)
return column_preview
+ def _get_page_row_ids(
+ self,
+ skip: int,
+ take: int,
+ response: GetRowIdsResponse,
+ ) -> Union[list[int], range]:
+ """Get the row IDs for a page of data.
+
+ When all rows are present (no filter applied, e.g. sort-only),
+ this reads actual ``_marimo_row_id`` values from the searched
+ manager so that style/hover dict keys match what the frontend
+ uses for lookup -- regardless of sort column or direction.
+
+ For tables without stable row IDs (list/dict data), positional
+ indices are returned since both the backend and frontend use
+ positional indexing.
+ """
+ # If there was an error computing row IDs (e.g. lazy/unknown-row-count),
+ # fall back to positional indexing without attempting to read from data.
+ if response.error:
+ return range(skip, skip + take)
+
+ if response.all_rows:
+ if self._has_stable_row_id:
+ try:
+ # Slice to the requested page via take(), then read
+ # the index column. This avoids materializing the full
+ # index column and handles lazy backends (polars
+ # LazyFrame, duckdb, ibis) that do not support direct
+ # slice indexing on the data attribute.
+ page_manager = self._searched_manager.take(take, skip)
+ page_frame = getattr(page_manager, "as_frame", None)
+ if page_frame is not None:
+ page_data = page_frame()
+ else:
+ page_data = page_manager.data
+ return cast(
+ list[int],
+ page_data[INDEX_COLUMN_NAME].to_list(),
+ )
+ except Exception:
+ LOGGER.warning(
+ "Failed to read %s from searched manager; "
+ "falling back to positional indices",
+ INDEX_COLUMN_NAME,
+ )
+ return range(skip, skip + take)
+ return range(skip, skip + take)
+ return response.row_ids[skip : skip + take]
+
def _style_cells(
self,
skip: int,
take: int,
total_rows: Union[int, Literal["too_many"]],
- descending: bool = False,
) -> Optional[CellStyles]:
"""Calculate the styling of the cells in the table."""
if self._style_cell is None:
@@ -1270,16 +1319,9 @@ class table(
if total_rows != "too_many" and skip + take > total_rows:
take = total_rows - skip
- # Determine row range
- row_ids: Union[list[int], range]
- if response.all_rows or response.error:
- row_ids = range(skip, skip + take)
- if descending and total_rows != "too_many":
- row_ids = range(
- total_rows - 1 - skip, total_rows - 1 - skip - take, -1
- )
- else:
- row_ids = response.row_ids[skip : skip + take]
+ row_ids: Union[list[int], range] = self._get_page_row_ids(
+ skip, take, response
+ )
return {
str(row): {col: do_style_cell(str(row), col) for col in columns}
@@ -1291,7 +1333,6 @@ class table(
skip: int,
take: int,
total_rows: Union[int, Literal["too_many"]],
- descending: bool = False,
) -> Optional[dict[RowId, dict[ColumnName, Optional[str]]]]:
"""Calculate hover text for cells in the table (plain strings or None)."""
if self._hover_cell is None:
@@ -1320,16 +1361,9 @@ class table(
if total_rows != "too_many" and skip + take > total_rows:
take = total_rows - skip
- # Determine row range
- row_ids: Union[list[int], range]
- if response.all_rows or response.error:
- row_ids = range(skip, skip + take)
- if descending and total_rows != "too_many":
- row_ids = range(
- total_rows - 1 - skip, total_rows - 1 - skip - take, -1
- )
- else:
- row_ids = response.row_ids[skip : skip + take]
+ row_ids: Union[list[int], range] = self._get_page_row_ids(
+ skip, take, response
+ )
return {
str(row): {col: do_hover_cell(str(row), col) for col in columns}
@@ -1428,27 +1462,18 @@ class table(
# Save the manager to be used for selection
self._searched_manager = result
- descending = False
-
if self._lazy:
total_rows = "too_many"
else:
total_rows = result.get_num_rows(force=True) or 0
- if args.sort and (self._style_cell or self._hover_cell):
- for element in args.sort:
- if element.descending:
- descending = True
-
formatted_data, raw_data = clamp_rows_and_columns(result)
return SearchTableResponse(
data=formatted_data,
total_rows=total_rows,
- cell_styles=self._style_cells(
- offset, args.page_size, total_rows, descending
- ),
+ cell_styles=self._style_cells(offset, args.page_size, total_rows),
cell_hover_texts=self._hover_cells(
- offset, args.page_size, total_rows, descending
+ offset, args.page_size, total_rows
),
raw_data=raw_data,
)
diff --git a/tests/_plugins/ui/_impl/test_table.py b/tests/_plugins/ui/_impl/test_table.py
index c7b59a3932..f819493101 100644
--- a/tests/_plugins/ui/_impl/test_table.py
+++ b/tests/_plugins/ui/_impl/test_table.py
@@ -1925,6 +1925,124 @@ def test_cell_styles_sorted_with_pagination(df: Any):
assert page2.cell_styles["9"]["Value"] == {"color": "red"}
+ "df",
+ create_dataframes(
+ {
+ "Name": ["alpha", "beta", "gamma", "delta"],
+ "Score": [4.0, 1.0, 3.0, 2.0],
+ },
+ exclude=NON_EAGER_LIBS,
+ ),
+)
+def test_cell_styles_descending_non_index_column(df: Any):
+ """Test that cell styles work when sorting by a non-index column.
+
+ Regression test for issue #8847 - style_cell styles lost when sorting
+ in descending order. The root cause was that _style_cells generated
+ row IDs assuming index-column ordering rather than reading actual
+ _marimo_row_id values from the sorted data.
+
+ Uses non-monotonic scores so the sorted order [0, 2, 3, 1] does NOT
+ match a reversed-sequential pattern, which the old buggy range-based
+ logic would have generated.
+ """
+
+ def style(_row_id, _col, value):
+ try:
+ v = float(value)
+ return {"color": "green" if v >= 3.0 else "red"}
+ except (TypeError, ValueError):
+ return {}
+
+ table = ui.table(df, style_cell=style)
+
+ # Sort by Score descending: 4.0 (row 0), 3.0 (row 2), 2.0 (row 3), 1.0 (row 1)
+ # Row IDs on page should be [0, 2, 3, 1] - NOT reversed sequential [3, 2, 1, 0]
+ page = table._search(
+ SearchTableArgs(
+ page_size=10,
+ page_number=0,
+ query="",
+ sort=[SortArgs(by="Score", descending=True)],
+ )
+ )
+ # All 4 original row IDs must be present
+ assert "0" in page.cell_styles
+ assert "1" in page.cell_styles
+ assert "2" in page.cell_styles
+ assert "3" in page.cell_styles
+ # alpha (row 0, score 4.0) should be green
+ assert page.cell_styles["0"]["Score"] == {"color": "green"}
+ # gamma (row 2, score 3.0) should be green
+ assert page.cell_styles["2"]["Score"] == {"color": "green"}
+ # delta (row 3, score 2.0) should be red
+ assert page.cell_styles["3"]["Score"] == {"color": "red"}
+ # beta (row 1, score 1.0) should be red
+ assert page.cell_styles["1"]["Score"] == {"color": "red"}
+
+ # Also test ascending - should produce identical styles
+ page_asc = table._search(
+ SearchTableArgs(
+ page_size=10,
+ page_number=0,
+ query="",
+ sort=[SortArgs(by="Score", descending=False)],
+ )
+ )
+ assert page_asc.cell_styles["0"]["Score"] == {"color": "green"}
+ assert page_asc.cell_styles["1"]["Score"] == {"color": "red"}
+
+
+ "df",
+ create_dataframes(
+ {
+ "Index": list(range(20)),
+ "Category": [f"Label {i % 5}" for i in range(20)],
+ "Value": [i * ((-1) ** i) for i in range(20)],
+ },
+ exclude=NON_EAGER_LIBS,
+ ),
+)
+def test_cell_styles_sorted_by_value_with_pagination(df: Any):
+ """Test styles when sorting by a non-index column with pagination.
+
+ Regression test for issue #8847 - when sorting by a column that does
+ not correlate with _marimo_row_id, the page's row IDs are arbitrary
+ and must be read from the sorted data, not generated sequentially.
+ """
+
+ def cell_style(_row_id, _col, value):
+ try:
+ v = float(value)
+ return {"color": "black" if v > 0 else "red"}
+ except (TypeError, ValueError):
+ return {}
+
+ table = ui.table(df, style_cell=cell_style)
+
+ # Sort by Value descending. Top values: 18 (row 18), 16 (row 16),
+ # 14 (row 14), 12 (row 12), 10 (row 10)
+ page0 = table._search(
+ SearchTableArgs(
+ page_size=5,
+ page_number=0,
+ query="",
+ sort=[SortArgs(by="Value", descending=True)],
+ )
+ )
+ # Page 0 should have row IDs for the top-5 values (even indices)
+ assert "18" in page0.cell_styles
+ assert "16" in page0.cell_styles
+ assert "14" in page0.cell_styles
+ assert "12" in page0.cell_styles
+ assert "10" in page0.cell_styles
+ # All top-5 values are positive, so all should be black
+ assert page0.cell_styles["18"]["Value"] == {"color": "black"}
+ assert page0.cell_styles["16"]["Value"] == {"color": "black"}
+
+
@pytest.mark.skipif(
not DependencyManager.pandas.has(),
reason="Pandas not installed, only pandas has multi-col idx",
@@ -2546,9 +2664,9 @@ def test_cell_search_df_hover_texts(df: Any):
"carrots",
]
},
+ exclude=NON_EAGER_LIBS,
),
)
[email protected](reason="Sorted rows are not supported for hover yet")
def test_cell_search_df_hover_texts_sorted(df: Any):
def hover_text(_row: str, _col: str, value: Any) -> str:
return f"hover:{value}"
@@ -2559,7 +2677,7 @@ def test_cell_search_df_hover_texts_sorted(df: Any):
page_size=2,
page_number=0,
query="",
- sort=SortArgs(by="column_0", descending=True),
+ sort=[SortArgs(by="column_0", descending=True)],
)
)
assert page.cell_hover_texts == {