Skip to content

[Data] Don't register out-of-scope callbacks on blocks passed through from input to output - #66369

Merged
matthewdeng merged 6 commits into
ray-project:masterfrom
marwan116:marwan/data-brc-foreign-owned-blocks
Sep 22, 2026
Merged

matthewdeng merged 6 commits into
ray-project:masterfrom
marwan116:marwan/data-brc-foreign-owned-blocks

Conversation

@marwan116

@marwan116 marwan116 commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Description

A Ray Train job dies before it reads a single row. Its input pipeline shuffles a dataset that was already materialized:

ds = ray.data.range(100, override_num_blocks=10).materialize()
ds = ds.randomize_block_order()
(it,) = ds.streaming_split(1, equal=True)
list(it.iter_rows())
(SplitCoordinator pid=42263) Split 0 epoch 0 get() failed after 0 rows: Cannot register
an out-of-scope/freed callback for object 6f1bcddfc6570c62…: it is not owned by this
worker (it may be owned by another worker, or have no ownership record). These callbacks
can only be registered by the owner.

Why it happens

BlockRefCounter tracks object-store memory. To do that, it asks Ray Core to call it back when a block is freed. Only the block's owner may register that callback, and the owner is the process that created the block.

streaming_split runs the plan inside a SplitCoordinator actor. But the blocks were created earlier, by materialize() on the caller. The same holds for any InputData source, such as from_arrow or from_pandas.

  caller                        SplitCoordinator actor
  ──────────────                ──────────────────────
  materialize()   ── refs ──▶   randomize_block_order → … → split(N)
  owns B1..B10                  owns nothing it was handed

AllToAllOperator.all_inputs_done registered a callback for every block it sent downstream. That is right for sort, shuffle and repartition. Their output blocks come from reduce tasks the operator itself submitted, so it owns them.

It is wrong for RandomizeBlocks. That operator creates no blocks. It reorders its input bundles and returns the same refs. So the actor asks Ray Core to watch blocks the caller owns, Ray Core refuses, and the execution fails.

The fix

Register a block only when its ref was not among the operator's inputs:

input_refs = {entry.ref for b in input_bundles for entry in b.blocks}
...
for bundle in output_buffer:
    for entry in bundle.blocks:
        if entry.ref in input_refs:
            continue
        self._block_ref_counter.on_block_produced(...)

Returned refs are skipped. New ones are still registered. OutputSplitter already uses the same test on _split_block output.

Why not RefBundle.owns_blocks? That flag says whether the blocks may be destroyed, not who made them. The shuffle, sort and split-repartition schedulers copy it from their input onto blocks their own reduce tasks made (input_owned = all(b.owns_blocks for b in refs) at pull_based_shuffle_task_scheduler.py:50, used at :145). A filter on that flag would drop real blocks from the counter whenever the source is from_* or materialize, and under-report their memory. Bugbot caught this in the first version of this PR.

Where it came from

#64157 added BlockRefCounter to the operators in 2.57, and the crash has been there since. It was reported from a Ray Train job on 2.58.0. That job's input pipeline is from_arrow → repartition → materialize → randomize_block_order → map_batches → repartition → streaming_split, and all four splits fail at 0 rows.

Related issues

None open. I searched ray-project/ray for open PRs and issues mentioning BlockRefCounter, owns_blocks, streaming_split materialized, and the error text "Cannot register an out-of-scope callback". Two open PRs touch the counter: #65878 (consumer-held bytes) and #65220 (deferring gRPC frees). Neither changes this registration path, and no open issue tracks the crash, so this is not duplicate work.

Additional information

Tests. test_streaming_split_over_materialized_all_to_all reproduces the failure end to end. The two tests in test_operators.py cover both sides of the check; the second fails if the check uses owns_blocks, which is what the first version of this PR did.

$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_streaming_integration.py \
    -k test_streaming_split_over_materialized_all_to_all -q
1 passed, 25 deselected in 9.28s        # fails on master with the error above

$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_operators.py \
    python/ray/data/tests/test_randomize_block_order.py \
    python/ray/data/tests/unit/test_block_ref_counter.py \
    python/ray/data/tests/unit/test_resource_manager.py -q
29 passed in 16.10s

$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_streaming_integration.py -k streaming_split -q
13 passed, 13 deselected in 68.67s

The last command needs #66366 applied locally. On master, request_remaining=True in rate_based_cluster_autoscaler.py raises TypeError: 'bool' object is not iterable in the autoscaling coordinator, which makes these tests flaky.

CI. The buildkite/premerge failure here is that same master bug. All three pyrefly errors are in rate_based_cluster_autoscaler.py, a file this PR does not touch. #66366 and #66370 both fix it, and this PR is unblocked once either one lands.

AI assistance was used for the diagnosis, the patch, and this description.

@marwan116 marwan116 added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Sep 22, 2026
@marwan116
marwan116 marked this pull request as ready for review September 22, 2026 13:58
@marwan116
marwan116 requested a review from a team as a code owner September 22, 2026 13:58

@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 prevents ValueError exceptions during execution by ensuring that operators only register block callbacks for bundles they actually own. Specifically, a check was added in base_physical_operator.py to skip registration if bundle.owns_blocks is false, which is common for pass-through operators like randomize_block_order. A regression test was also added to verify this fix. There are no review comments, so no additional feedback is provided.

@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 using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 67c4986. Configure here.

@marwan116 marwan116 self-assigned this Sep 22, 2026
…idn't produce

`AllToAllOperator.all_inputs_done` registers a Ray Core object out-of-scope
callback for every block in its output bundles, so `BlockRefCounter` can
attribute object-store memory to the operator. But a `bulk_fn` may forward its
input bundles instead of producing new blocks -- `RandomizeBlocks` only reorders
them -- and those blocks can be owned by a different worker.

That happens whenever an `InputData` source (a materialized dataset,
`from_arrow`, ...) feeds a plan executing inside a `SplitCoordinator` actor,
which is what `streaming_split` and Ray Train ingest do: the blocks belong to
whoever built the dataset, usually the driver, not to the coordinator. Only the
owner may call `add_object_out_of_scope_callback`, so registration raises and
the whole execution fails before a single row is read:

    ds = ray.data.range(100, override_num_blocks=10).materialize()
    ds = ds.randomize_block_order()
    (it,) = ds.streaming_split(1, equal=True)
    list(it.iter_rows())

    ValueError: Cannot register an out-of-scope/freed callback for object
    6f1bcddfc6570c62...: it is not owned by this worker

Register only blocks whose refs are not among the operator's inputs. Forwarded
blocks are not this operator's to account for, and it cannot observe when they
go out of scope. `RefBundle.owns_blocks` looks like the right predicate but is
not: it is a destroy-permission flag, and the shuffle, sort and split-repartition
schedulers copy it from their input onto blocks their reduce tasks genuinely
produced, so filtering on it would under-report object-store memory for those
operators whenever the source is `from_*` or `materialize`. Ref identity is the
same test `OutputSplitter` already applies.

Introduced in 2.57 by ray-project#64157, which wired `BlockRefCounter` into the operators.

Signed-off-by: Marwan Sarieddine <[email protected]>
ray-project#64521 removed `clear()`, but two comments still explain the `_registered_ids`
membership check in terms of it, pointing a reader at a method that is no
longer there. With `clear()` gone the check guards a repeat notification for
an ID that is already gone, so say that instead.

Comment-only, and bundled here because this PR is already editing the file.

Signed-off-by: Marwan Sarieddine <[email protected]>
@marwan116
marwan116 force-pushed the marwan/data-brc-foreign-owned-blocks branch from f54542c to 6dc81a0 Compare September 22, 2026 14:43
@ayushk7102
ayushk7102 self-requested a review September 22, 2026 17:18

@ayushk7102 ayushk7102 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 for the fix. Nit: Can we change the PR title to "don't register out-of-scope callbacks on blocks the operator passes through from input to output"?

Just so that we don't confuse this change with owns_blocks, which IIUC the check doesn't depend on

@marwan116 marwan116 changed the title [Data] Don't register out-of-scope callbacks on blocks the operator doesn't own [Data] Don't register out-of-scope callbacks on blocks passed through from input to output Sep 22, 2026
Reverts 6dc81a0 to keep this PR to the bug fix alone.

Those two comments do name a method that ray-project#64521 removed, so the cleanup is
correct on master. But it is unrelated to the crash, and on releases/2.57.0 --
the earliest branch this fix has to reach, since BlockRefCounter arrived in
2.57 -- `clear()` still exists. Reworded there, the comments would be wrong.

Leaving them untouched keeps the backport a single hunk-for-hunk cherry-pick
with nothing a backporter has to remember to drop.

