Skip to content

[Data] Preserve schema for empty datasets in schema unification and to_pandas() - #65539

Merged
richardliaw merged 7 commits into
ray-project:masterfrom
lonexreb:fix/59946-empty-dataset-schema
Oct 6, 2026
Merged

richardliaw merged 7 commits into
ray-project:masterfrom
lonexreb:fix/59946-empty-dataset-schema

Conversation

@lonexreb

Copy link
Copy Markdown
Contributor

Why are these changes needed?

Dataset.to_pandas() (and schema propagation generally) drops columns for an empty dataset:

import pyarrow as pa, ray
empty_ref = ray.put(pa.table([pa.array([], pa.int32())], ["apples"]))
rd = ray.data.from_arrow_refs([empty_ref])
assert list(rd.to_pandas().columns) == ["apples"]  # fails on master: columns == []

Two layers cause this:

  1. Metadata layer: unify_block_metadata_schema() / unify_ref_bundles_schema() skip blocks with num_rows == 0, so a dataset made only of empty blocks reports no schema — even though an empty Arrow table carries a perfectly valid one (as noted by @mango766 on the issue). This PR makes empty-block schemas a fallback when no non-empty block provides a schema; non-empty blocks still take precedence.
  2. Consumption layer: to_pandas() builds its result from iter_batches(), which yields no batches for an empty dataset, so PandasBlockBuilder.build() produced a DataFrame with zero columns. This PR reconstructs columns and dtypes from the dataset schema, routing Arrow-backed schemas through the same BlockAccessor.to_pandas() path used for non-empty blocks so empty and non-empty results agree on dtypes.

This supersedes #64721 (same fix for layer 2, closed by the stale bot after both bot-review comments had been addressed; GitHub would not allow reopening it). This PR carries those commits, rebased on current master, plus the new metadata-layer fix.

Related issue number

Fixes #59946

Checks

  • I've signed off every commit (DCO).
  • I've run pre-commit formatting (black==22.10.0 per repo pin) on changed files.
  • Testing strategy:
    • Added test_to_pandas_empty_dataset_preserves_columns (Arrow-backed and pandas-backed empty datasets, dtype parity with non-empty datasets).
    • Added test_unify_block_metadata_schema_all_empty_blocks (fallback + precedence).
    • Ran locally against master with the Ray nightly wheel + setup-dev.py symlinks:
      • pytest python/ray/data/tests/test_util.py → 39 passed
      • pytest python/ray/data/tests/test_arrow_block.py -k to_pandas → 13 passed
      • Issue's exact repro passes.

Notes for reviewers / AI-assistance disclosure

@lonexreb
lonexreb requested a review from a team as a code owner August 17, 2026 19:21

@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 issue #59946 by ensuring that empty datasets preserve their schema's columns and dtypes when converted to pandas DataFrames, and that schemas are correctly unified when all blocks or bundles are empty. The review feedback highlights critical issues in the implementation: pyarrow.Schema lacks an empty_table() method, which will cause an AttributeError, and retrieving column types from base_schema for pandas-backed datasets will fail and fall back to losing dtypes. Additionally, the reviewer suggests caching bundle.num_rows() to avoid duplicate calls and adding a test case for a 0-block empty dataset to ensure full coverage of the fallback path.

Comment thread python/ray/data/dataset.py Outdated
Comment on lines +7559 to +7565
base_schema = getattr(schema, "base_schema", None)
if isinstance(base_schema, pa.Schema):
# Route the empty Arrow table through the same
# `BlockAccessor.to_pandas()` path used for non-empty blocks
# so the two agree on column types (types_mapper, tensor
# casting, etc.).
df = BlockAccessor.for_block(base_schema.empty_table()).to_pandas()

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.

critical

The pyarrow.Schema class does not have an empty_table() method. Calling base_schema.empty_table() will raise an AttributeError when executing this path (e.g., for a 0-block empty dataset like ray.data.range(0)). Instead, use pyarrow.Table.from_batches([], schema=base_schema) to create an empty table with the given schema.

Suggested change
base_schema = getattr(schema, "base_schema", None)
if isinstance(base_schema, pa.Schema):
# Route the empty Arrow table through the same
# `BlockAccessor.to_pandas()` path used for non-empty blocks
# so the two agree on column types (types_mapper, tensor
# casting, etc.).
df = BlockAccessor.for_block(base_schema.empty_table()).to_pandas()
base_schema = getattr(schema, "base_schema", None)
if isinstance(base_schema, pa.Schema):
# Route the empty Arrow table through the same
# `BlockAccessor.to_pandas()` path used for non-empty blocks
# so the two agree on column types (types_mapper, tensor
# casting, etc.).
df = BlockAccessor.for_block(pa.Table.from_batches([], schema=base_schema)).to_pandas()

