Skip to content

[data] Support Arrow-based transformations for preprocessors - #59810

Merged
raulchen merged 5 commits into
masterfrom
cem/arrow
Jan 2, 2026
Merged

raulchen merged 5 commits into
masterfrom
cem/arrow

Conversation

@cem-anyscale

Copy link
Copy Markdown
Contributor
  • Add Arrow-based transformation support in preprocessor base class
  • Implement Arrow-based transformations for OrdinalEncoder
  • Add batch_format parameter to StatComputationPlan.add_aggregator for Arrow post-processing

- Add Arrow-based transformation support in preprocessor base class
- Implement Arrow-based transformations for OrdinalEncoder
- Add batch_format parameter to StatComputationPlan.add_aggregator for Arrow post-processing

Signed-off-by: cem <[email protected]>
@cem-anyscale
cem-anyscale requested a review from a team as a code owner January 2, 2026 17:54

@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 support for Arrow-based transformations in preprocessors, which is a great step towards improving performance. The changes are well-structured, with updates to the Preprocessor base class, an Arrow-native implementation for OrdinalEncoder, and a refactoring of the statistics computation logic to handle Arrow formats efficiently. The addition of comprehensive tests, including parameterized tests for both pandas and Arrow paths, is commendable. I've found one minor issue related to some seemingly copy-pasted code that should be addressed. Otherwise, the changes look solid.

Comment on lines +588 to +595
def _encode_list_element(self, element: list, *, column_name: str):
ordinal_map = self.stats_[f"unique_values({column_name})"]
# If encoding lists, entire column is flattened, hence we map individual
# elements inside the list element (of the column)
if self.encode_lists:
return [ordinal_map.get(x) for x in element]

return ordinal_map.get(tuple(element))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

It seems the _encode_list_element method has been copied from OrdinalEncoder into MultiHotEncoder. This method appears to be unused within MultiHotEncoder and its logic is incorrect for multi-hot encoding.

Specifically:

  • It uses self.encode_lists, which is an attribute of OrdinalEncoder but not MultiHotEncoder.
  • The implementation returns a list of ordinal mappings, which is the behavior of OrdinalEncoder, not MultiHotEncoder.

This looks like dead code from a copy-paste and could be confusing. I recommend removing this method from MultiHotEncoder.

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.

yeah, this seems unused.

if self.encode_lists:
return [ordinal_map.get(x) for x in element]

return ordinal_map.get(tuple(element))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

MultiHotEncoder method references undefined attribute

The newly added MultiHotEncoder._encode_list_element method references self.encode_lists at line 592, but MultiHotEncoder doesn't define this attribute in its __init__. This appears to be copy-pasted from OrdinalEncoder without adaptation. While the method is currently dead code (not called by _transform_pandas), it would raise an AttributeError if ever invoked. The OrdinalEncoder defines encode_lists at line 139, but MultiHotEncoder has no such attribute.

Fix in Cursor Fix in Web

Signed-off-by: cem <[email protected]>
@cem-anyscale cem-anyscale added the go add ONLY when ready to merge, run all tests label Jan 2, 2026
self._transform_arrow,
batch_format="pyarrow",
zero_copy_batch=True,
**kwargs,

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.

nit: update the error message below to include arrow format.

Comment on lines +588 to +595
def _encode_list_element(self, element: list, *, column_name: str):
ordinal_map = self.stats_[f"unique_values({column_name})"]
# If encoding lists, entire column is flattened, hence we map individual
# elements inside the list element (of the column)
if self.encode_lists:
return [ordinal_map.get(x) for x in element]

return ordinal_map.get(tuple(element))

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.

yeah, this seems unused.

@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Jan 2, 2026
@raulchen
raulchen merged commit e94a52c into master Jan 2, 2026
@raulchen
raulchen deleted the cem/arrow branch January 2, 2026 21:18
@kyuds

kyuds commented Jan 12, 2026

Copy link
Copy Markdown
Member

just a quick question: what is the rationale behind removing the post_key_fn for AggregateStatSpec? I am currently trying to migrate OrdinalEncoders to use Unique aggregators, but as the post_key_fn is gone, it is impossible for me to differentiate aggregation results between different columns.

AYou0207 pushed a commit to AYou0207/ray that referenced this pull request Jan 13, 2026
…ject#59810)

- Add Arrow-based transformation support in preprocessor base class
- Implement Arrow-based transformations for OrdinalEncoder
- Add batch_format parameter to StatComputationPlan.add_aggregator for
Arrow post-processing

---------

Signed-off-by: cem <[email protected]>
Signed-off-by: jasonwrwang <[email protected]>
marwan116 added a commit that referenced this pull request Sep 29, 2026
`Preprocessor._transform_batch` converts a pandas batch with
`pa.Table.from_pandas`, which records the input dtypes in the table's pandas
schema metadata. `_transform_arrow` then changes the column types -- int64 to
double for a scaler, string to int64 for an ordinal encoding -- and that
metadata rides along unchanged, so converting back with `to_pandas` trusts it
and casts the results to their pre-transform dtypes.

Since 2.56 the batch a pandas UDF receives is Arrow-backed, so calling a
preprocessor's `transform_batch` inside a `map_batches(batch_format="pandas")`
UDF fails three different 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

