Repository navigation
[Data] Preserve Arrow types through pandas roundtrip - #63017
goutamvenkat-anyscale merged 21 commits into
Conversation
Signed-off-by: Goutam <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces the use of pd.ArrowDtype to preserve Arrow types during round-trips between Arrow and Pandas. Review feedback points out that pd.ArrowDtype is only available in Pandas 2.0.0+, which will cause AttributeError on older supported versions. The reviewer recommends adding compatibility checks and skipping the new tests on older Pandas versions.
| def _types_mapper(t): | ||
| if isinstance(t, pyarrow.ExtensionType) or pyarrow.types.is_dictionary(t): | ||
| return None | ||
| return pd.ArrowDtype(t) |
There was a problem hiding this comment.
pd.ArrowDtype was introduced in pandas 2.0.0. Since Ray supports older versions of pandas (e.g., 1.3+), using pd.ArrowDtype directly will raise an AttributeError for users on those versions. You should check for its existence before attempting to use it as a return value in the mapper.
def _types_mapper(t):
if isinstance(t, pyarrow.ExtensionType) or pyarrow.types.is_dictionary(t):
return None
if hasattr(pd, "ArrowDtype"):
return pd.ArrowDtype(t)
return NoneThere was a problem hiding this comment.
your info is outdated bud. Ray is officially pandas >= 2.3 only...
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
| ds = ray.data.range(100) | ||
| # Schema: {'id': int64} | ||
| ds = ds.add_column("group_key", lambda x: x % 3) | ||
| ds = ds.add_column( |
There was a problem hiding this comment.
FYI mod kernel isn't implemented in pyarrow: apache/arrow#28497
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
Signed-off-by: Goutam <[email protected]>
| ) | ||
| eval_table = pa.concat_tables( | ||
| eval_shard.iter_batches(batch_format="pyarrow", batch_size=None) | ||
| ) |
There was a problem hiding this comment.
Empty shard causes crash in pa.concat_tables call
Low Severity
pa.concat_tables raises an error when given an empty iterable (e.g., ArrowInvalid: Must pass at least one table). If a Ray Train worker receives an empty data shard (possible when num_workers > num_blocks), iter_batches yields nothing and this call crashes. The previous code using .materialize().to_pandas() handled empty shards gracefully by returning an empty DataFrame.
Reviewed by Cursor Bugbot for commit fd1e95c. Configure here.
| if numpy_dtype is not None: | ||
| arrow_to_numpy[col] = numpy_dtype | ||
| if arrow_to_numpy: | ||
| df = df.astype(arrow_to_numpy) |
There was a problem hiding this comment.
Float-to-numpy cast in _sort_df silently loses null-vs-NaN distinction
Low Severity
When _sort_df casts Arrow-backed float columns to numpy via df.astype(arrow_to_numpy), both pd.NA (Arrow null) and actual NaN values become numpy NaN. Arrow-backed floats can distinguish null from NaN (they're semantically different), but after this cast, that distinction is lost. For multi-column sorting, rows that originally had NaN in a float column (valid data, sorts among other values) versus pd.NA (missing, sorts last) would now all sort to the end. This could produce a different row order than sorting the original Arrow-backed DataFrame, potentially causing rows_same to report false negatives or false positives when comparing DataFrames that mix NaN and null in float columns.
Reviewed by Cursor Bugbot for commit 79f2096. Configure here.
## Summary
`BlockAccessor.to_pandas()` now passes pyarrow's `types_mapper` (keyed
on `BaseExtensionType`) so columns retain Arrow-backed dtypes
(`int64[pyarrow]`, `string[pyarrow]`, registered tensor extension types,
etc.) across the Arrow → pandas → Arrow round-trip instead of falling
back to numpy. Previously, the trip silently widened/narrowed types and
dropped Arrow extension types.
## Production changes
- `_internal/arrow_block.py`, `_internal/pandas_block.py`,
`_internal/tensor_extensions/pandas.py`: route conversions through a
`types_mapper` that resolves registered extension types via
`BaseExtensionType`, so user extension types survive.
- `_internal/util.py::_sort_df`: cast Arrow-backed **float** columns
(only) to numpy before `df.sort_values`. pandas's multi-column lex-sort
builds an ordered `Categorical` per key; with Arrow-backed floats it
rejects `-0.0` / `0.0` ("categories must be unique") because Arrow keeps
them distinct but pandas treats them as equal. Cast is intentionally
narrow — int/bool/string arrow columns stay as-is to avoid
`IntCastingNaNError` on nullable ints (numpy `int64` can't represent
`<NA>`) and to avoid the `<NA>`-sorts-first vs `None`-sorts-last
divergence on strings. The original Categorical bug only affects floats
anyway.
- `aggregate.py`, `preprocessors/discretizer.py`: minor adjustments for
Arrow-backed inputs.
## Doc / example updates
- `doc/source/data/aggregating-data.rst`: `add_column("group_key",
lambda x: x % 3)` → `lambda x: x["id"].to_numpy() % 3`. Arrow has no mod
compute kernel, and pandas's Arrow-backed extension array doesn't
implement `__mod__`.
- `doc/source/train/doc_code/lightgbm_quickstart.py`: switched from
`to_pandas()` to `iter_batches(batch_format="pyarrow")` +
`pa.concat_tables`, passing the resulting `pyarrow.Table` /
`ChunkedArray` directly to `lgb.Dataset`. LightGBM (≥ 4.2.0; Ray pins
4.6.0) accepts Arrow natively, avoiding LightGBM's
`_check_for_bad_pandas_dtypes` rejection of `double[pyarrow]`.
## Test updates (~30 files)
- Most `df.equals(...)` / `assert_frame_equal(actual, expected)`
assertions were updated to align expected dtypes with the
now-Arrow-backed `to_pandas()` output:
`expected.astype(actual.dtypes.to_dict())`.
- For tests where the expected DataFrame contains Python `None` in
object columns and the actual is Arrow-backed (`<NA>`), the expected
side casts the offending column(s) to `"string"` (pandas nullable
string) so the null sentinel is `<NA>` on both sides — applied in
`test_iceberg.py`'s `_create_typed_dataframe` helper and in
`test_delta.py::test_delta_read_schema_evolution`.
- `test_map_batches.py::test_map_batches_batch_zero_copy`: restructured
to assert the source dataset is unchanged after a UDF tries to mutate
its batch, rather than relying on the old "tried to mutate a zero-copy
read-only batch" `ValueError`. Arrow-backed columns rebind on assignment
instead of writing through to the underlying buffer, so the
writable-buffer trigger no longer fires (and the property still holds,
just implicitly).
## Test plan
- [x] Updated tests pass locally for: `test_with_column`, `test_join`,
`test_csv`, `test_json`, `test_pandas`, `test_mongo` (modified, no live
mongo), `test_imputer`, `test_normalizer`, `test_scaler`,
`test_transformer`, `test_arithmetic`, `test_predicate`,
`test_map_batches`, `test_map_transformer`,
`test_execution_optimizer_advanced`, `test_delta`.
- [x] LightGBM doc snippet smoke-tested locally with `lightgbm==4.6.0` +
`pyarrow==23.0.0`.
- [ ] Full CI (Data + dependent suites + doctests + Iceberg
integration).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Signed-off-by: Goutam <[email protected]>
Signed-off-by: elliot-barn <[email protected]>
Co-authored-by: elliot-barn <[email protected]>
Signed-off-by: Alexandr Plashchinsky <[email protected]>
## Description ray-project#63017 updated pyarrow types for ray data however the LightGBM trainer wasn't updated and is raising errors in `test_trainer_restore`. While we work out the best solution, this PR disables the test to allow others to continue working --------- Signed-off-by: Mark Towers <[email protected]> Co-authored-by: Mark Towers <[email protected]> Signed-off-by: Alexandr Plashchinsky <[email protected]>
…at block overflow (#64768) ## Description Ray 2.56 (#63017) made `BlockAccessor.to_pandas` map standard Arrow types to pandas Arrow-backed dtypes (`pd.ArrowDtype`). That caused two regressions, fixed here in two commits. **1. Opt-out flag (symptom A).** `map_batches(batch_format="pandas")` UDFs that assign a multi-dimensional ndarray into a column (`ArrowInvalid: Can only convert 1-dimensional array values`) or use numpy-only ops (e.g. `%`) now break, with no opt-out. Adds `DataContext.enable_arrow_backed_pandas_conversion` (env `RAY_DATA_ENABLE_ARROW_BACKED_PANDAS_CONVERSION`, default `True`); set to `False` to restore the pre-2.56 numpy conversion. **2. Fix internal overflow (symptom B).** `Dataset.to_pandas()` crashed in `PandasBlockBuilder._combine_tables` → `pandas.concat` when a column is `int64[pyarrow]` in some blocks and `double[pyarrow]` in others (a block whose values are all null infers `double`): the checked `int64`→`double` promotion overflows for values above 2^53. Ray crashed converting its own blocks (pre-2.56 this path silently widened `int64`→`float64`). Now, when the float-typed blocks are null-only / integral, they are cast back to the integer type before the concat, so it stays lossless and cannot overflow. Columns with genuine fractional values are left to pandas' usual promotion. Repros (both fail on 2.56; B is fixed by default, A needs the flag off): ```python import ray, numpy as np, pandas as pd, pyarrow as pa # Symptom B -- fixed by default: ds = ray.data.from_arrow([ pa.table({"ts": pa.array([1782750729409928627], pa.int64())}), pa.table({"ts": pa.array([None], pa.float64())}), ]) ds.to_pandas() # int64 preserved exactly, no overflow # Symptom A -- opt out to restore numpy dtypes: ray.data.DataContext.get_current().enable_arrow_backed_pandas_conversion = False def add_k(df): df["k"] = [[1.0] * 9 for _ in range(len(df))]; return df def rotate(df): df.loc[:, "k"] = pd.Series([np.eye(3)] * len(df), index=df.index); return df (ray.data.from_items([{"x": i} for i in range(4)]) .map_batches(add_k, batch_format="pandas") .map_batches(rotate, batch_format="pandas") .materialize()) ``` ## Related issues Closes #64765. ## Additional information - The flag mirrors the existing `pandas_block_ignore_metadata` / `enable_tensor_extension_casting` pattern (env-backed default + dataclass field + docstring). - The B fix only downcasts when lossless (null-only / integral float blocks); genuinely fractional columns are untouched. - Tests: `test_arrow_block_to_pandas_opt_out_numpy_dtypes` (flag) and `test_to_pandas_reconciles_int_and_float_blocks` (overflow). Verified on Ray 2.56 that B no longer crashes and preserves `int64` exactly, A passes with the flag off, and normal pipelines are unchanged with the flag on. - Default is `True` to preserve #63017. Whether Arrow-backed conversion should remain the default is raised for maintainer input on the issue. --------- Signed-off-by: Marwan Sarieddine <[email protected]> Signed-off-by: Ayush Kumar <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: Ayush Kumar <[email protected]>
…#65187) ## Why are these changes needed? Follow-up to #64765 / #63017. `ArrowBlockAccessor.to_pandas()` maps Arrow types to `pd.ArrowDtype` via a `_types_mapper`, with carve-outs for extension and dictionary types. Arrow's `null` type needs the same carve-out. `null[pyarrow]` is unusable from pandas: the type carries no type information, so pandas cannot box a non-null value into such a column. `fillna` and masked assignment raise `ArrowInvalid`, and in some pyarrow/pandas combinations the failure comes out of Arrow C++ and aborts the worker process rather than raising. This is easy to hit in practice because the type is assigned per block, not per dataset. A column that has values overall can still be entirely null within one block — which is common with small blocks — so a pandas UDF like `map_batches(lambda df: df.fillna(...), batch_format="pandas")` fails on whichever block happens to hold only nulls: ```python ds = ray.data.from_items( [{"a": 1.0, "b": 2.0}, {"a": 3.0, "b": None}, {"a": None, "b": 4.0}], override_num_blocks=3, ) ds.map_batches(lambda df: df.fillna({"a": 0.0, "b": 0.0}), batch_format="pandas").take_all() # ArrowInvalid on the block where "a" (or "b") is all-null ``` The fix returns `None` from `_types_mapper` for null-typed columns, falling back to pandas' default conversion. The Arrow round-trip is unchanged: `PandasBlockAccessor.to_arrow()` already coerces all-null columns back to `pa.null()`. The one behavioral consequence, noted in a comment: a column that is all-null in *every* block stays null-typed instead of being promoted — same as before this change. ## Related issue number Follow-up to #64765. Two tests added: - `test_arrow_block_to_pandas_null_type_is_not_arrow_backed` — a `pa.null()` column is not `pd.ArrowDtype`, still round-trips back to `pa.null()` untouched, and `fillna` now works and adopts the fill value's type. - `test_pandas_udf_can_fill_per_block_null_columns` — end-to-end regression test for the `map_batches` + `fillna` failure above. Signed-off-by: Goutam <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Since ray-project#63017 (Ray 2.56) `BlockAccessor.to_pandas` returns Arrow-backed columns, so a missing value is `pd.NA` rather than `np.nan`. `pd.NA` propagates through comparisons as "unknown" instead of `False`, and it cannot be stored in a numeric NumPy array. Four preprocessors broke: - `PowerTransformer` raised `IndexError`, because `series >= 0` yields a three-valued `bool[pyarrow]` mask that cannot index a NumPy array. - `Categorizer` raised `TypeError: boolean value of NA is ambiguous`, because `is_null` did not recognize `pd.NA` and so it survived the filter into the category sort. - `Concatenator` silently emitted a column of pickled Python objects instead of a tensor, and raised `TypeError: ... not 'NAType'` when given an integer `dtype` or `flatten=True`. - `FeatureHasher` silently emitted pickled objects as well: `0 + pd.NA` is `pd.NA`, so a single null poisons every hash bucket. `is_null` now recognizes `pd.NA` and `pd.NaT`. The other three convert the columns they operate on through a new `to_numpy_backed` helper, which reproduces the conversion pandas performs when Arrow-backing is disabled (`int64` with nulls widens to `float64` with `np.nan`, strings become `object` with `None`), and is a no-op on already-NumPy-backed input. All of the tests are new. The existing preprocessor tests build their input with `from_pandas`, which never goes through `to_pandas`, so none of them could observe any of this. The new file also covers the null-typed-column `SimpleImputer` fix from ray-project#65187, which landed without a regression test. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Aarrya <[email protected]>
ray-project#63017 made every pandas batch Arrow-backed, including the batches Ray hands to user-supplied functions through `map_batches` and `iter_batches`. Two problems follow, neither of which involves a missing value: - pandas' Arrow backend leaves `mod`, `rmod`, `divmod` and `rdivmod` unimplemented, so `df["x"] % 2` inside a pandas UDF raises `NotImplementedError: mod not implemented.` (pandas-dev/pandas#58723). - `to_numpy()` and `.values` on an Arrow-backed frame return `dtype=object`, so code that passes the array to NumPy or to a model silently receives boxed Python objects instead of a numeric buffer. Ray cannot audit what a user's function does with the frame, so `map_batches` and `iter_batches` now convert pandas batches back to NumPy-backed pandas before calling it. Ray's own preprocessors are audited for `pd.NA` handling (see the preceding commit) and opt back in through an internal `arrow_backed_pandas` flag, so they keep the zero-copy conversion ray-project#63017 added. `Dataset.to_pandas` also keeps Arrow-backed dtypes. It returns a result to the driver rather than feeding a user function, and Arrow-backing is what lets an integer column containing nulls stay integral instead of widening to float. No public API signature changes: the flag is threaded through the existing `Dataset.map_batches_internal` and the private `DataIterator._iter_batches`. `test_basic[pandas]` in `block_batching/test_block_batching.py` asserted the old behavior by comparing against `ArrowBlockAccessor.to_pandas()`, so it now expects a NumPy-backed frame, and a new sibling test pins the opt-in side. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Aarrya <[email protected]>
Since ray-project#63017 (Ray 2.56) `BlockAccessor.to_pandas` returns Arrow-backed columns, so a missing value is `pd.NA` rather than `np.nan`. `pd.NA` propagates through comparisons as "unknown" instead of `False`, and it cannot be stored in a numeric NumPy array. Four preprocessors broke: - `PowerTransformer` raised `IndexError`, because `series >= 0` yields a three-valued `bool[pyarrow]` mask that cannot index a NumPy array. - `Categorizer` raised `TypeError: boolean value of NA is ambiguous`, because `is_null` did not recognize `pd.NA` and so it survived the filter into the category sort. - `Concatenator` silently emitted a column of pickled Python objects instead of a tensor, and raised `TypeError: ... not 'NAType'` when given an integer `dtype` or `flatten=True`. - `FeatureHasher` silently emitted pickled objects as well: `0 + pd.NA` is `pd.NA`, so a single null poisons every hash bucket. `is_null` now recognizes `pd.NA` and `pd.NaT`. The other three convert the columns they operate on through a new `to_numpy_backed` helper, which reproduces the conversion pandas performs when Arrow-backing is disabled (`int64` with nulls widens to `float64` with `np.nan`, strings become `object` with `None`), and is a no-op on already-NumPy-backed input. All of the tests are new. The existing preprocessor tests build their input with `from_pandas`, which never goes through `to_pandas`, so none of them could observe any of this. The new file also covers the null-typed-column `SimpleImputer` fix from ray-project#65187, which landed without a regression test. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Aarrya <[email protected]>
ray-project#63017 made every pandas batch Arrow-backed, including the batches Ray hands to user-supplied functions through `map_batches` and `iter_batches`. Two problems follow, neither of which involves a missing value: - pandas' Arrow backend leaves `mod`, `rmod`, `divmod` and `rdivmod` unimplemented, so `df["x"] % 2` inside a pandas UDF raises `NotImplementedError: mod not implemented.` (pandas-dev/pandas#58723). - `to_numpy()` and `.values` on an Arrow-backed frame return `dtype=object`, so code that passes the array to NumPy or to a model silently receives boxed Python objects instead of a numeric buffer. Ray cannot audit what a user's function does with the frame, so `map_batches` and `iter_batches` now convert pandas batches back to NumPy-backed pandas before calling it. Ray's own preprocessors are audited for `pd.NA` handling (see the preceding commit) and opt back in through an internal `arrow_backed_pandas` flag, so they keep the zero-copy conversion ray-project#63017 added. `Dataset.to_pandas` also keeps Arrow-backed dtypes. It returns a result to the driver rather than feeding a user function, and Arrow-backing is what lets an integer column containing nulls stay integral instead of widening to float. No public API signature changes: the flag is threaded through the existing `Dataset.map_batches_internal` and the private `DataIterator._iter_batches`. `test_basic[pandas]` in `block_batching/test_block_batching.py` asserted the old behavior by comparing against `ArrowBlockAccessor.to_pandas()`, so it now expects a NumPy-backed frame, and a new sibling test pins the opt-in side. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Aarrya <[email protected]>
Since ray-project#63017 (Ray 2.56) `BlockAccessor.to_pandas` returns Arrow-backed columns, so a missing value is `pd.NA` rather than `np.nan`. `pd.NA` propagates through comparisons as "unknown" instead of `False`, and it cannot be stored in a numeric NumPy array. Four preprocessors broke: - `PowerTransformer` raised `IndexError`, because `series >= 0` yields a three-valued `bool[pyarrow]` mask that cannot index a NumPy array. - `Categorizer` raised `TypeError: boolean value of NA is ambiguous`, because `is_null` did not recognize `pd.NA` and so it survived the filter into the category sort. - `Concatenator` silently emitted a column of pickled Python objects instead of a tensor, and raised `TypeError: ... not 'NAType'` when given an integer `dtype` or `flatten=True`. - `FeatureHasher` silently emitted pickled objects as well: `0 + pd.NA` is `pd.NA`, so a single null poisons every hash bucket. `is_null` now recognizes `pd.NA` and `pd.NaT`. The other three convert the columns they operate on through a new `to_numpy_backed` helper, which reproduces the conversion pandas performs when Arrow-backing is disabled (`int64` with nulls widens to `float64` with `np.nan`, strings become `object` with `None`), and is a no-op on already-NumPy-backed input. All of the tests are new. The existing preprocessor tests build their input with `from_pandas`, which never goes through `to_pandas`, so none of them could observe any of this. The new file also covers the null-typed-column `SimpleImputer` fix from ray-project#65187, which landed without a regression test. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Aarrya <[email protected]>
ray-project#63017 made every pandas batch Arrow-backed, including the batches Ray hands to user-supplied functions through `map_batches` and `iter_batches`. Two problems follow, neither of which involves a missing value: - pandas' Arrow backend leaves `mod`, `rmod`, `divmod` and `rdivmod` unimplemented, so `df["x"] % 2` inside a pandas UDF raises `NotImplementedError: mod not implemented.` (pandas-dev/pandas#58723). - `to_numpy()` and `.values` on an Arrow-backed frame return `dtype=object`, so code that passes the array to NumPy or to a model silently receives boxed Python objects instead of a numeric buffer. Ray cannot audit what a user's function does with the frame, so `map_batches` and `iter_batches` now convert pandas batches back to NumPy-backed pandas before calling it. Ray's own preprocessors are audited for `pd.NA` handling (see the preceding commit) and opt back in through an internal `arrow_backed_pandas` flag, so they keep the zero-copy conversion ray-project#63017 added. `Dataset.to_pandas` also keeps Arrow-backed dtypes. It returns a result to the driver rather than feeding a user function, and Arrow-backing is what lets an integer column containing nulls stay integral instead of widening to float. No public API signature changes: the flag is threaded through the existing `Dataset.map_batches_internal` and the private `DataIterator._iter_batches`. `test_basic[pandas]` in `block_batching/test_block_batching.py` asserted the old behavior by comparing against `ArrowBlockAccessor.to_pandas()`, so it now expects a NumPy-backed frame, and a new sibling test pins the opt-in side. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Aarrya <[email protected]>
Ray 2.56 (ray-project#63017) made `BlockAccessor.to_pandas` hand out Arrow-backed pandas frames, in which a missing value is `pd.NA` rather than `np.nan`. Five preprocessors regressed. Each is fixed locally; batches stay Arrow-backed, so ray-project#63017's memory and speed win is kept. The change swapped a sentinel that silently pretends to be a number for one that refuses to be anything. `np.nan` is a `float`, so it takes part in any float operation and always gives an answer: `np.nan >= 0` is False, `0 + np.nan` is `nan`, and a NumPy array holding it stays `float64`. None of those answers is meaningful for a missing value, but each is usable, and this code had been written to them. `pd.NA` gives none of them, and multi-column `df[cols].to_numpy()` over Arrow-backed columns returns `dtype=object` even with nothing missing, because pandas has no rule for combining Arrow extension types into one NumPy dtype. So each regression fix is the same shape: say out loud what `np.nan` used to say silently. - PowerTransformer: `.fillna(False)` on the sign mask, since `pd.NA >= 0` is `pd.NA` and a three-valued mask cannot index a NumPy array. A missing value takes the negative branch, where the arithmetic leaves it missing -- the same result as before, when `np.nan >= 0` was already False. - Concatenator: stack one column at a time instead of calling `to_numpy` on a multi-column selection. A single Arrow-backed column converts to its natural NumPy dtype. Previously the output tensor column silently became pickled Python objects, with no error raised and no null required to trigger it. - FeatureHasher: map a missing token count to `np.nan`. `0 + pd.NA` is `pd.NA`, which absorbs the accumulator and degrades the output column to `dtype=object`; `np.nan` propagates the same way but stays a float. - Encoder fit path: `_is_null` extended to `pd.NA`/`pd.NaT`, so a null is filtered before `sorted()` instead of raising `TypeError: boolean value of NA is ambiguous`, and the documented "consider imputing missing values first" ValueError is reached again. `Counter.update` guarded for the same reason. - `_is_series_composed_of_lists`: recognise a list column from an Arrow dtype. It gated on `is_object_dtype`, which is False for `list<item: string>[pyarrow]`, so list columns were treated as scalar and sent to `value_counts`, which has no pyarrow kernel for lists. This broke MultiHotEncoder with no nulls at all, and OrdinalEncoder on list columns. MaxAbsScaler is the mirror image: it needed to express something `np.nan` could not express. Fitting an all-null column leaves `stats_` holding None, and `s / None` has no answer for a float column, so it raised TypeError. For an Arrow-backed column None is a valid null scalar of the column's own type, so the division yields nulls -- the right answer, and the one StandardScaler was patched to give in ray-project#51281. An explicit guard mirroring StandardScaler's makes the two paths agree instead of leaving the correct result to depend on a pandas arithmetic rule. No behaviour change on the default path. The survey that found those regressions also found seven preprocessors that were already broken on missing data before ray-project#63017, failing identically on both representations. They are the same situations failing in the same illegible way, so they are fixed to the same rule: propagate the gap, or refuse with an error naming the column. Propagate, because the output can represent "missing" and the work is per-row: - MinMaxScaler, RobustScaler -- an all-null column has no range and no quantiles, so `fit` has no statistic to store. Return nulls, as StandardScaler has for an uncomputable mean or std since ray-project#51281. MinMaxScaler previously reported `'DataFrame' object has no attribute 'name'`: the real failure is `max - min` on two Nones, but `DataFrame.transform` retries a failing per-column function with the whole frame, and the retry dies on `s.name` instead. RobustScaler failed earlier still, in `fit`, unpacking an empty list of quantiles. - Tokenizer, CountVectorizer, HashingVectorizer -- a missing document is not tokenized, and contributes nothing to CountVectorizer's vocabulary. It gets no token list and no count vector, rather than a zero vector that would be indistinguishable from a document containing none of the vocabulary. These three died on a single missing cell in a text column, with `AttributeError: 'NAType' object has no attribute 'split'`. The guard lives at the call site rather than in `simple_split_tokenizer`, because a user-supplied `tokenization_fn` should not have to know about `pd.NA` either. Refuse, because no defensible output exists: - UniformKBinsDiscretizer -- with no observed values there is no range to divide into `bins` intervals. Was `TypeError: unsupported operand type(s) for +: 'NoneType' and 'float'`. - SimpleImputer(strategy="most_frequent") -- nothing to impute from. This message already existed for `strategy="mean"` (f4c4c81) but was unreachable here: the strategy died during `fit` on `most_common(1)[0][0]` with `IndexError: list index out of range`, before the guard that raises it. Tests: `tests/test_preprocessors_arrow_backed.py` covers 19 preprocessors across four input shapes -- no nulls, some nulls, an all-null column, and the same data as a NumPy-backed pandas block -- asserting that output stays numeric rather than `dtype=object`, that a missing input stays missing, and that the two refusals name the column rather than only raising the right exception type. Its `_is_missing` helper also counts `pd.NA`, which is what a missing value looks like when the output column keeps the block in pandas, as a column of Python lists does. The RobustScaler all-null case is worth a note: it was passing locally only because `datasketches` was absent, which skipped the test. It fails without this fix anywhere that optional package is installed, including CI. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Aarrya <[email protected]>
…ray-project#65187) ## Why are these changes needed? Follow-up to ray-project#64765 / ray-project#63017. `ArrowBlockAccessor.to_pandas()` maps Arrow types to `pd.ArrowDtype` via a `_types_mapper`, with carve-outs for extension and dictionary types. Arrow's `null` type needs the same carve-out. `null[pyarrow]` is unusable from pandas: the type carries no type information, so pandas cannot box a non-null value into such a column. `fillna` and masked assignment raise `ArrowInvalid`, and in some pyarrow/pandas combinations the failure comes out of Arrow C++ and aborts the worker process rather than raising. This is easy to hit in practice because the type is assigned per block, not per dataset. A column that has values overall can still be entirely null within one block — which is common with small blocks — so a pandas UDF like `map_batches(lambda df: df.fillna(...), batch_format="pandas")` fails on whichever block happens to hold only nulls: ```python ds = ray.data.from_items( [{"a": 1.0, "b": 2.0}, {"a": 3.0, "b": None}, {"a": None, "b": 4.0}], override_num_blocks=3, ) ds.map_batches(lambda df: df.fillna({"a": 0.0, "b": 0.0}), batch_format="pandas").take_all() # ArrowInvalid on the block where "a" (or "b") is all-null ``` The fix returns `None` from `_types_mapper` for null-typed columns, falling back to pandas' default conversion. The Arrow round-trip is unchanged: `PandasBlockAccessor.to_arrow()` already coerces all-null columns back to `pa.null()`. The one behavioral consequence, noted in a comment: a column that is all-null in *every* block stays null-typed instead of being promoted — same as before this change. ## Related issue number Follow-up to ray-project#64765. Two tests added: - `test_arrow_block_to_pandas_null_type_is_not_arrow_backed` — a `pa.null()` column is not `pd.ArrowDtype`, still round-trips back to `pa.null()` untouched, and `fillna` now works and adopts the fill value's type. - `test_pandas_udf_can_fill_per_block_null_columns` — end-to-end regression test for the `map_batches` + `fillna` failure above. Signed-off-by: Goutam <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…roject#63427) ## Description ray-project#63017 updated Ray Data's Arrow-to-pandas conversion to preserve Arrow-backed pandas dtypes, such as `int64[pyarrow]`, so dtypes can roundtrip more faithfully. This exposed an incompatibility with LightGBM's pandas input path. Ray Train's LightGBM examples and legacy trainer code convert Ray Data shards to pandas before constructing `lightgbm.Dataset`. With Arrow-backed Ray Data inputs, those pandas DataFrames can now contain Arrow-backed dtypes, and LightGBM rejects them during pandas dtype validation even when the logical column type is numeric. This PR updates the LightGBM paths to normalize pandas DataFrames to NumPy-nullable pandas dtypes before passing them to LightGBM. It also updates documentation and examples to show the same conversion for user-authored LightGBM training loops. ## Changes - Normalize pandas DataFrames in the legacy `LightGBMTrainer` path before constructing `lightgbm.Dataset`. - Update LightGBM docs and docstring examples to call `convert_dtypes(dtype_backend="numpy_nullable")` after `to_pandas()`. - Add a regression test covering Arrow-backed Ray Data input from `ray.data.from_items(...)`. - Keep the restore test focused on trainer restore behavior by using a pandas-backed test dataset. - Update the LightGBM release benchmark to avoid passing Arrow-backed pandas dtypes to LightGBM. --------- Signed-off-by: Mark Towers <[email protected]> Signed-off-by: matthewdeng <[email protected]> Co-authored-by: Mark Towers <[email protected]> Co-authored-by: matthewdeng <[email protected]> Signed-off-by: 400Ping <[email protected]>
…at block overflow (ray-project#64768) ## Description Ray 2.56 (ray-project#63017) made `BlockAccessor.to_pandas` map standard Arrow types to pandas Arrow-backed dtypes (`pd.ArrowDtype`). That caused two regressions, fixed here in two commits. **1. Opt-out flag (symptom A).** `map_batches(batch_format="pandas")` UDFs that assign a multi-dimensional ndarray into a column (`ArrowInvalid: Can only convert 1-dimensional array values`) or use numpy-only ops (e.g. `%`) now break, with no opt-out. Adds `DataContext.enable_arrow_backed_pandas_conversion` (env `RAY_DATA_ENABLE_ARROW_BACKED_PANDAS_CONVERSION`, default `True`); set to `False` to restore the pre-2.56 numpy conversion. **2. Fix internal overflow (symptom B).** `Dataset.to_pandas()` crashed in `PandasBlockBuilder._combine_tables` → `pandas.concat` when a column is `int64[pyarrow]` in some blocks and `double[pyarrow]` in others (a block whose values are all null infers `double`): the checked `int64`→`double` promotion overflows for values above 2^53. Ray crashed converting its own blocks (pre-2.56 this path silently widened `int64`→`float64`). Now, when the float-typed blocks are null-only / integral, they are cast back to the integer type before the concat, so it stays lossless and cannot overflow. Columns with genuine fractional values are left to pandas' usual promotion. Repros (both fail on 2.56; B is fixed by default, A needs the flag off): ```python import ray, numpy as np, pandas as pd, pyarrow as pa # Symptom B -- fixed by default: ds = ray.data.from_arrow([ pa.table({"ts": pa.array([1782750729409928627], pa.int64())}), pa.table({"ts": pa.array([None], pa.float64())}), ]) ds.to_pandas() # int64 preserved exactly, no overflow # Symptom A -- opt out to restore numpy dtypes: ray.data.DataContext.get_current().enable_arrow_backed_pandas_conversion = False def add_k(df): df["k"] = [[1.0] * 9 for _ in range(len(df))]; return df def rotate(df): df.loc[:, "k"] = pd.Series([np.eye(3)] * len(df), index=df.index); return df (ray.data.from_items([{"x": i} for i in range(4)]) .map_batches(add_k, batch_format="pandas") .map_batches(rotate, batch_format="pandas") .materialize()) ``` ## Related issues Closes ray-project#64765. ## Additional information - The flag mirrors the existing `pandas_block_ignore_metadata` / `enable_tensor_extension_casting` pattern (env-backed default + dataclass field + docstring). - The B fix only downcasts when lossless (null-only / integral float blocks); genuinely fractional columns are untouched. - Tests: `test_arrow_block_to_pandas_opt_out_numpy_dtypes` (flag) and `test_to_pandas_reconciles_int_and_float_blocks` (overflow). Verified on Ray 2.56 that B no longer crashes and preserves `int64` exactly, A passes with the flag off, and normal pipelines are unchanged with the flag on. - Default is `True` to preserve ray-project#63017. Whether Arrow-backed conversion should remain the default is raised for maintainer input on the issue. --------- Signed-off-by: Marwan Sarieddine <[email protected]> Signed-off-by: Ayush Kumar <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: Ayush Kumar <[email protected]> Signed-off-by: 400Ping <[email protected]>
…ray-project#65187) ## Why are these changes needed? Follow-up to ray-project#64765 / ray-project#63017. `ArrowBlockAccessor.to_pandas()` maps Arrow types to `pd.ArrowDtype` via a `_types_mapper`, with carve-outs for extension and dictionary types. Arrow's `null` type needs the same carve-out. `null[pyarrow]` is unusable from pandas: the type carries no type information, so pandas cannot box a non-null value into such a column. `fillna` and masked assignment raise `ArrowInvalid`, and in some pyarrow/pandas combinations the failure comes out of Arrow C++ and aborts the worker process rather than raising. This is easy to hit in practice because the type is assigned per block, not per dataset. A column that has values overall can still be entirely null within one block — which is common with small blocks — so a pandas UDF like `map_batches(lambda df: df.fillna(...), batch_format="pandas")` fails on whichever block happens to hold only nulls: ```python ds = ray.data.from_items( [{"a": 1.0, "b": 2.0}, {"a": 3.0, "b": None}, {"a": None, "b": 4.0}], override_num_blocks=3, ) ds.map_batches(lambda df: df.fillna({"a": 0.0, "b": 0.0}), batch_format="pandas").take_all() # ArrowInvalid on the block where "a" (or "b") is all-null ``` The fix returns `None` from `_types_mapper` for null-typed columns, falling back to pandas' default conversion. The Arrow round-trip is unchanged: `PandasBlockAccessor.to_arrow()` already coerces all-null columns back to `pa.null()`. The one behavioral consequence, noted in a comment: a column that is all-null in *every* block stays null-typed instead of being promoted — same as before this change. ## Related issue number Follow-up to ray-project#64765. Two tests added: - `test_arrow_block_to_pandas_null_type_is_not_arrow_backed` — a `pa.null()` column is not `pd.ArrowDtype`, still round-trips back to `pa.null()` untouched, and `fillna` now works and adopts the fill value's type. - `test_pandas_udf_can_fill_per_block_null_columns` — end-to-end regression test for the `map_batches` + `fillna` failure above. Signed-off-by: Goutam <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: 400Ping <[email protected]>
## Description Ray 2.56 (#63017) made `BlockAccessor.to_pandas` hand out **Arrow-backed** pandas frames — columns typed `double[pyarrow]` rather than `float64`, with a missing value spelled `pd.NA` rather than `np.nan`. Preprocessors receive that frame directly, and five of them broke. The change swapped a sentinel that silently pretends to be a number for one that refuses to be anything. `np.nan` is a `float`, so it joins in any float operation and always produces an answer: `np.nan >= 0` is `False`, `0 + np.nan` is `nan`, and a NumPy array holding it stays `float64`. None of those answers is *meaningful* for a missing value, but each is *usable*, and this code had been written to them. `pd.NA` provides none of them. Separately, and with nothing to do with missing values, `df[["a", "b"]].to_numpy()` over more than one Arrow-backed column returns `dtype=object` even when nothing is missing. This PR fixes those five, plus seven more preprocessors that the same survey found already broken on missing data before #63017. Every fix is local to `preprocessors/`: **batches stay Arrow-backed**, so #63017's memory and speed win is kept — nothing is converted back to NumPy-backed pandas. ## Related issues Related to CI-2270. ## Additional information ### What this means for UDFs A user's `map_batches(fn, batch_format="pandas")` UDF receives the same Arrow-backed frame these preprocessors do, and can hit the same problems. Those problems are upstream in Arrow-backed pandas rather than in Ray, so **this PR does not change what a UDF is handed** — reverting the conversion is what would give up #63017's win. The workarounds are small and local, and are the same ones used below: - A mask is now three-valued: `s >= 0` yields `True`/`False`/`pd.NA`, and a mask containing `pd.NA` cannot index a NumPy array. `(s >= 0).fillna(False)` makes it indexable again without giving the missing row a value. - Convert one column at a time rather than calling `df[cols].to_numpy()` on a multi-column selection, which is what degrades to `dtype=object`. A UDF that needs the old representation can opt out per-job with `DataContext.get_current().enable_arrow_backed_pandas_conversion = False`. That is the same flag used to measure every "pre-2.56" line below, so both behaviours are reachable from one install. ### Regressions from #63017 All five restore the pre-2.56 result, so nothing new is decided here. ``` PowerTransformer What it does Applies a Yeo-Johnson style power transform with a user-supplied power `p`, using a different formula on either side of zero: a non-negative value becomes `((x + 1)**p - 1) / p`, and a negative one becomes `-((-x + 1)**(2 - p) - 1) / (2 - p)`, with logarithms substituted at `p == 0` and `p == 2` where those would divide by zero. Which formula a row gets is decided by a boolean mask of the non-negative rows, which is then used to index the output array. The case One value in the column is missing. One is enough -- not a degenerate input. Pre-2.56 ok -> the missing row stays missing Post-2.56 IndexError Changed to pre-2.56. ``` ``` Concatenator What it does Packs several numeric columns into one tensor column, a fixed-width vector per row -- typically the last step before features reach a model. The case Two or more numeric columns. Nothing has to be missing: two doubles are enough for the stacked array to come out `dtype=object`. A missing value is only what makes it visible at the Dataset level, since with no nulls Ray rebuilds a numeric tensor from that object array on the way out. Pre-2.56 ok -> ArrowTensorType, dtype=double Post-2.56 dtype=object, silently; ArrowPythonObjectType -- pickled Python objects -- once a value is missing Changed to pre-2.56. ``` ``` FeatureHasher What it does Applies the hashing trick to a table of token counts: each input column is one token, each cell that token's count for that row. It hashes every token name to one of `num_features` buckets and sums the counts of the tokens sharing a bucket, giving a fixed-width vector per row. The case One token count is missing, so one bucket's sum is unknown. Pre-2.56 ok -> dtype=float64, that bucket holds nan Post-2.56 ok -> dtype=object Changed to pre-2.56. ``` ``` OrdinalEncoder / OneHotEncoder / LabelEncoder (the shared fit path) What it does Maps each distinct category to an integer during fit. A null is not a category, so all three refuse to fit a column containing one and tell the user to impute first. The case One label is missing. Pre-2.56 ValueError: Unable to fit column because it contains null values. Consider imputing missing values first. Post-2.56 TypeError: boolean value of NA is ambiguous Refusing is correct and deliberate here; what regressed is which error arrives. Changed to pre-2.56. ``` ``` MultiHotEncoder / OrdinalEncoder on list columns What it does MultiHotEncoder turns a column of lists into a fixed-width count vector, one position per category seen during fit. Whether a column is judged to hold lists is what selects that behaviour over scalar encoding. The case A list column with no missing values anywhere. The one regression that needs no nulls at all -- it broke MultiHotEncoder outright. Pre-2.56 ok Post-2.56 ArrowNotImplementedError Changed to pre-2.56. ``` #### `MaxAbsScaler`, the mirror image The five above lost something when `np.nan` became `pd.NA`. `MaxAbsScaler` gained something, because it needed to express what `np.nan` cannot: a statistic that *does not exist*. ``` MaxAbsScaler What it does Divides a column by the largest absolute value seen during fit, mapping it onto [-1, 1] without shifting zero. The case A column with no observed values at all, so fit has no absolute maximum to store. A single missing value is fine and always was. Pre-2.56 AttributeError: 'DataFrame' object has no attribute 'name' Post-2.56 ok -> nulls Changed to post-2.56, for the NumPy-backed path too: post-2.56 only gets nulls because dividing an Arrow-backed column by None happens to yield nulls, so without an explicit guard this still fails under `enable_arrow_backed_pandas_conversion = False`. ``` ### Already broken before #63017 Seven cases, none a regression: each fails identically on Arrow-backed and NumPy-backed blocks. Four need a column with **no observed values at all**; the three text ones need only **a single missing cell**, which is why they are the ones most likely to be hit in production. These are the cases where we pick neither the pre- nor the post-2.56 result, so each says why. ``` MinMaxScaler What it does Rescales a column onto [0, 1] using a min and max computed during fit. The case A column with no observed values, so fit stores None for both the min and the max and there is no range to scale into. Pre-2.56 AttributeError: 'DataFrame' object has no attribute 'name' Post-2.56 AttributeError: 'DataFrame' object has no attribute 'name' The error names the wrong thing entirely. `max - min` on two Nones raises `TypeError`, but the per-column function is applied by pandas' `DataFrame.transform`, which answers a per-column failure by retrying with the whole frame -- and the retry dies first, on `s.name`. So the user hears about a missing `DataFrame` attribute, and never about the column or the missing data. What we chose Propagate: every row of the output column is null. Scaling a missing value gives a missing value, and a column with no observed values has nothing that is not missing. Refusing would be wrong because an all-null column is ordinary at scale -- one partition of a large table, or a feature populated only for some records -- and failing the whole job is worse than returning nulls the caller can see. The *other* degenerate case is already handled a few lines away, a constant column, whose near-zero range is treated as 1. ``` ``` RobustScaler What it does Centres a column on its median and scales it by the distance between two quantiles, all three taken from an approximate-quantile sketch built during fit. The case A column with no observed values. The sketch is empty, so fit gets an empty list where it expects three quantiles. Pre-2.56 ValueError: not enough values to unpack (expected 3, got 0) Post-2.56 ValueError: not enough values to unpack (expected 3, got 0) What we chose Propagate: fit records "no quantile" for each of the three statistics and every row of the output column is null. A column with no observed values has nothing to centre or scale by, and an all-null column is ordinary at scale -- failing the whole job over one is worse than returning nulls. Fit is also where it has to be fixed, since that is where it fails; guarding the transform alone would not have been enough. ``` ``` UniformKBinsDiscretizer What it does Buckets a numeric column into N equal-width bins, deriving the bin edges from the column's min and max during fit. The case A column with no observed values, so the min and max are None and computing the bin edges does arithmetic on None. Pre-2.56 TypeError: unsupported operand type(s) for +: 'NoneType' and 'float' Post-2.56 TypeError: unsupported operand type(s) for +: 'NoneType' and 'float' What we chose Refuse, naming the column: `Column x has no values to bin. Check the data used to fit the discretizer.` The one case here that cannot propagate -- with no range there are no bins, so the fitted preprocessor is meaningless rather than just this column's output. `CustomKBinsDiscretizer` is unaffected, since its edges come from the user. ``` ``` SimpleImputer(strategy="most_frequent") What it does Fills a column's missing values with its commonest value, found during fit by counting values across the dataset. The case A column with no observed values, so the counter is empty and fit asks it for its most common entry. Pre-2.56 IndexError: list index out of range Post-2.56 IndexError: list index out of range What we chose Refuse with the error this file already raises whenever the fitted fill value is missing: `Column x has no fill value. Check the data used to fit the SimpleImputer.` There is nothing to impute from, and it is the same preprocessor in the same impossible situation, so it should be the same error. The guard is strategy-agnostic, but only `"mean"` could reach it -- an all-null column gives it a fill value of None and fit still succeeds, whereas `"most_frequent"` crashed during fit and never got there. Comments pointing this out **That error already existed in this file and was simply unreachable for this strategy.** `most_frequent` crashed during fit, before the transform guard that raises it could run. The guard came from f4c4c81, whose description names this exact class of bug -- "the preprocessor fails with an unintuitive error" -- so the fix was written and this strategy slipped past it. All it needed was for fit to report "no value" instead of indexing an empty list. ``` ``` Tokenizer What it does Replaces each string with a list of tokens; the default tokenizer splits on spaces. Row-wise -- it computes nothing during fit. The case One row's text is missing, and the tokenizer is handed it. Pre-2.56 AttributeError: 'NoneType' object has no attribute 'split' Post-2.56 AttributeError: 'NAType' object has no attribute 'split' The same failure both times, only the missing-value object is named differently. One empty cell in a text column kills the whole job. What we chose Propagate: a missing document is never passed to the tokenizer and its output stays null. Null rather than an empty list, so "no text" stays distinguishable from "text containing no words" -- a caller can always fill the nulls, but cannot recover the distinction once it is gone. The guard sits where the tokenizer is called rather than inside the default tokenizer, because the tokenization function can be supplied by the user, and a user's function should not have to know about `pd.NA` either. It is `Series.map(fn, na_action="ignore")`, so a custom tokenizer is covered too. ``` ``` CountVectorizer What it does Turns a text column into a per-token count vector, over a vocabulary of the most frequent tokens collected during fit. The case One row's text is missing. Fit tokenizes every row to count tokens and is handed the missing one, so this fails during fit rather than transform. Pre-2.56 AttributeError: 'NoneType' object has no attribute 'split' Post-2.56 AttributeError: 'NAType' object has no attribute 'split' What we chose Propagate: a missing document contributes no tokens to the vocabulary and its count vector is null. Skipping it corrupts nothing -- the vocabulary built from the remaining documents is exactly the vocabulary of the text that exists. ``` ``` HashingVectorizer What it does Turns a text column into a fixed-width count vector by hashing each token into one of `num_features` buckets. It learns no vocabulary, so it needs no fit. The case One row's text is missing, and tokenizing it is what fails. Pre-2.56 AttributeError: 'NoneType' object has no attribute 'split' Post-2.56 AttributeError: 'NAType' object has no attribute 'split' What we chose Propagate: a missing document gets a null count vector rather than a zero vector, so it stays distinguishable from a document whose tokens all hash elsewhere. The least ambiguous of the three text cases: with no fitted state at all, a missing row cannot affect any other row's output. ``` ### Tests New file `python/ray/data/tests/test_preprocessors_arrow_backed.py` runs 19 preprocessors over four input shapes — no nulls, one null per column, a column that is entirely null, and the same data as a NumPy-backed pandas block, so every case is checked against both representations rather than only the new one. It asserts that output stays numeric rather than `dtype=object`, that a missing input stays missing, and that the two refusals name the column. 91 passed, 1 skipped (a pandas block cannot carry a Python-list column, which is a block limitation rather than anything these tests measure). Existing `tests/preprocessors/`: 249 passed, 2 pre-existing skips. Run against the pre-fix code the new file fails 18 of its cases, so it measures the fixes rather than describing them. One of those 18 was already red rather than xfailed: the all-null `RobustScaler` case was passing locally only because `RobustScaler`'s fit needs the optional `datasketches` package, whose absence skipped the test. It fails without this PR anywhere that package is installed, including CI. --------- Signed-off-by: Aarrya <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
`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]>
`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]>
`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]>
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]>
) ## 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]>
…ray-project#65187) ## Why are these changes needed? Follow-up to ray-project#64765 / ray-project#63017. `ArrowBlockAccessor.to_pandas()` maps Arrow types to `pd.ArrowDtype` via a `_types_mapper`, with carve-outs for extension and dictionary types. Arrow's `null` type needs the same carve-out. `null[pyarrow]` is unusable from pandas: the type carries no type information, so pandas cannot box a non-null value into such a column. `fillna` and masked assignment raise `ArrowInvalid`, and in some pyarrow/pandas combinations the failure comes out of Arrow C++ and aborts the worker process rather than raising. This is easy to hit in practice because the type is assigned per block, not per dataset. A column that has values overall can still be entirely null within one block — which is common with small blocks — so a pandas UDF like `map_batches(lambda df: df.fillna(...), batch_format="pandas")` fails on whichever block happens to hold only nulls: ```python ds = ray.data.from_items( [{"a": 1.0, "b": 2.0}, {"a": 3.0, "b": None}, {"a": None, "b": 4.0}], override_num_blocks=3, ) ds.map_batches(lambda df: df.fillna({"a": 0.0, "b": 0.0}), batch_format="pandas").take_all() # ArrowInvalid on the block where "a" (or "b") is all-null ``` The fix returns `None` from `_types_mapper` for null-typed columns, falling back to pandas' default conversion. The Arrow round-trip is unchanged: `PandasBlockAccessor.to_arrow()` already coerces all-null columns back to `pa.null()`. The one behavioral consequence, noted in a comment: a column that is all-null in *every* block stays null-typed instead of being promoted — same as before this change. ## Related issue number Follow-up to ray-project#64765. Two tests added: - `test_arrow_block_to_pandas_null_type_is_not_arrow_backed` — a `pa.null()` column is not `pd.ArrowDtype`, still round-trips back to `pa.null()` untouched, and `fillna` now works and adopts the fill value's type. - `test_pandas_udf_can_fill_per_block_null_columns` — end-to-end regression test for the `map_batches` + `fillna` failure above. Signed-off-by: Goutam <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
## Description Ray 2.56 (ray-project#63017) made `BlockAccessor.to_pandas` hand out **Arrow-backed** pandas frames — columns typed `double[pyarrow]` rather than `float64`, with a missing value spelled `pd.NA` rather than `np.nan`. Preprocessors receive that frame directly, and five of them broke. The change swapped a sentinel that silently pretends to be a number for one that refuses to be anything. `np.nan` is a `float`, so it joins in any float operation and always produces an answer: `np.nan >= 0` is `False`, `0 + np.nan` is `nan`, and a NumPy array holding it stays `float64`. None of those answers is *meaningful* for a missing value, but each is *usable*, and this code had been written to them. `pd.NA` provides none of them. Separately, and with nothing to do with missing values, `df[["a", "b"]].to_numpy()` over more than one Arrow-backed column returns `dtype=object` even when nothing is missing. This PR fixes those five, plus seven more preprocessors that the same survey found already broken on missing data before ray-project#63017. Every fix is local to `preprocessors/`: **batches stay Arrow-backed**, so ray-project#63017's memory and speed win is kept — nothing is converted back to NumPy-backed pandas. ## Related issues Related to CI-2270. ## Additional information ### What this means for UDFs A user's `map_batches(fn, batch_format="pandas")` UDF receives the same Arrow-backed frame these preprocessors do, and can hit the same problems. Those problems are upstream in Arrow-backed pandas rather than in Ray, so **this PR does not change what a UDF is handed** — reverting the conversion is what would give up ray-project#63017's win. The workarounds are small and local, and are the same ones used below: - A mask is now three-valued: `s >= 0` yields `True`/`False`/`pd.NA`, and a mask containing `pd.NA` cannot index a NumPy array. `(s >= 0).fillna(False)` makes it indexable again without giving the missing row a value. - Convert one column at a time rather than calling `df[cols].to_numpy()` on a multi-column selection, which is what degrades to `dtype=object`. A UDF that needs the old representation can opt out per-job with `DataContext.get_current().enable_arrow_backed_pandas_conversion = False`. That is the same flag used to measure every "pre-2.56" line below, so both behaviours are reachable from one install. ### Regressions from ray-project#63017 All five restore the pre-2.56 result, so nothing new is decided here. ``` PowerTransformer What it does Applies a Yeo-Johnson style power transform with a user-supplied power `p`, using a different formula on either side of zero: a non-negative value becomes `((x + 1)**p - 1) / p`, and a negative one becomes `-((-x + 1)**(2 - p) - 1) / (2 - p)`, with logarithms substituted at `p == 0` and `p == 2` where those would divide by zero. Which formula a row gets is decided by a boolean mask of the non-negative rows, which is then used to index the output array. The case One value in the column is missing. One is enough -- not a degenerate input. Pre-2.56 ok -> the missing row stays missing Post-2.56 IndexError Changed to pre-2.56. ``` ``` Concatenator What it does Packs several numeric columns into one tensor column, a fixed-width vector per row -- typically the last step before features reach a model. The case Two or more numeric columns. Nothing has to be missing: two doubles are enough for the stacked array to come out `dtype=object`. A missing value is only what makes it visible at the Dataset level, since with no nulls Ray rebuilds a numeric tensor from that object array on the way out. Pre-2.56 ok -> ArrowTensorType, dtype=double Post-2.56 dtype=object, silently; ArrowPythonObjectType -- pickled Python objects -- once a value is missing Changed to pre-2.56. ``` ``` FeatureHasher What it does Applies the hashing trick to a table of token counts: each input column is one token, each cell that token's count for that row. It hashes every token name to one of `num_features` buckets and sums the counts of the tokens sharing a bucket, giving a fixed-width vector per row. The case One token count is missing, so one bucket's sum is unknown. Pre-2.56 ok -> dtype=float64, that bucket holds nan Post-2.56 ok -> dtype=object Changed to pre-2.56. ``` ``` OrdinalEncoder / OneHotEncoder / LabelEncoder (the shared fit path) What it does Maps each distinct category to an integer during fit. A null is not a category, so all three refuse to fit a column containing one and tell the user to impute first. The case One label is missing. Pre-2.56 ValueError: Unable to fit column because it contains null values. Consider imputing missing values first. Post-2.56 TypeError: boolean value of NA is ambiguous Refusing is correct and deliberate here; what regressed is which error arrives. Changed to pre-2.56. ``` ``` MultiHotEncoder / OrdinalEncoder on list columns What it does MultiHotEncoder turns a column of lists into a fixed-width count vector, one position per category seen during fit. Whether a column is judged to hold lists is what selects that behaviour over scalar encoding. The case A list column with no missing values anywhere. The one regression that needs no nulls at all -- it broke MultiHotEncoder outright. Pre-2.56 ok Post-2.56 ArrowNotImplementedError Changed to pre-2.56. ``` #### `MaxAbsScaler`, the mirror image The five above lost something when `np.nan` became `pd.NA`. `MaxAbsScaler` gained something, because it needed to express what `np.nan` cannot: a statistic that *does not exist*. ``` MaxAbsScaler What it does Divides a column by the largest absolute value seen during fit, mapping it onto [-1, 1] without shifting zero. The case A column with no observed values at all, so fit has no absolute maximum to store. A single missing value is fine and always was. Pre-2.56 AttributeError: 'DataFrame' object has no attribute 'name' Post-2.56 ok -> nulls Changed to post-2.56, for the NumPy-backed path too: post-2.56 only gets nulls because dividing an Arrow-backed column by None happens to yield nulls, so without an explicit guard this still fails under `enable_arrow_backed_pandas_conversion = False`. ``` ### Already broken before ray-project#63017 Seven cases, none a regression: each fails identically on Arrow-backed and NumPy-backed blocks. Four need a column with **no observed values at all**; the three text ones need only **a single missing cell**, which is why they are the ones most likely to be hit in production. These are the cases where we pick neither the pre- nor the post-2.56 result, so each says why. ``` MinMaxScaler What it does Rescales a column onto [0, 1] using a min and max computed during fit. The case A column with no observed values, so fit stores None for both the min and the max and there is no range to scale into. Pre-2.56 AttributeError: 'DataFrame' object has no attribute 'name' Post-2.56 AttributeError: 'DataFrame' object has no attribute 'name' The error names the wrong thing entirely. `max - min` on two Nones raises `TypeError`, but the per-column function is applied by pandas' `DataFrame.transform`, which answers a per-column failure by retrying with the whole frame -- and the retry dies first, on `s.name`. So the user hears about a missing `DataFrame` attribute, and never about the column or the missing data. What we chose Propagate: every row of the output column is null. Scaling a missing value gives a missing value, and a column with no observed values has nothing that is not missing. Refusing would be wrong because an all-null column is ordinary at scale -- one partition of a large table, or a feature populated only for some records -- and failing the whole job is worse than returning nulls the caller can see. The *other* degenerate case is already handled a few lines away, a constant column, whose near-zero range is treated as 1. ``` ``` RobustScaler What it does Centres a column on its median and scales it by the distance between two quantiles, all three taken from an approximate-quantile sketch built during fit. The case A column with no observed values. The sketch is empty, so fit gets an empty list where it expects three quantiles. Pre-2.56 ValueError: not enough values to unpack (expected 3, got 0) Post-2.56 ValueError: not enough values to unpack (expected 3, got 0) What we chose Propagate: fit records "no quantile" for each of the three statistics and every row of the output column is null. A column with no observed values has nothing to centre or scale by, and an all-null column is ordinary at scale -- failing the whole job over one is worse than returning nulls. Fit is also where it has to be fixed, since that is where it fails; guarding the transform alone would not have been enough. ``` ``` UniformKBinsDiscretizer What it does Buckets a numeric column into N equal-width bins, deriving the bin edges from the column's min and max during fit. The case A column with no observed values, so the min and max are None and computing the bin edges does arithmetic on None. Pre-2.56 TypeError: unsupported operand type(s) for +: 'NoneType' and 'float' Post-2.56 TypeError: unsupported operand type(s) for +: 'NoneType' and 'float' What we chose Refuse, naming the column: `Column x has no values to bin. Check the data used to fit the discretizer.` The one case here that cannot propagate -- with no range there are no bins, so the fitted preprocessor is meaningless rather than just this column's output. `CustomKBinsDiscretizer` is unaffected, since its edges come from the user. ``` ``` SimpleImputer(strategy="most_frequent") What it does Fills a column's missing values with its commonest value, found during fit by counting values across the dataset. The case A column with no observed values, so the counter is empty and fit asks it for its most common entry. Pre-2.56 IndexError: list index out of range Post-2.56 IndexError: list index out of range What we chose Refuse with the error this file already raises whenever the fitted fill value is missing: `Column x has no fill value. Check the data used to fit the SimpleImputer.` There is nothing to impute from, and it is the same preprocessor in the same impossible situation, so it should be the same error. The guard is strategy-agnostic, but only `"mean"` could reach it -- an all-null column gives it a fill value of None and fit still succeeds, whereas `"most_frequent"` crashed during fit and never got there. Comments pointing this out **That error already existed in this file and was simply unreachable for this strategy.** `most_frequent` crashed during fit, before the transform guard that raises it could run. The guard came from f4c4c81, whose description names this exact class of bug -- "the preprocessor fails with an unintuitive error" -- so the fix was written and this strategy slipped past it. All it needed was for fit to report "no value" instead of indexing an empty list. ``` ``` Tokenizer What it does Replaces each string with a list of tokens; the default tokenizer splits on spaces. Row-wise -- it computes nothing during fit. The case One row's text is missing, and the tokenizer is handed it. Pre-2.56 AttributeError: 'NoneType' object has no attribute 'split' Post-2.56 AttributeError: 'NAType' object has no attribute 'split' The same failure both times, only the missing-value object is named differently. One empty cell in a text column kills the whole job. What we chose Propagate: a missing document is never passed to the tokenizer and its output stays null. Null rather than an empty list, so "no text" stays distinguishable from "text containing no words" -- a caller can always fill the nulls, but cannot recover the distinction once it is gone. The guard sits where the tokenizer is called rather than inside the default tokenizer, because the tokenization function can be supplied by the user, and a user's function should not have to know about `pd.NA` either. It is `Series.map(fn, na_action="ignore")`, so a custom tokenizer is covered too. ``` ``` CountVectorizer What it does Turns a text column into a per-token count vector, over a vocabulary of the most frequent tokens collected during fit. The case One row's text is missing. Fit tokenizes every row to count tokens and is handed the missing one, so this fails during fit rather than transform. Pre-2.56 AttributeError: 'NoneType' object has no attribute 'split' Post-2.56 AttributeError: 'NAType' object has no attribute 'split' What we chose Propagate: a missing document contributes no tokens to the vocabulary and its count vector is null. Skipping it corrupts nothing -- the vocabulary built from the remaining documents is exactly the vocabulary of the text that exists. ``` ``` HashingVectorizer What it does Turns a text column into a fixed-width count vector by hashing each token into one of `num_features` buckets. It learns no vocabulary, so it needs no fit. The case One row's text is missing, and tokenizing it is what fails. Pre-2.56 AttributeError: 'NoneType' object has no attribute 'split' Post-2.56 AttributeError: 'NAType' object has no attribute 'split' What we chose Propagate: a missing document gets a null count vector rather than a zero vector, so it stays distinguishable from a document whose tokens all hash elsewhere. The least ambiguous of the three text cases: with no fitted state at all, a missing row cannot affect any other row's output. ``` ### Tests New file `python/ray/data/tests/test_preprocessors_arrow_backed.py` runs 19 preprocessors over four input shapes — no nulls, one null per column, a column that is entirely null, and the same data as a NumPy-backed pandas block, so every case is checked against both representations rather than only the new one. It asserts that output stays numeric rather than `dtype=object`, that a missing input stays missing, and that the two refusals name the column. 91 passed, 1 skipped (a pandas block cannot carry a Python-list column, which is a block limitation rather than anything these tests measure). Existing `tests/preprocessors/`: 249 passed, 2 pre-existing skips. Run against the pre-fix code the new file fails 18 of its cases, so it measures the fixes rather than describing them. One of those 18 was already red rather than xfailed: the all-null `RobustScaler` case was passing locally only because `RobustScaler`'s fit needs the optional `datasketches` package, whose absence skipped the test. It fails without this PR anywhere that package is installed, including CI. --------- Signed-off-by: Aarrya <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…-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]>


Summary
BlockAccessor.to_pandas()now passes pyarrow'stypes_mapper(keyed onBaseExtensionType) so columns retain Arrow-backed dtypes (int64[pyarrow],string[pyarrow], registered tensor extension types, etc.) across the Arrow → pandas → Arrow round-trip instead of falling back to numpy. Previously, the trip silently widened/narrowed types and dropped Arrow extension types.Production changes
_internal/arrow_block.py,_internal/pandas_block.py,_internal/tensor_extensions/pandas.py: route conversions through atypes_mapperthat resolves registered extension types viaBaseExtensionType, so user extension types survive._internal/util.py::_sort_df: cast Arrow-backed float columns (only) to numpy beforedf.sort_values. pandas's multi-column lex-sort builds an orderedCategoricalper key; with Arrow-backed floats it rejects-0.0/0.0("categories must be unique") because Arrow keeps them distinct but pandas treats them as equal. Cast is intentionally narrow — int/bool/string arrow columns stay as-is to avoidIntCastingNaNErroron nullable ints (numpyint64can't represent<NA>) and to avoid the<NA>-sorts-first vsNone-sorts-last divergence on strings. The original Categorical bug only affects floats anyway.aggregate.py,preprocessors/discretizer.py: minor adjustments for Arrow-backed inputs.Doc / example updates
doc/source/data/aggregating-data.rst:add_column("group_key", lambda x: x % 3)→lambda x: x["id"].to_numpy() % 3. Arrow has no mod compute kernel, and pandas's Arrow-backed extension array doesn't implement__mod__.doc/source/train/doc_code/lightgbm_quickstart.py: switched fromto_pandas()toiter_batches(batch_format="pyarrow")+pa.concat_tables, passing the resultingpyarrow.Table/ChunkedArraydirectly tolgb.Dataset. LightGBM (≥ 4.2.0; Ray pins 4.6.0) accepts Arrow natively, avoiding LightGBM's_check_for_bad_pandas_dtypesrejection ofdouble[pyarrow].Test updates (~30 files)
df.equals(...)/assert_frame_equal(actual, expected)assertions were updated to align expected dtypes with the now-Arrow-backedto_pandas()output:expected.astype(actual.dtypes.to_dict()).Nonein object columns and the actual is Arrow-backed (<NA>), the expected side casts the offending column(s) to"string"(pandas nullable string) so the null sentinel is<NA>on both sides — applied intest_iceberg.py's_create_typed_dataframehelper and intest_delta.py::test_delta_read_schema_evolution.test_map_batches.py::test_map_batches_batch_zero_copy: restructured to assert the source dataset is unchanged after a UDF tries to mutate its batch, rather than relying on the old "tried to mutate a zero-copy read-only batch"ValueError. Arrow-backed columns rebind on assignment instead of writing through to the underlying buffer, so the writable-buffer trigger no longer fires (and the property still holds, just implicitly).Test plan
test_with_column,test_join,test_csv,test_json,test_pandas,test_mongo(modified, no live mongo),test_imputer,test_normalizer,test_scaler,test_transformer,test_arithmetic,test_predicate,test_map_batches,test_map_transformer,test_execution_optimizer_advanced,test_delta.lightgbm==4.6.0+pyarrow==23.0.0.🤖 Generated with Claude Code