Skip to content

[Data] Fix preprocessors crashing on Arrow-backed pandas batches - #66578

Merged
elliot-barn merged 4 commits into
masterfrom
marwan/data-fix-preprocessor-pandas-roundtrip
Sep 30, 2026
Merged

elliot-barn merged 4 commits into
masterfrom
marwan/data-fix-preprocessor-pandas-roundtrip

Conversation

@marwan116

@marwan116 marwan116 commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

What broke

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:

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.

Why

_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.

The fix

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.

Behaviour changes

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.

Not a fix for

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.

Not a duplicate

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.

Testing

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

@marwan116
marwan116 requested a review from a team as a code owner September 29, 2026 17:24

@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 addresses an issue in Preprocessor._transform_batch where converting an Arrow-backed pandas DataFrame to a PyArrow Table and back would incorrectly cast transformed columns back to their pre-transform dtypes due to schema metadata. The changes strip the schema metadata during conversion and manually restore the index and backing type, supported by a new _transform_arrow_preserves_row_order flag. Feedback on the changes points out a potential compatibility issue where referencing pd.ArrowDtype directly could raise an AttributeError on older pandas versions (< 2.0.0) supported by Ray, and suggests dynamically checking for ArrowDtype using getattr.

Comment thread python/ray/data/preprocessor.py Resolved

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

Comment thread python/ray/data/preprocessor.py Resolved
@marwan116
marwan116 force-pushed the marwan/data-fix-preprocessor-pandas-roundtrip branch 2 times, most recently from c8c782b to 04a0bc0 Compare September 29, 2026 17:52
@marwan116 marwan116 added the data Ray Data-related issues label Sep 29, 2026
@marwan116
marwan116 force-pushed the marwan/data-fix-preprocessor-pandas-roundtrip branch from 04a0bc0 to 6736c4f Compare September 29, 2026 18:07
@marwan116 marwan116 added the go add ONLY when ready to merge, run all tests label Sep 29, 2026

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

Comment thread python/ray/data/preprocessor.py Resolved
Calling a preprocessor's `transform_batch` inside a
`map_batches(batch_format="pandas")` UDF fails on Ray >= 2.56, three ways:

    StandardScaler on an int column
        ArrowInvalid: Float value -1.341641 was truncated converting to int64

    OrdinalEncoder / OneHotEncoder on a string column
        ValueError: ArrowStringArray requires a PyArrow (chunked) array of
        large_string type

    any list column merely present in the batch
        TypeError: data type 'list<item: string>[pyarrow]' not understood

