Repository navigation
[Data] Keep pandas metadata on Arrow blocks parsable by pandas - #67576
Conversation
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]>
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
|
I've verified the updated behavior locally. Beyond the list-column repro, I checked Arrow-backed As controls, nullable I also verified the public The change looks correct to me. LGTM. |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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 ==
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
nit: Is the bare except Exception required here, or can we narrow this?
There was a problem hiding this comment.
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]>
…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]>
…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]>
…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]>
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" whenenable_arrow_backed_pandas_conversionis 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
pa.Table.from_pandasbuilds it and records each column's pandas dtype name in the block's metadata.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.dictionaryArrow-backed column breaks the flag-on path too, because the mapper returnsNonefor dictionary types.write_parquetcarries the same metadata into files, andpd.read_parquetfails on them the same way.TypeError: data type 'list<item: int64>[pyarrow]' not understoodxis an object column of arraysChange
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._from_pandas_saferewrites each dtype name pandas cannot parse toobjecton the fast path. The slow path builds the table column by column and never had metadata.Int64,booleanandstring.from_pandascall it follows, and the cached path is a dictionary lookup.Decisions to confirm
ignore_metadata=True. Dropping it would turn a UDF'sInt64column with nulls intofloat64on the flag-off path, which 2.56 to 2.59 restore today.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
pandas_block_ignore_metadatafor tensor dtype names in the same metadata; it is off by default.Testing
The new tests fail without the fix and pass with it:
AI assistance (Claude Code) was used to find the root cause and write this change.
🤖 Generated with Claude Code