Skip to content

[Data] Fix _backfill_missing_fields crash on zero-chunk struct ChunkedArray - #68052

Merged
richardliaw merged 2 commits into
ray-project:masterfrom
deep1blue:fix/pyarrow-backfill-empty-chunked-struct
Nov 24, 2026
Merged

richardliaw merged 2 commits into
ray-project:masterfrom
deep1blue:fix/pyarrow-backfill-empty-chunked-struct

Conversation

@deep1blue

Copy link
Copy Markdown
Contributor

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:

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 ChunkedArrays (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

@deep1blue
deep1blue requested a review from a team as a code owner November 11, 2026 00:58
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Nov 11, 2026
@deep1blue
deep1blue force-pushed the fix/pyarrow-backfill-empty-chunked-struct branch from fecbb03 to 0a22f64 Compare November 11, 2026 08:15
…dArray

Use column.combine_chunks() instead of pa.concat_arrays(column.chunks) when flattening a ChunkedArray in _backfill_missing_fields so 0-row filtered tables (num_chunks == 0) do not raise ArrowInvalid when concatenated with blocks containing additional struct fields.

Signed-off-by: Parth Vadera <[email protected]>
@deep1blue
deep1blue force-pushed the fix/pyarrow-backfill-empty-chunked-struct branch from 0a22f64 to 403c622 Compare November 17, 2026 00:25
@abhishekverma-ray abhishekverma-ray added the go add ONLY when ready to merge, run all tests label Nov 18, 2026

@abhishekverma-ray abhishekverma-ray 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.

LGTM, thanks. Could the test move to tests/unit/test_transform_pyarrow.py, as a zero-chunk case of the existing struct-alignment tests (e.g. test_align_struct_fields_empty_blocks)? That's where those tests live. Optionally, the existing combine_chunked_array() helper also handles zero chunks.

@deep1blue

Copy link
Copy Markdown
Contributor Author

Thanks @abhishekverma-ray! Moved the test in 79ed1f25d4 to python/ray/data/tests/unit/test_transform_pyarrow.py by parametrizing test_align_struct_fields_empty_blocks over zero_chunks=[False, True] (2 passed in pytest python/ray/data/tests/unit/test_transform_pyarrow.py -k test_align_struct_fields_empty_blocks). Kept column.combine_chunks() in _backfill_missing_fields because combine_chunked_array() returns the ChunkedArray unchanged when len(array.chunks) == 1, whereas pa.StructArray.from_arrays(..., mask=column.is_null()) requires pa.Array inputs.

goutamvenkat-anyscale added a commit that referenced this pull request Nov 19, 2026
…s present (#68259)

## Summary

`unify_schemas` returns an order-dependent result that is not an upper
bound of its inputs when one arm is a `list<null>`. Adding a block whose
lists are all empty turns a hard schema conflict into a silent pick of
whichever type arrived first, discarding the wider one.

```python
unify_schemas([list<int32>, list<int64>, list<null>])  -> list<int32>
unify_schemas([list<int64>, list<int32>, list<null>])  -> list<int64>
unify_schemas([list<int32>, list<int64>])              -> ArrowTypeError
```

This PR fixes that, and adds the property-based testing that found it.

## Why this is a bug

`_reconcile_field`'s null-typed-list branch returns the *first* arm that
is not a `list<null>`:

```python
if null_lists:
    # Find first non-null list type
    for t in non_null_types:
        if not (pyarrow.types.is_list(t) and pyarrow.types.is_null(t.value_type)):
            return t
```

It never checks that the remaining arms agree with each other, so one
`list<null>` arm suppresses a genuine conflict between the others. The
returned type is then applied as an override to every schema, so a block
that genuinely holds `list<int64>` is relabelled `list<int32>`.

Schema unification is a join on a type lattice: the result must be an
upper bound of every input and must not depend on input order. Blocks
arrive from parallel tasks in nondeterministic order, so today the same
job can reconcile the same data differently between runs.

Both conditions are ordinary in real data: a `list<null>` column is just
a block whose lists are all empty, and differing integer widths for one
column across files are routine when reading many Parquet files in
parallel.

Scope: `promote_types=False` only, which is the default and what
`concat`, `delta_datasink.py:418,714` and `iceberg_datasink.py:1258`
use. `promote_types=True` (used by `Dataset.schema()` via
`unify_schemas_with_validation`) already behaves correctly.

`concat` does not silently corrupt data — it fails downstream — but the
failure degrades from a clear `ArrowSchemaUnificationError` naming the
column to a bare `RuntimeError: Types mismatch`. The Delta and Iceberg
datasinks take the returned schema as the schema to write.

## Fix

Unify the remaining arms instead of returning the first, and fall back
to `None` so PyArrow reports a real conflict. The intended case this
branch exists for — `list<null>` next to one concrete list type — is
unchanged.

## Property-based tests

The bug was found by property-based testing, so this PR also adds
`hypothesis` and the module that found it.
`test_unify_schemas_null_with_list_null_and_list_int` already existed
directly adjacent to the defect and did not catch it: it checks one
hand-picked triple, and the bug needs two conflicting concrete arms
*plus* a `list<null>`.

`test_transform_pyarrow_properties.py` checks the four laws
`unify_schemas` must satisfy as a lattice join, over a generated space
of PyArrow types — commutativity, associativity, idempotence, and
independence from block arrival order. The generated types cover the
branches `_reconcile_field` special-cases: `null` (the lattice bottom),
nested structs, and lists.

Runs are **derandomized** via a registered profile, so a given commit
always explores the same inputs — a failure is reproducible, not a
flake. `deadline=None` avoids timing flakes on loaded CI machines, and
`max_examples=200` keeps the module inside the `small` Bazel test size
(1.5s locally).

Worth an explicit maintainer call: if a future change violates one of
these laws, CI goes red on an unrelated PR. That is the intent, but only
if the team reads it as a real signal rather than a flake to retry.

### Dependency placement

`hypothesis` is pinned in
`python/requirements/ml/data-test-requirements.txt` — the file
`ci_data.depsets.yaml` actually installs. (`test-requirements.txt` is
only a *constraint* for the data depsets, so a pin there would not
install it.) That file is also a `compile_pip_dependencies` source, so
the version is pinned in the shared compiled lock too.

Two exact pins with markers, because hypothesis 6.169+ requires Python
>= 3.11 and the data locks still compile for py3.10:

```
hypothesis==6.168.5 ; python_version < '3.11'
hypothesis==6.170.15 ; python_version >= '3.11'
```

Exact pins rather than ranges because pip-compile only preserves a
marker when the source declaration is an exact pin. Both have
cp310–cp314 wheels. The only core transitive dep is `sortedcontainers`
(already pinned at 2.4.0 in the compiled lock) plus `exceptiongroup` on
py<3.11.

`hypothesis.*` is added to `ignore-missing-imports` in `pyrefly.toml`,
matching the other test-only deps (`pytest.*`, `freezegun.*`,
`testcontainers.*`) — the pyrefly pre-commit hook runs in an isolated
env with no third-party packages.

## Lock files

Regenerated on x86_64 Linux (CI's `pip_compile_dependencies` job uses
Python 3.11, so `compile_pip_dependencies` ran under 3.11 with pip
25.2):

```bash
ci/ci.sh compile_pip_dependencies
ci/ci.sh compile_pip_dependencies_py314
bazelisk run //ci/raydepsets:raydepsets -- build --all-configs
```

The diff only adds lines; no existing pin moves:

- `requirements_compiled.txt` gains `hypothesis==6.170.15 ;
python_version >= "3.11"`. The marker survives, so the py3.10 data
depsets aren't constrained to it. `requirements_compiled_py3.14.txt`
gains `hypothesis==6.170.15`.
- The 10 Ray Data locks under `python/deplocks/ci/` (all from
`ci_data.depsets.yaml`, the only config that reads
`data-test-requirements.txt`) gain `hypothesis==6.168.5` on py3.10 and
`hypothesis==6.170.15` on py3.11/3.12.
- Otherwise, only `# via hypothesis` annotations are added to the
existing `sortedcontainers` and (py3.10) `exceptiongroup` pins.

## Subsystems

Block / data format; CI dependencies

## Testing

```
pytest python/ray/data/tests/unit/test_transform_pyarrow_properties.py \
       python/ray/data/tests/unit/test_transform_pyarrow.py \
       python/ray/data/tests/test_transform_pyarrow.py \
       python/ray/data/tests/test_infer_schema.py \
       python/ray/data/tests/unit/datasource_v2/test_schema_inference.py \
       python/ray/data/tests/test_unify_schemas_performance.py \
       python/ray/data/tests/test_arrow_block.py
-> 347 passed in 45.76s
```

Both new test layers fail-to-pass correctly. Without the fix,
`test_unify_schemas_null_list_arm_does_not_mask_conflicting_types` and
`test_unify_schemas_is_order_independent` fail and everything else
passes; with the fix all pass. The existing
`test_unify_schemas_null_with_list_null_and_list_int` and
`test_unify_schemas_null_list_reconciled_when_pyarrow_cannot_unify`
continue to pass, confirming the intended reconciliation is preserved.
`pre-commit run` passes on all changed files.

`bazelisk run //ci/raydepsets:raydepsets -- build --all-configs --check`
passes against the regenerated locks.

## Not a duplicate

No open PR or issue touches `_reconcile_field` or null-list
reconciliation. Searched `unify_schemas`, `_reconcile_field`, `schema
unification`, `promote_types`. The nearest open PR, #68052, fixes
`_backfill_missing_fields`, a different function. `hypothesis` is
currently not a dependency anywhere in the repo — no entry in
`python/requirements*`, `python/deplocks/**` or
`ci/raydepsets/configs/*`, and no `import hypothesis` anywhere.

AI assistance was used for this change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Goutam <[email protected]>
Signed-off-by: goutam <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@richardliaw
richardliaw merged commit c7db8e8 into ray-project:master Nov 24, 2026
6 checks passed
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 go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants