Skip to content

fix:null rows in tensor columns - #67236

Closed
moiz-naeem wants to merge 4 commits into
ray-project:masterfrom
moiz-naeem:ray-data
Closed

moiz-naeem wants to merge 4 commits into
ray-project:masterfrom
moiz-naeem:ray-data

Conversation

@moiz-naeem

Copy link
Copy Markdown
Contributor

Null rows in tensor columns (for example, unmatched rows after a left outer join)
were not handled by the bulk array conversions. take_all() correctly returned
None for a null row, but to_pandas() and iter_batches(batch_format="numpy"|"pandas")
did not:

  • a variable-shaped tensor column returned another row's value, or raised
    TypeError: Use () not None as shape arguments on NumPy >= 2.3;
  • a fixed-shape tensor column raised TypeError: buffer is too small for requested array.

This happened because ArrowTensorArray.to_numpy and
ArrowVariableShapedTensorArray.to_numpy read every row straight from the data
buffer without checking the Arrow null mask. A null row reserves no bytes in that
buffer so reading it ran off the end or into a neighbouring row.

This PR makes the bulk conversions null-aware, so a null tensor row now comes back
as missing everywhere None in NumPy batches and <NA> in pandas matching
take_all() and plain list columns. Rows that are not null are unchanged and
still take the existing dense, zero-copy path.

Related issues

Closes #67200

Additional information

What changed

Every change is gated on the null case, so behaviour for null-free columns is
unchanged.

@moiz-naeem
moiz-naeem requested a review from a team as a code owner October 21, 2026 12:23

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request addresses issues with handling null rows in Ray's Arrow and Pandas tensor extension arrays, ensuring that null rows are correctly surfaced as missing (None) rather than causing crashes or reading incorrect bytes. Key changes include falling back to ragged arrays when nulls are present, preserving None values during Pandas TensorArray initialization, and adding comprehensive tests. The code review identified two critical issues: a potential ValueError when concatenating mixed null/non-null chunks in a pa.ChunkedArray, and a bug where struct-level nulls bypass the shape is None check in variable-shaped tensor arrays. Solutions were suggested for both issues to ensure robust null handling.

Comment on lines +460 to +464
if (
self.element_shape
and all(s is not None for s in self.element_shape)
and array.null_count == 0
):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

Mismatched Dimensions in Chunked Array Concatenation

There is a critical bug when array is a pa.ChunkedArray with multiple chunks and contains nulls (i.e., array.null_count > 0).

If some chunks have no nulls (e.g., chunk.null_count == 0) and other chunks have nulls (e.g., chunk.null_count > 0):

  1. For chunks without nulls, chunk.to_numpy(zero_copy_only=False) returns a dense multidimensional array of shape (N, *shape).
  2. For chunks with nulls, chunk.to_numpy(zero_copy_only=False) returns a 1D ragged object array of shape (M,).

When np.concatenate is called on these chunks (lines 444-449), it will raise a ValueError because the arrays have different dimensions (e.g., 3D vs 1D).

Suggested Fix

To prevent this crash, we should combine the chunks of the pa.ChunkedArray first if it contains any nulls. This ensures that we convert the entire array as a single unit and consistently get a 1D ragged object array.

You can add this check at the beginning of __from_arrow__ (around line 435):

if isinstance(array, pa.ChunkedArray) and array.null_count > 0:
    array = array.combine_chunks()