Comment thread python/ray/data/dataset.py Outdated
Comment on lines +7569 to +7579
# Pandas-backed schema: preserve per-column dtypes when known.
types = getattr(base_schema, "types", None)
if types is not None and len(types) == len(schema.names):
df = pandas.DataFrame(
{
name: pandas.Series([], dtype=dtype)
for name, dtype in zip(schema.names, types)
}
)
else:
df = pandas.DataFrame(columns=list(schema.names))

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

For pandas-backed datasets, base_schema is typically a pandas.Index or pandas.Series of dtypes, neither of which has a types attribute. Thus, getattr(base_schema, "types", None) will return None, causing it to always fall back to the else block and lose the dtypes. Instead, use schema.types directly, which is a standard property of the Ray Schema class and is guaranteed to contain the column types.

Suggested change
# Pandas-backed schema: preserve per-column dtypes when known.
types = getattr(base_schema, "types", None)
if types is not None and len(types) == len(schema.names):
df = pandas.DataFrame(
{
name: pandas.Series([], dtype=dtype)
for name, dtype in zip(schema.names, types)
}
)
else:
df = pandas.DataFrame(columns=list(schema.names))
# Pandas-backed schema: preserve per-column dtypes when known.
types = schema.types
if types and len(types) == len(schema.names):
df = pandas.DataFrame(
{
name: pandas.Series([], dtype=dtype)
for name, dtype in zip(schema.names, types)
}
)
else:
df = pandas.DataFrame(columns=list(schema.names))

Comment thread python/ray/data/_internal/util.py Outdated
Comment on lines +864 to +870
for bundle in ref_bundles:
if bundle.schema is not None and (
bundle.num_rows() is None or bundle.num_rows() > 0
):
if bundle.schema is None:
continue
if bundle.num_rows() is None or bundle.num_rows() > 0:
schemas_to_unify.append(bundle.schema)
else:
empty_bundle_schemas.append(bundle.schema)

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.

medium

Calling bundle.num_rows() twice in the condition can be optimized by caching the result in a local variable num_rows.

Suggested change
for bundle in ref_bundles:
if bundle.schema is not None and (
bundle.num_rows() is None or bundle.num_rows() > 0
):
if bundle.schema is None:
continue
if bundle.num_rows() is None or bundle.num_rows() > 0:
schemas_to_unify.append(bundle.schema)
else:
empty_bundle_schemas.append(bundle.schema)
for bundle in ref_bundles:
if bundle.schema is None:
continue
num_rows = bundle.num_rows()
if num_rows is None or num_rows > 0:
schemas_to_unify.append(bundle.schema)
else:
empty_bundle_schemas.append(bundle.schema)

Comment on lines +508 to +516
# Pandas-backed empty datasets preserve columns and dtypes too.
pandas_df = pd.DataFrame(
{"a": pd.Series([], dtype="int64"), "b": pd.Series([], dtype="float64")}
)
ds3 = ray.data.from_pandas(pandas_df)
df3 = ds3.to_pandas()
assert list(df3.columns) == ["a", "b"]
assert df3["a"].dtype == np.int64
assert df3["b"].dtype == np.float64

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.

medium

The current tests only cover empty datasets with 1 empty block (since from_arrow_refs and from_pandas with empty tables/DataFrames still create 1 block). In these cases, df.shape[1] is not 0, so the fallback code path in to_pandas() is never executed. To ensure the fallback code path is actually tested and works (especially for 0-block datasets), we should add test cases for 0-block datasets (e.g., using ray.data.range(0)).

Suggested change
# Pandas-backed empty datasets preserve columns and dtypes too.
pandas_df = pd.DataFrame(
{"a": pd.Series([], dtype="int64"), "b": pd.Series([], dtype="float64")}
)
ds3 = ray.data.from_pandas(pandas_df)
df3 = ds3.to_pandas()
assert list(df3.columns) == ["a", "b"]
assert df3["a"].dtype == np.int64
assert df3["b"].dtype == np.float64
# Pandas-backed empty datasets preserve columns and dtypes too.
pandas_df = pd.DataFrame(
{"a": pd.Series([], dtype="int64"), "b": pd.Series([], dtype="float64")}
)
ds3 = ray.data.from_pandas(pandas_df)
df3 = ds3.to_pandas()
assert list(df3.columns) == ["a", "b"]
assert df3["a"].dtype == np.int64
assert df3["b"].dtype == np.float64
# Test 0-block empty dataset (Arrow-backed) to ensure the fallback path is covered.
ds_zero = ray.data.range(0)
df_zero = ds_zero.to_pandas()
assert list(df_zero.columns) == ["id"]
assert df_zero["id"].dtype == np.int64

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

Stale Bugbot comment from a previous run.

Comment thread python/ray/data/dataset.py Resolved
@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Aug 18, 2026
@lonexreb

Copy link
Copy Markdown
Contributor Author

Thanks for the reviews — addressed in 682e386. Point-by-point:

  • "pyarrow.Schema lacks an empty_table() method" (gemini): pa.Schema.empty_table() is a real PyArrow API (available well before Ray's pyarrow >= 17 floor; verified on 24.0.0/25.0.1). test_to_pandas_empty_dataset_preserves_columns exercises exactly this path and passes, including the dtype-parity assertion against a non-empty dataset. No change made.
  • "base_schema lacks a types attribute for pandas-backed datasets" (gemini): for pandas-backed datasets Schema.base_schema is a PandasBlockSchema, which does have .types (the test asserts the preserved int64/float64 dtypes). The access is also getattr-guarded with a column-name fallback, so a schema without types degrades to names-only rather than failing.
  • Cache bundle.num_rows() (gemini): done.
  • 0-block coverage (gemini): added — ray.data.range(0).to_pandas() returns an empty DataFrame cleanly.
  • Pandas-backed empty branch bypasses BlockAccessor conversion (cursor): fair point — the empty pandas DataFrame is now routed through the same BlockAccessor.to_pandas() conversion as non-empty blocks, so internal extension dtypes (e.g. TensorDtype) convert identically, with a guard for dtypes that can't back an empty Series.

All 42 tests in test_util.py + the regression test pass locally against master.

@lonexreb
lonexreb force-pushed the fix/59946-empty-dataset-schema branch from 682e386 to b0dfb18 Compare September 4, 2026 06:55
`Dataset.to_pandas()` builds the result by iterating `iter_batches`, which
yields no batches for an empty dataset. The `PandasBlockBuilder` then produces
a DataFrame with zero columns, so e.g.
`from_arrow_refs([empty_table_with_columns]).to_pandas()` returned a frame with
no columns even though the dataset's schema is known (issue ray-project#59946).

When the built DataFrame has no columns, reconstruct the columns (and dtypes,
when the underlying schema is an Arrow schema) from the dataset schema.

Closes ray-project#59946

Signed-off-by: lonexreb <[email protected]>
Address review feedback: when the empty dataset's schema is a PandasBlockSchema,
build the empty DataFrame with per-column dtypes from schema.types instead of
falling back to object dtype. Expand the test to assert dtypes for both
Arrow-backed and Pandas-backed empty datasets.

Signed-off-by: lonexreb <[email protected]>
… parity

Address review feedback (cursor): reconstruct the empty Arrow-backed result via
BlockAccessor.for_block(...).to_pandas() instead of pyarrow's empty_table().to_pandas()
so empty and non-empty results agree on column dtypes (e.g. both use the Arrow-backed
int32[pyarrow] dtype). Update the test to assert the empty dtype matches a non-empty
dataset of the same schema.

Signed-off-by: lonexreb <[email protected]>
unify_block_metadata_schema and unify_ref_bundles_schema skip blocks with
num_rows == 0, so a dataset made only of empty blocks (e.g.
from_arrow_refs on an empty table) reported no schema even though an
empty Arrow table carries a valid one. Use the empty blocks' schemas as
a fallback when no non-empty block provides a schema.

Issue ray-project#59946

Signed-off-by: lonexreb <[email protected]>
- Route the pandas-backed empty DataFrame through the same
  BlockAccessor.to_pandas() conversion used for non-empty blocks so
  internal extension dtypes (e.g. TensorDtype) convert identically, with
  a guard for dtypes that cannot back an empty Series.
- Cache bundle.num_rows() in unify_ref_bundles_schema.
- Add 0-block dataset coverage to the to_pandas regression test.

Signed-off-by: lonexreb <[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 Sep 30, 2026
elliot-barn pushed a commit that referenced this pull request Sep 30, 2026
)

## What broke

Calling a preprocessor's `transform_batch` inside a
`map_batches(batch_format="pandas")`
UDF fails on Ray >= 2.56. Three shapes, reported by a user upgrading
from 2.55:

```python
ds = ray.data.from_items([{"n": 1}, {"n": 2}, {"n": 3}, {"n": 4}])
scaler = StandardScaler(columns=["n"]).fit(ds)
ds.map_batches(lambda b: scaler.transform_batch(b), batch_format="pandas").take_all()
```

| input | error |
|---|---|
| int column, `StandardScaler` | `ArrowInvalid: Float value -1.341641
was truncated converting to int64` |
| string column, `OrdinalEncoder` / `OneHotEncoder` | `ValueError:
ArrowStringArray requires a PyArrow (chunked) array of large_string
type` |
| a list column merely *present* in the batch | `TypeError: data type
'list<item: string>[pyarrow]' not understood` |

The third needs no list-typed input to the preprocessor — a `tags`
column sitting
unused in the batch is enough while a float column is scaled.

## Why

`_transform_batch` converted the whole batch with
`pa.Table.from_pandas`, which records
the input dtypes in the table's pandas schema metadata, ran
`_transform_arrow`, and
converted back with `to_pandas`. The transform changes column types —
int64 to double
for a scaler, string to int64 for an ordinal encoding — but the metadata
still described
the input, so the conversion back cast the results to their
pre-transform dtypes.

That round trip landed in 2.54 (#59810). 2.56 (#63017) made pandas
batches Arrow-backed,
which is what made those cast-backs fail. So this is a latent bug that
2.56 exposed
rather than one 2.56 introduced: the same call already failed on 2.55
when handed an
Arrow-backed frame directly.

## The fix

Stop round-tripping the batch. Only the columns the preprocessor reads
(`get_input_columns`) cross into Arrow, without the metadata, and only
the ones it writes
(`get_output_columns`) come back. The result is a shallow copy of the
caller's frame with
those columns replaced, so untouched columns, the index, the axis names
and `attrs` never
leave pandas — there is nothing to rebuild.

- A written column that keeps its Arrow type keeps the dtype of the
column it replaces
  (a scaled `Float64` stays `Float64`).
- Otherwise it keeps that column's backing. An Arrow-backed column stays
Arrow-backed
whatever `enable_arrow_backed_pandas_conversion` says — the flag governs
how Ray
converts its own blocks, not the caller's columns — except for the types
Ray never maps
to an Arrow-backed dtype (extension, dictionary, null), which go through
its block
conversion as before. A NumPy-backed column converts plainly, and a
newly created column
  follows the frame.
- That Arrow-to-pandas type mapping moves unchanged from a closure in
`ArrowBlockAccessor.to_pandas` to module level in `arrow_block.py`, so
both paths share
  one rule.
- A preprocessor that declares no columns falls back to sending the
whole frame.

Writing columns back by position needs `_transform_arrow` to return the
rows it was
given, in order. A changed row count now raises a `ValueError`, and the
`_transform_arrow`
docstring states the contract. All three built-in `_transform_arrow`
implementations are
column transforms and satisfy it.

## Behaviour changes

Both come from untouched columns no longer being re-inferred from Arrow:

- An object column of numbers stays `object`; it used to come back
`int64` / `float64`.
- Integer column labels stay integers; they used to be turned into
strings.

And one for implementers: `_transform_arrow` on a pandas batch now
receives only the
declared input columns, and must not change the rows. The previous code
tolerated a
filtering transform by carrying the index through as a column; it now
raises instead.

## Not a fix for

`enable_arrow_backed_pandas_conversion=False` mitigates this only for
Arrow-block sources.
A pandas block built from an already-Arrow-backed frame — what
`pd.read_parquet(..., dtype_backend="pyarrow")` returns — never
undergoes an
Arrow-to-pandas conversion, so the flag does not reach it; this change
fixes that path.

Two related gaps are left for follow-ups rather than widening this PR:

- `Preprocessor.transform(ds)` has the same stale-metadata defect for a
dataset built from
an Arrow-backed pandas frame with the flag set to `False` (it works with
the default).
- `transform_batch(pa.Table)` returns a table that still carries the
caller's pandas
metadata, so calling `.to_pandas()` on the result can fail the same way.

## Not a duplicate

No open PR touches `_transform_batch` or this pandas/Arrow round trip.
The open
preprocessor work (#66088, #66091) is about how preprocessors are
*fitted* and does not
change the transform path; #60533 adds a `drop` option to the one-hot
encoders in
`encoder.py`. The other open Arrow/pandas PRs are elsewhere: #65539 is
schema
unification for empty datasets, #63938 preserves `CategoricalDtype` in
`Schema.types`.

No open issue covers it either. #64765, the umbrella 2.56 `to_pandas`
regression, is
closed, fixed by #64768 — which added the
`enable_arrow_backed_pandas_conversion`
opt-out and left this round trip untouched.

## Testing

35 `transform_batch` cases added to

`python/ray/data/tests/preprocessors/test_preprocessors_arrow_backed.py`:

- `test_transform_batch_inside_a_pandas_udf` — the three reported
preprocessors through a
  pandas UDF, parametrized over `enable_arrow_backed_pandas_conversion`.
- `test_transform_batch_on_an_arrow_backed_pandas_block` — the shape the
flag does not cover.
- `test_transform_batch_passes_through_an_untouched_list_column` — the
list-column case.
- `test_transform_batch_matches_the_input_backing` /
`..._decides_the_backing_per_column`
— NumPy in gives NumPy out, Arrow in gives Arrow out, and a mixed frame
keeps both.
- `test_transform_batch_keeps_arrow_backing_with_the_flag_off` — the
same holds for all
three preprocessors with `enable_arrow_backed_pandas_conversion=False`.
- `test_transform_batch_keeps_pass_through_extension_dtypes` — nullable
`Int64`, `boolean`
  and `string` columns come back intact, including a value past 2**53.
- `test_transform_batch_leaves_untouched_columns_exactly_as_they_were` —
object columns of
  numbers, a categorical over pandas strings, Python lists.
- `test_transform_batch_preserves_the_index` — named, `MultiIndex` and
tz-aware
  `DatetimeIndex` on both backings, plus the columns axis name.
- `test_transform_batch_keeps_integer_column_labels`,
`..._does_not_modify_the_callers_frame`,
`..._rejects_a_transform_that_changes_the_row_count`,
  `..._on_an_empty_batch`.

The cases assert on values rather than on "did not raise": where the
stale metadata
permitted the cast, the result was silently wrong rather than an error —
an ordinal
encoding coming back as the strings `"0"`, `"1"`, `"2"`.

Against the unmodified source, 21 of the 35 fail:

- 15 are the reported crash on Arrow-backed input.
- 5 are the behaviour changes above: master re-typed untouched object
and categorical
  columns and stringified integer labels.
- 1 is the new contract: master tolerated a filtering
`_transform_arrow`; this raises.

The other 14 pass on master too and are controls — the NumPy-backed
halves, the empty
batch, and the pass-through dtype cases, which guard against a
regression a naive fix
would introduce.

```
$ PYTHONPATH=python/ray/data/tests python -m pytest -q \
    python/ray/data/tests/preprocessors/ --ignore=.../test_torch.py
381 passed, 5 skipped

$ PYTHONPATH=python/ray/data/tests python -m pytest -q python/ray/data/tests/test_arrow_block.py
30 passed
```

The three reported repros were also run end to end through `map_batches`
in Ray workers.
`test_torch.py` is excluded because `torch` is not installed in this
environment; it is
untouched by this change. Pre-commit passes on all three changed files.

Only the declared columns are converted, so wide frames stop paying for
every column:
`StandardScaler(columns=["n"]).transform_batch` on a 1000-column ×
2k-row NumPy frame
goes from ~27 ms to under 1 ms.

AI assistance was used for this change.

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

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Aarrya <[email protected]>

@iamjustinhsu iamjustinhsu 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.

Thanks! left a couple comments

schemas_to_unify = []
empty_block_schemas = []
for m in block_metadata_with_schemas:
if m.schema is not None and (m.num_rows is None or m.num_rows > 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.

I'm wondering if we can just avoid the 2nd check: (m.num_rows is None or m.num_rows > 0). And also can we filter the schemas in the unify_schemas_with_validation function?

# DataFrame with no columns. Restore the columns and dtypes from the
# dataset schema so the result still matches the dataset's structure
# (issue #59946).
if df.shape[1] == 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.

If we remove the num_rows > 0 check, do we need these LOC?

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Oct 1, 2026
@lonexreb

lonexreb commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review @iamjustinhsu! Answering both questions:

1. Is the (m.num_rows is None or m.num_rows > 0) check necessary / could the filtering live in unify_schemas_with_validation?

The two-tier precedence (non-empty schemas first, empty-block schemas only as a fallback) is deliberate: a zero-row block can carry a degenerate schema — e.g. columns inferred as null-typed from zero rows, or an empty pandas block that inferred object dtypes — and letting it participate in unification when real data exists could change the unified schema for datasets that work today. The fallback shape keeps this PR strictly additive: results are identical to master whenever at least one non-empty block has a schema, and only the previously-broken all-empty case changes (it now returns the empty blocks' schema instead of None).

If you'd prefer dropping the num_rows distinction entirely and unifying every non-None schema, I'm happy to do that — it's simpler — but it's a behavior change beyond the bug fix, so I'd want your call on it. Moving the filtering into unify_schemas_with_validation is also doable, though it would need (schema, num_rows) pairs rather than bare schemas, which is why I kept it at the two call sites.

2. Would the zero-column check in to_pandas() still be needed if the num_rows check were removed?

Yes — it's independent of the metadata-layer fix. to_pandas() builds its result from iter_batches(), which yields no batches at all for an empty dataset, so PandasBlockBuilder.build() produces a zero-column DataFrame no matter what the unified metadata schema says. The reconstruction from ds.schema() is what carries the columns/dtypes into the pandas result; the unification fix alone only repairs ds.schema() and plan metadata.

@iamjustinhsu iamjustinhsu 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.

  1. Yea I would prefer to remove that check and the fallback. It simplifies stuff.
  2. I see, makes sense.

Comment thread python/ray/data/dataset.py Outdated

schema = self.schema(fetch_if_missing=True)
if schema is not None and schema.names:
base_schema = getattr(schema, "base_schema", None)

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.

We can get rid of the getattr, and just use schema.base_schema

Comment thread python/ray/data/dataset.py Outdated
import pandas

# Pandas-backed schema: preserve per-column dtypes when known.
types = getattr(base_schema, "types", None)

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.

Here too, I don't think we need to use getattr, it should be there

Comment thread python/ray/data/dataset.py Outdated

# Pandas-backed schema: preserve per-column dtypes when known.
types = getattr(base_schema, "types", None)
if types is not None and len(types) == len(schema.names):

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.

hmm, len(types) == len(schema.names) should always be the case. Let's assert here instead, and then we can remove the else branch

- unify_block_metadata_schema / unify_ref_bundles_schema no longer
  filter on num_rows: every non-None schema participates in
  unification, since empty blocks still carry valid schemas.
- to_pandas() uses schema.base_schema and base_schema.types directly
  instead of getattr guards, and asserts the types/names invariant
  instead of silently falling back.

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

lonexreb commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

All four suggestions applied in bd3a882:

  • num_rows filtering + fallback removed — both unify functions now just collect every non-None schema; empty blocks participate in unification directly.
  • getattr guards dropped — schema.base_schema and base_schema.types are accessed directly.
  • len(types) == len(schema.names) is now an assert (with the values in the message) and the silent else-branch is gone.

The net diff is pleasantly negative (-24 lines). Tests updated — the mixed empty/non-empty case now documents that empty-block schemas participate in unification (int32 + int64 promotes to int64). test_util.py + test_arrow_block.py pass locally (57 tests).

@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 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit bd3a882. Configure here.

Comment thread python/ray/data/_internal/util.py Resolved
Signed-off-by: iamjustinhsu <[email protected]>
@iamjustinhsu iamjustinhsu added the go add ONLY when ready to merge, run all tests label Oct 5, 2026

@iamjustinhsu iamjustinhsu 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.

Thanks!

@richardliaw
richardliaw merged commit 3e5af52 into ray-project:master Oct 6, 2026
7 checks passed
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…-project#66578)

## What broke

Calling a preprocessor's `transform_batch` inside a
`map_batches(batch_format="pandas")`
UDF fails on Ray >= 2.56. Three shapes, reported by a user upgrading
from 2.55:

```python
ds = ray.data.from_items([{"n": 1}, {"n": 2}, {"n": 3}, {"n": 4}])
scaler = StandardScaler(columns=["n"]).fit(ds)
ds.map_batches(lambda b: scaler.transform_batch(b), batch_format="pandas").take_all()
```

| input | error |
|---|---|
| int column, `StandardScaler` | `ArrowInvalid: Float value -1.341641
was truncated converting to int64` |
| string column, `OrdinalEncoder` / `OneHotEncoder` | `ValueError:
ArrowStringArray requires a PyArrow (chunked) array of large_string
type` |
| a list column merely *present* in the batch | `TypeError: data type
'list<item: string>[pyarrow]' not understood` |

The third needs no list-typed input to the preprocessor — a `tags`
column sitting
unused in the batch is enough while a float column is scaled.

## Why

`_transform_batch` converted the whole batch with
`pa.Table.from_pandas`, which records
the input dtypes in the table's pandas schema metadata, ran
`_transform_arrow`, and
converted back with `to_pandas`. The transform changes column types —
int64 to double
for a scaler, string to int64 for an ordinal encoding — but the metadata
still described
the input, so the conversion back cast the results to their
pre-transform dtypes.

That round trip landed in 2.54 (ray-project#59810). 2.56 (ray-project#63017) made pandas
batches Arrow-backed,
which is what made those cast-backs fail. So this is a latent bug that
2.56 exposed
rather than one 2.56 introduced: the same call already failed on 2.55
when handed an
Arrow-backed frame directly.

## The fix

Stop round-tripping the batch. Only the columns the preprocessor reads
(`get_input_columns`) cross into Arrow, without the metadata, and only
the ones it writes
(`get_output_columns`) come back. The result is a shallow copy of the
caller's frame with
those columns replaced, so untouched columns, the index, the axis names
and `attrs` never
leave pandas — there is nothing to rebuild.

- A written column that keeps its Arrow type keeps the dtype of the
column it replaces
  (a scaled `Float64` stays `Float64`).
- Otherwise it keeps that column's backing. An Arrow-backed column stays
Arrow-backed
whatever `enable_arrow_backed_pandas_conversion` says — the flag governs
how Ray
converts its own blocks, not the caller's columns — except for the types
Ray never maps
to an Arrow-backed dtype (extension, dictionary, null), which go through
its block
conversion as before. A NumPy-backed column converts plainly, and a
newly created column
  follows the frame.
- That Arrow-to-pandas type mapping moves unchanged from a closure in
`ArrowBlockAccessor.to_pandas` to module level in `arrow_block.py`, so
both paths share
  one rule.
- A preprocessor that declares no columns falls back to sending the
whole frame.

Writing columns back by position needs `_transform_arrow` to return the
rows it was
given, in order. A changed row count now raises a `ValueError`, and the
`_transform_arrow`
docstring states the contract. All three built-in `_transform_arrow`
implementations are
column transforms and satisfy it.

## Behaviour changes

Both come from untouched columns no longer being re-inferred from Arrow:

- An object column of numbers stays `object`; it used to come back
`int64` / `float64`.
- Integer column labels stay integers; they used to be turned into
strings.

And one for implementers: `_transform_arrow` on a pandas batch now
receives only the
declared input columns, and must not change the rows. The previous code
tolerated a
filtering transform by carrying the index through as a column; it now
raises instead.

## Not a fix for

`enable_arrow_backed_pandas_conversion=False` mitigates this only for
Arrow-block sources.
A pandas block built from an already-Arrow-backed frame — what
`pd.read_parquet(..., dtype_backend="pyarrow")` returns — never
undergoes an
Arrow-to-pandas conversion, so the flag does not reach it; this change
fixes that path.

Two related gaps are left for follow-ups rather than widening this PR:

- `Preprocessor.transform(ds)` has the same stale-metadata defect for a
dataset built from
an Arrow-backed pandas frame with the flag set to `False` (it works with
the default).
- `transform_batch(pa.Table)` returns a table that still carries the
caller's pandas
metadata, so calling `.to_pandas()` on the result can fail the same way.

## Not a duplicate

No open PR touches `_transform_batch` or this pandas/Arrow round trip.
The open
preprocessor work (ray-project#66088, ray-project#66091) is about how preprocessors are
*fitted* and does not
change the transform path; ray-project#60533 adds a `drop` option to the one-hot
encoders in
`encoder.py`. The other open Arrow/pandas PRs are elsewhere: ray-project#65539 is
schema
unification for empty datasets, ray-project#63938 preserves `CategoricalDtype` in
`Schema.types`.

No open issue covers it either. ray-project#64765, the umbrella 2.56 `to_pandas`
regression, is
closed, fixed by ray-project#64768 — which added the
`enable_arrow_backed_pandas_conversion`
opt-out and left this round trip untouched.

## Testing

35 `transform_batch` cases added to

`python/ray/data/tests/preprocessors/test_preprocessors_arrow_backed.py`:

- `test_transform_batch_inside_a_pandas_udf` — the three reported
preprocessors through a
  pandas UDF, parametrized over `enable_arrow_backed_pandas_conversion`.
- `test_transform_batch_on_an_arrow_backed_pandas_block` — the shape the
flag does not cover.
- `test_transform_batch_passes_through_an_untouched_list_column` — the
list-column case.
- `test_transform_batch_matches_the_input_backing` /
`..._decides_the_backing_per_column`
— NumPy in gives NumPy out, Arrow in gives Arrow out, and a mixed frame
keeps both.
- `test_transform_batch_keeps_arrow_backing_with_the_flag_off` — the
same holds for all
three preprocessors with `enable_arrow_backed_pandas_conversion=False`.
- `test_transform_batch_keeps_pass_through_extension_dtypes` — nullable
`Int64`, `boolean`
  and `string` columns come back intact, including a value past 2**53.
- `test_transform_batch_leaves_untouched_columns_exactly_as_they_were` —
object columns of
  numbers, a categorical over pandas strings, Python lists.
- `test_transform_batch_preserves_the_index` — named, `MultiIndex` and
tz-aware
  `DatetimeIndex` on both backings, plus the columns axis name.
- `test_transform_batch_keeps_integer_column_labels`,
`..._does_not_modify_the_callers_frame`,
`..._rejects_a_transform_that_changes_the_row_count`,
  `..._on_an_empty_batch`.

The cases assert on values rather than on "did not raise": where the
stale metadata
permitted the cast, the result was silently wrong rather than an error —
an ordinal
encoding coming back as the strings `"0"`, `"1"`, `"2"`.

Against the unmodified source, 21 of the 35 fail:

- 15 are the reported crash on Arrow-backed input.
- 5 are the behaviour changes above: master re-typed untouched object
and categorical
  columns and stringified integer labels.
- 1 is the new contract: master tolerated a filtering
`_transform_arrow`; this raises.

The other 14 pass on master too and are controls — the NumPy-backed
halves, the empty
batch, and the pass-through dtype cases, which guard against a
regression a naive fix
would introduce.

```
$ PYTHONPATH=python/ray/data/tests python -m pytest -q \
    python/ray/data/tests/preprocessors/ --ignore=.../test_torch.py
381 passed, 5 skipped

$ PYTHONPATH=python/ray/data/tests python -m pytest -q python/ray/data/tests/test_arrow_block.py
30 passed
```

The three reported repros were also run end to end through `map_batches`
in Ray workers.
`test_torch.py` is excluded because `torch` is not installed in this
environment; it is
untouched by this change. Pre-commit passes on all three changed files.

Only the declared columns are converted, so wide frames stop paying for
every column:
`StandardScaler(columns=["n"]).transform_batch` on a 1000-column ×
2k-row NumPy frame
goes from ~27 ms to under 1 ms.

AI assistance was used for this change.

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

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Signed-off-by: Aarrya <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Aarrya <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…o_pandas() (ray-project#65539)

## Why are these changes needed?

`Dataset.to_pandas()` (and schema propagation generally) drops columns
for an empty dataset:

```python
import pyarrow as pa, ray
empty_ref = ray.put(pa.table([pa.array([], pa.int32())], ["apples"]))
rd = ray.data.from_arrow_refs([empty_ref])
assert list(rd.to_pandas().columns) == ["apples"]  # fails on master: columns == []
```

Two layers cause this:

1. **Metadata layer**: `unify_block_metadata_schema()` /
`unify_ref_bundles_schema()` skip blocks with `num_rows == 0`, so a
dataset made *only* of empty blocks reports no schema — even though an
empty Arrow table carries a perfectly valid one (as noted by @mango766
on the issue). This PR makes empty-block schemas a fallback when no
non-empty block provides a schema; non-empty blocks still take
precedence.
2. **Consumption layer**: `to_pandas()` builds its result from
`iter_batches()`, which yields no batches for an empty dataset, so
`PandasBlockBuilder.build()` produced a DataFrame with zero columns.
This PR reconstructs columns and dtypes from the dataset schema, routing
Arrow-backed schemas through the same `BlockAccessor.to_pandas()` path
used for non-empty blocks so empty and non-empty results agree on
dtypes.

This supersedes ray-project#64721 (same fix for layer 2, closed by the stale bot
after both bot-review comments had been addressed; GitHub would not
allow reopening it). This PR carries those commits, rebased on current
master, plus the new metadata-layer fix.

## Related issue number

Fixes ray-project#59946

## Checks

- [x] I've signed off every commit (DCO).
- [x] I've run pre-commit formatting (`black==22.10.0` per repo pin) on
changed files.
- [x] Testing strategy:
- Added `test_to_pandas_empty_dataset_preserves_columns` (Arrow-backed
and pandas-backed empty datasets, dtype parity with non-empty datasets).
- Added `test_unify_block_metadata_schema_all_empty_blocks` (fallback +
precedence).
- Ran locally against master with the Ray nightly wheel + `setup-dev.py`
symlinks:
    - `pytest python/ray/data/tests/test_util.py` → 39 passed
- `pytest python/ray/data/tests/test_arrow_block.py -k to_pandas` → 13
passed
    - Issue's exact repro passes.

### Notes for reviewers / AI-assistance disclosure

- This PR was prepared with AI assistance; I have reviewed every changed
line and run the tests above locally.
- Duplicate-work check: no other open PR references ray-project#59946; the only
prior PR was my own ray-project#64721, which this supersedes.

---------

Signed-off-by: lonexreb <[email protected]>
Signed-off-by: iamjustinhsu <[email protected]>
Co-authored-by: iamjustinhsu <[email protected]>
sai-miduthuri added a commit that referenced this pull request Nov 13, 2026
…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]>
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 unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Data] from_arrow_refs converts an empty table with one column into an empty table with zero columns

3 participants