Repository navigation
[cherry-pick][2.59.2][Data] Keep tensor columns with null rows mergeable across blocks (#67579) - #68025
Conversation
…7579) 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. - 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 | ``` 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 | - 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. Block / data format (`arrow_ops/transform_pyarrow.py`, `tensor_extensions/arrow.py`, `tensor_extensions/pandas.py`). - 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. ``` 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]> (cherry picked from commit 1acc2c3) Signed-off-by: Sai Miduthuri <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces robust support for null rows (represented as None) in tensor columns across Ray Data's Arrow, Pandas, and PyTorch integrations. It ensures that validity bitmaps are respected during conversions, preventing null rows from reading back as arbitrary data (like zeros) and instead representing them as None within object/ragged arrays. Schema unification and array concatenation have also been updated to correctly handle and promote null-typed arrays. The review feedback suggests a performance optimization in _to_numpy_with_null_rows by replacing slow .to_pylist() calls with vectorized NumPy operations to construct the validity mask.
| is_valid = [ | ||
| struct_valid and data_valid and shape is not None | ||
| for struct_valid, data_valid, shape in zip( | ||
| self.is_valid().to_pylist(), data_array.is_valid().to_pylist(), shapes | ||
| ) | ||
| ] |
There was a problem hiding this comment.
Converting PyArrow boolean arrays to Python lists using .to_pylist() is slow and memory-intensive because it constructs a Python list of Python bool objects. Since numpy is already imported, we can convert the boolean arrays to NumPy arrays using np.asarray() and perform a vectorized bitwise AND (&) in C. This avoids the overhead of .to_pylist() and speeds up the validity check significantly.
is_valid_mask = np.asarray(self.is_valid()) & np.asarray(data_array.is_valid())
is_valid = [
valid and shape is not None
for valid, shape in zip(is_valid_mask, shapes)
]There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 4e34d59. Configure here.
| return (1,) * (ndim - len(shape)) + shape | ||
|
|
||
|
|
||
| def _null_row_mask(arr: np.ndarray) -> Optional[np.ndarray]: |
There was a problem hiding this comment.
Null rows break variable-shape promotion
Medium Severity
ArrowVariableShapedTensorArray.to_var_shaped_tensor_array still pads every shape and rebuilds storage without a null mask. A null row makes _pad_shape_with_singleton_axes receive None and raise, and even if that were skipped the new struct would treat those slots as valid and read a neighbor's bytes. unify_tensor_arrays takes this path when a ragged column with missing rows is promoted to a higher ndim.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 4e34d59. Configure here.
| elif self._tensor.dtype.type is np.object_ and first is not None: | ||
| # Fixed-shape tensors stored one per element, next to null rows. | ||
| dtype = first.dtype | ||
| shape = first.shape |
There was a problem hiding this comment.
Pandas concat fails on mixed null tensors
Medium Severity
A TensorArray without missing rows stays a dense (N, *shape) ndarray, while one with a null row becomes a 1D object array of per-row tensors and None. Both still report the same element_shape, so _concat_same_type takes np.concatenate and raises on the ndim mismatch. Combining pandas blocks after a pandas UDF that returns None for some rows hits this.
Additional Locations (2)
Reviewed by Cursor Bugbot for commit 4e34d59. Configure here.
… in Arrow-backed to_pandas (#67566) (#68022) ## Description Cherry-pick of #67566 (master commit af8f74e) onto `releases/2.59.2`. 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, so elements disappear. For example, a `list<null>` column `[[None, None], [None]]` comes back as `[[None, None], []]`. When the batch goes back to Arrow untouched, it fails instead with `ArrowInvalid: Length spanned by list offsets (3) larger than values array (length 2)`. Users hit this with sparse list columns. #67566 maps types that nest a null type to a `pd.ArrowDtype` subclass that skips the identity cast. ## Related issues Related to #67566. The same pick for 2.60.1 is #67994. ## Additional information ### Cherry-pick details Applied with `git cherry-pick -x`. `arrow_block.py` merged cleanly. `test_arrow_block.py` conflicted only on its import list: master also imports `ArrowRow` there, from a master-only change that this branch's tests don't use. I added only #67566's `_arrow_backed_pandas_dtype` import. The added and removed lines are identical to the master commit, and `git patch-id` differs only because of that context line. No prerequisite commits are missing. The new code hooks into `_arrow_backed_pandas_dtype`, which this branch already has from the #66578 pick (#66617). The two files differ from master at af8f74e only by master commits this change doesn't use. This PR and the #67579 pick (#68025) both edit `arrow_block.py` and `test_arrow_block.py`. This commit merges cleanly with the #66521, #67579 and #67806 stack and passes the tests below. Not a duplicate: this branch doesn't contain #67566, and no PR against `releases/2.59.2` references it. #67994 picks the same commit onto `releases/2.60.1`. ### Testing | Command | Result | |---|---| | `pre-commit run --files <the 2 changed files>` | Passed | | `pytest python/ray/data/tests/test_arrow_block.py python/ray/data/tests/test_pandas_block.py` | 87 passed | | `pytest python/ray/data/tests/test_arrow_block.py`, run with this PR's tests against the branch code without the fix | 3 failed (the 3 new nested-null cases of `test_arrow_block_to_pandas_preserves_arrow_types_through_roundtrip`), 24 passed | | `pytest test_arrow_block.py test_pandas_block.py test_tensor_extension.py`, with the #66521, #67579 and #67806 stack also applied | 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 and numpy 2.1.3, 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: Sai Miduthuri <[email protected]> Co-authored-by: Marwan Sarieddine <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
…conciliation and struct alignment (#66521) (#68024) ## Description Cherry-pick of #66521 (master commit 6fa1a28) onto `releases/2.59.2`. **Bottom of a 3-PR stack on `releases/2.59.2`:** this PR, then #68025 (the #67579 pick), then #68026 (the #67806 pick). Merge the stack with `gh stack merge 68026`, which lands all three in order. This is a prerequisite for the #67579 pick. #66521 fixes null-type handling when Ray Data reconciles Arrow schemas across blocks: - A nested field that is all-null in one block and a struct in another crashes `_backfill_missing_fields` with `TypeError: 'pyarrow.lib.DataType' object is not iterable`. - `_reconcile_field` reconciles `[null, list<null>, list<int64>]` to `null` instead of `list<int64>`. Without it, two of the tests #67579 adds fail on this branch. Both are the case where one block's tensor column is fixed-shape, another's is null, and a third's has a different shape. They fail with `ArrowTypeError: Casting from 'extension<ray.data.arrow_variable_shaped_tensor<...>>' to different extension type 'extension<ray.data.arrow_tensor_v2<...>>' not permitted`. ## Related issues Related to #66521. Needed by the #67579 pick. The same pick for 2.60.1 is #67995. ## Additional information ### Cherry-pick details Applied cleanly with `git cherry-pick -x`. It has the same 2 files, +233/-30, and the same `git patch-id --stable` as the master commit. The two files differ from master at 6fa1a28 only by master commits this change doesn't use: #66197, #66269 and #64961 in `transform_pyarrow.py`, and #66269 in `unit/test_transform_pyarrow.py`. Not a duplicate: this branch doesn't contain #66521, and no PR against `releases/2.59.2` references it. #67995 picks the same commit onto `releases/2.60.1`. ### Testing | Command | Result | |---|---| | `pre-commit run --files <the 2 changed files>` | Passed | | `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` | 123 passed | The #67579 pick's description, #68025, has the results with the stack applied. 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 and numpy 2.1.3, 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: dragongu <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: dragongu <[email protected]>
…#67806) (#68026) ## Description Cherry-pick of #67806 (master commit d0d059f) onto `releases/2.59.2`. **Top of a 3-PR stack on `releases/2.59.2`:** #68024 (the #66521 pick), then #68025 (the #67579 pick), then this PR. Merging this PR with `gh stack merge` lands all three in order. #67579 makes `native_tensor_array_to_numpy` return `None` for the null rows of a pyarrow-native tensor column. It calls `to_numpy_ndarray()` first. That reads null rows as zeros on pyarrow 23–25, but pyarrow 26 raises `ArrowInvalid: Array contains nulls`. Ray requires only `pyarrow >= 17.0.0`. So with `FixedShapeTensorFormat.ARROW_NATIVE` on pyarrow 26, the #67579 pick alone breaks batches with a null tensor row. #67806 converts the same storage without its validity bitmap, which gives the dense array on every pyarrow version, and then fills in `None` as before. ## Related issues Related to #67806, the follow-up to #67579. The same pick for 2.60.1 is #68019, requested in [this review on #67999](#67999 (review)). ## Additional information ### Cherry-pick details Applied cleanly with `git cherry-pick -x` on top of the #67579 pick. It has the same 2 files, +21/-5, and the same `git patch-id --stable` as the master commit. It changes only `native_tensor_array_to_numpy`, which #67579 adds, and the test #67579 adds for it, so it needs nothing else from master. Not a duplicate: neither this branch nor the stack below it contains #67806, and no PR against `releases/2.59.2` references it. #68019 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 2 changed files>` | Passed | | `pytest <the six files>`, pyarrow 23.0.1, with this PR | 478 passed | | `pytest <the six files>`, pyarrow 26.0.1, the #67579 pick without this PR | 19 failed, 459 passed. All 19 are `ARROW_NATIVE` null-row tests that #67579 adds (`test_batches_keep_tensor_column_*` and `test_native_tensor_array_to_numpy_with_null_rows`) | | `pytest <the six files>`, pyarrow 26.0.1, with this PR | 478 passed | CI on this branch runs the Data tests on pyarrow 23.0.1 and 17.0.0, so it doesn't exercise this failure. 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, numpy 2.1.3 and torch 2.9.0+cpu, with pyarrow 23.0.1 or 26.0.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: rayo5o <[email protected]> Signed-off-by: Sai Miduthuri <[email protected]> Co-authored-by: ray05 <[email protected]>


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 withgh 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 returnsNonefor 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:arrow_ops/transform_pyarrow.pychunked_tensor_takeimports (#64961)create_ragged_ndarrayimporttensor_extensions/arrow.pytensor_array_to_numpyand_to_dense_ndarray_or_none(#66122)native_tensor_array_to_numpytensor_extensions/pandas.pyTensorArray.dtypedocstring reformat (#67539)first = _first_non_null(self._tensor), under this branch's docstringtests/test_arrow_block.pytests/test_tensor_extension.pyI 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-iddiffers only because of the context lines.Prerequisite: #66521. Without it,
test_arrow_concat_tensor_with_null_keeps_tensor_type[last_shape1]andtest_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.2references it. #67999 picks the same commit ontoreleases/2.60.1.Testing
The six test files, under
python/ray/data/tests/, aretest_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.pre-commit run --files <the 10 changed files>pytest <the six files>, with the whole stack (#66521, this PR, #67806)pytest --continue-on-collection-errors <the six files>, with this PR's tests against the code with only #66521test_tensor_extension.pyfails to collect, because it imports a helper this PR addspytest <the six files>, with this pick directly onreleases/2.59.2, without #66521pytest test_arrow_block.py test_pandas_block.py test_tensor_extension.py, with the stack and the #67566 pick (#68022) applied togetherI ran these against the Ray 2.59.1 release wheel, with this branch's
python/ray/dataandpython/ray/testscopied over it. The wheel was built fromreleases/2.59.1at 7bdaad7, and its Python sources matchreleases/2.59.2except 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 forbazel testwasn't practical on my machine.AI assistance was used to prepare this cherry-pick.
🤖 Generated with Claude Code