`_transform_batch` converted the whole batch with `pa.Table.from_pandas`,
which records the input dtypes in the schema metadata, ran `_transform_arrow`,
and converted back with `to_pandas`. The transform changes column types --
int64 to double, string to int64 -- but the metadata still describes the
input, so the conversion back cast the results to their pre-transform dtypes.
The round trip landed in 2.54 (#59810); 2.56 (#63017) made pandas batches
Arrow-backed, which is what made those cast-backs fail.

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 and nothing has to be
rebuilt. A written column that keeps its Arrow type keeps the dtype of the
column it replaces; otherwise it keeps that column's backing, going through
Ray's block conversion when it is Arrow-backed. 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, and the
`_transform_arrow` docstring states the contract.

Two visible differences from before, both from untouched columns no longer
being re-inferred from Arrow: an object column of numbers stays object rather
than becoming int64 or float64, and integer column labels are no longer turned
into strings. Converting only the declared columns also takes scaling one
column of a 1000-column frame from about 27 ms to under 1 ms.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
@marwan116
marwan116 force-pushed the marwan/data-fix-preprocessor-pandas-roundtrip branch from 6736c4f to 2768aab Compare September 29, 2026 18:42

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 2768aab. Configure here.

Comment thread python/ray/data/preprocessor.py Resolved
Comment thread python/ray/data/preprocessor.py Resolved
@marwan116

marwan116 commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor Author

Alternative considered and not taken: route pandas batches to _transform_pandas

All three preprocessors with a _transform_arrow also have a _transform_pandas, and before 2.54 transform_batch(df) simply called it. The round trip this PR fixes exists because _determine_transform_to_use picks by implementation rather than by batch type: it chooses Arrow because the Dataset path prefers it, then applies that choice to a pandas batch too. So one option was to route by what the batch actually is:

elif transform_type == BatchFormat.ARROW:
    if isinstance(data, pd.DataFrame) and has_transform_pandas:
        return self._transform_pandas(data.copy(deep=False))
    ...  # Arrow path only for Arrow tables, and for subclasses with no pandas implementation

It fixes the three reported failures without converting anything, and it looked clearly better than an earlier revision of this PR, which converted the whole frame to Arrow and rebuilt it afterwards. The current revision sends only the preprocessor's own columns through Arrow, and against that the pandas route loses on two counts.

1. transform_batch would stop matching transform(ds). Preprocessors are usually applied with transform(ds) in training and transform_batch at inference, so the two need to agree. Arrow-backed batch, with a category unseen at fit time:

transform(ds) this PR pandas route
StandardScaler double[pyarrow] same same
OrdinalEncoder int64[pyarrow], <NA> for the unseen category same float64, NaN
OneHotEncoder fixed_size_list<item: uint8>[3][pyarrow] same object column of Python lists

The values agree; the types a model receives don't.

2. OneHotEncoder._transform_pandas is much slower, since it works row by row. Milliseconds, best of 5, Arrow-backed input:

this PR pandas route
OneHotEncoder, 200k rows 3.7 160.6
OneHotEncoder, 300 columns × 20k rows 1.0 16.3
OrdinalEncoder, 200k rows 2.6 3.6
StandardScaler, either shape 0.5 0.5–0.6

So the PR keeps the Arrow path. Happy to revisit if a reviewer prefers the pandas route and would accept its types diverging from transform(ds).

… off

`transform_batch` gives a rewritten column the backing of the column it
replaces, but an Arrow-backed one was built through Ray's block conversion,
which follows `enable_arrow_backed_pandas_conversion`. With the flag off, an
Arrow-backed frame therefore came back with the rewritten column NumPy-backed
beside Arrow-backed ones -- in the configuration the fix is meant to cover: a
pandas block built from an Arrow-backed frame, which the flag never converts.

Build the Arrow-backed array directly instead, so the column keeps its backing
whatever the flag says; the flag governs how Ray converts its own blocks, not
the caller's columns. Types Ray never maps to an Arrow-backed dtype (extension,
dictionary and null) still go through its conversion. To keep that rule in one
place, the mapper moves unchanged from a closure in
`ArrowBlockAccessor.to_pandas` to module level.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
@marwan116 marwan116 self-assigned this Sep 29, 2026
`transform_batch` is typed to return any batch format, so pyrefly rejected the
tests using its result as a DataFrame (`.columns`, `.dtypes`, `.index`), and
rejected the pandas UDFs' `(pd.DataFrame) -> pd.DataFrame` annotations as
arguments to `map_batches`, which takes `(DataBatch) -> DataBatch`.

Driver-side calls now go through a small helper that asserts the result is a
DataFrame, which narrows the type. The UDFs lose their annotations, as in the
other checked tests. They run in Ray workers, so they deliberately don't call a
helper defined in this module, which a worker would have to import to unpickle.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
@AarryaSaraf

AarryaSaraf commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

iiuc a new column is arrow backed if any column in the dataframe is arrow-backed independent of the column it was made from. Shouldnt it take the backing of the column it is made from?

…ndas metadata

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Aarrya <[email protected]>
@elliot-barn
elliot-barn merged commit 00994a0 into master Sep 30, 2026
6 checks passed
@elliot-barn
elliot-barn deleted the marwan/data-fix-preprocessor-pandas-roundtrip branch September 30, 2026 21:07
elliot-barn added a commit that referenced this pull request Oct 1, 2026
…d pandas batches (#66578) (#66617)

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](https://claude.com/claude-code)

Signed-off-by: Marwan Sarieddine <[email protected]>
Signed-off-by: Aarrya <[email protected]>
Signed-off-by: elliot-barn <[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 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]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…-project#66578)

## What broke

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.

## Why

`_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 (ray-project#59810). 2.56 (ray-project#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.

## The fix

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.

## Behaviour changes

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.

## Not a fix for

`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.

## Not a duplicate

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

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

## Testing

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]>
sai-miduthuri added a commit that referenced this pull request Nov 13, 2026
… 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]>
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

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.

4 participants