Repository navigation
[Data] Keep every element of nested-null columns in Arrow-backed to_pandas - #67566
Conversation
…andas Problem: - Before pandas 3.1, pd.ArrowDtype.__from_arrow__ casts a column even to its own type. - Arrow's cast resizes a nested null child to the number of rows. A list<null> [[None, None], [None]] comes back as [[None, None], []]. - Pandas UDFs then see shortened lists, or the batch fails with ArrowInvalid when it goes back to Arrow. Change: - _arrow_backed_pandas_dtype returns None for types that nest a null. - to_pandas wraps those columns as ArrowExtensionArray directly, with no cast. The dtype is the same pd.ArrowDtype as before. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces support for handling nested null types (such as list or struct<a: null>) during Arrow-to-Pandas conversion in Ray Data, preventing nested null children from being incorrectly resized. It adds helper functions _has_nested_null_type and _wrap_nested_null_columns to wrap these columns as Arrow-backed without casting, along with corresponding unit tests. The review feedback suggests two important improvements: first, updating _has_nested_null_type to correctly inspect dictionary value types, and second, ensuring _wrap_nested_null_columns handles numpy integer types returned by pandas' get_loc to avoid silently skipping column wrapping.
…ping them Problem: - Mapping a nested-null column to no dtype made pyarrow read the block's pandas metadata for it. A block that came back from a pandas UDF names the Arrow-backed dtype there, and pandas cannot parse that string, so the next to_pandas() failed with "data type 'list<item: null>[pyarrow]' not understood". - The in-place wrapping also depended on column positions after the fact. Change: - The types mapper returns _ArrowDtypeWithoutIdentityCast for nested-null types. Its __from_arrow__ skips the cast to the column's own type, as pandas 3.1 does, so pyarrow handles the column like any other. - The column keeps a plain pd.ArrowDtype, and the mapper's dtype compares equal to it. - Tests cover the second conversion through a round-tripped block and the pandas-UDF-then-to_pandas path. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
Problem: - The nested-null cases lived in their own parametrized test next to the existing round-trip test that checks the same things. Change: - The round-trip test takes the nested-null cases, checks the dtype both ways, and converts the round-tripped block to pandas a second time. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
|
Nit: it would be good to track somewhere that we can clean this up once pandas minimum becomes 3.1 in Ray. Perhaps a code comment as a todo? |
Change: - A TODO on _ArrowDtypeWithoutIdentityCast: remove it once Ray requires pandas >= 3.1, which skips the identity cast itself. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
|
Fixed in 3621344. A TODO on |
## Summary A pandas UDF that returns an Arrow-backed list column makes the next `to_pandas()` fail with "data type 'list<item: int64>[pyarrow]' not understood" when `enable_arrow_backed_pandas_conversion` is off. This PR makes the pandas metadata on blocks built from pandas batches parsable by pandas, so pyarrow falls back to its own conversion for those columns. ## Problem - Since #61733 (2.56), the batch a pandas UDF returns becomes an Arrow block right away. With no object column, `pa.Table.from_pandas` builds it and records each column's pandas dtype name in the block's metadata. - When `to_pandas()` has no types mapper for a column, pyarrow rebuilds the dtype from that name. pandas cannot parse the names of parametrized Arrow-backed dtypes, so the conversion raises. - The flag-off path has no mapper, so any Arrow-backed list, struct or map column from a UDF breaks it. A `dictionary` Arrow-backed column breaks the flag-on path too, because the mapper returns `None` for dictionary types. - `write_parquet` carries the same metadata into files, and `pd.read_parquet` fails on them the same way. ```python import pyarrow as pa, pandas as pd, ray ray.data.DataContext.get_current().enable_arrow_backed_pandas_conversion = False def udf(df): return pd.DataFrame({"x": pd.array([[1, 2], [3]], dtype=pd.ArrowDtype(pa.list_(pa.int64())))}) ray.data.from_items([{"x": 1}, {"x": 2}]).map_batches(udf, batch_format="pandas").to_pandas() ``` | | Result | |---|---| | 2.55 | works, the batch stays a pandas block | | 2.56 to master | `TypeError: data type 'list<item: int64>[pyarrow]' not understood` | | After | works, `x` is an object column of arrays | ## Change A pandas batch becomes an Arrow block with a note of each column's pandas dtype. One note is unreadable, so the next `to_pandas()` crashes. The fix rewrites just that note when the block is built. ``` column pandas dtype note before after x list<item: int64>[pyarrow] TypeError object (pyarrow's default) n Int64 Int64 Int64 (unchanged) ``` - `_from_pandas_safe` rewrites each dtype name pandas cannot parse to `object` on the fast path. The slow path builds the table column by column and never had metadata. - Names that parse are left alone, so the flag-off path still restores nullable dtypes such as `Int64`, `boolean` and `string`. - The rewrite is cached on the metadata bytes. For scale: the uncached check on a 51-column schema costs about as much as the `from_pandas` call it follows, and the cached path is a dictionary lookup. ## Decisions to confirm - Rewriting only the unparsable names, rather than dropping the metadata or passing `ignore_metadata=True`. Dropping it would turn a UDF's `Int64` column with nulls into `float64` on the flag-off path, which 2.56 to 2.59 restore today. - Doing it where the block is built, rather than in `to_pandas()`. Blocks are built once and read many times, and files written from them become readable by pandas. ## Subsystems Block / data format (`pandas_block.py`). ## Related - Reported by a customer upgrading from 2.55 to 2.59, found while fixing #67566. - The same metadata path broke the first version of #67566; this PR covers the case that version left behind. - #56402 added `pandas_block_ignore_metadata` for tensor dtype names in the same metadata; it is off by default. - Upstream: pandas cannot parse its own Arrow-backed dtype names, tracked in pandas-dev/pandas#57411. The pandas fix, pandas-dev/pandas#66758, is on hold behind the wider pyarrow compatibility work in pandas-dev/pandas#59780, so Ray rewrites the names on its side until a pandas release carries it. - Not a duplicate: no open issue or PR covers unparsable pandas dtype names on blocks. ## Testing The new tests fail without the fix and pass with it: ``` pytest python/ray/data/tests/test_pandas_block.py python/ray/data/tests/test_arrow_block.py # 103 passed pytest python/ray/data/tests/test_map_batches.py python/ray/data/tests/datasource/test_parquet.py \ python/ray/data/tests/test_transform_pyarrow.py python/ray/data/tests/preprocessors # 1474 passed, 11 skipped ``` AI assistance (Claude Code) was used to find the root cause and write this change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Ayush Kumar <[email protected]>
…andas-nested-null
|
The fix also covers a worse symptom than the one in the description. When the pandas UDF gets a slice of the block ( Ray counts that as a system failure and retries the task with no limit. The repro from the description with Other inputs I checked on 5484fa4 and on the merge base d6974fe, with pandas 3.0.6 and 2.2.3 (pyarrow 26.0.0): a sliced block (offset 1), a two-chunk column,
Outside this PR: |
…7579) ## Summary A batch that spans blocks whose tensor column is null in one of them fails with "Trying to unify unsupported tensor type: null". This PR lets tensor arrays carry null rows, so such blocks merge and the column stays a tensor column, with `None` for the missing rows. A column that is a tensor in one block and pickled objects in another keeps raising; a follow-up PR extends that error with the columns and types found. ## Problem - Since #61733 (2.56), the batch a pandas UDF returns becomes an Arrow block right away. Each one-row block types a column from its own value: a stacked array becomes a tensor, `None` becomes null. - Merging those blocks into a batch reconciles the schemas. A tensor with a null arm passed reconciliation and then failed in the tensor unifier, which rejected null. - Tensor arrays could already hold null rows, but `to_numpy()` on them failed with "buffer is too small", so nothing could read them (#67200). - In 2.55 the batches stayed pandas blocks, so there was no Arrow schema to unify. ```python import numpy as np, ray def decode(batch): row = int(batch["id"][0]) return {"img": [None if row == 5 else np.full((2, 2), row, np.float32)]} ds = ray.data.range(8).map_batches(decode, batch_size=1) next(iter(ds.iter_batches(batch_size=8, batch_format="numpy"))) ``` | | Result | |---|---| | 2.55 | works | | 2.56 to master | `ValueError: Trying to unify unsupported tensor type: null` | | After | works, `img` is a tensor column with `None` in row 5 | ## Change ``` block 1 img = stacked array -> tensor block 2 img = None -> null Before: unify schemas -> tensor -> concat: "unsupported tensor type: null" After: unify schemas -> tensor -> null chunk becomes null rows of the tensor type ``` - `unify_tensor_arrays` turns a null-typed chunk into null rows of the unified tensor type, so `concat` keeps the column a tensor column. - Both tensor array classes read null rows: `to_numpy()` returns one ndarray view per row with `None` for each null row, and `from_numpy()` accepts `None` among the tensors. A variable-shaped row is null when its struct slot or either child is null. Null rows survive promotion to the variable-shaped type. - `TensorArray` accepts `None` rows, so such a column converts to pandas and back. - The torch conversion error names `None` rows instead of blaming ragged shapes. - A column that is a tensor in one block and pickled objects in another still raises "Found columns with both objects and tensors". Merging them would silently turn every row into a pickled object and lose the type. What a batch looks like, for a tensor column where one row is missing: | batch | before | after | |---|---|---| | no missing row | error | `float32 (8, 2, 2)` | | one missing row | error | `object (8,)`, views and `None`, nothing pickled | | schema | error | tensor | ## Decisions to confirm - A batch holding a null row comes back as one ndarray per row with `None`, since a dense array has no slot for a missing row. Filling the row with zeros or NaN would invent data and has no form for integer or ragged tensors. - `from_numpy()` with `None` among the tensors now builds a tensor array with null rows. Before, such a column fell back to pickled objects with a warning. - Tensors next to pickled objects keep raising rather than merging to objects, per review. Users make every row the same kind, for example by returning ragged arrays as nested lists. ## Subsystems Block / data format (`arrow_ops/transform_pyarrow.py`, `tensor_extensions/arrow.py`, `tensor_extensions/pandas.py`). ## Related - Reported by a customer upgrading from 2.55 to 2.59, alongside #67566. - Fixes #67200: `to_pandas()` and numpy batches now return `None` for a null tensor row instead of another row's value or an error. - Overlaps #67236, which makes the same two `to_numpy` paths null-aware and makes `to_pandas` raise on null rows. This PR also builds tensor arrays from input holding `None`, converts null rows to pandas and back, keeps them through shape promotion, and merges null chunks. The rule that a null child marks a null row is taken from #67236. - Leaves the native `fixed_shape_tensor` type alone; #67293 covers its null rows. - A follow-up PR extends the objects-and-tensors error with the columns and types found. ## Testing ``` pytest python/ray/data/tests/unit/test_transform_pyarrow.py \ python/ray/data/tests/test_transform_pyarrow.py \ python/ray/data/tests/test_arrow_block.py \ python/ray/data/tests/test_tensor_extension.py \ python/ray/data/tests/test_torch_tensor_utils.py # 387 passed ``` AI assistance (Claude Code) was used to find the root cause and write this change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Marwan Sarieddine <[email protected]> Signed-off-by: Elliot Barnwell <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Elliot Barnwell <[email protected]>
Problem: the parametrized round-trip test carried five nested-null cases that exercise the same cast as list<null>, and two map_batches tests that the round-trip test's second pandas conversion now covers. No case checked a sliced block, which is the input that makes the cast abort the worker on master. Change: keep the list<null> and list<list<null>> cases, add a sliced list<null> case, and drop the rest along with the two map_batches tests. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
|
Thanks, that is the same cast failing one level earlier. A sliced |
… in Arrow-backed to_pandas (#67566) (#67994) ## Description Cherry-pick of #67566 (master commit af8f74e) onto `releases/2.60.1`. 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. ## Additional information ### Cherry-pick details Applied cleanly with `git cherry-pick -x`. It has the same 2 files, +89/-2, and the same `git patch-id --stable` as the master commit. No prerequisite commits are missing. The new code hooks into `_arrow_backed_pandas_dtype`, which this branch already has from the #66578 pick (#66644). The two files differ from master at af8f74e only by master commits this change doesn't use. This PR and the #67579 pick both edit `arrow_block.py` and `test_arrow_block.py`. I applied this commit on top of the #66521 and #67579 picks, and it merges cleanly and passes the tests below. Not a duplicate: this branch doesn't contain #67566, and no PR against `releases/2.60.1` references it. ### 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` | 106 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`), 31 passed | | `pytest test_arrow_block.py test_pandas_block.py test_tensor_extension.py`, with the #66521 and #67579 picks also applied | 397 passed | I ran these against the Ray 2.60.0 release wheel, with this branch's `python/ray/data` and `python/ray/tests` copied over it. The wheel was built from `releases/2.60.0` at b7f4259, and its Python sources match `releases/2.60.1` except for `_version.py`. The environment was Python 3.12 with pandas 2.3.3 and pyarrow 23.0.1, the versions CI pins. 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 Opus 5.5 <[email protected]>
… in Arrow-backed to_pandas (#67566) (#68022) ## 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](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 Opus 5.5 <[email protected]>
…ble across blocks (#67579) (#67999) ## Description Cherry-pick of #67579 (master commit 1acc2c3) onto `releases/2.60.1`. **Middle of a 3-PR stack on `releases/2.60.1`:** #67995 (the #66521 pick), then this PR, then #68019 (the #67806 pick, which fixes this change on pyarrow 26). Merge the stack with `gh stack merge 68019`, 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 #67995, the #66521 pick. ## Additional information ### Cherry-pick details Applied with `git cherry-pick -x`. 9 of the 10 files merged cleanly. `tensor_extensions/pandas.py` conflicted only on the `TensorArray.dtype` docstring. Master had reformatted it in #67539 (ruff D212/D200), which isn't on this branch. I kept this branch's docstring and added the PR's one new line, `first = _first_non_null(self._tensor)`. The added and removed lines are identical to the master commit. `git patch-id` differs only because of that docstring context line. 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. These are the cases where the tensor blocks have different shapes. I applied each master-only commit that touched `transform_pyarrow.py` or the tensor extensions between the branch cut and #67579 on top of this pick. #66521 alone fixes both tests. The other files differ from master only by master commits this change doesn't use. Not a duplicate: this branch doesn't contain #67579, and no PR against `releases/2.60.1` references it. ### Testing All of these ran with the #66521 pick applied underneath. | Command | Result | |---|---| | `pre-commit run --files <the 10 changed files>` | Passed | | `pytest 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` (under `python/ray/data/tests/`) | 526 passed, 3 skipped | | The same test files from this PR, against the code with only #66521 (no #67579) | 60 failed, 155 passed, and `test_tensor_extension.py` fails to collect, because it imports a helper this PR adds | | This pick directly on `releases/2.60.1`, without #66521 | The 2 tests above fail | | `test_arrow_block.py test_pandas_block.py test_tensor_extension.py` with the #67566 pick (#67994) also applied | 397 passed | `test_tensor_column_no_memory_leak` needs `scipy`, which my environment didn't have at first. The 526 passed is from a run with scipy installed. I ran these against the Ray 2.60.0 release wheel, with this branch's `python/ray/data` and `python/ray/tests` copied over it. The wheel was built from `releases/2.60.0` at b7f4259, and its Python sources match `releases/2.60.1` except for `_version.py`. The environment was Python 3.12 with pandas 2.3.3 and pyarrow 23.0.1, the versions CI pins, plus numpy 2.2.6 and torch 2.9.0+cpu. 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]>
…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]>
Summary
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.Problem
ArrowBlockAccessor.to_pandas()maps each column topd.ArrowDtype. Before pandas 3.1,pd.ArrowDtype.__from_arrow__casts every column, even to its own type.list<null>when no row has a real value. Users see it with sparse list columns.[{'x': [None, None]}, {'x': []}][{'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).Change
_arrow_backed_pandas_dtypereturns_ArrowDtypeWithoutIdentityCastfor 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.pd.ArrowDtype, and the subclass compares equal to that dtype, so users see no dtype change.list<item: null>[pyarrow]). That is what broke the first version of this PR on a block coming back from a pandas UDF.enable_arrow_backed_pandas_conversion=False, nothing changes.Decisions to confirm
_has_nested_null_type, at the cost of changing the conversion path of every column on pandas < 3.1.struct<a: null>casts correctly but takes the new path too, because one rule ("any nested null") is simpler to reason about.Subsystems
Block / data format (
arrow_block.py).Related
enable_arrow_backed_pandas_conversion.to_pandas().pd.ArrowDtypelist column makes the nextto_pandas()fail with the same "not understood" error. Since [Data] Deprecate Pandas internal blocks: Convert Pandas UDF batches as Arrow blocks internally #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.Testing
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 whenbatch_sizeis smaller than the block. Run locally with pandas 2.3.3 and pyarrow 23.0.1: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