Skip to content

[Data] Make RefBundle and other classes properly frozen - #61059

Merged
alexeykudinkin merged 40 commits into
masterfrom
ak/ref-bndl-frz-fix
Mar 12, 2026
Merged

alexeykudinkin merged 40 commits into
masterfrom
ak/ref-bndl-frz-fix

Conversation

@alexeykudinkin

Copy link
Copy Markdown
Contributor

Description

  • Cleaning up to make BundleClass, BlockMetadata, BlockSlice and other classes properly frozen;
  • Added PandasBlockSchema as data class

Related issues

Link related issues: "Fixes #1234", "Closes #1234", or "Related to #1234".

Additional information

Optional: Add implementation details, API changes, usage examples, screenshots, etc.

@alexeykudinkin
alexeykudinkin requested a review from a team as a code owner February 13, 2026 21:49
@alexeykudinkin alexeykudinkin added the go add ONLY when ready to merge, run all tests label Feb 13, 2026
Comment thread python/ray/data/block.py Resolved

@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 does a great job of refactoring several data classes to be immutable by using @dataclass(frozen=True). This is a solid improvement for code robustness, preventing accidental state changes. The changes consistently update related code to use immutable tuples instead of lists and correctly use dataclasses.replace for updating frozen instances. I have a couple of minor suggestions to improve consistency and conciseness in some of the __post_init__ methods.

Comment on lines +79 to +80
if self.slices is None:
self.slices = [None] * len(self.blocks)
self.slices = (None,) * len(self.blocks)

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

For consistency with other assignments in __post_init__ and to prepare for making RefBundle a frozen dataclass, it would be better to use object.__setattr__ here as well. This avoids potential issues if frozen=True is added to the RefBundle dataclass later.

Suggested change
if self.slices is None:
self.slices = [None] * len(self.blocks)
self.slices = (None,) * len(self.blocks)
if self.slices is None:
object.__setattr__(self, "slices", (None,) * len(self.blocks))

Comment thread python/ray/data/block.py Outdated
Comment on lines +257 to +267
def __post_init__(self):
super().__post_init__()

input_files = self.input_files

if input_files is None:
input_files = tuple()
elif not isinstance(input_files, tuple):
input_files = tuple(input_files)

object.__setattr__(self, "input_files", input_files)

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 logic in __post_init__ can be made more concise and slightly more efficient by only calling object.__setattr__ when the input_files attribute is not already a tuple. This avoids an unnecessary attribute assignment when it's already in the correct format.

Suggested change
def __post_init__(self):
super().__post_init__()
input_files = self.input_files
if input_files is None:
input_files = tuple()
elif not isinstance(input_files, tuple):
input_files = tuple(input_files)
object.__setattr__(self, "input_files", input_files)
def __post_init__(self):
super().__post_init__()
if not isinstance(self.input_files, tuple):
input_files = tuple() if self.input_files is None else tuple(self.input_files)
object.__setattr__(self, "input_files", input_files)

Comment on lines +353 to +354
names: Tuple[str]
types: Tuple["pandas.DataType"]

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 want to be compatible with pyarrow, why not create a dataclass called Field and then have pandasSchema have list[Field]? That way we can also ensure that len(names) == len(types)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not tackling that here

)

def __eq__(self, other) -> bool:
def __eq__(self, other: "RefBundle"):

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.

nit: typing?

Comment thread python/ray/data/_internal/split.py Resolved
Comment thread python/ray/data/_internal/split.py Resolved
@ray-gardener ray-gardener Bot added the data Ray Data-related issues label Feb 27, 2026
Comment on lines +350 to +358
@dataclass(frozen=True, init=False)
class PandasBlockSchema:
# Stored as tuples for hash-ability.
names: Tuple[str, ...]
types: Tuple

def __init__(self, names, types):
object.__setattr__(self, "names", tuple(names))
object.__setattr__(self, "types", tuple(types))

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.

Might be slightly more pythonic:

from pandas.api.extensions import ExtensionDtype

@dataclass(frozen=True)
class PandasBlockSchema:
    names: tuple[str, ...]
    types: tuple[np.dtype | ExtensionDtype, ...]

    def __post_init__(self):
        object.__setattr__(self, "names", tuple(self.names))
        object.__setattr__(self, "types", tuple(self.types))

@alexeykudinkin
alexeykudinkin enabled auto-merge (squash) March 11, 2026 01:15
@github-actions
github-actions Bot disabled auto-merge March 11, 2026 19:51
Comment thread python/ray/data/block.py Resolved
Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>

# Conflicts:
#	python/ray/data/block.py

Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>

# Conflicts:
#	python/ray/data/_internal/execution/legacy_compat.py

Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>
This reverts commit 69cc34b.

Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>
Revisited builder

Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>
Signed-off-by: Alexey Kudinkin <[email protected]>

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

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Comment thread python/ray/data/dataset.py Resolved
@alexeykudinkin
alexeykudinkin enabled auto-merge (squash) March 12, 2026 22:58
@alexeykudinkin
alexeykudinkin merged commit 02d61af into master Mar 12, 2026
4 checks passed
@alexeykudinkin
alexeykudinkin deleted the ak/ref-bndl-frz-fix branch March 12, 2026 23:48
alexeykudinkin pushed a commit that referenced this pull request Mar 17, 2026
…ist (#61774)

## Description
as titled, this #61059 caused
ref bundles to be the same using the same object_ref, so used a unique
one. Also, made the input_file to tuples over lists

## Related issues

## Additional information

Signed-off-by: iamjustinhsu <[email protected]>
This was referenced Mar 25, 2026
Lucas61000 pushed a commit to Lucas61000/ray that referenced this pull request May 15, 2026
…ist (ray-project#61774)

## Description
as titled, this ray-project#61059 caused
ref bundles to be the same using the same object_ref, so used a unique
one. Also, made the input_file to tuples over lists

## Related issues

## Additional information

Signed-off-by: iamjustinhsu <[email protected]>
richardliaw pushed a commit that referenced this pull request Nov 18, 2026
…_blocks_rows (#67662)

## Summary

Fixes a lost `BlockMetadata.num_rows` update and sequential `ray.get`
bottleneck in `_calculate_blocks_rows`
(`python/ray/data/_internal/split.py`).

## Before

When PR `#61059` made `BlockMetadata` immutable
(`@dataclass(frozen=True)`), `_calculate_blocks_rows` was updated from
`metadata.num_rows = num_rows` to `metadata = replace(metadata,
num_rows=num_rows)` inside `for block, metadata in
blocks_with_metadata:`, which only rebound the local loop variable
without writing `(block, metadata)` back into `blocks_with_metadata[i]`.
In addition, when multiple blocks had `metadata.num_rows is None`,
`_calculate_blocks_rows` executed `ray.get(get_num_rows.remote(block))`
sequentially one block at a time.

As a result, whenever any input block had `metadata.num_rows is None`:
1. `_equalize()` in `python/ray/data/_internal/equalize.py:51` crashed
with `TypeError: unsupported operand type(s) for +: 'int' and
'NoneType'` at `sum([meta.num_rows for _, meta in shaved_split])`
because untouched blocks retained `meta.num_rows is None`.
2. `_split_leftovers` -> `_split_at_indices` (`equalize.py:66`) had to
re-run `get_num_rows.remote(block)` a second time on leftover blocks
whose `metadata.num_rows` was never persisted.

```mermaid
flowchart LR
    subgraph Sub["Subsystem: Shuffle / aggregation"]
        subgraph Mod["Module: split.py / equalize.py"]
            calc["_calculate_blocks_rows()<br/>1. Serial ray.get per block<br/>2. Local `metadata = replace(...)` lost"]
            eq["_equalize()<br/>sum(meta.num_rows) -> TypeError: int + NoneType"]
            calc --> eq
        end
    end
    style calc fill:#f8d7da,stroke:#dc3545,color:#000
    style eq fill:#f8d7da,stroke:#dc3545,color:#000
```

## After

`_calculate_blocks_rows` collects all indices with `metadata.num_rows is
None`, fetches their row counts in a single batched
`ray.get([get_num_rows.remote(...) for i in missing_indices])` call, and
writes `(block, replace(metadata, num_rows=num_rows))` back into
`blocks_with_metadata[i]`.

```mermaid
flowchart LR
    subgraph Sub["Subsystem: Shuffle / aggregation"]
        subgraph Mod["Module: split.py / equalize.py"]
            calc["_calculate_blocks_rows()<br/>1. Batched ray.get across missing blocks<br/>2. Persists replace(metadata, num_rows=...) in blocks_with_metadata"]
            eq["_equalize()<br/>All shaved & leftover blocks have populated meta.num_rows"]
            calc --> eq
        end
    end
    style calc fill:#d4edda,stroke:#28a745,color:#000
    style eq fill:#d4edda,stroke:#28a745,color:#000
```

## Subsystems

- [x] Shuffle / aggregation (`python/ray/data/_internal/split.py`,
`python/ray/data/_internal/equalize.py`)

## Testing

- Added
`test_calculate_blocks_rows_updates_metadata_and_batches_ray_get` and
`test_equalize_with_unknown_num_rows_metadata` in
`python/ray/data/tests/test_split.py`.
- Verified `_calculate_blocks_rows`, `_split_at_indices`, and
`_equalize` with `BlockMetadata(num_rows=None, ...)`.

## Duplicate-Work Check & Acknowledgments

- Searched open and closed issues and PRs in `ray-project/ray` for
`_calculate_blocks_rows`, `_equalize`, and `BlockMetadata` `num_rows`;
no existing issue or PR covers this bug.
- Credits and thanks to Alexey Kudinkin (`@alexeykudinkin`, `#61059`),
`@wufeiye` (`#62665`), and Balaji Veeramani (`@bveeramani`, `#45481`)
for their work on immutable `BlockMetadata` and Ray Data
splitting/equalization.
- *AI assistance disclosure: GitHub Copilot CLI (Claude Sonnet 4.6) was
used to assist with test scaffolding and PR formatting; all changes were
verified locally.*

---------

Signed-off-by: Parth Vadera <[email protected]>
Co-authored-by: Copilot <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

Ray fails to serialize self-reference objects

2 participants