Signed-off-by: Marwan Sarieddine <[email protected]>
@matthewdeng
matthewdeng enabled auto-merge (squash) September 22, 2026 21:47
@matthewdeng
matthewdeng merged commit 428f0dd into ray-project:master Sep 22, 2026
7 checks passed
elliot-barn added a commit that referenced this pull request Sep 23, 2026
…blocks passed through from input to output (#66369) (#66403)

Cherry-pick of #66369 (master commit
428f0dd) onto `releases/2.57.1`, the
new patch-release branch cut from `releases/2.57.0` (this PR sits on top
of the `bumping ray version to 2.57.1` commit).

Fixes the `streaming_split` over a materialized / `from_*` dataset
followed by `randomize_block_order` crash (`Cannot register an
out-of-scope/freed callback for object ...: it is not owned by this
worker`). The bug shipped with #64157 in 2.57 and was reported from a
Ray Train job on 2.58.0.

Applied cleanly with `git cherry-pick -x`. `block_ref_counter.py` on
this branch predates a small unrelated refactor on master, so the two
docstring/TODO hunks landed at different line offsets, but the content
is identical to the master commit; the other three files were
byte-identical to master's parent. Not re-run locally (no Ray build for
the release branch on this box); relying on the branch CI for
`python/ray/data/tests/test_operators.py` and
`test_streaming_integration.py`, which passed on master in #66369. Same
change as #66401 for 2.59.0.

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

Signed-off-by: Marwan Sarieddine <[email protected]>
Signed-off-by: elliot-barn <[email protected]>
Co-authored-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Ayush Kumar <[email protected]>
elliot-barn added a commit that referenced this pull request Sep 23, 2026
…blocks passed through from input to output (#66369) (#66404)

Cherry-pick of #66369 (master commit
428f0dd) onto `releases/2.58.1`, the
new patch-release branch cut from `releases/2.58.0` (this PR sits on top
of the `bumping ray version to 2.58.1` commit).

Fixes the `streaming_split` over a materialized / `from_*` dataset
followed by `randomize_block_order` crash (`Cannot register an
out-of-scope/freed callback for object ...: it is not owned by this
worker`). The bug shipped with #64157 in 2.57 and was reported from a
Ray Train job on 2.58.0.

Applied cleanly with `git cherry-pick -x`; all four touched files were
identical between master's parent commit and `releases/2.58.0`, and the
resulting diff is byte-identical to the master commit. Not re-run
locally (no Ray build for the release branch on this box); relying on
the branch CI for `python/ray/data/tests/test_operators.py` and
`test_streaming_integration.py`, which passed on master in #66369. Same
change as #66401 for 2.59.0.

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

Signed-off-by: Marwan Sarieddine <[email protected]>
Signed-off-by: elliot-barn <[email protected]>
Co-authored-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Ayush Kumar <[email protected]>
elliot-barn added a commit that referenced this pull request Sep 23, 2026
…blocks passed through from input to output (#66369) (#66401)

Cherry-pick of #66369 (master commit
428f0dd) onto releases/2.59.0.

Fixes the `streaming_split` over a materialized / `from_*` dataset
followed by `randomize_block_order` crash (`Cannot register an
out-of-scope/freed callback for object ...: it is not owned by this
worker`). The bug shipped with #64157 in 2.57 and was reported from a
Ray Train job on 2.58.0, so 2.59.0 carries it too.

Applied cleanly with `git cherry-pick -x`; the four touched files were
identical between master's parent commit and `releases/2.59.0`, and the
resulting diff is byte-identical to the master commit. Not re-run
locally (no Ray build for the release branch on this box); relying on
the branch CI for `python/ray/data/tests/test_operators.py` and
`test_streaming_integration.py`, which passed on master in #66369.

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