Comment on lines 1426 to 1436
return create_ragged_ndarray(
[
_to_ndarray_helper(shape, data_value_type, offset, data_array_buffer)
# A null row has no shape or backing data: reading it returns
# another row's bytes or passes shape=None to np.ndarray
# (TypeError on NumPy >= 2.3).
None
if shape is None
else _to_ndarray_helper(shape, data_value_type, offset, data_array_buffer)
for shape, offset in zip(shapes, offsets)
]
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

Struct-Level Nulls Bypass shape is None Check

In PyArrow, a StructArray's nulls are stored in its own validity bitmap. When you extract a child array using self.storage.field("shape"), the child array does not automatically inherit the parent's nulls in its own validity bitmap.

If a row is null at the struct level (which is common after joins or certain slice/take operations), shapes_array.to_pylist() will return a valid shape list (e.g., [2, 2]) instead of None because the child array itself is not marked null at that index. As a result, shape is None evaluates to False, and _to_ndarray_helper is called, reading incorrect bytes or crashing.

Suggested Fix

To make this robust against nulls at any level (struct, data, or shape), we should check self.is_null() when self.null_count > 0.

We can optimize this by only performing the is_null() check when self.null_count > 0 to avoid any overhead in the common null-free case.

        if self.null_count > 0:
            nulls = self.is_null().to_pylist()
            return create_ragged_ndarray(
                [
                    None
                    if is_null or shape is None
                    else _to_ndarray_helper(shape, data_value_type, offset, data_array_buffer)
                    for is_null, shape, offset in zip(nulls, shapes, offsets)
                ]
            )

        return create_ragged_ndarray(
            [
                _to_ndarray_helper(shape, data_value_type, offset, data_array_buffer)
                for shape, offset in zip(shapes, offsets)
            ]
        )

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 4a26cfe. Configure here.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Oct 21, 2026
@ShawnGarello

Copy link
Copy Markdown

Thanks for picking this up. I filed #67200 and had a fix on a local branch, so I ran my tests against this one. Two things came up:

  1. pandas round trip: with a null row, the column comes back as TensorDtype(shape=(), dtype=object) (Bugbot's second comment) and can't go back to Arrow:

    import numpy as np, pyarrow as pa, ray
    from ray.data.extensions import ArrowTensorArray
    
    col = ArrowTensorArray.from_numpy(np.array([[10.0, 11.0], [20.0, 21.0]])).take(pa.array([0, None, 1]))
    ds = ray.data.from_arrow(pa.table({"t": col}))
    ray.data.from_pandas(ds.to_pandas()).take_all()  # ArrowConversionError

    Since TensorArray has no null representation, I went the other way: raise a clear ValueError in TensorDtype.__from_arrow__ pointing to batch_format="numpy". Either seems reasonable; maintainers' call.

  2. Child-level nulls (minor): the new branches are gated on self.null_count, which only counts struct-level nulls. A variable-shaped row that's null only in its data (or shape) child still comes back as the hidden values instead of None. take() and joins null every level, so this mostly matters for arrays built elsewhere.

I have tests covering V1/V2/ragged × float64/int64/bool, take and take+slice, and nulls at each level. Happy to share them here if they're useful.

Separately, pa.fixed_shape_tensor (ARROW_NATIVE) columns have the same problem in numpy batches: a null row comes back as zeros. That's out of scope here, as your test notes, so I'll open a separate PR for it.

Addresses review feedback on ray-project#67236.

to_numpy() on a variable-shaped tensor column only consulted the struct's
own validity bitmap. A row that is null in just its data or shape child
passes that check, so the row was rebuilt from offsets that address another
row's bytes and came back as that row's data, with no error. Build the null
mask from the struct and the data child, and keep the existing shape-is-None
test, so a null at any level reads as missing.

TensorArray has no null representation, so a null row forced the backing
ndarray to object dtype. The column then reported TensorDtype(shape=(),
dtype=object) and could not be converted back to Arrow. Refuse the
conversion in TensorDtype.__from_arrow__ with a message pointing at
batch_format="numpy" instead of returning a TensorArray that cannot round
trip. Checked twice: up front on null_count, which also keeps a multi-chunk
column away from a concatenate that cannot mix dense and ragged chunks, and
again on the converted values, which is what catches a child-level null.

test_variable_shaped_null_rows_to_pandas_unchanged pinned the old pandas
output as a regression guard for ray-project#66122. That baseline was the bug: it
compared to_numpy() against to_pandas().to_numpy(), both reading through the
same broken path, so it held while both returned another row's bytes. It now
asserts the column is refused.

Signed-off-by: moiz-naeem <[email protected]>
@moiz-naeem

Copy link
Copy Markdown
Contributor Author

Thanks for picking this up. I filed #67200 and had a fix on a local branch, so I ran my tests against this one. Two things came up:

  1. pandas round trip: with a null row, the column comes back as TensorDtype(shape=(), dtype=object) (Bugbot's second comment) and can't go back to Arrow:

    import numpy as np, pyarrow as pa, ray
    from ray.data.extensions import ArrowTensorArray
    
    col = ArrowTensorArray.from_numpy(np.array([[10.0, 11.0], [20.0, 21.0]])).take(pa.array([0, None, 1]))
    ds = ray.data.from_arrow(pa.table({"t": col}))
    ray.data.from_pandas(ds.to_pandas()).take_all()  # ArrowConversionError

    Since TensorArray has no null representation, I went the other way: raise a clear ValueError in TensorDtype.__from_arrow__ pointing to batch_format="numpy". Either seems reasonable; maintainers' call.

  2. Child-level nulls (minor): the new branches are gated on self.null_count, which only counts struct-level nulls. A variable-shaped row that's null only in its data (or shape) child still comes back as the hidden values instead of None. take() and joins null every level, so this mostly matters for arrays built elsewhere.

I have tests covering V1/V2/ragged × float64/int64/bool, take and take+slice, and nulls at each level. Happy to share them here if they're useful.

Separately, pa.fixed_shape_tensor (ARROW_NATIVE) columns have the same problem in numpy batches: a null row comes back as zeros. That's out of scope here, as your test notes, so I'll open a separate PR for it.

Thanks, both were real. Fixed in 2e901f8.

1. pandas round trip. Went with the ValueError, as you suggested. TensorArray has no way to represent a null, so a null row forced the whole column to object dtype which is why you saw TensorDtype(shape=(), dtype=object) and why it couldn't go back to Arrow. Rather than hand back something broken, TensorDtype.__from_arrow__ now refuses the column and points at batch_format="numpy". The numpy path still returns null rows as None. This meant reverting the pandas-side null handling from my earlier commits, so pandas.py is now a much smaller change than it was.

2. Child-level nulls. It was worse than a missing case: it fails silently. With a null in only the data child, the row came back as another row's values and nothing raised. The mask now comes from the struct and the data child together, with the existing shape is None check still covering the shape child. Worth noting _to_dense_ndarray_or_none already checked both children, so to_numpy was the odd one out.

One thing reviewers should look at: I had to change test_variable_shaped_null_rows_to_pandas_unchanged (added in #66122). It pinned the old pandas output as a regression guard, but that baseline was the bug it compared to_numpy() against to_pandas().to_numpy(), both reading through the same broken path, so it passed while both returned another row's bytes. It now asserts the column is refused. Happy to revisit if a maintainer prefers the other direction on point 1.

marwan116 added a commit that referenced this pull request Oct 30, 2026
Problem:
- A variable-shaped row can be null in its data or shape child rather
  than in the struct slot. to_numpy() only checked the struct slot, so
  such a row read a neighbour's bytes or raised.

Change:
- A row is null when the struct slot, the data child or the shape child
  is null. Same rule as PR #67236.

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

Copy link
Copy Markdown
Contributor

Heads up on an overlap, found by a reviewer of #67579. That PR started on a merge error ("Found columns with both objects and tensors") and, during review, gained null-row support for Ray's tensor arrays: the same two to_numpy paths this PR makes null-aware, plus from_numpy accepting None rows, null rows surviving to_pandas and the way back, null rows kept through shape promotion, and null chunks merging in concat. Its tests include the #67200 repro. I took one thing from here, with credit in the PR: a row is null when either child of the variable-shaped storage is null, not only the struct slot. I'd leave it to the Data maintainers to pick how to land the two, and I'm happy to rebase either way.

goutamvenkat-anyscale pushed a commit that referenced this pull request Nov 3, 2026
…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]>
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Nov 14, 2026
goutamvenkat-anyscale pushed a commit that referenced this pull request Nov 18, 2026
…able-shaped one (#67266)

## Description

`ArrowVariableShapedTensorArray.to_var_shaped_tensor_array()` fails
whenever the target `ndim` is larger than the array's own, so a tensor
column that is fixed-shape in one block and variable-shaped with fewer
dimensions in another can't be concatenated. Two lines were wrong, and
null rows weren't handled:

- `shapes_array.to_pylist()` returns lists, and
`_pad_shape_with_singleton_axes()` does `(1,) * k + shape`, so it raised
`TypeError: can only concatenate tuple (not "list") to tuple`. The
shapes are now converted with `tuple(s)`.
- `pa.StructArray.from_arrays()` was called without field names and
raised `ValueError: Must pass either names or fields`. It now passes
`["data", "shape"]`, the same as the other two places in the file that
build this storage.
- Null rows have a `None` shape, so they are skipped when padding, and
the source null mask is passed to `StructArray.from_arrays()` so they
stay null.
- When every row is null or there are no rows, `pa.array()` infers a
null type for the padded shapes and wrapping the storage fails with
`Incompatible storage type`. The shape type is now passed explicitly
(raised in review).

Added `test_unify_fixed_shaped_with_lower_ndim_variable_shaped`, which
unifies and concatenates a fixed-shape 2D array with a variable-shaped
1D one in both orders, `..._null_rows`, which does the same with a
sliced array that has a null row, and `..._no_valid_rows`, which uses an
all-null and an empty variable-shaped array in both orders. Existing
tests only unified arrays with the same `ndim`, so this branch wasn't
covered. The null-row tests read rows one at a time because `to_numpy()`
on null variable-shaped rows fails on master regardless of this change
(#67236 addresses that).

The 1D tensors come back as `(1, n)` because of the existing
singleton-axis padding. This PR doesn't change that.

## Related issues

Closes #67265

## Additional information

- Not a duplicate: #60389 had the same two changes as part of a larger
rework of `unify_tensor_arrays`, but it was closed as stale in February.
This PR only takes those two lines, handles null rows, and adds tests. I
searched open PRs for `to_var_shaped_tensor_array`,
`_pad_shape_with_singleton_axes`, `unify_tensor_arrays` and
tensor-related keywords; #66997 and #67236 touch other functions.
- Tests, run locally on master `7da1b4c` (`python/ray/data` from source
on a nightly wheel), Python 3.12.3, pyarrow 26.0.0, numpy 2.5.4:
- `pytest python/ray/data/tests/test_tensor_extension.py -k
unify_fixed_shaped_with_lower_ndim`: 21 passed. Without the fix, the
first 9 fail with `TypeError`. With the `None` guard but no mask, the
null-row test fails because the null row becomes valid. Without the
explicit shape type, the 12 `no_valid_rows` cases fail with
`Incompatible storage type`.
- The repro in #67265 and its `repartition(1).take_all()` variants in
both union orders now succeed.
- `pytest python/ray/data/tests/test_tensor_extension.py
python/ray/data/tests/test_transform_pyarrow.py
python/ray/data/tests/test_tensor.py
python/ray/data/tests/test_arrow_block.py
python/ray/data/tests/test_union.py`: 356 passed, 3 skipped, 5 failed.
The 5 fail the same way on unmodified master in my environment:
`test_tensor_array_scalar_cast` (3 formats),
`test_variable_shaped_null_rows_to_pandas_unchanged`, and
`test_tensors_sort[ARROW_NATIVE]`.
  - `pre-commit run --files <changed files>`: passed.
- AI assistance was used to prepare this PR.

---------

Signed-off-by: rayo5o <[email protected]>
goutamvenkat-anyscale pushed a commit that referenced this pull request Nov 24, 2026
…mns to pandas (#67283)

## Description

Since #66122, a variable-shaped tensor column whose rows all have the
same shape converts to pandas as one dense view, but only when the
column has a single chunk. A batch that spans two blocks reaches
`TensorDtype.__from_arrow__` with two chunks, and each chunk still went
through `to_numpy()`, which returns one ndarray per row for the result
to be stacked from.

The multi-chunk branch now converts each chunk with
`tensor_array_to_numpy()` and joins them with one `np.concatenate`:

- If the chunks can't share one dense array (a ragged or null-bearing
chunk next to a dense one, which #66122 noted can't be concatenated, or
dense chunks of different row shapes), the dense chunks are converted
back to one ndarray per row and all rows are joined one by one, which is
what master does for null rows since #67579.
- Empty chunks are skipped, so a column with only one non-empty chunk is
still a view, like the single-chunk path.
- The chunks sit in separate buffers, so the joined array is still a
copy, as before. It just isn't built row by row.

`iter_batches(batch_format="pandas")` over uniformly shaped
`ArrowVariableShapedTensorArray` rows, where each block is half a batch
so every batch column has 2 chunks. Median of 5 runs, each in a fresh
process:

| rows | batch size | | master | this PR |
|---|---:|---|---:|---:|
| 65,536 × (128,) float32 | 1024 | whole loop | 346 ms | 179 ms |
| | | inside `__from_arrow__` | 156 ms | 30 ms |
| 2,048 × (224, 224, 3) uint8 | 64 | whole loop | 172 ms | 147 ms |
| | | inside `__from_arrow__` | 82 ms | 54 ms |

When each block is exactly one batch (1 chunk per batch), nothing
changes. The benchmark script is in #67282.

New tests in `test_tensor_extension.py`:

-
`test_variable_shaped_uniform_rows_multi_chunk_to_pandas_skips_per_row`:
uniform rows in two chunks convert without calling `to_numpy()`.
- `test_variable_shaped_mixed_chunks_to_pandas`: dense then ragged,
ragged then dense, and dense chunks of different row shapes still
convert row by row.
- `test_variable_shaped_zero_dim_mixed_chunks_to_pandas`: with 0-d rows,
a dense chunk next to a chunk with a null row still falls back. A dense
chunk of 0-d rows is 1-d like a per-row chunk, so row shapes alone can't
tell them apart (found by Cursor Bugbot).
-
`test_variable_shaped_multi_chunk_with_empty_chunks_to_pandas_is_zero_copy`:
empty chunks around one non-empty chunk give a view of it.

## Why this matters

A variable-shaped tensor column whose rows all share one shape reaches
`TensorDtype.__from_arrow__` as several chunks whenever a batch spans
more than one block. Before this PR only the single-chunk case took the
dense path from #66122; with two or more chunks, every row became its
own NumPy view and the rows were stacked one by one.

A NumPy view holds no data, but it is still a Python object: ~112 bytes
of metadata (refcount, type, data pointer, shape/strides, base, dtype,
flags, ...) no matter how small the row is. So the old path's memory and
time overhead grew with the number of **rows**; the new path's grows
with the number of **chunks**.

```
Arrow buffers: 2 chunks, 6 rows of 4 x float32
  chunk A: [r0][r1]        chunk B: [r2][r3][r4][r5]

BEFORE: one view per row, then np.stack
  [r0] [r1] [r2] [r3] [r4] [r5]        <- 6 ndarray objects (~112 B of metadata each)
    |    |    |    |    |    |
    +----+----+--+-+----+----+
                 |  np.stack: makes another view per row, then copies row by row
                 v
          [ 6x4 float32 ]

AFTER: one view per chunk, then one np.concatenate
  [r0 r1]         [r2 r3 r4 r5]          <- 2 ndarray objects
  shape (2, 4)    shape (4, 4)              same buffers; a leading row dim with a 16 B stride
     |               |
     +-------+-------+
             |  np.concatenate: one block copy per chunk, in C
             v
      [ 6x4 float32 ]
```

Both paths copy the payload once into the output. The difference is the
per-object metadata around it, roughly (number of NumPy objects) x ~112
B, so it matters for many small tensors and fades for a few large ones.
That's why the benchmark above gains most on the `(128,)` float32 rows
(156 ms -> 30 ms inside `__from_arrow__`) and less on the images. Peak
memory follows the same pattern. In a standalone NumPy reproduction of
the two paths with 1M rows of `(4,)` float32 (16 MB of data), the old
path peaked at ~313 MB, about 240 MB of it per-row view objects
(`np.stack` makes a second set). The new path peaked at 16 MB.

If only one non-empty chunk is left, the result is a view of the Arrow
buffer with no copy at all.

### How chunks are joined now

```mermaid
flowchart TD
  A["Drop empty chunks"] --> B["tensor_array_to_numpy() per chunk"]
  B --> C{"All dense, same row shape?<br/>no object dtype, one shape[1:]"}
  C -- yes --> D["One np.concatenate<br/>(single chunk: stays a view)"]
  C -- no --> E["Fall back to one ndarray per row<br/>(ragged chunk, null row, or mixed row shapes)"]
```

The dtype check is needed for 0-d rows: a dense chunk of scalars and a
per-row chunk with a null row are both 1-D, so `shape[1:]` alone can't
tell them apart.

## Related issues

Closes #67282

## Additional information

- Not a duplicate: #66122 left multi-chunk columns out of scope, and no
open issue or PR covers them. #67236 also edits `__from_arrow__`, but
only adds null-row checks around this branch, so whichever lands second
needs a small rebase.
- I also compared this branch with master on 33 cases: uniform,
multi-dimensional rows, mixed dense/ragged in both orders, different row
shapes, ragged only, a null row, empty chunks in different positions,
bool, 0-d rows with and without a null row, fixed-shape, and fixed-shape
columns with null rows (before or after a dense chunk, an all-null
chunk, next to an empty chunk, a slice after a null row) in the V1, V2
and native formats. The resulting `TensorArray` has the same dtype,
shape and values in all of them.
- Tests, run locally after rebasing on master `e65c2e2d`
(`python/ray/data` from source on a nightly wheel), Python 3.12.3, numpy
2.5.4, pandas 3.0.6, with pyarrow 26.0.0 and 23.0.1:
- `pytest python/ray/data/tests/test_tensor_extension.py -k "multi_chunk
or mixed_chunks"`: 6 passed. On master, `..._skips_per_row` and
`..._with_empty_chunks_to_pandas_is_zero_copy` fail, and the 0-d test
fails without the second commit. The other mixed-chunk cases pass either
way and guard the fallback.
- `pytest python/ray/data/tests/test_tensor_extension.py
python/ray/data/tests/test_pandas_block.py
python/ray/data/tests/test_arrow_serialization.py
python/ray/data/tests/unit/test_transform_pyarrow.py
python/ray/data/tests/unit/test_data_batch_conversion.py
python/ray/data/tests/test_batcher.py
python/ray/data/tests/test_tensor.py`: 616 passed, 6 skipped, 8 failed
on pyarrow 26, and 617 passed, 6 skipped, 7 failed on pyarrow 23. The
same tests fail on unmodified master in my environment:
`test_tensor_array_scalar_cast` (3 formats),
`TestSizeBytes::test_small`, `TestSizeBytes::test_large_str`,
`test_numpy_to_tensor_warning` (2 params), and on pyarrow 26 only
`test_tensors_sort[ARROW_NATIVE]`.
  - `pre-commit run --files <changed files>`: passed.
- AI assistance was used to prepare this PR.

---------

Signed-off-by: rayo5o <[email protected]>
@github-actions

Copy link
Copy Markdown

This pull request has been automatically closed because there has been no more activity in the 14 days
since being marked stale.

Please feel free to reopen or open a new pull request if you'd still like this to be addressed.

Again, you can always ask for help on our discussion forum or Ray's public slack channel.

Thanks again for your contribution!

@github-actions github-actions Bot closed this Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community data Ray Data-related issues stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data] to_pandas() returns another row's value or raises for null rows in tensor columns

3 participants