Repository navigation
[Data] Fix null-type handling in Arrow schema reconciliation and struct alignment - #66521
Conversation
There was a problem hiding this comment.
Code Review
This pull request improves PyArrow schema unification and struct field alignment in Ray Data. Key changes include stripping null types first during field reconciliation, ensuring struct fields are only reconciled when all arms are structs (preventing incorrect unification of struct and primitive mixes), and properly handling all-null nested fields by filling them with nulls of the target struct type. Comprehensive unit tests are also added. The reviewer suggested a performance optimization in _reconcile_field to immediately return the single type when only one non-null type is present, avoiding unnecessary overhead.
e225e52 to
e888075
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit e888075. Configure here.
12a6e99 to
3249dac
Compare
iamjustinhsu
left a comment
There was a problem hiding this comment.
Wow nice catch! tyty
|
@iamjustinhsu don't forget to click go/enable auto-merge if ready to merge |
…ct alignment Fix three bugs in the struct alignment / schema reconciliation path: A) Nested all-null field crashes _backfill_missing_fields with TypeError because the recursive call doesn't guard against pa.null() columns. B) Top-level all-null struct column is silently skipped by _align_struct_fields (pre-existing), causing pa.concat_tables to fail in default promote mode. C) _reconcile_field step 4 (null-list reconciliation) iterates the unfiltered type list, so a pa.null() arm is returned instead of the concrete list type (pre-existing). Root cause of (C): the parameter named non_null_types actually received pa.null() entries from the caller. Fix by filtering pa.null() once at function entry, renaming the parameter to field_types, and simplifying the struct branch to use all(is_struct(...)). Signed-off-by: dragongu <[email protected]>
16f77c1 to
baae2d0
Compare
Address review feedback on the null-handling fix: * ``_reconcile_diverging_fields`` used to reconcile a field on the fly and then skip every later schema for that field. Combined with the early return in ``_reconcile_field`` (a single non-null type is already the complete result), a field could be locked before a later schema was inspected: ``[struct, null, int64]`` silently unified to ``struct`` instead of raising, and a null arm could shadow a later concrete type. Collect all field types first, reconcile once afterwards. * ``_align_struct_fields`` no longer duplicates the null/struct handling that ``_backfill_missing_fields`` already implements; it now delegates every mismatched column, which also means all-null columns are aligned explicitly instead of relying on PyArrow's promote mode. Tests: * ``test_unify_schemas_rejects_late_struct_primitive_mix`` pins that a later incompatible type is not hidden by an earlier null arm. * ``test_align_struct_fields_top_level_non_struct_field`` pins the guard for a non-struct column aligned against a struct schema. * ``test_unify_schemas_null_list_reconciled_when_pyarrow_cannot_unify`` covers null-list reconciliation when another field forces the reconciliation path (PyArrow >= 17 unifies the single-field case on its own, so it never reached ``_reconcile_field`` before). Signed-off-by: dragongu <[email protected]>
Review nit: comments were dropped from code whose behaviour did not change. Restore them and clarify the one branch whose rationale is not obvious: * ``# Find first non-null list type`` in ``_reconcile_field`` step 4. * ``# Check if the column type matches a struct type`` / ``# Align struct fields`` / ``# Replace the column with the aligned version`` in ``_align_struct_fields``. * Spell out why ``_backfill_missing_fields`` handles all-null columns explicitly rather than relying on PyArrow's promote mode. Signed-off-by: dragongu <[email protected]>
baae2d0 to
07f79f8
Compare
…ct alignment (ray-project#66521) ## Description Fix null-type handling in Arrow schema reconciliation and struct alignment. 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`. This PR fixes the nested case and one pre-existing bug. ### Bug A — Nested all-null field crashes alignment (the original fix) `_align_struct_fields` guards top-level columns with `isinstance(column.type, pa.StructType)`, but its recursive call only inspects the *target* field type, so a nested `pa.null()` column slips through. ```python t1 = pa.table({"outer": pa.array([{"inner": {"y": 1}}])}) t2 = pa.table({"outer": pa.array([{"inner": None}, {"inner": None}])}) concat([t1, t2]) # before: TypeError: 'pyarrow.lib.DataType' object is not iterable # after: [{"inner": {"y": 1}}, {"inner": None}, {"inner": None}] ``` ### Bug B — `_reconcile_field` step 4 returns `pa.null()` instead of list type (pre-existing) The `non_null_types` parameter actually received `pa.null()` entries from the caller. Step 3 (struct reconciliation) had its own per-step null filter, but step 4 (null-list reconciliation) iterated the unfiltered list. When the input was `[pa.null(), pa.list_(pa.null()), pa.list_(pa.int64())]`, step 4 returned `pa.null()` instead of `pa.list_(pa.int64())`. ```python unify_schemas([ pa.schema([("col", pa.null())]), pa.schema([("col", pa.list_(pa.null()))]), pa.schema([("col", pa.list_(pa.int64()))]), ]) # before: reconciled to null (wrong) # after: reconciled to list<int64> ``` Fixed by filtering `pa.null()` once at the top of `_reconcile_field` instead of per-step, and renaming the parameter from `non_null_types` to `field_types` to reflect its actual contract. ## Reproduction script Save as `repro.py` and run on `main` **before** this PR to see both bugs. After applying this PR both print `OK`. ```python """Reproduce two null-handling bugs in Ray Data struct alignment. Prerequisites: pip install "ray[data]" pyarrow Usage: python repro.py """ import ray import pyarrow as pa ray.init(runtime_env={"env_vars": {"RAY_MINIMAL": "1"}}) from ray.data._internal.arrow_ops.transform_pyarrow import ( _align_struct_fields, concat, unify_schemas, ) # Bug A: nested all-null field crashes with TypeError print("=== Bug A: nested all-null field ===") t1 = pa.table({"outer": pa.array([{"inner": {"y": 1}}])}) t2 = pa.table({"outer": pa.array([{"inner": None}, {"inner": None}])}) try: result = concat([t1, t2]) print(f"OK: {result['outer'].to_pylist()}") except TypeError as e: print(f"CRASH: TypeError: {e}") # Expected: OK: [{'inner': {'y': 1}}, {'inner': None}, {'inner': None}] # Bug B: null arm shadows concrete list type in _reconcile_field step 4 print("\n=== Bug B: null + list<null> + list<int64> ===") s1 = pa.schema([("col", pa.null())]) s2 = pa.schema([("col", pa.list_(pa.null()))]) s3 = pa.schema([("col", pa.list_(pa.int64()))]) unified = unify_schemas([s1, s2, s3]) col_type = unified.field("col").type if col_type == pa.list_(pa.int64()): print(f"OK: {col_type}") else: print(f"BUG: expected list<int64>, got {col_type}") # Expected: OK: list<int64> ``` --------- Signed-off-by: dragongu <[email protected]>
… in Arrow-backed to_pandas (#67566) (#67994) ## Description Cherry-pick of #67566 (master commit af8f74e) onto `releases/2.60.1`. 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. ## Additional information ### Cherry-pick details Applied cleanly with `git cherry-pick -x`. It has the same 2 files, +89/-2, and the same `git patch-id --stable` as the master commit. No prerequisite commits are missing. The new code hooks into `_arrow_backed_pandas_dtype`, which this branch already has from the #66578 pick (#66644). The two files differ from master at af8f74e only by master commits this change doesn't use. This PR and the #67579 pick both edit `arrow_block.py` and `test_arrow_block.py`. I applied this commit on top of the #66521 and #67579 picks, and it merges cleanly and passes the tests below. Not a duplicate: this branch doesn't contain #67566, and no PR against `releases/2.60.1` references it. ### 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` | 106 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`), 31 passed | | `pytest test_arrow_block.py test_pandas_block.py test_tensor_extension.py`, with the #66521 and #67579 picks also applied | 397 passed | 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. 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]>
… 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) (#67995) ## Description Cherry-pick of #66521 (master commit 6fa1a28) onto `releases/2.60.1`. This is a prerequisite for the #67579 pick, #67999. The two sit in a 3-PR stack on `releases/2.60.1` under #68019 (the #67806 pick); merge it with `gh stack merge 68019`. #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. ## 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. After the pick, `unit/test_transform_pyarrow.py` is identical to master at 6fa1a28. `transform_pyarrow.py` differs only by #66197's rename of `PreparedChunkedTensorTake` to `PreparedTensorTake`. #66197 is the only master commit that touched these files between the branch cut and #66521, and this change doesn't depend on it. To find what #67579 needed, I applied each master-only commit that touched `transform_pyarrow.py` or the tensor extensions on top of the #67579 pick: #66521, #65961, #66508, #66197, #66703 and #66522. #66521 alone makes the two failing tests pass, and none of the others changes the result. Not a duplicate: this branch doesn't contain #66521, and no PR on any branch references it. ### 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` | 145 passed, 3 skipped | The #67579 pick's description has the results with both picks applied. 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. 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]>
…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]>
…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) (#68019) ## Description Cherry-pick of #67806 (master commit d0d059f) onto `releases/2.60.1`. **Top of a 3-PR stack on `releases/2.60.1`:** #67995 (the #66521 pick), then #67999 (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, #67999 alone breaks batches with a null tensor row that work in 2.60.0. #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. 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 open PR picks it. The only open PR that mentions it is #67999, through the review that asks for this pick. ### Testing The six test files are the ones from #67999: `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/`. | Command | Result | |---|---| | `pre-commit run --files <the 2 changed files>` | Passed | | `pytest <the six files>`, pyarrow 23.0.1, with this PR | 526 passed, 3 skipped, the same as #67999 alone | | `pytest <the six files>`, pyarrow 26.0.1, #67999 without this PR | 19 failed, 507 passed, 3 skipped. 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`), and all fail with `ArrowInvalid: Array contains nulls` | | `pytest <the six files>`, pyarrow 26.0.1, with this PR | 526 passed, 3 skipped | I also ran an end-to-end check on pyarrow 26.0.1. A pandas UDF returns an ndarray for some rows and `None` for others, followed by `take_all()` with `ARROW_NATIVE`: | Case | `releases/2.60.1` (fa795b8) | #67999 (715ce08) | #67999 + this PR | |---|---|---|---| | `None` rows inside one block | works | `ArrowInvalid` | works | | same, after slicing off the first row | works | `ArrowInvalid` | works | With the default V2 format, both cases work on all three. 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.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, numpy 2.2.6 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]>
…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]>
…#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]>
…dArray (#68052) ## Why are these changes needed? When concatenating PyArrow tables whose struct columns have mismatched fields (e.g. one block has `struct<x: int64>` and another has `struct<x: int64, y: string>`), `transform_pyarrow.concat` calls `_concat_mismatched_blocks` -> `_align_struct_fields` -> `_backfill_missing_fields`. Inside `_backfill_missing_fields`, `ChunkedArray` columns were flattened via: ```python if isinstance(column, pa.ChunkedArray): column = pa.concat_arrays(column.chunks) ``` When an upstream filter produces a 0-row `pa.Table` (such as `table.filter(mask)` where all rows are filtered out), its struct column is a `pa.ChunkedArray` with `num_chunks == 0` (`column.chunks == []`). Passing `[]` to `pa.concat_arrays` raises: ``` pyarrow.lib.ArrowInvalid: Must pass at least one array ``` Replacing `pa.concat_arrays(column.chunks)` with `column.combine_chunks()` handles both non-empty and zero-chunk `ChunkedArray`s (returning an empty typed `StructArray` when `num_chunks == 0`). ### Acknowledgments Building on the PyArrow schema unification and struct field alignment work in `transform_pyarrow.py` by @dragongu (#66521), @Arnavsharma2 (#65961), @947132885 (#58364), and @Yin-1022 (#67935). ## Related issue number N/A (self-discovered while inspecting `ChunkedArray` handling in `_backfill_missing_fields`). ## Checks - [x] I've signed off every commit(by using the -s flag, i.e., `git commit -s`) in this PR. - [x] I've run `scripts/format.sh` to lint the changes in this PR. - [x] I've included any doc changes needed for https://docs.ray.io/en/master/. - [x] I've made sure the tests are passing. Note that there might be a few flaky tests, see the recent failures at https://flakey-tests.ray.io/ - Testing Strategy - [x] Unit tests (`pytest python/ray/data/tests/test_transform_pyarrow.py -k test_concat_empty_chunked_struct_column_with_extra_field`) --------- Signed-off-by: Parth Vadera <[email protected]> Co-authored-by: Copilot <[email protected]>

Description
Fix null-type handling in Arrow schema reconciliation and struct alignment.
A nested field that is all-null in one block and a struct in another crashes
_backfill_missing_fieldswithTypeError: 'pyarrow.lib.DataType' object is not iterable. This PR fixes the nested case and one pre-existing bug.Bug A — Nested all-null field crashes alignment (the original fix)
_align_struct_fieldsguards top-level columns withisinstance(column.type, pa.StructType), but its recursive call only inspects the target field type, so a nestedpa.null()column slips through.Bug B —
_reconcile_fieldstep 4 returnspa.null()instead of list type (pre-existing)The
non_null_typesparameter actually receivedpa.null()entries from the caller. Step 3 (struct reconciliation) had its own per-step null filter, but step 4 (null-list reconciliation) iterated the unfiltered list. When the input was[pa.null(), pa.list_(pa.null()), pa.list_(pa.int64())], step 4 returnedpa.null()instead ofpa.list_(pa.int64()).Fixed by filtering
pa.null()once at the top of_reconcile_fieldinstead of per-step, and renaming the parameter fromnon_null_typestofield_typesto reflect its actual contract.Reproduction script
Save as
repro.pyand run onmainbefore this PR to see both bugs. After applying this PR both printOK.