Signed-off-by: Marwan Sarieddine <[email protected]>
Signed-off-by: elliot-barn <[email protected]>
Co-authored-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Ayush Kumar <[email protected]>
owenowenisme pushed a commit to owenowenisme/ray that referenced this pull request Sep 23, 2026
… from input to output (ray-project#66369)

## Description

A Ray Train job dies before it reads a single row. Its input pipeline
shuffles a dataset that was already materialized:

```python
ds = ray.data.range(100, override_num_blocks=10).materialize()
ds = ds.randomize_block_order()
(it,) = ds.streaming_split(1, equal=True)
list(it.iter_rows())
```

```
(SplitCoordinator pid=42263) Split 0 epoch 0 get() failed after 0 rows: Cannot register
an out-of-scope/freed callback for object 6f1bcddfc6570c62…: it is not owned by this
worker (it may be owned by another worker, or have no ownership record). These callbacks
can only be registered by the owner.
```

### Why it happens

`BlockRefCounter` tracks object-store memory. To do that, it asks Ray
Core to call it back when a block is freed. Only the block's owner may
register that callback, and the owner is the process that created the
block.

`streaming_split` runs the plan inside a `SplitCoordinator` actor. But
the blocks were created earlier, by `materialize()` on the caller. The
same holds for any `InputData` source, such as `from_arrow` or
`from_pandas`.

```
  caller                        SplitCoordinator actor
  ──────────────                ──────────────────────
  materialize()   ── refs ──▶   randomize_block_order → … → split(N)
  owns B1..B10                  owns nothing it was handed
```

`AllToAllOperator.all_inputs_done` registered a callback for every block
it sent downstream. That is right for sort, shuffle and repartition.
Their output blocks come from reduce tasks the operator itself
submitted, so it owns them.

It is wrong for `RandomizeBlocks`. That operator creates no blocks. It
reorders its input bundles and returns the same refs. So the actor asks
Ray Core to watch blocks the caller owns, Ray Core refuses, and the
execution fails.

### The fix

Register a block only when its ref was not among the operator's inputs:

```python
input_refs = {entry.ref for b in input_bundles for entry in b.blocks}
...
for bundle in output_buffer:
    for entry in bundle.blocks:
        if entry.ref in input_refs:
            continue
        self._block_ref_counter.on_block_produced(...)
```

Returned refs are skipped. New ones are still registered.
`OutputSplitter` already uses the same test on `_split_block` output.

**Why not `RefBundle.owns_blocks`?** That flag says whether the blocks
may be destroyed, not who made them. The shuffle, sort and
split-repartition schedulers copy it from their input onto blocks their
own reduce tasks made (`input_owned = all(b.owns_blocks for b in refs)`
at `pull_based_shuffle_task_scheduler.py:50`, used at `:145`). A filter
on that flag would drop real blocks from the counter whenever the source
is `from_*` or `materialize`, and under-report their memory. Bugbot
caught this in the first version of this PR.

### Where it came from

ray-project#64157 added `BlockRefCounter` to the operators in 2.57, and the crash
has been there since. It was reported from a Ray Train job on 2.58.0.
That job's input pipeline is `from_arrow → repartition → materialize →
randomize_block_order → map_batches → repartition → streaming_split`,
and all four splits fail at 0 rows.

## Related issues

None open. I searched ray-project/ray for open PRs and issues mentioning
`BlockRefCounter`, `owns_blocks`, `streaming_split materialized`, and
the error text "Cannot register an out-of-scope callback". Two open PRs
touch the counter: ray-project#65878 (consumer-held bytes) and ray-project#65220 (deferring
gRPC frees). Neither changes this registration path, and no open issue
tracks the crash, so this is not duplicate work.

## Additional information

**Tests.** `test_streaming_split_over_materialized_all_to_all`
reproduces the failure end to end. The two tests in `test_operators.py`
cover both sides of the check; the second fails if the check uses
`owns_blocks`, which is what the first version of this PR did.

```
$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_streaming_integration.py \
    -k test_streaming_split_over_materialized_all_to_all -q
1 passed, 25 deselected in 9.28s        # fails on master with the error above

$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_operators.py \
    python/ray/data/tests/test_randomize_block_order.py \
    python/ray/data/tests/unit/test_block_ref_counter.py \
    python/ray/data/tests/unit/test_resource_manager.py -q
29 passed in 16.10s

$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_streaming_integration.py -k streaming_split -q
13 passed, 13 deselected in 68.67s
```

The last command needs ray-project#66366 applied locally. On master,
`request_remaining=True` in `rate_based_cluster_autoscaler.py` raises
`TypeError: 'bool' object is not iterable` in the autoscaling
coordinator, which makes these tests flaky.

**CI.** The `buildkite/premerge` failure here is that same master bug.
All three pyrefly errors are in `rate_based_cluster_autoscaler.py`, a
file this PR does not touch. ray-project#66366 and ray-project#66370 both fix it, and this PR
is unblocked once either one lands.

**AI assistance was used** for the diagnosis, the patch, and this
description.

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Ayush Kumar <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
… from input to output (ray-project#66369)

## Description

A Ray Train job dies before it reads a single row. Its input pipeline
shuffles a dataset that was already materialized:

```python
ds = ray.data.range(100, override_num_blocks=10).materialize()
ds = ds.randomize_block_order()
(it,) = ds.streaming_split(1, equal=True)
list(it.iter_rows())
```

```
(SplitCoordinator pid=42263) Split 0 epoch 0 get() failed after 0 rows: Cannot register
an out-of-scope/freed callback for object 6f1bcddfc6570c62…: it is not owned by this
worker (it may be owned by another worker, or have no ownership record). These callbacks
can only be registered by the owner.
```

### Why it happens

`BlockRefCounter` tracks object-store memory. To do that, it asks Ray
Core to call it back when a block is freed. Only the block's owner may
register that callback, and the owner is the process that created the
block.

`streaming_split` runs the plan inside a `SplitCoordinator` actor. But
the blocks were created earlier, by `materialize()` on the caller. The
same holds for any `InputData` source, such as `from_arrow` or
`from_pandas`.

```
  caller                        SplitCoordinator actor
  ──────────────                ──────────────────────
  materialize()   ── refs ──▶   randomize_block_order → … → split(N)
  owns B1..B10                  owns nothing it was handed
```

`AllToAllOperator.all_inputs_done` registered a callback for every block
it sent downstream. That is right for sort, shuffle and repartition.
Their output blocks come from reduce tasks the operator itself
submitted, so it owns them.

It is wrong for `RandomizeBlocks`. That operator creates no blocks. It
reorders its input bundles and returns the same refs. So the actor asks
Ray Core to watch blocks the caller owns, Ray Core refuses, and the
execution fails.

### The fix

Register a block only when its ref was not among the operator's inputs:

```python
input_refs = {entry.ref for b in input_bundles for entry in b.blocks}
...
for bundle in output_buffer:
    for entry in bundle.blocks:
        if entry.ref in input_refs:
            continue
        self._block_ref_counter.on_block_produced(...)
```

Returned refs are skipped. New ones are still registered.
`OutputSplitter` already uses the same test on `_split_block` output.

**Why not `RefBundle.owns_blocks`?** That flag says whether the blocks
may be destroyed, not who made them. The shuffle, sort and
split-repartition schedulers copy it from their input onto blocks their
own reduce tasks made (`input_owned = all(b.owns_blocks for b in refs)`
at `pull_based_shuffle_task_scheduler.py:50`, used at `:145`). A filter
on that flag would drop real blocks from the counter whenever the source
is `from_*` or `materialize`, and under-report their memory. Bugbot
caught this in the first version of this PR.

### Where it came from

ray-project#64157 added `BlockRefCounter` to the operators in 2.57, and the crash
has been there since. It was reported from a Ray Train job on 2.58.0.
That job's input pipeline is `from_arrow → repartition → materialize →
randomize_block_order → map_batches → repartition → streaming_split`,
and all four splits fail at 0 rows.

## Related issues

None open. I searched ray-project/ray for open PRs and issues mentioning
`BlockRefCounter`, `owns_blocks`, `streaming_split materialized`, and
the error text "Cannot register an out-of-scope callback". Two open PRs
touch the counter: ray-project#65878 (consumer-held bytes) and ray-project#65220 (deferring
gRPC frees). Neither changes this registration path, and no open issue
tracks the crash, so this is not duplicate work.

## Additional information

**Tests.** `test_streaming_split_over_materialized_all_to_all`
reproduces the failure end to end. The two tests in `test_operators.py`
cover both sides of the check; the second fails if the check uses
`owns_blocks`, which is what the first version of this PR did.

```
$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_streaming_integration.py \
    -k test_streaming_split_over_materialized_all_to_all -q
1 passed, 25 deselected in 9.28s        # fails on master with the error above

$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_operators.py \
    python/ray/data/tests/test_randomize_block_order.py \
    python/ray/data/tests/unit/test_block_ref_counter.py \
    python/ray/data/tests/unit/test_resource_manager.py -q
29 passed in 16.10s

$ PYTHONPATH=python/ray/data/tests python -m pytest \
    python/ray/data/tests/test_streaming_integration.py -k streaming_split -q
13 passed, 13 deselected in 68.67s
```

The last command needs ray-project#66366 applied locally. On master,
`request_remaining=True` in `rate_based_cluster_autoscaler.py` raises
`TypeError: 'bool' object is not iterable` in the autoscaling
coordinator, which makes these tests flaky.

**CI.** The `buildkite/premerge` failure here is that same master bug.
All three pyrefly errors are in `rate_based_cluster_autoscaler.py`, a
file this PR does not touch. ray-project#66366 and ray-project#66370 both fix it, and this PR
is unblocked once either one lands.

**AI assistance was used** for the diagnosis, the patch, and this
description.

---------

Signed-off-by: Marwan Sarieddine <[email protected]>
Co-authored-by: Ayush Kumar <[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.

3 participants