Skip to content

[cherry-pick][2.59.0][Data] Fix preprocessors crashing on Arrow-backed pandas batches (#66578) - #66617

Merged
elliot-barn merged 1 commit into
releases/2.59.0from
cherry-pick-66578-2.59.0
Oct 1, 2026
Merged

elliot-barn merged 1 commit into
releases/2.59.0from
cherry-pick-66578-2.59.0

Conversation

@elliot-barn

Copy link
Copy Markdown
Collaborator

Cherry-pick of #66578 (master commit 00994a0) onto releases/2.59.0.

Conflict resolved: the original commit also extends python/ray/data/tests/preprocessors/test_preprocessors_arrow_backed.py, but that file was created on master by #65272 (not on this branch) and its baseline tests assert #65272 behavior the branch doesn't have — so this pick carries the code fix only (preprocessor.py, arrow_block.py) without the test file. If test coverage on the branch is wanted, #65272 would need to be picked first.

🤖 Generated with Claude Code

)

Calling a preprocessor's `transform_batch` inside a
`map_batches(batch_format="pandas")`
UDF fails on Ray >= 2.56. Three shapes, reported by a user upgrading
from 2.55:

```python
ds = ray.data.from_items([{"n": 1}, {"n": 2}, {"n": 3}, {"n": 4}])
scaler = StandardScaler(columns=["n"]).fit(ds)
ds.map_batches(lambda b: scaler.transform_batch(b), batch_format="pandas").take_all()
```

| input | error |
|---|---|
| int column, `StandardScaler` | `ArrowInvalid: Float value -1.341641
was truncated converting to int64` |
| string column, `OrdinalEncoder` / `OneHotEncoder` | `ValueError:
ArrowStringArray requires a PyArrow (chunked) array of large_string
type` |
| a list column merely *present* in the batch | `TypeError: data type
'list<item: string>[pyarrow]' not understood` |

The third needs no list-typed input to the preprocessor — a `tags`
column sitting
unused in the batch is enough while a float column is scaled.

`_transform_batch` converted the whole batch with
`pa.Table.from_pandas`, which records
the input dtypes in the table's pandas schema metadata, ran
`_transform_arrow`, and
converted back with `to_pandas`. The transform changes column types —
int64 to double
for a scaler, string to int64 for an ordinal encoding — but the metadata
still described
the input, so the conversion back cast the results to their
pre-transform dtypes.

