Repository navigation
[Data] Deprecate Pandas internal blocks: Convert Pandas UDF batches as Arrow blocks internally - #61733
Conversation
There was a problem hiding this comment.
Code Review
This pull request refactors Ray Data's internal block handling to prefer Arrow format for Pandas UDF outputs, which is a good step towards unifying the internal data representation. The implementation introduces a _safe_from_pandas utility for robust conversion and a DataContext flag for control. The changes are logical and well-structured. I've found a performance issue related to unnecessary data copying and a minor style improvement, for which I've left detailed comments.
alvinttang
left a comment
There was a problem hiding this comment.
Solid change — converting Pandas UDF outputs back to Arrow blocks via _safe_from_pandas is the right fix for object-dtype columns containing tensors, images, etc. that pa.Table.from_pandas can't handle natively.
Some observations:
-
_safe_from_pandassplits columns into object-dtype vs non-object-dtype and converts them separately. This is correct but has an edge case: if a non-object column's conversion depends on pandas metadata from an object column (unlikely but possible with MultiIndex or categorical types referencing object columns), the split could produce different results. In practice this shouldn't happen for Ray Data's use cases, but worth noting. -
The
_make_batch_writablefunction inutil.pycopies read-only numpy arrays whenensure_copy=True. This is a good fix for the Arrow-to-numpy writability issue. However, it only checksisinstance(v, np.ndarray)— if a column contains an Arrow extension array that wasn't converted to numpy (e.g., a tensor column), it would pass through without copying. Is that the intended behavior? -
The
batch_to_block_arrow_formatcontext flag defaults toTrue, meaning Pandas DataFrame outputs from UDFs will now be converted to Arrow blocks by default. This is a behavioral change for existing users — if any downstream code expects Pandas blocks after amap_batcheswithbatch_format="pandas", it could break. The env varRAY_DATA_DEFAULT_BATCH_TO_BLOCK_ARROW_FORMATprovides an escape hatch, which is good. -
In
block.py, the newelif isinstance(batch, pandas.DataFrame)branch callscls.for_block(batch).to_arrow(), which goes throughPandasBlockAccessor.to_arrow(), which now calls_safe_from_pandas. This double-dispatch is a bit indirect —batch_to_blockcreates aPandasBlockAccessorthen immediately converts to Arrow. Consider whether_safe_from_pandas(batch)could be called directly here to avoid the accessor overhead. -
The
_safe_from_pandasfunction usesconvert_to_pyarrow_arrayfor object-dtype columns, which handles tensors and falls back to pickle. The pickle fallback (ArrowPythonObjectArray) means that object columns with non-serializable objects will silently succeed but produce opaque binary columns. This is probably the right trade-off (fail-safe over fail-loud), but worth documenting. -
Missing test: there's no test for
_make_batch_writablewith a dict batch where some columns are writable and some aren't — the function handles this correctly per the code, but an explicit test would prevent regressions.
…block Signed-off-by: Ayush Kumar <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
…s DF with object-dtype columns into Arrow blocks Signed-off-by: Ayush Kumar <[email protected]>
…o_numpy() causing read-only views Signed-off-by: Ayush Kumar <[email protected]>
… blocks Signed-off-by: Ayush Kumar <[email protected]>
… Arrow semantics Signed-off-by: Ayush Kumar <[email protected]>
662b2ea to
0a5f09f
Compare
Signed-off-by: Ayush Kumar <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
Signed-off-by: Ayush Kumar <[email protected]>
…res on converting to Arrow Blocks internally (ray-project#61801) Stacked on ray-project#61733 This PR adds Agg/Null test fixes on top of the minimal change to ensure result batches from UDFs are converted to Arrow instead of Pandas blocks. --------- Signed-off-by: Ayush Kumar <[email protected]>
…arrow_batch_format
Signed-off-by: Ayush Kumar <[email protected]>
…nternally (ray-project#61733) ## Description When a UDF returns a `pd.DataFrame` or dict batch, Ray Data previously stored it as a Pandas block in the object store. This PR changes that behavior: UDF output is now immediately converted to an Arrow block before being stored, making Arrow the single internal block format ## Related issues None ## Additional information - Config key : `DEFAULT_BATCH_TO_BLOCK_ARROW_FORMAT` (default: `True` ). Get via `ray.data.DataContext.get_current().batch_to_block_arrow_format` - Implementation overview : - In `batch_to_block`, if the above key is set (Arrow is the default block format), convert each batched result Pandas dataframe into an Arrow block using `for_block(batch).to_arrow()` - `_safe_from_pandas(df)` replaces the direct pa.Table.from_pandas() call in PandasBlockAccessor.to_arrow(). The standard PyArrow conversion fails on object-dtype columns containing multi-dimensional numpy arrays, PIL images, or mixed types. This function routes object-dtype columns through `convert_to_pyarrow_array` - The new `_make_batch_writable()` function explicitly copies any read-only numpy arrays in the formatted batch. Wire down `ensure_copy` through `format_batch()`. This is required, as pa.Array.to_numpy() returns read-only views by default - Test/Bug fixes : - Updated `test_map_transformer` and `test_strict_schema` to correctly assert for Arrow blocks instead of Pandas. - Update `arrow_serialization.py` to pass ordered_flag to from_arrays(), dropping the flag results when deserializing Arrow dictionary arrays - Fixed `find_partition_index` behaviour for Arrow blocks, null semantics - Modify empty list check in Quantile Aggregate to match numpy and list semantics - Fix crash in multi aggregation tests by coercing accumulator type to list from numpy array in `/data/_internal/tensor_extensions/pandas.py` > Note: ray-project#61801 was originally stacked on this PR and has since been merged into it. --------- Signed-off-by: Ayush Kumar <[email protected]> Signed-off-by: Ayush Kumar <[email protected]>
## Description `PandasBlockAccessor.size_bytes()` estimates string/object column sizes by sampling up to 200 rows via `pandas.DataFrame.sample(n=...)` without a seed, so two blocks holding identical data report different sizes. That estimate drives block splitting in streaming generators, so a re-executed task can emit a different number of objects than the original attempt — which leaves downstream consumers silently hanging or silently dropping data (the companion #64394 fails fast when that mismatch occurs). This PR fixes the sampling non-determinism by passing `random_state=0`, and skips sampling entirely when the column fits in the sample. User UDFs remain responsible for their own determinism. **Symptom.** A streaming generator task re-executed for lineage reconstruction can leave the pipeline silently hanging or silently dropping data, with no error logged. **Root cause.** `PandasBlockAccessor.size_bytes()` estimates string/object columns by sampling up to 200 rows via `pandas.DataFrame.sample(n=...)`. No seed is passed, so each call samples different rows and two blocks holding identical data report different sizes. **How it turns into a bug.** That estimate drives block splitting: 1. `OutputBuffer.next()` calls `size_bytes()` to compute `target_num_rows`, so a task can split the same output into a different number of blocks each time it runs. 2. The first successful attempt pins the end-of-stream index to the object count it produced. 3. On re-execution, a different split produces a different object count: - **fewer** → downstream consumers block on indices that are never produced (silent hang); - **more** → the extras past the pinned end-of-stream index are dropped by `ObjectRefStream::InsertToStream` (silent data loss). **Fix.** Pass `random_state=0` to `sample()`, and skip sampling when the column has fewer than `sample_size` rows. Identical input now always yields the same size estimate. This removes one Ray-internal source of streaming-generator object-count non-determinism; user UDFs remain responsible for their own determinism. **Scope.** Only `PandasBlockAccessor.size_bytes()` is affected — the Arrow equivalent already uses `table.nbytes` and is deterministic. Pandas blocks are produced along several common paths: - a UDF that returns a `pandas.DataFrame` (e.g. `map_batches(fn, batch_format="pandas")`), kept as a pandas block by `BlockAccessor.batch_to_block`; - batches that Arrow cannot convert (object/ragged columns), which fall back to pandas blocks; - `split_repartition` preserving a pandas input schema; and - the built-in preprocessors (`encoder`, `vectorizer`, `imputer`). On released branches these paths default to pandas, so the bug is broadly reachable. On `master`, #61733 added a default that converts many UDF outputs to Arrow, but the fallback and pandas-schema paths above still build pandas blocks. ## Related issues None. ## Additional information **Reproduction** (before this PR, the two printed sizes frequently differ): ```python import pandas as pd from ray.data._internal.pandas_block import PandasBlockAccessor data = [f"str_{i}" for i in range(10_000)] b1 = pd.DataFrame({"col": pd.Series(data, dtype="string")}) b2 = pd.DataFrame({"col": pd.Series(data, dtype="string")}) print(PandasBlockAccessor.for_block(b1).size_bytes()) print(PandasBlockAccessor.for_block(b2).size_bytes()) ``` - **Test**: added `TestSizeBytes.test_deterministic_across_blocks`, asserting that two blocks holding identical data report the same `size_bytes()`. Signed-off-by: dragongu <[email protected]>
Converting a tensor-extension column to pandas crashed when the column had zero-size elements (element_shape containing a 0, e.g. an operator emitting empty per-row tensors). `TensorDtype.__from_arrow__` reshaped with a `-1` dimension, which numpy cannot infer from a size-0 array, raising `ValueError: cannot reshape array of size 0 into shape (0)`. Reshape with the explicit row count instead of `-1`, and short-circuit the empty-block (num_rows == 0) case by building the correctly typed empty buffer directly (`np.stack` needs at least one array). Regressed in 2.56 by ray-project#61733. Closes ray-project#64766. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Marwan Sarieddine <[email protected]>
…64767) ## Description `Dataset.to_pandas()` (and any Arrow → pandas batch conversion) crashes on Ray 2.56 when a tensor-extension column has zero-size elements, i.e. `element_shape` contains a `0`. This happens naturally when a per-frame / per-group operator emits an empty tensor for some rows (e.g. a detection op that finds nothing in a frame). `TensorDtype.__from_arrow__` reshapes the reconstructed values with a `-1` dimension: ```python values = values.reshape((-1,) + self.element_shape) ``` numpy cannot infer a `-1` dimension from a size-0 array when another dimension is `0`, so this raises: ``` ValueError: cannot reshape array of size 0 into shape (0) ``` Minimal repro (fails on 2.56.0, worked on 2.55): ```python import ray, numpy as np ray.data.from_items([{"pts": np.zeros((0,), np.float32)} for _ in range(3)]).to_pandas() ``` This regressed in 2.56 via #61733, which added the reshape (2.55's `__from_arrow__` simply returned `TensorArray(values)` with no reshape). ## Related issues Closes #64766. ## Additional information The fix uses the explicit row count instead of `-1` (numpy no longer has to infer a dimension), and builds the empty buffer directly for the zero-row `object`-dtype case, since `np.stack` requires at least one array: ```python num_rows = len(array) if values.dtype == object: values = ( np.stack(values) if num_rows > 0 else np.empty((0,) + self.element_shape, dtype=self._dtype) ) values = values.reshape((num_rows,) + self.element_shape) ``` Added `test_tensors_in_tables_pandas_roundtrip_empty_elements`, parametrized over element shapes `(0,)` and `(0, 2)` plus the existing tensor-format (V1 / V2 / ARROW_NATIVE) and auto-cast fixtures. Verified locally that the V1 and V2 paths crash before this fix and pass after; the native `pa.fixed_shape_tensor` path did not crash (it does not route through `__from_arrow__`) and continues to work. Signed-off-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: Ayush Kumar <[email protected]>
## Description `PandasBlockAccessor.size_bytes()` estimates string/object column sizes by sampling up to 200 rows via `pandas.DataFrame.sample(n=...)` without a seed, so two blocks holding identical data report different sizes. That estimate drives block splitting in streaming generators, so a re-executed task can emit a different number of objects than the original attempt — which leaves downstream consumers silently hanging or silently dropping data (the companion ray-project#64394 fails fast when that mismatch occurs). This PR fixes the sampling non-determinism by passing `random_state=0`, and skips sampling entirely when the column fits in the sample. User UDFs remain responsible for their own determinism. **Symptom.** A streaming generator task re-executed for lineage reconstruction can leave the pipeline silently hanging or silently dropping data, with no error logged. **Root cause.** `PandasBlockAccessor.size_bytes()` estimates string/object columns by sampling up to 200 rows via `pandas.DataFrame.sample(n=...)`. No seed is passed, so each call samples different rows and two blocks holding identical data report different sizes. **How it turns into a bug.** That estimate drives block splitting: 1. `OutputBuffer.next()` calls `size_bytes()` to compute `target_num_rows`, so a task can split the same output into a different number of blocks each time it runs. 2. The first successful attempt pins the end-of-stream index to the object count it produced. 3. On re-execution, a different split produces a different object count: - **fewer** → downstream consumers block on indices that are never produced (silent hang); - **more** → the extras past the pinned end-of-stream index are dropped by `ObjectRefStream::InsertToStream` (silent data loss). **Fix.** Pass `random_state=0` to `sample()`, and skip sampling when the column has fewer than `sample_size` rows. Identical input now always yields the same size estimate. This removes one Ray-internal source of streaming-generator object-count non-determinism; user UDFs remain responsible for their own determinism. **Scope.** Only `PandasBlockAccessor.size_bytes()` is affected — the Arrow equivalent already uses `table.nbytes` and is deterministic. Pandas blocks are produced along several common paths: - a UDF that returns a `pandas.DataFrame` (e.g. `map_batches(fn, batch_format="pandas")`), kept as a pandas block by `BlockAccessor.batch_to_block`; - batches that Arrow cannot convert (object/ragged columns), which fall back to pandas blocks; - `split_repartition` preserving a pandas input schema; and - the built-in preprocessors (`encoder`, `vectorizer`, `imputer`). On released branches these paths default to pandas, so the bug is broadly reachable. On `master`, ray-project#61733 added a default that converts many UDF outputs to Arrow, but the fallback and pandas-schema paths above still build pandas blocks. ## Related issues None. ## Additional information **Reproduction** (before this PR, the two printed sizes frequently differ): ```python import pandas as pd from ray.data._internal.pandas_block import PandasBlockAccessor data = [f"str_{i}" for i in range(10_000)] b1 = pd.DataFrame({"col": pd.Series(data, dtype="string")}) b2 = pd.DataFrame({"col": pd.Series(data, dtype="string")}) print(PandasBlockAccessor.for_block(b1).size_bytes()) print(PandasBlockAccessor.for_block(b2).size_bytes()) ``` - **Test**: added `TestSizeBytes.test_deterministic_across_blocks`, asserting that two blocks holding identical data report the same `size_bytes()`. Signed-off-by: dragongu <[email protected]> Signed-off-by: 400Ping <[email protected]>
…ay-project#64767) ## Description `Dataset.to_pandas()` (and any Arrow → pandas batch conversion) crashes on Ray 2.56 when a tensor-extension column has zero-size elements, i.e. `element_shape` contains a `0`. This happens naturally when a per-frame / per-group operator emits an empty tensor for some rows (e.g. a detection op that finds nothing in a frame). `TensorDtype.__from_arrow__` reshapes the reconstructed values with a `-1` dimension: ```python values = values.reshape((-1,) + self.element_shape) ``` numpy cannot infer a `-1` dimension from a size-0 array when another dimension is `0`, so this raises: ``` ValueError: cannot reshape array of size 0 into shape (0) ``` Minimal repro (fails on 2.56.0, worked on 2.55): ```python import ray, numpy as np ray.data.from_items([{"pts": np.zeros((0,), np.float32)} for _ in range(3)]).to_pandas() ``` This regressed in 2.56 via ray-project#61733, which added the reshape (2.55's `__from_arrow__` simply returned `TensorArray(values)` with no reshape). ## Related issues Closes ray-project#64766. ## Additional information The fix uses the explicit row count instead of `-1` (numpy no longer has to infer a dimension), and builds the empty buffer directly for the zero-row `object`-dtype case, since `np.stack` requires at least one array: ```python num_rows = len(array) if values.dtype == object: values = ( np.stack(values) if num_rows > 0 else np.empty((0,) + self.element_shape, dtype=self._dtype) ) values = values.reshape((num_rows,) + self.element_shape) ``` Added `test_tensors_in_tables_pandas_roundtrip_empty_elements`, parametrized over element shapes `(0,)` and `(0, 2)` plus the existing tensor-format (V1 / V2 / ARROW_NATIVE) and auto-cast fixtures. Verified locally that the V1 and V2 paths crash before this fix and pass after; the native `pa.fixed_shape_tensor` path did not crash (it does not route through `__from_arrow__`) and continues to work. Signed-off-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: Ayush Kumar <[email protected]> Signed-off-by: 400Ping <[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" 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 #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. ```python 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 - Reported by a customer upgrading from 2.55 to 2.59, found while fixing #67566. - The same metadata path broke the first version of #67566; this PR covers the case that version left behind. - #56402 added `pandas_block_ignore_metadata` for tensor dtype names in the same metadata; it is off by default. - Upstream: pandas cannot parse its own Arrow-backed dtype names, tracked in pandas-dev/pandas#57411. The pandas fix, pandas-dev/pandas#66758, is on hold behind the wider pyarrow compatibility work in pandas-dev/pandas#59780, so Ray rewrites the names on its side until a pandas release carries it. - Not a duplicate: no open issue or PR covers unparsable pandas dtype names on blocks. ## 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](https://claude.com/claude-code) --------- Signed-off-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) (#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]>
…7579) ## Summary A batch that spans blocks whose tensor column is null in one of them fails with "Trying to unify unsupported tensor type: null". This PR lets tensor arrays carry null rows, so such blocks merge and the column stays a tensor column, with `None` for the missing rows. A column that is a tensor in one block and pickled objects in another keeps raising; a follow-up PR extends that error with the columns and types found. ## Problem - Since #61733 (2.56), the batch a pandas UDF returns becomes an Arrow block right away. Each one-row block types a column from its own value: a stacked array becomes a tensor, `None` becomes null. - Merging those blocks into a batch reconciles the schemas. A tensor with a null arm passed reconciliation and then failed in the tensor unifier, which rejected null. - Tensor arrays could already hold null rows, but `to_numpy()` on them failed with "buffer is too small", so nothing could read them (#67200). - In 2.55 the batches stayed pandas blocks, so there was no Arrow schema to unify. ```python import numpy as np, ray def decode(batch): row = int(batch["id"][0]) return {"img": [None if row == 5 else np.full((2, 2), row, np.float32)]} ds = ray.data.range(8).map_batches(decode, batch_size=1) next(iter(ds.iter_batches(batch_size=8, batch_format="numpy"))) ``` | | Result | |---|---| | 2.55 | works | | 2.56 to master | `ValueError: Trying to unify unsupported tensor type: null` | | After | works, `img` is a tensor column with `None` in row 5 | ## Change ``` block 1 img = stacked array -> tensor block 2 img = None -> null Before: unify schemas -> tensor -> concat: "unsupported tensor type: null" After: unify schemas -> tensor -> null chunk becomes null rows of the tensor type ``` - `unify_tensor_arrays` turns a null-typed chunk into null rows of the unified tensor type, so `concat` keeps the column a tensor column. - Both tensor array classes read null rows: `to_numpy()` returns one ndarray view per row with `None` for each null row, and `from_numpy()` accepts `None` among the tensors. A variable-shaped row is null when its struct slot or either child is null. Null rows survive promotion to the variable-shaped type. - `TensorArray` accepts `None` rows, so such a column converts to pandas and back. - The torch conversion error names `None` rows instead of blaming ragged shapes. - A column that is a tensor in one block and pickled objects in another still raises "Found columns with both objects and tensors". Merging them would silently turn every row into a pickled object and lose the type. What a batch looks like, for a tensor column where one row is missing: | batch | before | after | |---|---|---| | no missing row | error | `float32 (8, 2, 2)` | | one missing row | error | `object (8,)`, views and `None`, nothing pickled | | schema | error | tensor | ## Decisions to confirm - A batch holding a null row comes back as one ndarray per row with `None`, since a dense array has no slot for a missing row. Filling the row with zeros or NaN would invent data and has no form for integer or ragged tensors. - `from_numpy()` with `None` among the tensors now builds a tensor array with null rows. Before, such a column fell back to pickled objects with a warning. - Tensors next to pickled objects keep raising rather than merging to objects, per review. Users make every row the same kind, for example by returning ragged arrays as nested lists. ## Subsystems Block / data format (`arrow_ops/transform_pyarrow.py`, `tensor_extensions/arrow.py`, `tensor_extensions/pandas.py`). ## Related - Reported by a customer upgrading from 2.55 to 2.59, alongside #67566. - Fixes #67200: `to_pandas()` and numpy batches now return `None` for a null tensor row instead of another row's value or an error. - Overlaps #67236, which makes the same two `to_numpy` paths null-aware and makes `to_pandas` raise on null rows. This PR also builds tensor arrays from input holding `None`, converts null rows to pandas and back, keeps them through shape promotion, and merges null chunks. The rule that a null child marks a null row is taken from #67236. - Leaves the native `fixed_shape_tensor` type alone; #67293 covers its null rows. - A follow-up PR extends the objects-and-tensors error with the columns and types found. ## Testing ``` pytest python/ray/data/tests/unit/test_transform_pyarrow.py \ python/ray/data/tests/test_transform_pyarrow.py \ python/ray/data/tests/test_arrow_block.py \ python/ray/data/tests/test_tensor_extension.py \ python/ray/data/tests/test_torch_tensor_utils.py # 387 passed ``` AI assistance (Claude Code) was used to find the root cause and write this change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Marwan Sarieddine <[email protected]> Signed-off-by: Elliot Barnwell <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Elliot Barnwell <[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]>
…ble across blocks (#67579) (#67999) ## Description Cherry-pick of #67579 (master commit 1acc2c3) onto `releases/2.60.1`. **Middle of a 3-PR stack on `releases/2.60.1`:** #67995 (the #66521 pick), then this PR, then #68019 (the #67806 pick, which fixes this change on pyarrow 26). Merge the stack with `gh stack merge 68019`, which lands all three in order. Since #61733 (2.56), a batch that spans blocks whose tensor column is null in one of them fails with `ValueError: Trying to unify unsupported tensor type: null`. A pandas UDF that returns `None` for some rows and an ndarray for others is enough to hit it. It worked in 2.55. #67579 lets tensor arrays carry null rows, so these blocks merge, the column stays a tensor column, and missing rows read back as `None`. ## Related issues Related to #67579. Depends on #67995, the #66521 pick. ## Additional information ### Cherry-pick details Applied with `git cherry-pick -x`. 9 of the 10 files merged cleanly. `tensor_extensions/pandas.py` conflicted only on the `TensorArray.dtype` docstring. Master had reformatted it in #67539 (ruff D212/D200), which isn't on this branch. I kept this branch's docstring and added the PR's one new line, `first = _first_non_null(self._tensor)`. The added and removed lines are identical to the master commit. `git patch-id` differs only because of that docstring context line. Prerequisite: #66521. Without it, `test_arrow_concat_tensor_with_null_keeps_tensor_type[last_shape1]` and `test_unify_schemas_tensor_with_null_keeps_tensor_type[other_shape1]` fail on this branch. These are the cases where the tensor blocks have different shapes. I applied each master-only commit that touched `transform_pyarrow.py` or the tensor extensions between the branch cut and #67579 on top of this pick. #66521 alone fixes both tests. The other files differ from master only by master commits this change doesn't use. Not a duplicate: this branch doesn't contain #67579, and no PR against `releases/2.60.1` references it. ### Testing All of these ran with the #66521 pick applied underneath. | Command | Result | |---|---| | `pre-commit run --files <the 10 changed files>` | Passed | | `pytest test_arrow_block.py test_tensor_extension.py test_torch_tensor_utils.py unit/test_transform_pyarrow.py test_transform_pyarrow.py test_pandas_block.py` (under `python/ray/data/tests/`) | 526 passed, 3 skipped | | The same test files from this PR, against the code with only #66521 (no #67579) | 60 failed, 155 passed, and `test_tensor_extension.py` fails to collect, because it imports a helper this PR adds | | This pick directly on `releases/2.60.1`, without #66521 | The 2 tests above fail | | `test_arrow_block.py test_pandas_block.py test_tensor_extension.py` with the #67566 pick (#67994) also applied | 397 passed | `test_tensor_column_no_memory_leak` needs `scipy`, which my environment didn't have at first. The 526 passed is from a run with scipy installed. I ran these against the Ray 2.60.0 release wheel, with this branch's `python/ray/data` and `python/ray/tests` copied over it. The wheel was built from `releases/2.60.0` at b7f4259, and its Python sources match `releases/2.60.1` except for `_version.py`. The environment was Python 3.12 with pandas 2.3.3 and pyarrow 23.0.1, the versions CI pins, plus numpy 2.2.6 and torch 2.9.0+cpu. 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: Elliot Barnwell <[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: Elliot Barnwell <[email protected]>
…ble across blocks (#67579) (#68025) ## Description Cherry-pick of #67579 (master commit 1acc2c3) onto `releases/2.59.2`. **Middle of a 3-PR stack on `releases/2.59.2`:** #68024 (the #66521 pick), then this PR, then #68026 (the #67806 pick, which fixes this change on pyarrow 26). Merge the stack with `gh stack merge 68026`, which lands all three in order. Since #61733 (2.56), a batch that spans blocks whose tensor column is null in one of them fails with `ValueError: Trying to unify unsupported tensor type: null`. A pandas UDF that returns `None` for some rows and an ndarray for others is enough to hit it. It worked in 2.55. #67579 lets tensor arrays carry null rows, so these blocks merge, the column stays a tensor column, and missing rows read back as `None`. ## Related issues Related to #67579. Depends on #68024, the #66521 pick. The same pick for 2.60.1 is #67999. ## Additional information ### Cherry-pick details Applied with `git cherry-pick -x`. 5 of the 10 files merged cleanly. In the other 5, each conflict was master-only code that sits next to #67579's additions: | File | Master-only context | Kept from #67579 | |---|---|---| | `arrow_ops/transform_pyarrow.py` | the `chunked_tensor_take` imports (#64961) | the `create_ragged_ndarray` import | | `tensor_extensions/arrow.py` | `tensor_array_to_numpy` and `_to_dense_ndarray_or_none` (#66122) | `native_tensor_array_to_numpy` | | `tensor_extensions/pandas.py` | the `TensorArray.dtype` docstring reformat (#67539) | `first = _first_non_null(self._tensor)`, under this branch's docstring | | `tests/test_arrow_block.py` | earlier tests, such as #65539's | the 68 lines of new tests | | `tests/test_tensor_extension.py` | #66122's tests | the 280 lines of new tests | I resolved each conflict by applying only #67579's change relative to its parent, which was a pure insertion every time, and dropping the master-only lines. Across all 10 files, the added and removed lines are identical to the master commit. `git patch-id` differs only because of the context lines. Prerequisite: #66521. Without it, `test_arrow_concat_tensor_with_null_keeps_tensor_type[last_shape1]` and `test_unify_schemas_tensor_with_null_keeps_tensor_type[other_shape1]` fail on this branch, as they do on 2.60.1. Not a duplicate: this branch doesn't contain #67579, and no PR against `releases/2.59.2` references it. #67999 picks the same commit onto `releases/2.60.1`. ### Testing The six test files, under `python/ray/data/tests/`, are `test_arrow_block.py test_tensor_extension.py test_torch_tensor_utils.py unit/test_transform_pyarrow.py test_transform_pyarrow.py test_pandas_block.py`. | Command | Result | |---|---| | `pre-commit run --files <the 10 changed files>` | Passed | | `pytest <the six files>`, with the whole stack (#66521, this PR, #67806) | 478 passed | | `pytest --continue-on-collection-errors <the six files>`, with this PR's tests against the code with only #66521 | 60 failed, 203 passed, and `test_tensor_extension.py` fails to collect, because it imports a helper this PR adds | | `pytest <the six files>`, with this pick directly on `releases/2.59.2`, without #66521 | The 2 tests above fail, 465 passed | | `pytest test_arrow_block.py test_pandas_block.py test_tensor_extension.py`, with the stack and the #67566 pick (#68022) applied together | 365 passed | I ran these against the Ray 2.59.1 release wheel, with this branch's `python/ray/data` and `python/ray/tests` copied over it. The wheel was built from `releases/2.59.1` at 7bdaad7, and its Python sources match `releases/2.59.2` except for `_version.py`. The environment was Python 3.12 with pandas 2.3.3, pyarrow 23.0.1, numpy 2.1.3, scipy 1.17.1 and torch 2.9.0+cpu, the versions CI pins on this branch. 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: Elliot Barnwell <[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: Elliot Barnwell <[email protected]>
Description
When a UDF returns a
pd.DataFrameor dict batch, Ray Data previously stored it as a Pandas block in the objectstore. This PR changes that behavior: UDF output is now immediately converted to an Arrow block before being stored, making Arrow the single internal block format
Related issues
None
Additional information
Config key :
DEFAULT_BATCH_TO_BLOCK_ARROW_FORMAT(default:True). Get viaray.data.DataContext.get_current().batch_to_block_arrow_formatImplementation overview :
batch_to_block, if the above key is set (Arrow is the default block format), convert each batched result Pandas dataframe into an Arrow block usingfor_block(batch).to_arrow()_safe_from_pandas(df)replaces the direct pa.Table.from_pandas() call in PandasBlockAccessor.to_arrow(). The standard PyArrow conversion fails on object-dtype columns containing multi-dimensional numpy arrays, PIL images, or mixed types. This function routes object-dtype columns throughconvert_to_pyarrow_array_make_batch_writable()function explicitly copies any read-only numpy arrays in the formatted batch. Wire downensure_copythroughformat_batch(). This is required, as pa.Array.to_numpy() returns read-only views by defaultTest/Bug fixes :
test_map_transformerandtest_strict_schemato correctly assert for Arrow blocks instead of Pandas.arrow_serialization.pyto pass ordered_flag to from_arrays(), dropping the flag results when deserializing Arrow dictionary arraysfind_partition_indexbehaviour for Arrow blocks, null semantics/data/_internal/tensor_extensions/pandas.py