Skip to content

[cherry-pick][2.59.2][Data] Keep every element of nested-null columns in Arrow-backed to_pandas (#67566) - #68022

Merged
sai-miduthuri merged 1 commit into
releases/2.59.2from
sai-miduthuri/cherry-pick-67566-2.59.2
Nov 13, 2026
Merged

sai-miduthuri merged 1 commit into
releases/2.59.2from
sai-miduthuri/cherry-pick-67566-2.59.2

Conversation

@sai-miduthuri

@sai-miduthuri sai-miduthuri commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Description

Cherry-pick of #67566 (master commit af8f74e) onto releases/2.59.2.

Since 2.56, ArrowBlockAccessor.to_pandas() maps each column to pd.ArrowDtype. Before pandas 3.1, pd.ArrowDtype.__from_arrow__ casts every column, even to its own type. Arrow's cast of a nested null child resizes that child to the number of rows, so elements disappear. For example, a list<null> column [[None, None], [None]] comes back as [[None, None], []]. When the batch goes back to Arrow untouched, it fails instead with ArrowInvalid: Length spanned by list offsets (3) larger than values array (length 2). Users hit this with sparse list columns.

#67566 maps types that nest a null type to a pd.ArrowDtype subclass that skips the identity cast.

Related issues

Related to #67566. The same pick for 2.60.1 is #67994.

Additional information

Cherry-pick details

Applied with git cherry-pick -x. arrow_block.py merged cleanly. test_arrow_block.py conflicted only on its import list: master also imports ArrowRow there, from a master-only change that this branch's tests don't use. I added only #67566's _arrow_backed_pandas_dtype import. The added and removed lines are identical to the master commit, and git patch-id differs only because of that context line.

No prerequisite commits are missing. The new code hooks into _arrow_backed_pandas_dtype, which this branch already has from the #66578 pick (#66617). The two files differ from master at af8f74e only by master commits this change doesn't use.

This PR and the #67579 pick (#68025) both edit arrow_block.py and test_arrow_block.py. This commit merges cleanly with the #66521, #67579 and #67806 stack and passes the tests below.

Not a duplicate: this branch doesn't contain #67566, and no PR against releases/2.59.2 references it. #67994 picks the same commit onto releases/2.60.1.

Testing

Command Result
pre-commit run --files <the 2 changed files> Passed
pytest python/ray/data/tests/test_arrow_block.py python/ray/data/tests/test_pandas_block.py 87 passed
pytest python/ray/data/tests/test_arrow_block.py, run with this PR's tests against the branch code without the fix 3 failed (the 3 new nested-null cases of test_arrow_block_to_pandas_preserves_arrow_types_through_roundtrip), 24 passed
pytest test_arrow_block.py test_pandas_block.py test_tensor_extension.py, with the #66521, #67579 and #67806 stack also applied 365 passed

I ran these against the Ray 2.59.1 release wheel, with this branch's python/ray/data and python/ray/tests copied over it. The wheel was built from releases/2.59.1 at 7bdaad7, and its Python sources match releases/2.59.2 except for _version.py. The environment was Python 3.12 with pandas 2.3.3, pyarrow 23.0.1 and numpy 2.1.3, the versions CI pins on this branch. 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

…andas (#67566)

A pandas batch silently loses elements from a column whose type nests
Arrow's null type, such as `list<null>`. This PR converts those columns
to Arrow-backed pandas columns without the cast that drops the elements.

- Since 2.56, `ArrowBlockAccessor.to_pandas()` maps each column to
`pd.ArrowDtype`. Before pandas 3.1, `pd.ArrowDtype.__from_arrow__` casts
every column, even to its own type.
- Arrow's cast of a nested null child resizes that child to the number
of rows. Elements past that point disappear.
- A list of all-null values is typed `list<null>` when no row has a real
value. Users see it with sparse list columns.

```python
import pyarrow as pa, ray

t = pa.table({"x": pa.array([[None, None], [None]], type=pa.list_(pa.null()))})
ds = ray.data.from_arrow(t).map_batches(
    lambda df: {"x": [list(v) for v in df["x"]]}, batch_format="pandas"
)
print(ds.take_all())
```

| | Output |
|---|---|
| Current (pandas < 3.1) | `[{'x': [None, None]}, {'x': []}]` |
| Expected | `[{'x': [None, None]}, {'x': [None]}]` |

When the batch goes back to Arrow untouched, the same column fails
instead: `ArrowInvalid: Length spanned by list offsets (3) larger than
values array (length 2)`.

```
              Before                                     After
Arrow block ──types_mapper──▶ pd.ArrowDtype    Arrow block ──types_mapper──▶ _ArrowDtypeWithoutIdentityCast
                 │                                               │
     __from_arrow__: cast(list<null>)              __from_arrow__: same type, no cast
                 │                                               │
                 ▼                                               ▼
  list<null>[pyarrow], child cut to N rows        list<null>[pyarrow], every element kept
```

- `_arrow_backed_pandas_dtype` returns `_ArrowDtypeWithoutIdentityCast`
for a type with a null type nested anywhere inside it. The subclass's
`__from_arrow__` skips the cast to the column's own type, which is what
pandas 3.1 does for every column.
- The column it builds carries a plain `pd.ArrowDtype`, and the subclass
compares equal to that dtype, so users see no dtype change.
- pyarrow handles the column like any other. In particular it never
reads the block's pandas metadata for it, which names a dtype string
pandas cannot parse (`list<item: null>[pyarrow]`). That is what broke
the first version of this PR on a block coming back from a pandas UDF.
- Other columns are untouched. With
`enable_arrow_backed_pandas_conversion=False`, nothing changes.

- The fix skips the identity cast for nested-null types only. Returning
the subclass for every column would match pandas 3.1 exactly and drop
`_has_nested_null_type`, at the cost of changing the conversion path of
every column on pandas < 3.1.
- A top-level `struct<a: null>` casts correctly but takes the new path
too, because one rule ("any nested null") is simpler to reason about.

Block / data format (`arrow_block.py`).

- Reported by a customer upgrading from 2.55 to 2.59.
- Follows #64768, which added `enable_arrow_backed_pandas_conversion`.
- Not a duplicate: no open issue or PR covers nested null types in
`to_pandas()`.
- Fixed in #67576, now merged; this branch carries it, which the pyarrow
17 CI job needs: with the flag off, a pandas UDF that returns its own
`pd.ArrowDtype` list column makes the next `to_pandas()` fail with the
same "not understood" error. Since #61733 the UDF's batch becomes an
Arrow block with pandas metadata, and with no mapper pyarrow reads that
metadata. On 2.55 the batch stayed a pandas block and it worked.

The three nested-null cases of the round-trip test fail without the fix
and pass with it. The sliced `list<null>` case aborts the worker inside
Arrow on master (`Slice offset (3) greater than array length (2)`),
which is what a pandas UDF hits when `batch_size` is smaller than the
block. Run locally with pandas 2.3.3 and pyarrow 23.0.1:

```
pytest python/ray/data/tests/test_arrow_block.py \
       python/ray/data/tests/test_pandas_block.py \
       python/ray/data/tests/test_transform_pyarrow.py \
       python/ray/data/tests/preprocessors --ignore=.../test_torch.py   # 563 passed, 5 skipped
pytest python/ray/data/tests/test_map_batches.py python/ray/data/tests/test_batcher.py   # 766 passed, 1 failed (test_local_shuffle_buffer_warns_if_too_large: OutOfDiskError from a full local disk, fails the same way without this change)
```

The `__from_arrow__` and equality behaviour of the subclass was also
checked on pandas 2.2.3 (Ray's floor) and 3.1.0 against every type in
the parametrized test.

AI assistance (Claude Code) was used to reproduce the bug and write this
change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
(cherry picked from commit af8f74e)
Signed-off-by: Sai Miduthuri <[email protected]>

@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 introduces a workaround for a pandas bug (prior to version 3.1) where casting nested null types (like list) resizes the nested null child to the number of rows. It introduces _has_nested_null_type and a custom _ArrowDtypeWithoutIdentityCast class to skip the identity cast when constructing Arrow-backed pandas columns. Additionally, comprehensive unit tests are added to verify the round-trip behavior and ensure the custom dtype behaves identically to a plain pd.ArrowDtype in comparisons and hashing. There are no review comments to address, and I have no additional feedback to provide.

@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Nov 10, 2026
@sai-miduthuri sai-miduthuri added the go add ONLY when ready to merge, run all tests label Nov 10, 2026
@sai-miduthuri
sai-miduthuri merged commit e38a6e1 into releases/2.59.2 Nov 13, 2026
7 checks passed
@sai-miduthuri
sai-miduthuri deleted the sai-miduthuri/cherry-pick-67566-2.59.2 branch November 13, 2026 00:59
sai-miduthuri added a commit that referenced this pull request Nov 13, 2026
…ble across blocks (#67579) (#68025)

## Description

Cherry-pick of #67579 (master commit
1acc2c3) onto `releases/2.59.2`.

**Middle of a 3-PR stack on `releases/2.59.2`:** #68024 (the #66521
pick), then this PR, then #68026 (the #67806 pick, which fixes this
change on pyarrow 26). Merge the stack with `gh stack merge 68026`,
which lands all three in order.

Since #61733 (2.56), a batch that spans blocks whose tensor column is
null in one of them fails with `ValueError: Trying to unify unsupported
tensor type: null`. A pandas UDF that returns `None` for some rows and
an ndarray for others is enough to hit it. It worked in 2.55.

#67579 lets tensor arrays carry null rows, so these blocks merge, the
column stays a tensor column, and missing rows read back as `None`.

## Related issues

Related to #67579. Depends on #68024, the #66521 pick. The same pick for
2.60.1 is #67999.

## Additional information

### Cherry-pick details

Applied with `git cherry-pick -x`. 5 of the 10 files merged cleanly. In
the other 5, each conflict was master-only code that sits next to
#67579's additions:

| File | Master-only context | Kept from #67579 |
|---|---|---|
| `arrow_ops/transform_pyarrow.py` | the `chunked_tensor_take` imports
(#64961) | the `create_ragged_ndarray` import |
| `tensor_extensions/arrow.py` | `tensor_array_to_numpy` and
`_to_dense_ndarray_or_none` (#66122) | `native_tensor_array_to_numpy` |
| `tensor_extensions/pandas.py` | the `TensorArray.dtype` docstring
reformat (#67539) | `first = _first_non_null(self._tensor)`, under this
branch's docstring |
| `tests/test_arrow_block.py` | earlier tests, such as #65539's | the 68
lines of new tests |
| `tests/test_tensor_extension.py` | #66122's tests | the 280 lines of
new tests |

I resolved each conflict by applying only #67579's change relative to
its parent, which was a pure insertion every time, and dropping the
master-only lines. Across all 10 files, the added and removed lines are
identical to the master commit. `git patch-id` differs only because of
the context lines.

Prerequisite: #66521. Without it,
`test_arrow_concat_tensor_with_null_keeps_tensor_type[last_shape1]` and
`test_unify_schemas_tensor_with_null_keeps_tensor_type[other_shape1]`
fail on this branch, as they do on 2.60.1.

Not a duplicate: this branch doesn't contain #67579, and no PR against
`releases/2.59.2` references it. #67999 picks the same commit onto
`releases/2.60.1`.

### Testing

The six test files, under `python/ray/data/tests/`, are
`test_arrow_block.py test_tensor_extension.py test_torch_tensor_utils.py
unit/test_transform_pyarrow.py test_transform_pyarrow.py
test_pandas_block.py`.

| Command | Result |
|---|---|
| `pre-commit run --files <the 10 changed files>` | Passed |
| `pytest <the six files>`, with the whole stack (#66521, this PR,
#67806) | 478 passed |
| `pytest --continue-on-collection-errors <the six files>`, with this
PR's tests against the code with only #66521 | 60 failed, 203 passed,
and `test_tensor_extension.py` fails to collect, because it imports a
helper this PR adds |
| `pytest <the six files>`, with this pick directly on
`releases/2.59.2`, without #66521 | The 2 tests above fail, 465 passed |
| `pytest test_arrow_block.py test_pandas_block.py
test_tensor_extension.py`, with the stack and the #67566 pick (#68022)
applied together | 365 passed |

I ran these against the Ray 2.59.1 release wheel, with this branch's
`python/ray/data` and `python/ray/tests` copied over it. The wheel was
built from `releases/2.59.1` at 7bdaad7, and its Python sources match
`releases/2.59.2` except for `_version.py`. The environment was Python
3.12 with pandas 2.3.3, pyarrow 23.0.1, numpy 2.1.3, scipy 1.17.1 and
torch 2.9.0+cpu, the versions CI pins on this branch. 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: Elliot Barnwell <[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: Elliot Barnwell <[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.

3 participants