Repository navigation
[cherry-pick][2.60.0][Data] Fix preprocessors crashing on Arrow-backed pandas batches (#66578) - #66644
Merged
Conversation
) ## 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]> (cherry picked from commit 00994a0) Signed-off-by: sai.miduthuri <[email protected]>
Contributor
There was a problem hiding this comment.
Code Review
This pull request refactors Preprocessor.transform_batch for Arrow-backed pandas blocks to prevent lossy round-trips and incorrect casting of transformed columns. Instead of converting the entire pandas DataFrame to an Arrow Table and back, only the columns read by the preprocessor are converted to Arrow, transformed, and merged back into the original DataFrame. This preserves untouched columns, indices, axis names, and the original column backing types (NumPy, nullable, or Arrow). Additionally, helper functions for dropping stale pandas metadata and mapping Arrow types to pandas dtypes are introduced, along with comprehensive unit tests. I have no feedback to provide as there are no review comments.
AarryaSaraf
approved these changes
Oct 3, 2026
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.0already has #65272, which createdtest_preprocessors_arrow_backed.py.Not a duplicate: no existing PR against
releases/2.60.0references #66578.Testing: Ray wheel built from the branch-cut commit (838592a) with the branch's
ray/dataandray/testslinked in viasetup-dev.py, pandas 2.3.3 / pyarrow 23.0.1 / datasketches 5.2.0 (the data CI pins):The 3 skips are by design (a pandas block can't carry a list column). With
preprocessor.pyandarrow_block.pyreverted to the branch's pre-pick versions (run beforedatasketcheswas 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