Repository navigation
[Data] Fix Arrow-backed to_pandas regressions: opt-out flag + int/float block overflow - #64768
Conversation
Ray 2.56 (ray-project#63017) made BlockAccessor.to_pandas map standard Arrow types to pandas Arrow-backed dtypes (pd.ArrowDtype). This broke pandas UDFs that assign multi-dimensional arrays into columns or use numpy-only operations (e.g. `%`), with no way to opt out. Add DataContext.enable_arrow_backed_pandas_conversion (env RAY_DATA_ENABLE_ARROW_BACKED_PANDAS_CONVERSION, default True). When set to False, to_pandas restores the pre-2.56 numpy conversion. First step for ray-project#64765 (opt-out / symptom A). A follow-up will make to_pandas not crash when concatenating blocks with divergent numeric column types (symptom B). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces a new configuration option, enable_arrow_backed_pandas_conversion, in DataContext (backed by the environment variable RAY_DATA_ENABLE_ARROW_BACKED_PANDAS_CONVERSION). This option allows users to opt out of the Arrow-backed pandas conversion and restore the previous behavior of converting standard Arrow types to NumPy dtypes. This is useful for unblocking pandas UDFs that rely on NumPy-only operations or assign multi-dimensional arrays into columns. A corresponding unit test has been added to verify this behavior. I have no feedback to provide.
d4ab345 to
6d74a22
Compare
6d74a22 to
592320f
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 592320f. Configure here.
Dataset.to_pandas concatenates per-block pandas frames in PandasBlockBuilder._combine_tables. When a column is int64 in some blocks and double in others (e.g. a block whose values are all null infers double), pandas.concat promotes to double with a *checked* cast that raises ArrowInvalid for int64 values above 2**53. Ray thus crashed converting its own blocks (pre-2.56 the numpy path silently widened int64 -> float64 instead). Reconcile such columns before the concat: cast the float blocks to the widest integer type among the int blocks, but only when every non-null float value is recoverable exactly as that type -- integral, within +-2**53 (float64's exact-integer range), and within the target type's range (bit width and signedness). Otherwise leave the blocks for pandas' usual float promotion, so an imprecise or out-of-range float is never silently coerced to a wrong integer. Second step for ray-project#64765 (symptom B). Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
592320f to
6691eab
Compare
ayushk7102
left a comment
There was a problem hiding this comment.
LGTM, thanks Marwan!
Can we document in which cases we will still raise invalid conversion error after reconciling arrow-backed columns?
| if not np.all(is_integral & in_range): | ||
| lossless = False | ||
| break |
There was a problem hiding this comment.
We should document that in the case that it's not lossless we still fail with an ArrowInvalid
| else: | ||
| type_min = -(2 ** (target_type.bit_width - 1)) | ||
| type_max = 2 ** (target_type.bit_width - 1) - 1 | ||
| lo = max(type_min, -(2**53)) |
There was a problem hiding this comment.
Can we store this is a variable i.e.
| lo = max(type_min, -(2**53)) | |
| lo = max(type_min, -(FLOAT64_MAX_INTEGER_VALUE)) |
| on = ArrowBlockAccessor(table).to_pandas() | ||
| assert isinstance(on.dtypes["x"], pd.ArrowDtype) |
There was a problem hiding this comment.
Should we have an equality predicate to assert that this is a pd.ArrowDtype[int64]?
Signed-off-by: Ayush Kumar <[email protected]>
… int/float block overflow (#64768) (#64793) Cherry-pick of #64768 onto the `releases/2.56.1` branch. ## Why are these changes needed? Fixes two Ray Data `to_pandas` regressions introduced in 2.56: 1. Adds `DataContext.enable_arrow_backed_pandas_conversion` (env `RAY_DATA_ENABLE_ARROW_BACKED_PANDAS_CONVERSION`, default `True`) as an opt-out for Arrow-backed pandas conversion. 2. Reconciles divergent numeric column types before concatenation to prevent int64/double[pyarrow] overflow crashes. ## Related issue number Cherry-pick of #64768 ## Checks Cherry-pick applied cleanly (no conflicts). DCO sign-off added. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Marwan Sarieddine <[email protected]> Signed-off-by: Ayush Kumar <[email protected]> Signed-off-by: elliot-barn <[email protected]> Co-authored-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: Ayush Kumar <[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]>
) ## 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]>
…-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]>
…andas (#67566) ## Summary A pandas batch silently loses elements from a column whose type nests Arrow's null type, such as `list<null>`. This PR converts those columns to Arrow-backed pandas columns without the cast that drops the elements. ## Problem - Since 2.56, `ArrowBlockAccessor.to_pandas()` maps each column to `pd.ArrowDtype`. Before pandas 3.1, `pd.ArrowDtype.__from_arrow__` casts every column, even to its own type. - Arrow's cast of a nested null child resizes that child to the number of rows. Elements past that point disappear. - A list of all-null values is typed `list<null>` when no row has a real value. Users see it with sparse list columns. ```python import pyarrow as pa, ray t = pa.table({"x": pa.array([[None, None], [None]], type=pa.list_(pa.null()))}) ds = ray.data.from_arrow(t).map_batches( lambda df: {"x": [list(v) for v in df["x"]]}, batch_format="pandas" ) print(ds.take_all()) ``` | | Output | |---|---| | Current (pandas < 3.1) | `[{'x': [None, None]}, {'x': []}]` | | Expected | `[{'x': [None, None]}, {'x': [None]}]` | When the batch goes back to Arrow untouched, the same column fails instead: `ArrowInvalid: Length spanned by list offsets (3) larger than values array (length 2)`. ## Change ``` Before After Arrow block ──types_mapper──▶ pd.ArrowDtype Arrow block ──types_mapper──▶ _ArrowDtypeWithoutIdentityCast │ │ __from_arrow__: cast(list<null>) __from_arrow__: same type, no cast │ │ ▼ ▼ list<null>[pyarrow], child cut to N rows list<null>[pyarrow], every element kept ``` - `_arrow_backed_pandas_dtype` returns `_ArrowDtypeWithoutIdentityCast` for a type with a null type nested anywhere inside it. The subclass's `__from_arrow__` skips the cast to the column's own type, which is what pandas 3.1 does for every column. - The column it builds carries a plain `pd.ArrowDtype`, and the subclass compares equal to that dtype, so users see no dtype change. - pyarrow handles the column like any other. In particular it never reads the block's pandas metadata for it, which names a dtype string pandas cannot parse (`list<item: null>[pyarrow]`). That is what broke the first version of this PR on a block coming back from a pandas UDF. - Other columns are untouched. With `enable_arrow_backed_pandas_conversion=False`, nothing changes. ## Decisions to confirm - The fix skips the identity cast for nested-null types only. Returning the subclass for every column would match pandas 3.1 exactly and drop `_has_nested_null_type`, at the cost of changing the conversion path of every column on pandas < 3.1. - A top-level `struct<a: null>` casts correctly but takes the new path too, because one rule ("any nested null") is simpler to reason about. ## Subsystems Block / data format (`arrow_block.py`). ## Related - Reported by a customer upgrading from 2.55 to 2.59. - Follows #64768, which added `enable_arrow_backed_pandas_conversion`. - Not a duplicate: no open issue or PR covers nested null types in `to_pandas()`. - Fixed in #67576, now merged; this branch carries it, which the pyarrow 17 CI job needs: with the flag off, a pandas UDF that returns its own `pd.ArrowDtype` list column makes the next `to_pandas()` fail with the same "not understood" error. Since #61733 the UDF's batch becomes an Arrow block with pandas metadata, and with no mapper pyarrow reads that metadata. On 2.55 the batch stayed a pandas block and it worked. ## Testing The three nested-null cases of the round-trip test fail without the fix and pass with it. The sliced `list<null>` case aborts the worker inside Arrow on master (`Slice offset (3) greater than array length (2)`), which is what a pandas UDF hits when `batch_size` is smaller than the block. Run locally with pandas 2.3.3 and pyarrow 23.0.1: ``` pytest python/ray/data/tests/test_arrow_block.py \ python/ray/data/tests/test_pandas_block.py \ python/ray/data/tests/test_transform_pyarrow.py \ python/ray/data/tests/preprocessors --ignore=.../test_torch.py # 563 passed, 5 skipped pytest python/ray/data/tests/test_map_batches.py python/ray/data/tests/test_batcher.py # 766 passed, 1 failed (test_local_shuffle_buffer_warns_if_too_large: OutOfDiskError from a full local disk, fails the same way without this change) ``` The `__from_arrow__` and equality behaviour of the subclass was also checked on pandas 2.2.3 (Ray's floor) and 3.1.0 against every type in the parametrized test. AI assistance (Claude Code) was used to reproduce the bug and write this change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>

Description
Ray 2.56 (#63017) made
BlockAccessor.to_pandasmap 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. AddsDataContext.enable_arrow_backed_pandas_conversion(envRAY_DATA_ENABLE_ARROW_BACKED_PANDAS_CONVERSION, defaultTrue); set toFalseto restore the pre-2.56 numpy conversion.2. Fix internal overflow (symptom B).
Dataset.to_pandas()crashed inPandasBlockBuilder._combine_tables→pandas.concatwhen a column isint64[pyarrow]in some blocks anddouble[pyarrow]in others (a block whose values are all null infersdouble): the checkedint64→doublepromotion overflows for values above 2^53. Ray crashed converting its own blocks (pre-2.56 this path silently widenedint64→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):
Related issues
Closes #64765.
Additional information
pandas_block_ignore_metadata/enable_tensor_extension_castingpattern (env-backed default + dataclass field + docstring).test_arrow_block_to_pandas_opt_out_numpy_dtypes(flag) andtest_to_pandas_reconciles_int_and_float_blocks(overflow). Verified on Ray 2.56 that B no longer crashes and preservesint64exactly, A passes with the flag off, and normal pipelines are unchanged with the flag on.Trueto preserve [Data] Preserve Arrow types through pandas roundtrip #63017. Whether Arrow-backed conversion should remain the default is raised for maintainer input on the issue.