That round trip landed in 2.54 (#59810). 2.56 (#63017) made pandas
batches Arrow-backed,
which is what made those cast-backs fail. So this is a latent bug that
2.56 exposed
rather than one 2.56 introduced: the same call already failed on 2.55
when handed an
Arrow-backed frame directly.

Stop round-tripping the batch. Only the columns the preprocessor reads
(`get_input_columns`) cross into Arrow, without the metadata, and only
the ones it writes
(`get_output_columns`) come back. The result is a shallow copy of the
caller's frame with
those columns replaced, so untouched columns, the index, the axis names
and `attrs` never
leave pandas — there is nothing to rebuild.

- A written column that keeps its Arrow type keeps the dtype of the
column it replaces
  (a scaled `Float64` stays `Float64`).
- Otherwise it keeps that column's backing. An Arrow-backed column stays
Arrow-backed
whatever `enable_arrow_backed_pandas_conversion` says — the flag governs
how Ray
converts its own blocks, not the caller's columns — except for the types
Ray never maps
to an Arrow-backed dtype (extension, dictionary, null), which go through
its block
conversion as before. A NumPy-backed column converts plainly, and a
newly created column
  follows the frame.
- That Arrow-to-pandas type mapping moves unchanged from a closure in
`ArrowBlockAccessor.to_pandas` to module level in `arrow_block.py`, so
both paths share
  one rule.
- A preprocessor that declares no columns falls back to sending the
whole frame.

Writing columns back by position needs `_transform_arrow` to return the
rows it was
given, in order. A changed row count now raises a `ValueError`, and the
`_transform_arrow`
docstring states the contract. All three built-in `_transform_arrow`
implementations are
column transforms and satisfy it.

Both come from untouched columns no longer being re-inferred from Arrow:

- An object column of numbers stays `object`; it used to come back
`int64` / `float64`.
- Integer column labels stay integers; they used to be turned into
strings.

And one for implementers: `_transform_arrow` on a pandas batch now
receives only the
declared input columns, and must not change the rows. The previous code
tolerated a
filtering transform by carrying the index through as a column; it now
raises instead.

`enable_arrow_backed_pandas_conversion=False` mitigates this only for
Arrow-block sources.
A pandas block built from an already-Arrow-backed frame — what
`pd.read_parquet(..., dtype_backend="pyarrow")` returns — never
undergoes an
Arrow-to-pandas conversion, so the flag does not reach it; this change
fixes that path.

Two related gaps are left for follow-ups rather than widening this PR:

- `Preprocessor.transform(ds)` has the same stale-metadata defect for a
dataset built from
an Arrow-backed pandas frame with the flag set to `False` (it works with
the default).
- `transform_batch(pa.Table)` returns a table that still carries the
caller's pandas
metadata, so calling `.to_pandas()` on the result can fail the same way.

No open PR touches `_transform_batch` or this pandas/Arrow round trip.
The open
preprocessor work (#66088, #66091) is about how preprocessors are
*fitted* and does not
change the transform path; #60533 adds a `drop` option to the one-hot
encoders in
`encoder.py`. The other open Arrow/pandas PRs are elsewhere: #65539 is
schema
unification for empty datasets, #63938 preserves `CategoricalDtype` in
`Schema.types`.

No open issue covers it either. #64765, the umbrella 2.56 `to_pandas`
regression, is
closed, fixed by #64768 — which added the
`enable_arrow_backed_pandas_conversion`
opt-out and left this round trip untouched.

35 `transform_batch` cases added to

`python/ray/data/tests/preprocessors/test_preprocessors_arrow_backed.py`:

- `test_transform_batch_inside_a_pandas_udf` — the three reported
preprocessors through a
  pandas UDF, parametrized over `enable_arrow_backed_pandas_conversion`.
- `test_transform_batch_on_an_arrow_backed_pandas_block` — the shape the
flag does not cover.
- `test_transform_batch_passes_through_an_untouched_list_column` — the
list-column case.
- `test_transform_batch_matches_the_input_backing` /
`..._decides_the_backing_per_column`
— NumPy in gives NumPy out, Arrow in gives Arrow out, and a mixed frame
keeps both.
- `test_transform_batch_keeps_arrow_backing_with_the_flag_off` — the
same holds for all
three preprocessors with `enable_arrow_backed_pandas_conversion=False`.
- `test_transform_batch_keeps_pass_through_extension_dtypes` — nullable
`Int64`, `boolean`
  and `string` columns come back intact, including a value past 2**53.
- `test_transform_batch_leaves_untouched_columns_exactly_as_they_were` —
object columns of
  numbers, a categorical over pandas strings, Python lists.
- `test_transform_batch_preserves_the_index` — named, `MultiIndex` and
tz-aware
  `DatetimeIndex` on both backings, plus the columns axis name.
- `test_transform_batch_keeps_integer_column_labels`,
`..._does_not_modify_the_callers_frame`,
`..._rejects_a_transform_that_changes_the_row_count`,
  `..._on_an_empty_batch`.

The cases assert on values rather than on "did not raise": where the
stale metadata
permitted the cast, the result was silently wrong rather than an error —
an ordinal
encoding coming back as the strings `"0"`, `"1"`, `"2"`.

Against the unmodified source, 21 of the 35 fail:

- 15 are the reported crash on Arrow-backed input.
- 5 are the behaviour changes above: master re-typed untouched object
and categorical
  columns and stringified integer labels.
- 1 is the new contract: master tolerated a filtering
`_transform_arrow`; this raises.

The other 14 pass on master too and are controls — the NumPy-backed
halves, the empty
batch, and the pass-through dtype cases, which guard against a
regression a naive fix
would introduce.

```
$ PYTHONPATH=python/ray/data/tests python -m pytest -q \
    python/ray/data/tests/preprocessors/ --ignore=.../test_torch.py
381 passed, 5 skipped

$ PYTHONPATH=python/ray/data/tests python -m pytest -q python/ray/data/tests/test_arrow_block.py
30 passed
```

The three reported repros were also run end to end through `map_batches`
in Ray workers.
`test_torch.py` is excluded because `torch` is not installed in this
environment; it is
untouched by this change. Pre-commit passes on all three changed files.

Only the declared columns are converted, so wide frames stop paying for
every column:
`StandardScaler(columns=["n"]).transform_batch` on a 1000-column ×
2k-row NumPy frame
goes from ~27 ms to under 1 ms.

AI assistance was used for this change.

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

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Aarrya <[email protected]>
(cherry picked from commit 00994a0)
Signed-off-by: elliot-barn <[email protected]>
@elliot-barn
elliot-barn requested a review from a team as a code owner October 1, 2026 00:02

@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 the preprocessor batch transformation logic to optimize pandas-to-Arrow round-trips. It extracts _arrow_backed_pandas_dtype for reuse, drops stale pandas metadata when columns are added or retyped, and ensures only the columns read by the preprocessor cross into Arrow while keeping other columns, indices, and axis names in pandas. The review feedback highlights compatibility issues with pandas versions older than 2.0.0, where pd.ArrowDtype is not defined, and suggests guarding these references with hasattr(pd, 'ArrowDtype') to prevent AttributeErrors.

Comment on lines +228 to +233
def _arrow_backed_pandas_dtype(t: "pyarrow.DataType") -> Optional["pd.ArrowDtype"]:
if isinstance(t, pyarrow.BaseExtensionType) or pyarrow.types.is_dictionary(t):
return None
if pyarrow.types.is_null(t):
return None
return pd.ArrowDtype(t)

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

Since pandas.ArrowDtype was introduced in pandas 2.0.0, referencing pd.ArrowDtype directly will raise an AttributeError on older pandas versions (e.g., pandas 1.x) which are still supported by Ray. We should guard this by checking hasattr(pd, 'ArrowDtype') first.

Suggested change
def _arrow_backed_pandas_dtype(t: "pyarrow.DataType") -> Optional["pd.ArrowDtype"]:
if isinstance(t, pyarrow.BaseExtensionType) or pyarrow.types.is_dictionary(t):
return None
if pyarrow.types.is_null(t):
return None
return pd.ArrowDtype(t)
def _arrow_backed_pandas_dtype(t: "pyarrow.DataType") -> Optional["pd.ArrowDtype"]:
if not hasattr(pd, "ArrowDtype"):
return None
if isinstance(t, pyarrow.BaseExtensionType) or pyarrow.types.is_dictionary(t):
return None
if pyarrow.types.is_null(t):
return None
return pd.ArrowDtype(t)

Comment on lines +100 to +101
as_arrow = isinstance(like, pd.ArrowDtype)
as_nullable = not as_arrow and getattr(like, "na_value", None) is pd.NA

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

To prevent AttributeError on pandas versions older than 2.0.0 where pd.ArrowDtype does not exist, we should guard the isinstance check with hasattr(pd, 'ArrowDtype').

Suggested change
as_arrow = isinstance(like, pd.ArrowDtype)
as_nullable = not as_arrow and getattr(like, "na_value", None) is pd.NA
as_arrow = hasattr(pd, "ArrowDtype") and isinstance(like, pd.ArrowDtype)
as_nullable = not as_arrow and getattr(like, "na_value", None) is pd.NA

Comment on lines +506 to +508
frame_is_arrow_backed = any(
isinstance(dtype, pd.ArrowDtype) for dtype in df.dtypes
)

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

Reference to pd.ArrowDtype will raise an AttributeError on pandas < 2.0.0. We should guard this check by verifying if pd.ArrowDtype exists.

Suggested change
frame_is_arrow_backed = any(
isinstance(dtype, pd.ArrowDtype) for dtype in df.dtypes
)
frame_is_arrow_backed = hasattr(pd, "ArrowDtype") and any(
isinstance(dtype, pd.ArrowDtype) for dtype in df.dtypes
)

@elliot-barn
elliot-barn merged commit dd83c3a into releases/2.59.0 Oct 1, 2026
4 of 5 checks passed
@elliot-barn
elliot-barn deleted the cherry-pick-66578-2.59.0 branch October 1, 2026 00:51
sai-miduthuri added a commit that referenced this pull request Oct 3, 2026
…d pandas batches (#66578) (#66644)

Cherry-pick of #66578 (master commit
00994a0) onto `releases/2.60.0`.

Applied cleanly with `git cherry-pick -x`; the diff is identical to the
master commit. Unlike the 2.59.0 pick (#66617), this one carries the
test file too: `releases/2.60.0` already has #65272, which created
`test_preprocessors_arrow_backed.py`.

Not a duplicate: no existing PR against `releases/2.60.0` references
#66578.

Testing: Ray wheel built from the branch-cut commit (838592a) with the
branch's `ray/data` and `ray/tests` linked in via `setup-dev.py`, pandas
2.3.3 / pyarrow 23.0.1 / datasketches 5.2.0 (the data CI pins):

```
python -m pytest --pyargs ray.data.tests.preprocessors.test_preprocessors_arrow_backed
137 passed, 3 skipped
```

The 3 skips are by design (a pandas block can't carry a list column).
With `preprocessor.py` and `arrow_block.py` reverted to the branch's
pre-pick versions (run before `datasketches` was installed), the same
file gives 26 failed, 106 passed, 8 skipped, so the tests exercise the
fix on this branch. The rest of the preprocessor suite wasn't run
locally; relying on branch CI.

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: Aarrya <[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]>
Co-authored-by: Aarrya <[email protected]>
sai-miduthuri added a commit that referenced this pull request Nov 13, 2026
… 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants