Skip to content

[Data][2.56.1] Fix Arrow-backed to_pandas regressions: opt-out flag + int/float block overflow (#64768) - #64793

Merged
elliot-barn merged 1 commit into
releases/2.56.1from
cherry-pick/2.56.1/pr-64768
Jul 16, 2026
Merged

elliot-barn merged 1 commit into
releases/2.56.1from
cherry-pick/2.56.1/pr-64768

Conversation

@elliot-barn

Copy link
Copy Markdown
Collaborator

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

…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]>
(cherry picked from commit f43ccb9)
Signed-off-by: elliot-barn <[email protected]>
@elliot-barn
elliot-barn requested a review from a team as a code owner July 16, 2026 03:08

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a mechanism to reconcile columns that are inferred as integers in some blocks and floats in others (e.g., due to null values) before concatenation, preventing ArrowInvalid crashes when integer values exceed 2**53. It also adds a configuration option to opt out of Arrow-backed pandas conversion. The review feedback suggests enhancing the reconciliation logic to support heterogeneous schemas (where columns are not present in all blocks), avoiding potential RuntimeWarnings when checking for integral floats in the presence of infinities, and adding a corresponding test case.

Comment on lines +97 to +115
common_columns = set(tables[0].columns)
for table in tables[1:]:
common_columns &= set(table.columns)

# column -> integer ArrowDtype to cast the float-typed blocks to.
casts = {}
for column in common_columns:
dtypes = [table[column].dtype for table in tables]
if not all(isinstance(dtype, pandas.ArrowDtype) for dtype in dtypes):
continue
arrow_types = [dtype.pyarrow_dtype for dtype in dtypes]
int_types = [t for t in arrow_types if pa.types.is_integer(t)]
float_columns = [
table[column]
for table in tables
if pa.types.is_floating(table[column].dtype.pyarrow_dtype)
]
if not int_types or not float_columns:
continue

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

Currently, _reconcile_arrow_backed_int_float_columns only reconciles columns that are present in all tables (common_columns). However, in heterogeneous schema scenarios (which are common in Ray Data), a column might be missing in some blocks but present in others. If that column has an integer/float mismatch in the blocks where it is present, pandas.concat will still attempt to promote them and can crash with ArrowInvalid if there are integer values exceeding 2**53.

We should find all unique columns across all tables and reconcile any column that is present in at least two tables with a mismatch, while safely checking for column existence before accessing table[column].

This ensures robust reconciliation in heterogeneous schema scenarios.

Suggested change
common_columns = set(tables[0].columns)
for table in tables[1:]:
common_columns &= set(table.columns)
# column -> integer ArrowDtype to cast the float-typed blocks to.
casts = {}
for column in common_columns:
dtypes = [table[column].dtype for table in tables]
if not all(isinstance(dtype, pandas.ArrowDtype) for dtype in dtypes):
continue
arrow_types = [dtype.pyarrow_dtype for dtype in dtypes]
int_types = [t for t in arrow_types if pa.types.is_integer(t)]
float_columns = [
table[column]
for table in tables
if pa.types.is_floating(table[column].dtype.pyarrow_dtype)
]
if not int_types or not float_columns:
continue
all_columns = set()
for table in tables:
all_columns.update(table.columns)
# column -> integer ArrowDtype to cast the float-typed blocks to.
casts = {}
for column in all_columns:
dtypes = [table[column].dtype for table in tables if column in table.columns]
if not all(isinstance(dtype, pandas.ArrowDtype) for dtype in dtypes):
continue
arrow_types = [dtype.pyarrow_dtype for dtype in dtypes]
int_types = [t for t in arrow_types if pa.types.is_integer(t)]
float_columns = [
table[column]
for table in tables
if column in table.columns and pa.types.is_floating(table[column].dtype.pyarrow_dtype)
]
if not int_types or not float_columns:
continue

Comment on lines +151 to +157
for table in tables:
replace = {
column: table[column].astype(target)
for column, target in casts.items()
if pa.types.is_floating(table[column].dtype.pyarrow_dtype)
}
reconciled.append(table.assign(**replace) if replace else table)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

Update the casting application loop to check if the column exists in the table before attempting to cast it, supporting the heterogeneous schema reconciliation.

Suggested change
for table in tables:
replace = {
column: table[column].astype(target)
for column, target in casts.items()
if pa.types.is_floating(table[column].dtype.pyarrow_dtype)
}
reconciled.append(table.assign(**replace) if replace else table)
for table in tables:
replace = {
column: table[column].astype(target)
for column, target in casts.items()
if column in table.columns and pa.types.is_floating(table[column].dtype.pyarrow_dtype)
}
reconciled.append(table.assign(**replace) if replace else table)

if non_null.empty:
continue
values = non_null.to_numpy(dtype="float64", na_value=np.nan)
is_integral = np.mod(values, 1) == 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Using np.mod(values, 1) == 0 will raise a RuntimeWarning: invalid value encountered in remainder if values contains inf or -inf.

Using np.floor(values) == values is a safer and warning-free way to check if float values are integral, as np.floor handles infinities without raising warnings (and the subsequent in_range check will correctly filter out infinities).

Suggested change
is_integral = np.mod(values, 1) == 0
is_integral = np.floor(values) == values

assert len(df) == 2
assert pa.types.is_floating(df["v"].dtype.pyarrow_dtype)
assert float_value in df["v"].dropna().tolist()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Add a test case to verify that reconciliation works correctly even when the mismatched column is missing in some blocks (heterogeneous schemas).

Suggested change
def test_to_pandas_reconciles_heterogeneous_schemas(ray_start_regular_shared):
# Verify that reconciliation works even when the mismatched column is missing in some blocks.
big = 1782750729409928627
ds = ray.data.from_arrow(
[
pa.table({"ts": pa.array([big], pa.int64()), "other": pa.array([1])}),
pa.table({"ts": pa.array([None], pa.float64())}), # missing "other"
]
)
df = ds.to_pandas()
assert len(df) == 2
assert df["ts"].dropna().tolist() == [big]

@elliot-barn elliot-barn added the go add ONLY when ready to merge, run all tests label Jul 16, 2026
@elliot-barn
elliot-barn merged commit 0672981 into releases/2.56.1 Jul 16, 2026
3 checks passed
@elliot-barn
elliot-barn deleted the cherry-pick/2.56.1/pr-64768 branch July 16, 2026 05:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants