Skip to content

[Data] Keep pandas metadata on Arrow blocks parsable by pandas - #67576

Merged
iamjustinhsu merged 4 commits into
masterfrom
marwan/data-pandas-metadata-parsable
Oct 30, 2026
Merged

iamjustinhsu merged 4 commits into
masterfrom
marwan/data-pandas-metadata-parsable

Conversation

@marwan116

@marwan116 marwan116 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A pandas UDF that returns an Arrow-backed list column makes the next to_pandas() fail with "data type 'list<item: int64>[pyarrow]' not understood" when enable_arrow_backed_pandas_conversion is off. This PR makes the pandas metadata on blocks built from pandas batches parsable by pandas, so pyarrow falls back to its own conversion for those columns.

Problem

  • Since [Data] Deprecate Pandas internal blocks: Convert Pandas UDF batches as Arrow blocks internally #61733 (2.56), the batch a pandas UDF returns becomes an Arrow block right away. With no object column, pa.Table.from_pandas builds it and records each column's pandas dtype name in the block's metadata.
  • When to_pandas() has no types mapper for a column, pyarrow rebuilds the dtype from that name. pandas cannot parse the names of parametrized Arrow-backed dtypes, so the conversion raises.
  • The flag-off path has no mapper, so any Arrow-backed list, struct or map column from a UDF breaks it. A dictionary Arrow-backed column breaks the flag-on path too, because the mapper returns None for dictionary types.
  • write_parquet carries the same metadata into files, and pd.read_parquet fails on them the same way.
import pyarrow as pa, pandas as pd, ray

ray.data.DataContext.get_current().enable_arrow_backed_pandas_conversion = False

def udf(df):
    return pd.DataFrame({"x": pd.array([[1, 2], [3]], dtype=pd.ArrowDtype(pa.list_(pa.int64())))})

ray.data.from_items([{"x": 1}, {"x": 2}]).map_batches(udf, batch_format="pandas").to_pandas()
Result
2.55 works, the batch stays a pandas block
2.56 to master TypeError: data type 'list<item: int64>[pyarrow]' not understood
After works, x is an object column of arrays

Change

A pandas batch becomes an Arrow block with a note of each column's pandas dtype. One note is unreadable, so the next to_pandas() crashes. The fix rewrites just that note when the block is built.

column   pandas dtype note          before          after
x        list<item: int64>[pyarrow]   TypeError       object (pyarrow's default)
n        Int64                        Int64           Int64 (unchanged)
  • _from_pandas_safe rewrites each dtype name pandas cannot parse to object on the fast path. The slow path builds the table column by column and never had metadata.
  • Names that parse are left alone, so the flag-off path still restores nullable dtypes such as Int64, boolean and string.
  • The rewrite is cached on the metadata bytes. For scale: the uncached check on a 51-column schema costs about as much as the from_pandas call it follows, and the cached path is a dictionary lookup.

Decisions to confirm

  • Rewriting only the unparsable names, rather than dropping the metadata or passing ignore_metadata=True. Dropping it would turn a UDF's Int64 column with nulls into float64 on the flag-off path, which 2.56 to 2.59 restore today.
  • Doing it where the block is built, rather than in to_pandas(). Blocks are built once and read many times, and files written from them become readable by pandas.

Subsystems

Block / data format (pandas_block.py).

Related

Testing

The new tests fail without the fix and pass with it:

pytest python/ray/data/tests/test_pandas_block.py python/ray/data/tests/test_arrow_block.py   # 103 passed
pytest python/ray/data/tests/test_map_batches.py python/ray/data/tests/datasource/test_parquet.py \
       python/ray/data/tests/test_transform_pyarrow.py python/ray/data/tests/preprocessors   # 1474 passed, 11 skipped

AI assistance (Claude Code) was used to find the root cause and write this change.

🤖 Generated with Claude Code

Problem:
- A pandas batch with no object column becomes an Arrow block through
  pa.Table.from_pandas, which records each column's pandas dtype name in
  the block's metadata.
- pandas cannot parse the names of parametrized Arrow-backed dtypes such
  as "list<item: int64>[pyarrow]". When no types mapper covers such a
  column, to_pandas() raises "data type ... not understood". That hits
  pandas UDFs returning Arrow-backed list, struct or map columns with
  enable_arrow_backed_pandas_conversion off, and dictionary columns with
  it on. Parquet files written from such blocks fail in pd.read_parquet
  the same way.

Change:
- _from_pandas_safe rewrites every dtype name pandas cannot parse to
  "object" before returning the block, so pyarrow falls back to its own
  conversion for that column. Names that parse, such as "Int64", stay.
- The rewrite is cached on the metadata bytes, since one schema recurs
  across batches.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
@marwan116
marwan116 requested a review from a team as a code owner October 30, 2026 03:37
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@marwan116 marwan116 added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Oct 30, 2026
@Yin-1022

Copy link
Copy Markdown
Contributor

I've verified the updated behavior locally.

Beyond the list-column repro, I checked Arrow-backed struct, map, and dictionary columns. Their unparsable pandas metadata is rewritten to object, and they all round-trip through to_pandas() successfully while preserving the underlying values. The dictionary case also still restores as a Pandas categorical.

As controls, nullable Int64, boolean, string, categorical, and timezone-aware datetime metadata remain unchanged and round-trip with their expected dtypes.

I also verified the public map_batches(...).to_pandas() path with an Arrow-backed struct column, plus the claimed write_parquet() -> pd.read_parquet() interoperability with an Arrow-backed dictionary column.

The change looks correct to me. LGTM.

@ayushk7102 ayushk7102 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.

Thanks a lot for the fix! LGTM if we can address a few comments

This seems to be an upstream bug in pandas, they have an open issue for this bug (pandas-dev/pandas#57411)

There also is an upstream PR (pandas-dev/pandas#66758) to fix this on the pandas side, but from the comments they want to wait/this is blocked till a larger effort to fix pyarrow/pandas compatibility is done.

Can we track this in our PR description & documentation @marwan116

if pandas_metadata is None:
return table
parsable = _parsable_pandas_metadata(pandas_metadata)
if parsable is pandas_metadata:

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.

Is is the right check here? Do we know parsable and pandas will share the same object, or will they rather be equal by value i.e. like ==

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in a53c90b. You're right: the cache returns the bytes object from the first call, so a later block with equal but distinct metadata bytes failed the identity check and was rewritten for nothing. It compares by value now.

continue
try:
pandas_dtype(dtype_name)
except Exception:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: Is the bare except Exception required here, or can we narrow this?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in a53c90b. It now catches TypeError, ValueError and NotImplementedError, which is what pandas raises for the unparsable names: list and struct give TypeError, map and dictionary ValueError, decimal and fixed-size list NotImplementedError.

Problem:
- The unchanged check compared the cached metadata bytes by identity, so
  an equal but distinct bytes object from a later block was rewritten
  for nothing.
- The dtype parse caught every exception.

Change:
- Compare by value.
- Catch the three exceptions pandas raises for a dtype name it cannot
  parse: TypeError, ValueError and NotImplementedError.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Marwan Sarieddine <[email protected]>
@marwan116

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Both comments are addressed in a53c90b, and the Related section now records the upstream pandas issue (#57411), the pandas fix PR (#66758) and the compatibility effort it waits on (#59780), so this rewrite can be dropped once a pandas release carries the fix.

@iamjustinhsu
iamjustinhsu merged commit d6974fe into master Oct 30, 2026
6 checks passed
@iamjustinhsu
iamjustinhsu deleted the marwan/data-pandas-metadata-parsable branch October 30, 2026 23:36
sai-miduthuri added a commit that referenced this pull request Oct 31, 2026
…able by pandas (#67576) (#67648)

Cherry-pick of #67576 (master commit
d6974fe) onto `releases/2.60.0`.

## Why

Since #61733 (2.56), the batch a pandas UDF returns becomes an Arrow
block built by `pa.Table.from_pandas`, which records each column's
pandas dtype name in the block's metadata. pandas cannot parse the names
of parametrized Arrow-backed dtypes. So when
`enable_arrow_backed_pandas_conversion` is off, a UDF that returns an
Arrow-backed list, struct or map column makes the next `to_pandas()`
fail with `TypeError: data type 'list<item: int64>[pyarrow]' not
understood`. `pd.read_parquet` fails the same way on files written from
these blocks. A customer hit this upgrading from 2.55 to 2.59.

#67576 rewrites each unparsable dtype name to `object` when
`_from_pandas_safe` builds the block, and leaves names that parse, such
as `Int64`, alone.

## Cherry-pick details

Applied cleanly with `git cherry-pick -x`. The same 2 files, +114/-1,
and the added and removed lines are identical to master's. `git
patch-id` differs only because of one context line: master reformatted
the `PandasRow` docstring in #67539, which isn't on this branch.

No prerequisite commits are missing. After the pick,
`_from_pandas_safe`, `_with_parsable_pandas_metadata` and
`_parsable_pandas_metadata` are identical to master's.

Not a duplicate: this branch doesn't contain #67576, and no PR against
`releases/2.60.0` references it. #67649 picks the same commit onto
`releases/2.59.1`.

## Testing

| Command | Result |
|---|---|
| `pre-commit run --files python/ray/data/_internal/pandas_block.py
python/ray/data/tests/test_pandas_block.py` | Passed |
| `pytest python/ray/data/tests/test_pandas_block.py
python/ray/data/tests/test_arrow_block.py` | 102 passed |
| #67576's repro (pandas UDF returning an Arrow-backed list column, flag
off), without and with the pick | Without: `TypeError: data type
'list<item: int64>[pyarrow]' not understood`. With: returns the lists as
an `object` column |

I ran these against the `releases/2.60.0` release wheel built at the
branch head (85ad153), with this branch's `python/ray/data` copied
over it, on Python 3.12 and pandas 2.3.3 (the version CI pins). Building
Ray from source for `bazel test` wasn't practical on my machine.

AI assistance was used to prepare this cherry-pick.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Marwan Sarieddine <[email protected]>
Signed-off-by: Sai Miduthuri <[email protected]>
Co-authored-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: Ayush Kumar <[email protected]>
elliot-barn pushed a commit that referenced this pull request Oct 31, 2026
…able by pandas (#67576) (#67649)

Cherry-pick of #67576 (master commit
d6974fe) onto `releases/2.59.1`.

## Why

Since #61733 (2.56), the batch a pandas UDF returns becomes an Arrow
block built by `pa.Table.from_pandas`, which records each column's
pandas dtype name in the block's metadata. pandas cannot parse the names
of parametrized Arrow-backed dtypes. So when
`enable_arrow_backed_pandas_conversion` is off, a UDF that returns an
Arrow-backed list, struct or map column makes the next `to_pandas()`
fail with `TypeError: data type 'list<item: int64>[pyarrow]' not
understood`. `pd.read_parquet` fails the same way on files written from
these blocks. A customer hit this upgrading from 2.55 to 2.59.

#67576 rewrites each unparsable dtype name to `object` when
`_from_pandas_safe` builds the block, and leaves names that parse, such
as `Int64`, alone.

## Cherry-pick details

Picked with `git cherry-pick -x`. `pandas_block.py` applied cleanly.
`test_pandas_block.py` conflicted in two places, because master's copy
has `PandasRow` tests and an import from #66116 and #66219, which aren't
on this branch. I resolved it by keeping only #67576's lines: the
`_parsable_pandas_metadata` import, the `_pandas_metadata_dtype_names`
helper and the three new tests. In both files, the added and removed
lines are identical to master's, and the commit is +114/-1 like #67576.

No prerequisite commits are missing. After the pick,
`_from_pandas_safe`, `_with_parsable_pandas_metadata` and
`_parsable_pandas_metadata` are identical to master's, and the
`restore_data_context` and `ray_start_regular_shared` fixtures the new
tests use exist on this branch.

Not a duplicate: this branch doesn't contain #67576, and no PR against
`releases/2.59.1` references it. #67648 picks the same commit onto
`releases/2.60.0`.

## Testing

| Command | Result |
|---|---|
| `pre-commit run --files python/ray/data/_internal/pandas_block.py
python/ray/data/tests/test_pandas_block.py` | Passed |
| `pytest python/ray/data/tests/test_pandas_block.py
python/ray/data/tests/test_arrow_block.py` | 83 passed |
| #67576's repro (pandas UDF returning an Arrow-backed list column, flag
off), without and with the pick | Without: `TypeError: data type
'list<item: int64>[pyarrow]' not understood`. With: returns the lists as
an `object` column |

I ran these against PyPI's `ray==2.59.0` wheel with this branch's
`python/ray/data` copied over it, on Python 3.12 and pandas 2.3.3 (the
version CI pins). `python/ray/data` has no changes between `ray-2.59.0`
and `releases/2.59.1`. Building Ray from source for `bazel test` wasn't
practical on my machine.

AI assistance was used to prepare this cherry-pick.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: Marwan Sarieddine <[email protected]>
Signed-off-by: Sai Miduthuri <[email protected]>
Co-authored-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: Ayush Kumar <[email protected]>
goutamvenkat-anyscale pushed a commit that referenced this pull request Nov 6, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants