Skip to content

[Data] Fix ZipOperator freeing shared blocks via _split_at_indices - #62665

Merged
richardliaw merged 12 commits into
ray-project:masterfrom
wufeiye:fix-zip-operator-shared-blocks-free
Apr 27, 2026
Merged

richardliaw merged 12 commits into
ray-project:masterfrom
wufeiye:fix-zip-operator-shared-blocks-free

Conversation

@wufeiye

@wufeiye wufeiye commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • ZipOperator._zip() called _split_at_indices() without specifying owned_by_consumer, which defaults to True
  • This caused ray.internal.free() to be called on blocks that may be shared with other operators in the DAG
  • Fixes ObjectFreedError in complex DAGs where a materialized dataset is consumed by both map_batches and zip

Root Cause

_split_at_indices (split.py:250) has owned_by_consumer: bool = True as default. When True, _split_all_blocks calls trace_deallocation(b, ..., free=True) which invokes
ray._private.internal_api.free(ref, local_only=False) — a global free that bypasses reference counting.

In complex DAGs where the same materialized blocks are shared with other operators, this causes ObjectFreedError.

Fix

Pass the correct owned_by_consumer flag based on the RefBundle.owns_blocks attribute of the input being split, accounting for the potential left/right swap in _zip().

Test plan

  • Added regression test: test_zip_does_not_free_shared_materialized_blocks
  • Existing zip tests pass

ZipOperator._zip() calls _split_at_indices() without specifying the
owned_by_consumer parameter, which defaults to True. This causes
ray.internal.free() to be called on blocks that may be shared with
other operators in the DAG (e.g., a materialized dataset consumed by
both a map_batches operator and a zip), leading to ObjectFreedError.

The fix passes the correct ownership flag based on the RefBundles'
owns_blocks attribute, accounting for the potential left/right swap
that occurs to minimize splitting work.

Signed-off-by: wufeiye1 <[email protected]>
@wufeiye
wufeiye requested a review from a team as a code owner April 16, 2026 14:47

@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 fixes a bug in the ZipOperator where shared blocks from materialized datasets were being incorrectly freed during splitting, causing ObjectFreedError. The fix involves determining block ownership before calling _split_at_indices. A regression test has been added to ensure that zipping shared materialized datasets works correctly. Feedback was provided to simplify the ownership check logic into a single line to improve readability and avoid redundant iterations.

@ray-gardener ray-gardener Bot added data Ray Data-related issues community-contribution Contributed by the community labels Apr 16, 2026
@richardliaw richardliaw added the go add ONLY when ready to merge, run all tests label Apr 18, 2026
@wufeiye
wufeiye force-pushed the fix-zip-operator-shared-blocks-free branch from 5b13e74 to 5b7bd6e Compare April 18, 2026 14:59
@owenowenisme owenowenisme self-assigned this Apr 21, 2026

@owenowenisme owenowenisme left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Overall LGTM, only a few nits. Thanks for fixing this!

Comment thread python/ray/data/tests/test_zip.py Resolved
wufeiye and others added 2 commits April 21, 2026 17:54
Remove the default True value to force callers to explicitly specify
block ownership, preventing accidental frees of shared blocks.

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

Copy link
Copy Markdown
Member

@WFY123wfy Could you fix the failed test?

wufeiye and others added 5 commits April 21, 2026 22:41
Use the correct API: ds._plan.execute() returns a single RefBundle,
not a list. Check owns_blocks directly instead of iterating over
non-existent _blocks attribute.

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

wufeiye commented Apr 21, 2026

Copy link
Copy Markdown
Contributor Author

@owenowenisme The failed test has been fixed. Please take a look again.

@owenowenisme owenowenisme left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM, thanks!

@wufeiye

wufeiye commented Apr 27, 2026

Copy link
Copy Markdown
Contributor Author

@owenowenisme All checks passed and the review is approved. Could you help merge this when you have a chance? Thanks!

@richardliaw
richardliaw merged commit 89b8df4 into ray-project:master Apr 27, 2026
3 checks passed
@wufeiye
wufeiye deleted the fix-zip-operator-shared-blocks-free branch April 28, 2026 03:00
Lucas61000 pushed a commit to Lucas61000/ray that referenced this pull request May 15, 2026
…ay-project#62665)

## Summary
- ZipOperator._zip() called `_split_at_indices()` without specifying
`owned_by_consumer`, which defaults to `True`
- This caused `ray.internal.free()` to be called on blocks that may be
shared with other operators in the DAG
- Fixes `ObjectFreedError` in complex DAGs where a materialized dataset
is consumed by both `map_batches` and `zip`
## Root Cause
`_split_at_indices` (`split.py:250`) has `owned_by_consumer: bool =
True` as default. When `True`, `_split_all_blocks` calls
`trace_deallocation(b, ..., free=True)` which invokes
`ray._private.internal_api.free(ref, local_only=False)` — a global free
that bypasses reference counting.
In complex DAGs where the same materialized blocks are shared with other
operators, this causes `ObjectFreedError`.
  ## Fix                                 
Pass the correct `owned_by_consumer` flag based on the
`RefBundle.owns_blocks` attribute of the input being split, accounting
for the potential left/right swap in `_zip()`.
  ## Test plan
- [x] Added regression test:
`test_zip_does_not_free_shared_materialized_blocks`
  - [x] Existing zip tests pass

---------

Signed-off-by: wufeiye1 <[email protected]>
Co-authored-by: wufeiye1 <[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

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