Repository navigation
[Data] Index block rows directly instead of materializing a one-row table - #66116
Conversation
…able Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Aarrya <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request refactors ArrowRow and PandasRow to store the underlying batch or DataFrame along with a row index, avoiding expensive slicing operations when retrieving rows. While this is a great performance improvement, the review comments correctly identify several areas where the new implementation introduces other inefficiencies, such as redundant column lookups and temporary Series creation in getitem and as_pydict for both Arrow and Pandas blocks. Additionally, a potential TypeError is pointed out in ArrowRow when handling pyarrow.RecordBatch inside _build_tensor_row.
| return tuple( | ||
| [ | ||
| ArrowBlockAccessor._build_tensor_row( | ||
| self._row, col_name=key, row_idx=0 | ||
| ) | ||
| for key in keys | ||
| ] | ||
| ArrowBlockAccessor._build_tensor_row( | ||
| self._batch, col_name=key, row_idx=self._row_idx | ||
| ) | ||
| for key in keys | ||
| ) |
There was a problem hiding this comment.
Calling ArrowBlockAccessor._build_tensor_row with self._batch (which can be a pyarrow.RecordBatch) will raise a TypeError because RecordBatch does not support string indexing (e.g., batch[col_name]). Instead, we can directly retrieve the column by index and call .as_py() on the scalar element, which is safer and more efficient.
return tuple(
self._batch.column(schema.get_field_index(key))[self._row_idx].as_py()
for key in keys
)| def as_pydict(self) -> Dict[str, Any]: | ||
| return dict(self.items()) | ||
| return {k: self[k] for k in self} |
There was a problem hiding this comment.
Implementing as_pydict by iterating over keys and calling self[k] is inefficient because it performs redundant schema lookups, imports, and type checks for every single column. We can optimize this by directly iterating over the schema and converting the values.
| def as_pydict(self) -> Dict[str, Any]: | |
| return dict(self.items()) | |
| return {k: self[k] for k in self} | |
| def as_pydict(self) -> Dict[str, Any]: | |
| schema = self._batch.schema | |
| pydict = {} | |
| for col_idx, col_name in enumerate(schema.names): | |
| col = self._batch.column(col_idx) | |
| val = col[self._row_idx] | |
| try: | |
| pydict[col_name] = val.as_py() | |
| except AttributeError: | |
| pydict[col_name] = val | |
| return pydict |
| for col_name in keys: | ||
| if col_name not in self._batch.columns: | ||
| return None | ||
| val = self._batch[col_name].iloc[self._row_idx] |
There was a problem hiding this comment.
Using self._batch[col_name].iloc[self._row_idx] is inefficient because it looks up the column and creates a temporary Series object for every key. Since self._row_idx is a positional index, we can use self._batch.iat with the column's integer position, which is significantly faster and avoids creating intermediate Series objects.
for col_name in keys:
if col_name not in self._batch.columns:
return None
col_idx = self._batch.columns.get_loc(col_name)
val = self._batch.iat[self._row_idx, col_idx]| for key in self: | ||
| value = self._batch[key].iloc[self._row_idx] | ||
| # Convert NA to None for consistency across block formats. `pd.isna` | ||
| # returns True for both NA and NaN, but since we want to preserve NaN | ||
| # values, we check for identity instead. | ||
| if is_scalar(value) and value is pd.NA: | ||
| pydict[key] = None | ||
| elif isinstance(value, TensorArrayElement): | ||
| pydict[key] = value.to_numpy() | ||
| elif isinstance(value, np.generic): | ||
| pydict[key] = value.item() | ||
| else: | ||
| pydict[key] = value |
There was a problem hiding this comment.
Iterating over columns and calling self._batch[key].iloc[self._row_idx] is inefficient because it performs .iloc once, and then iterating over its items.
| for key in self: | |
| value = self._batch[key].iloc[self._row_idx] | |
| # Convert NA to None for consistency across block formats. `pd.isna` | |
| # returns True for both NA and NaN, but since we want to preserve NaN | |
| # values, we check for identity instead. | |
| if is_scalar(value) and value is pd.NA: | |
| pydict[key] = None | |
| elif isinstance(value, TensorArrayElement): | |
| pydict[key] = value.to_numpy() | |
| elif isinstance(value, np.generic): | |
| pydict[key] = value.item() | |
| else: | |
| pydict[key] = value | |
| row_series = self._batch.iloc[self._row_idx] | |
| for key, value in row_series.items(): | |
| # Convert NA to None for consistency across block formats. `pd.isna` | |
| # returns True for both NA and NaN, but since we want to preserve NaN | |
| # values, we check for identity instead. | |
| if is_scalar(value) and value is pd.NA: | |
| pydict[key] = None | |
| elif isinstance(value, TensorArrayElement): | |
| pydict[key] = value.to_numpy() | |
| elif isinstance(value, np.generic): | |
| pydict[key] = value.item() | |
| else: | |
| pydict[key] = value |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Reviewed by Cursor Bugbot for commit c0d0881. Configure here.
| # See https://stackoverflow.com/questions/9452775/converting-numpy-dtypes-to-native-python-types. # noqa: E501 | ||
| return tuple(item for item in items) | ||
|
|
||
| return tuple(v.item() if hasattr(v, "item") else v for v in items) |
There was a problem hiding this comment.
Size-one arrays unwrapped by item
High Severity
PandasRow.__getitem__ calls .item() on every value that defines that method, including numpy arrays. Size-1 tensors and arrays therefore collapse to scalars, so row access no longer preserves array shape. as_pydict avoids this by only converting np.generic scalars.
Reviewed by Cursor Bugbot for commit c0d0881. Configure here.
| col_idx = schema.get_field_index(col_name) | ||
| if col_idx == -1: | ||
| # key not found | ||
| return None |
There was a problem hiding this comment.
Missing columns return None
Medium Severity
A missing column name now returns None instead of raising KeyError. Because both row types implement Mapping, membership tests and .get() with a default also treat absent columns as present, so a typo or stale name is silently accepted.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit c0d0881. Configure here.
…nsor values (#66219) ## Why `ArrowRow` and `PandasRow` are the `Mapping`s Ray Data hands out for a single row of a block. #66116 made both a lazy view over `(block, row_idx)` instead of slicing the block down to one row — a large speedup — but rewriting `__getitem__` changed three behaviours along the way. **A missing column stopped raising, inconsistently.** Measured on master: ``` arrow row["missing"] -> KeyError arrow row[["a", "missing"]] -> None <- silent pandas row["missing"] -> None <- silent ``` Both formats raised before #66116, via `table.select(keys)` and `df[keys]`. Arrow now only raises by accident: the tensor-type check does `schema.field(keys[0])` before the `get_field_index` guard, so the *first* key throws and the `col_idx == -1` branch is reachable only from the second key onward. **So `row.get()` answered differently per block format.** `Mapping.get` returns its default by catching `KeyError`, so `row.get("missing", 0)` returned `0` on Arrow and `None` on pandas — same dataset, different answer depending on whether an upstream operator left the block in pandas. **Tensor values lost their shape.** Pandas values are unwrapped with `v.item() if hasattr(v, "item")`, and `ndarray` has `.item()`. A shape-`(1,)` tensor silently became a Python scalar, so `row["emb"].shape` raised `AttributeError`. Larger tensors raised `ValueError`, which the `except` caught and recovered from — but logged a warning per lookup with the whole tensor formatted into the message. 30 lookups produced 30 warnings; on a 100k-row block of 224x224x3 images that is 100k tracebacks each rendering 150,000 numbers. ## What changes - Both classes raise `KeyError(col_name)` for a missing column, in the single-key and list forms alike. `ArrowRow` resolves every column index before the tensor probe, so the result no longer depends on a key's position. - `PandasRow` unwraps only `np.generic`, which is what `as_pydict` two methods down already does. `ArrowRow` returns tensor values as arrays via `_build_tensor_row` rather than `as_py()`, so this is the rule both formats now follow: scalars become Python natives, arrays stay arrays. The `try`/`except`/`logger.warning` is removed — `np.generic.item()` cannot raise. - `row[[]]` returns `()` in both, making `ArrowRow`'s unreachable `if not items` guard reachable. It previously returned `None` on Arrow and raised `IndexError` on pandas. - 19 tests across `test_arrow_block.py` and `test_pandas_block.py`. 10 of them fail against the current code. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Aarrya <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…able (ray-project#66116) ## Description `ArrowRow` and `PandasRow` are the objects Ray Data hands out for a single row of a block. Both are currently built by slicing the block down to one row: ```python def _get_row(self, index): base_row = self.slice(index, index + 1, copy=False) return ArrowRow(base_row) ``` and subscripting then selects a second time: ```python table = self._row.select(keys) items = [col[0] for col in table.columns] ``` Reading one field therefore costs two intermediate tables plus one sliced array per column in the block, regardless of how few columns the caller asked for. This PR makes both row types a lazy view over `(block, row_idx)`. Construction copies nothing, and subscripting indexes only the requested columns at `row_idx`. Paths affected: `BlockAccessor.iter_rows(public_row_format=False)` (row-wise `AggregateFn`s, `write_sql`, `write_kafka`, row-oriented file sinks), `BlockAccessor._iter_groups_sorted` (one row object per group on the group-by aggregation path), `PandasBlockAccessor.iter_rows(public_row_format=True)`, and `RandomAccessDataset`. ## Related issues N/A ## Additional information Benchmark: 100,000 rows, 3 columns (`int64`, `float64`, `string`), iterating every row with `BlockAccessor.iter_rows()`. | Backend | `public_row_format` | Before (rows/s) | After (rows/s) | Speedup | |---|---|---|---|---| | Arrow | `True` | 2,154,681 | 2,076,942 | unchanged | | Arrow | `False` | 1,748,955 | 11,051,250 | 6.3x | | Pandas | `True` | 6,063 | 170,909 | 28x | | Pandas | `False` | 189,162 | 10,692,995 | 57x | `public_row_format=True` yields plain `dict`s; `False` yields the `ArrowRow`/`PandasRow` objects this PR changes. Arrow's `True` path is unchanged because it goes through `table.to_batches()` → `batch.to_pylist()` and never constructs an `ArrowRow`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Aarrya <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…nsor values (ray-project#66219) ## Why `ArrowRow` and `PandasRow` are the `Mapping`s Ray Data hands out for a single row of a block. ray-project#66116 made both a lazy view over `(block, row_idx)` instead of slicing the block down to one row — a large speedup — but rewriting `__getitem__` changed three behaviours along the way. **A missing column stopped raising, inconsistently.** Measured on master: ``` arrow row["missing"] -> KeyError arrow row[["a", "missing"]] -> None <- silent pandas row["missing"] -> None <- silent ``` Both formats raised before ray-project#66116, via `table.select(keys)` and `df[keys]`. Arrow now only raises by accident: the tensor-type check does `schema.field(keys[0])` before the `get_field_index` guard, so the *first* key throws and the `col_idx == -1` branch is reachable only from the second key onward. **So `row.get()` answered differently per block format.** `Mapping.get` returns its default by catching `KeyError`, so `row.get("missing", 0)` returned `0` on Arrow and `None` on pandas — same dataset, different answer depending on whether an upstream operator left the block in pandas. **Tensor values lost their shape.** Pandas values are unwrapped with `v.item() if hasattr(v, "item")`, and `ndarray` has `.item()`. A shape-`(1,)` tensor silently became a Python scalar, so `row["emb"].shape` raised `AttributeError`. Larger tensors raised `ValueError`, which the `except` caught and recovered from — but logged a warning per lookup with the whole tensor formatted into the message. 30 lookups produced 30 warnings; on a 100k-row block of 224x224x3 images that is 100k tracebacks each rendering 150,000 numbers. ## What changes - Both classes raise `KeyError(col_name)` for a missing column, in the single-key and list forms alike. `ArrowRow` resolves every column index before the tensor probe, so the result no longer depends on a key's position. - `PandasRow` unwraps only `np.generic`, which is what `as_pydict` two methods down already does. `ArrowRow` returns tensor values as arrays via `_build_tensor_row` rather than `as_py()`, so this is the rule both formats now follow: scalars become Python natives, arrays stay arrays. The `try`/`except`/`logger.warning` is removed — `np.generic.item()` cannot raise. - `row[[]]` returns `()` in both, making `ArrowRow`'s unreachable `if not items` guard reachable. It previously returned `None` on Arrow and raised `IndexError` on pandas. - 19 tests across `test_arrow_block.py` and `test_pandas_block.py`. 10 of them fail against the current code. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Aarrya <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…able by pandas (#67576) (#67649) Cherry-pick of #67576 (master commit d6974fe) onto `releases/2.59.1`. ## Why Since #61733 (2.56), the batch a pandas UDF returns becomes an Arrow block built by `pa.Table.from_pandas`, which records each column's pandas dtype name in the block's metadata. pandas cannot parse the names of parametrized Arrow-backed dtypes. So when `enable_arrow_backed_pandas_conversion` is off, a UDF that returns an Arrow-backed list, struct or map column makes the next `to_pandas()` fail with `TypeError: data type 'list<item: int64>[pyarrow]' not understood`. `pd.read_parquet` fails the same way on files written from these blocks. A customer hit this upgrading from 2.55 to 2.59. #67576 rewrites each unparsable dtype name to `object` when `_from_pandas_safe` builds the block, and leaves names that parse, such as `Int64`, alone. ## Cherry-pick details Picked with `git cherry-pick -x`. `pandas_block.py` applied cleanly. `test_pandas_block.py` conflicted in two places, because master's copy has `PandasRow` tests and an import from #66116 and #66219, which aren't on this branch. I resolved it by keeping only #67576's lines: the `_parsable_pandas_metadata` import, the `_pandas_metadata_dtype_names` helper and the three new tests. In both files, the added and removed lines are identical to master's, and the commit is +114/-1 like #67576. No prerequisite commits are missing. After the pick, `_from_pandas_safe`, `_with_parsable_pandas_metadata` and `_parsable_pandas_metadata` are identical to master's, and the `restore_data_context` and `ray_start_regular_shared` fixtures the new tests use exist on this branch. Not a duplicate: this branch doesn't contain #67576, and no PR against `releases/2.59.1` references it. #67648 picks the same commit onto `releases/2.60.0`. ## Testing | Command | Result | |---|---| | `pre-commit run --files python/ray/data/_internal/pandas_block.py python/ray/data/tests/test_pandas_block.py` | Passed | | `pytest python/ray/data/tests/test_pandas_block.py python/ray/data/tests/test_arrow_block.py` | 83 passed | | #67576's repro (pandas UDF returning an Arrow-backed list column, flag off), without and with the pick | Without: `TypeError: data type 'list<item: int64>[pyarrow]' not understood`. With: returns the lists as an `object` column | I ran these against PyPI's `ray==2.59.0` wheel with this branch's `python/ray/data` copied over it, on Python 3.12 and pandas 2.3.3 (the version CI pins). `python/ray/data` has no changes between `ray-2.59.0` and `releases/2.59.1`. Building Ray from source for `bazel test` wasn't practical on my machine. AI assistance was used to prepare this cherry-pick. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Marwan Sarieddine <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Ayush Kumar <[email protected]>


Description
ArrowRowandPandasRoware the objects Ray Data hands out for a single row of a block. Both are currently built by slicing the block down to one row:and subscripting then selects a second time:
Reading one field therefore costs two intermediate tables plus one sliced array per column in the block, regardless of how few columns the caller asked for.
This PR makes both row types a lazy view over
(block, row_idx). Construction copies nothing, and subscripting indexes only the requested columns atrow_idx.Paths affected:
BlockAccessor.iter_rows(public_row_format=False)(row-wiseAggregateFns,write_sql,write_kafka, row-oriented file sinks),BlockAccessor._iter_groups_sorted(one row object per group on the group-by aggregation path),PandasBlockAccessor.iter_rows(public_row_format=True), andRandomAccessDataset.Related issues
N/A
Additional information
Benchmark: 100,000 rows, 3 columns (
int64,float64,string), iterating every row withBlockAccessor.iter_rows().public_row_formatTrueFalseTrueFalsepublic_row_format=Trueyields plaindicts;Falseyields theArrowRow/PandasRowobjects this PR changes. Arrow'sTruepath is unchanged because it goes throughtable.to_batches()→batch.to_pylist()and never constructs anArrowRow.🤖 Generated with Claude Code