The round trip landed in 2.54 (#59810); 2.56 (#63017) made pandas batches
Arrow-backed, which is what started feeding it dtypes it would then enforce.
The same call already failed on 2.55 when handed an Arrow-backed frame
directly, so this is a latent bug that 2.56 exposed rather than one it
introduced.

Drop the metadata on the way in, since the transform is about to invalidate
it, and choose the output backing to match the input rather than recovering it
from metadata that is now gone. Matching the input leaves every existing
caller's output dtypes unchanged, which a new test pins.

The metadata was only wrong for the columns `_transform_arrow` rewrites; for
every other column it was accurate, and dropping it wholesale takes those
dtypes with it. A pass-through nullable `Int64` would come back as `float64`,
turning `pd.NA` into `nan` and rounding any value past 2**53 -- silent damage
to a column the preprocessor never touched. Columns whose Arrow type the
transform did not change are therefore rebuilt from the Arrow array through
the dtype's own `__from_arrow__`. Casting the converted values instead would
be too late, since the conversion is where the loss happens.

Dropping the metadata also drops a caller's custom pandas index. This commit
on its own therefore returns a default RangeIndex where `transform_batch`
previously gave back the index a pandas input carried; the following commit
restores it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
marwan116 added a commit that referenced this pull request Sep 29, 2026
`Preprocessor._transform_batch` converts a pandas batch with
`pa.Table.from_pandas`, which records the input dtypes in the table's pandas
schema metadata. `_transform_arrow` then changes the column types -- int64 to
double for a scaler, string to int64 for an ordinal encoding -- and that
metadata rides along unchanged, so converting back with `to_pandas` trusts it
and casts the results to their pre-transform dtypes.

Since 2.56 the batch a pandas UDF receives is Arrow-backed, so calling a
preprocessor's `transform_batch` inside a `map_batches(batch_format="pandas")`
UDF fails three different 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

The round trip landed in 2.54 (#59810); 2.56 (#63017) made pandas batches
Arrow-backed, which is what started feeding it dtypes it would then enforce.
The same call already failed on 2.55 when handed an Arrow-backed frame
directly, so this is a latent bug that 2.56 exposed rather than one it
introduced.

Drop the metadata on the way in, since the transform is about to invalidate
it, and choose the output backing to match the input rather than recovering it
from metadata that is now gone. Matching the input leaves every existing
caller's output dtypes unchanged, which a new test pins.

The metadata was only wrong for the columns `_transform_arrow` rewrites; for
every other column it was accurate, and dropping it wholesale takes those
dtypes with it. A pass-through nullable `Int64` would come back as `float64`,
turning `pd.NA` into `nan` and rounding any value past 2**53 -- silent damage
to a column the preprocessor never touched. Columns whose Arrow type the
transform did not change are therefore rebuilt from the Arrow array through
the dtype's own `__from_arrow__`. Casting the converted values instead would
be too late, since the conversion is where the loss happens.

The axis labels go too: `preserve_index=False` stops carrying a pandas input's
index, and the columns axis name lived in the metadata. This commit on its own
therefore returns a default RangeIndex and an unnamed columns axis where
`transform_batch` used to hand both back; the following commit restores them.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
marwan116 added a commit that referenced this pull request Sep 29, 2026
`Preprocessor._transform_batch` converts a pandas batch with
`pa.Table.from_pandas`, which records the input dtypes in the table's pandas
schema metadata. `_transform_arrow` then changes the column types -- int64 to
double for a scaler, string to int64 for an ordinal encoding -- and that
metadata rides along unchanged, so converting back with `to_pandas` trusts it
and casts the results to their pre-transform dtypes.

Since 2.56 the batch a pandas UDF receives is Arrow-backed, so calling a
preprocessor's `transform_batch` inside a `map_batches(batch_format="pandas")`
UDF fails three different 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

The round trip landed in 2.54 (#59810); 2.56 (#63017) made pandas batches
Arrow-backed, which is what started feeding it dtypes it would then enforce.
The same call already failed on 2.55 when handed an Arrow-backed frame
directly, so this is a latent bug that 2.56 exposed rather than one it
introduced.

Drop the metadata on the way in, since the transform is about to invalidate
it, and put each column's dtype back afterwards from the input rather than
from metadata that is now gone. The decision is per column, not per frame: a
frame that mixes NumPy and Arrow-backed columns keeps both, and Ray produces
such frames, because the types mapper declines extension types and leaves a
tensor column as `object`.

A column the transform left alone gets its dtype back exactly; one whose type
changed keeps its backing over the new type. That matters beyond tidiness: the
metadata was only stale for the columns `_transform_arrow` rewrote, so dropping
it wholesale takes accurate dtypes with it, and a pass-through nullable `Int64`
would come back `float64` -- `pd.NA` becoming `nan` and any value past 2**53
rounded, in a column the preprocessor never touched. Rebuilding from the Arrow
array rather than casting the converted values is what keeps it exact, since
the conversion is where the loss happens.

The axis labels go too: `preserve_index=False` stops carrying a pandas input's
index, and the columns axis name lived in the metadata. This commit on its own
therefore returns a default RangeIndex and an unnamed columns axis where
`transform_batch` used to hand both back; the following commit restores them.

Co-Authored-By: Claude Opus 5 <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
marwan116 added a commit that referenced this pull request Sep 29, 2026
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]>
elliot-barn pushed a commit that referenced this pull request Sep 30, 2026
)

## 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 (#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](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]>
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]>
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