Skip to content

[Data] Restore KeyError on missing row columns and stop unwrapping tensor values - #66219

Merged
goutamvenkat-anyscale merged 2 commits into
ray-project:masterfrom
AarryaSaraf:data-fix-row-lookup-semantics
Sep 17, 2026
Merged

goutamvenkat-anyscale merged 2 commits into
ray-project:masterfrom
AarryaSaraf:data-fix-row-lookup-semantics

Conversation

@AarryaSaraf

Copy link
Copy Markdown
Contributor

Why

ArrowRow and PandasRow are the Mappings 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

…nsor values

Signed-off-by: Aarrya <[email protected]>
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@AarryaSaraf
AarryaSaraf marked this pull request as ready for review September 17, 2026 00:36
@AarryaSaraf
AarryaSaraf requested a review from a team as a code owner September 17, 2026 00:36
@AarryaSaraf AarryaSaraf added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Sep 17, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors column access in ArrowRow and PandasRow to improve robustness by resolving column indices upfront and raising KeyError for missing columns. It also refines the handling of NumPy scalars and tensor types to ensure consistent behavior. The reviewer identified a critical bug in ArrowRow where the tensor extension type check only considers the first column, which fails for mixed-type column access, and suggested a fix along with additional test cases to cover mixed-column scenarios.

Comment on lines 117 to +120
# Check for tensor extension type on first key
if isinstance(schema.field(keys[0]).type, tensor_arrow_extension_types):
if isinstance(
schema.field(col_indices[0]).type, tensor_arrow_extension_types
):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Checking only the first key's type (col_indices[0]) to decide whether to use _build_tensor_row or as_py() is problematic for rows with mixed column types (e.g., a mix of tensor and non-tensor columns).

  1. First key is a tensor column (e.g., row[["emb", "a"]]):
    It will attempt to call _build_tensor_row on all keys. For the non-tensor column "a", _build_tensor_row will call as_py() which returns a scalar (e.g., int), causing assert isinstance(arr, np.ndarray) to raise an AssertionError.
  2. First key is a non-tensor column (e.g., row[["a", "emb"]]):
    It will fall back to the as_py() path for all columns, which might not handle the tensor column correctly.

To fix this, the column type check and conversion should be performed individually per column/key rather than assuming all keys share the same type as the first key.

Here is a suggested implementation for get_item that processes columns individually:

        def get_item(keys: List[str]) -> Tuple[Any, ...]:
            # Resolve every column up front so that a missing one raises, rather
            # than depending on its position in ``keys``.
            col_indices = []
            for col_name in keys:
                col_idx = schema.get_field_index(col_name)
                if col_idx == -1:
                    raise KeyError(col_name)
                col_indices.append(col_idx)

            if not col_indices:
                return ()

            results = []
            for col_name, col_idx in zip(keys, col_indices):
                col_type = schema.field(col_idx).type
                if isinstance(col_type, tensor_arrow_extension_types):
                    val = ArrowBlockAccessor._build_tensor_row(
                        self._batch, col_name=col_name, row_idx=self._row_idx
                    )
                else:
                    item = self._batch.column(col_idx)[self._row_idx]
                    try:
                        val = item.as_py()
                    except AttributeError:
                        val = item
                results.append(val)
            return tuple(results)

Comment on lines +514 to +515
assert type(row["a"]) is int
np.testing.assert_array_equal(row["emb"], np.array([1]))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To prevent regressions and ensure that mixed-type column access works correctly, we should add test cases for mixed columns (e.g., row[["emb", "a"]] and row[["a", "emb"]]). Currently, these will fail or behave incorrectly due to the first-key type check in ArrowRow.__getitem__.

Suggested change
assert type(row["a"]) is int
np.testing.assert_array_equal(row["emb"], np.array([1]))
assert type(row["a"]) is int
np.testing.assert_array_equal(row["emb"], np.array([1]))
# Test mixed columns
mixed_res = row[["emb", "a"]]
assert type(mixed_res[1]) is int
np.testing.assert_array_equal(mixed_res[0], np.array([1]))
mixed_res_reverse = row[["a", "emb"]]
assert type(mixed_res_reverse[0]) is int
np.testing.assert_array_equal(mixed_res_reverse[1], np.array([1]))

@goutamvenkat-anyscale
goutamvenkat-anyscale merged commit aa608b1 into ray-project:master Sep 17, 2026
7 checks passed
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…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]>
elliot-barn pushed a commit that referenced this pull request Oct 31, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants