Skip to content

[Data] [Core] [2/n] Replace manual block reference accounting with Ray Core out-of-scope callbacks - #64157

Merged
bveeramani merged 17 commits into
ray-project:masterfrom
rayhhome:callback-data-changes
Jul 2, 2026
Merged

bveeramani merged 17 commits into
ray-project:masterfrom
rayhhome:callback-data-changes

Conversation

@rayhhome

@rayhhome rayhhome commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds BlockRefCounter, which tracks per-operator object-store memory usage via CoreWorker::add_object_out_of_scope_callback (#64011). A single callback registered at block-production time fires automatically when all Python ObjectRefs and running-task argument references to that block are released.

Implementation

block_ref_counter.py. on_block_produced(ref, size_bytes, producer_id) increments _bytes_by_producer[producer_id] and registers _on_object_freed. If registration returns False (object already out of scope), the increment is immediately undone.

Tests

  • test_block_ref_counter.py: pure-Python unit tests (accounting, clear() semantics, thread safety) plus three live-cluster lifecycle tests verifying the callback fires only after the last Python ref is dropped and only after any holding task completes.

Related issues

Depends on #64011 (Ray Core: add_object_out_of_scope_callback Cython bridge).
Related to #63601 (prototype), #63074 (previous manual BlockRefCounter).

@rayhhome rayhhome self-assigned this Jun 16, 2026
Copilot AI review requested due to automatic review settings June 16, 2026 22:00
@rayhhome
rayhhome requested a review from a team as a code owner June 16, 2026 22:00
@rayhhome rayhhome added core Issues that should be addressed in Ray Core data Ray Data-related issues go add ONLY when ready to merge, run all tests and removed go add ONLY when ready to merge, run all tests labels Jun 16, 2026

@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 introduces a centralized BlockRefCounter to track object-store memory usage per operator using Ray Core out-of-scope callbacks, replacing the previous queue-size metric estimation in ResourceManager. Feedback on these changes focuses on improving robustness and preventing memory leaks. Specifically, the reviewer suggests wrapping callback registration in a try...finally block to handle potential exceptions, deleting operator keys from the tracking dictionary when their memory usage drops to zero, adding a defensive assertion to ensure producer_id is provided alongside the counter, and replacing a strict assertion in AllToAllOperator with a graceful None check to prevent test failures.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Copilot AI 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.

Pull request overview

This PR replaces per-operator manual block lifecycle bookkeeping with a centralized BlockRefCounter that relies on Ray Core “out-of-scope” callbacks to decrement object-store memory accounting when ObjectRefs become unreachable. It wires this counter through the Ray Data streaming executor, updates resource accounting to read from the counter, and adds unit/integration tests plus a nightly benchmark and release-test entry.

Changes:

  • Add BlockRefCounter (Ray Core callback-based) and register produced blocks once at production time.
  • Inject the counter into operators / DataOpTask so blocks are registered automatically on yield, and avoid double-counting forwarded refs in AllToAllOperator.
  • Update ResourceManager object-store accounting, add extensive tests, and introduce a nightly convergence benchmark + release config entry.

Reviewed changes

Copilot reviewed 15 out of 15 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
release/release_data_tests.yaml Adds a new release test entry to run the callback convergence benchmark.
release/nightly_tests/dataset/callback_latency_benchmark.py New benchmark measuring callback settle/convergence time under a burst workload.
python/ray/data/tests/unit/test_resource_manager.py Updates unit tests for union attribution behavior under the new counter model.
python/ray/data/tests/test_streaming_executor.py Updates DataOpTask tests to provide counter + producer id defaults.
python/ray/data/tests/test_resource_manager.py Refactors resource manager tests to validate counter-based accounting and union behavior.
python/ray/data/tests/test_operators.py Ensures AllToAllOperator tests inject a counter before execution.
python/ray/data/tests/test_block_ref_counter.py New unit + integration tests for callback-driven accounting and lifecycle semantics.
python/ray/data/_internal/gpu_shuffle/hash_shuffle.py Passes counter + producer id into DataOpTask for GPU shuffle extraction outputs.
python/ray/data/_internal/execution/streaming_executor.py Propagates the shared counter to all operators and clears it on shutdown.
python/ray/data/_internal/execution/resource_manager.py Switches object-store accounting to pending-task-output metrics + counter bytes per producer.
python/ray/data/_internal/execution/operators/map_operator.py Passes counter + producer id into DataOpTask for map task outputs.
python/ray/data/_internal/execution/operators/hash_shuffle.py Passes counter + producer id into DataOpTask for finalize task outputs.
python/ray/data/_internal/execution/operators/base_physical_operator.py Avoids double-counting by only registering newly-created output refs in AllToAllOperator.
python/ray/data/_internal/execution/interfaces/physical_operator.py Extends DataOpTask to carry counter + producer id and registers blocks on metadata availability; adds operator setter for counter injection.
python/ray/data/_internal/execution/block_ref_counter.py Implements the centralized callback-based per-producer byte accounting.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@rayhhome

Copy link
Copy Markdown
Contributor Author

/gemini review

@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 introduces the BlockRefCounter class to track object-store memory usage per operator via Ray Core out-of-scope callbacks, replacing the previous queue-size metrics-based estimation in ResourceManager. This counter is integrated across physical operators and the StreamingExecutor, and is supported by new unit, integration, and benchmark tests. The review feedback suggests removing an empty if TYPE_CHECKING: block and using a more specific type annotation (set[bytes]) for _registered_ids to improve type safety.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@rayhhome

Copy link
Copy Markdown
Contributor Author

/gemini review

@rayhhome rayhhome changed the title [Data] [2/n] Replace manual block reference accounting with Ray Core out-of-scope callbacks [Data] [Core] [2/n] Replace manual block reference accounting with Ray Core out-of-scope callbacks Jun 16, 2026

@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 introduces BlockRefCounter to track object-store memory usage per operator using Ray Core out-of-scope callbacks, integrating it across physical operators, resource managers, and streaming executors to replace queue-metric-based estimations. Feedback on the changes highlights a testing anti-pattern in the unit tests where production logic is duplicated instead of executing the actual on_block_produced and _on_out_of_scope methods; mocking the core_worker dependency is recommended to ensure proper test coverage.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@rayhhome

Copy link
Copy Markdown
Contributor Author

/gemini review

@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 introduces a centralized BlockRefCounter to track object-store memory usage per operator using Ray Core out-of-scope callbacks, replacing the previous queue-size metric estimations and preventing double-counting. The feedback identifies a potential memory leak in BlockRefCounter where keys in self._bytes_by_producer are not deleted when their memory usage drops to zero, and provides actionable suggestions to clean up these keys.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@rayhhome

Copy link
Copy Markdown
Contributor Author

/gemini review

@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 introduces a centralized BlockRefCounter to track object-store memory usage per operator via Ray Core's out-of-scope callbacks, replacing the previous queue-size metrics-based estimation in ResourceManager. It propagates this counter across physical operators, DataOpTask, and other execution components, and adds comprehensive unit tests and a latency benchmark. One critical issue was identified in BlockRefCounter.on_block_produced where a race condition with clear() could cause the producer's memory usage counter to go negative in the finally block; a code suggestion has been provided to resolve this.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@rayhhome

Copy link
Copy Markdown
Contributor Author

/gemini review

@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 introduces a centralized BlockRefCounter to track object-store memory usage per operator via Ray Core's out-of-scope callbacks, replacing the previous queue-size estimation metrics. Feedback on the changes suggests defensively guarding self._resource_manager in StreamingExecutor.shutdown to prevent AttributeError during early failures, iterating over the concrete output_buffer list instead of the FIFOBundleQueue in base_physical_operator.py to avoid queue consumption issues, and avoiding the use of block_ref.hex() in warning logs to prevent potential failures when mock or fake references are used in tests.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@bveeramani bveeramani self-assigned this Jun 17, 2026

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

🤩

Comment on lines +220 to +224
# Propagate the block reference counter to every operator so that
# DataOpTask.on_data_ready can call on_block_produced for each yielded block.
counter = self._resource_manager.block_ref_counter
for op in self._topology:
op.set_block_ref_counter(counter)

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.

Can we avoid doing this "set after initialization"? The optional type makes things hard to reason about.

I think I called this out in the previous PR but I forget if you gave a strong reason to do this.

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.

It was because this change would lead to many cascading operator code changes in the prototype; but this should indeed be handled in this PR. Will address this by accounting for counter initialization in start functions.

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.

To make the ref counter mandatory, there are about 35 test call sites that need to be updated. Can this be a follow-up PR since updating all these tests will complicate reviewing?

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.

This change will been applied in the follow-up PR: [3/n] #64191.

Comment on lines +461 to +462
"""Replace the per-operator default counter with the executor-wide shared one."""
self._block_ref_counter = counter

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.

This feels weird. Why is there a per-operator default counter?

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.

The default counter was supposed to be a placeholder but it's true that the function and its accompanying docstring are misleading. Moving the BlockRefCounter initialization into start to make data flow clearer.

Comment on lines -187 to -189
# Attribute iterator / streaming_split prefetch to the executor sink only.
if op is self._output_operator:
self._mem_op_outputs[op] += self._external_consumer_bytes

@justinvyu justinvyu Jun 17, 2026 •

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.

Great simplification!!! Let's make sure that "external consumer bytes" is still tracked correctly in unit tests. Instead of external_consumer_bytes, it should be lumped into final operator output bytes instead.

A reminder of why we can remove this:

  1. We don't "hand off blocks" from Data -> Train anymore after this PR. Popping off the final operator queue to send to the train worker does not remove the object store memory usage from the system, so budget backpressure stays accurate.
  2. The Train worker will eventually consume the block and delete the last object ref, which will free the object and trigger our callback. The callback decrements the object store memory usage at the correct time. No need to track external consumer bytes / report back from the Train worker explicitly.

This is the most significant simplification as well as correctness improvement that comes out of this PR.

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.

Let's add a note in the PR description that the DownstreamCapacityBackpressurePolicy still depends on the "external consumer bytes." We need to rework / remove that fully in a followup. Fine for now.

Comment on lines +67 to +73
logger.warning(
"Failed to register out-of-scope callback for block %s; "
"object-store memory for operator %s may be under-counted.",
block_ref,
producer_id,
exc_info=True,
)

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.

This is a disastrous scenario right? We will end up with "leaked" object store memory that never gets decremented, which could eventually lead to the pipeline grinding to a halt due to being at the budget limit, even though the blocks are already gone.

When do we expect the internal core api to raise, and should we instead raise here instead of warning?

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.

Upon further analysis, I think it is very unlikely for core_worker.add_object_out_of_scope_callback to raise in any realistic scenario (and if it does, something is VERY wrong with our system). Therefore, I'll remove the try-except block here entirely.

Comment on lines +43 to +46
if id_binary in self._registered_ids:
# Same block already tracked; additional RefBundle slots don't
# change memory consumption.
return

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.

When do we expect duplicate on_block_produced calls?

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.

Once the input_refs check handles the InputDataBuffer -> AllToAllOperator case, I don't think there's any realistic scenario where we track the same blocks. Will remove this check!

Comment on lines +187 to +192
# Snapshot input refs before calling bulk_fn. Some bulk_fns (e.g.
# randomize_blocks) forward input ObjectRefs unchanged to the output.
# We only call on_block_produced for genuinely new refs to avoid
# double-counting; forwarded refs stay attributed to their original producer.
input_bundles = self._input_buffer.to_list()
input_refs = {entry.ref for bundle in input_bundles for entry in bundle.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.

Is this handled by the internal registered_ids set already? I think we're double-handling this "pass through randomize_blocks" case right now.

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.

The input_refs check is to gatekeeping the specific case when the data blocks coming from a InputDataBuffer (not registered in the counter's registered_ids) gets passed into an AllToAllOperator operator that doesn't create new ObjectRefs. And I think it would not be right to register InputDataBuffer Object IDs since they represent preexisting data before execution?

self._registered_ids.add(id_binary)
self._bytes_by_producer[producer_id] += size_bytes

def _on_out_of_scope(id_bytes: bytes) -> 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.

Suggested change
def _on_out_of_scope(id_bytes: bytes) -> None:
def _on_object_freed(object_ref_id_binary: bytes) -> None:

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.

Will apply!

@rayhhome rayhhome left a comment

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.

Thanks a lot for the review! Will apply the changes accordingly; could you also check if my responses address the comments appropriately?

Comment on lines +461 to +462
"""Replace the per-operator default counter with the executor-wide shared one."""
self._block_ref_counter = counter

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.

The default counter was supposed to be a placeholder but it's true that the function and its accompanying docstring are misleading. Moving the BlockRefCounter initialization into start to make data flow clearer.

self._registered_ids.add(id_binary)
self._bytes_by_producer[producer_id] += size_bytes

def _on_out_of_scope(id_bytes: bytes) -> None:

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.

Will apply!

Comment on lines +220 to +224
# Propagate the block reference counter to every operator so that
# DataOpTask.on_data_ready can call on_block_produced for each yielded block.
counter = self._resource_manager.block_ref_counter
for op in self._topology:
op.set_block_ref_counter(counter)

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.

It was because this change would lead to many cascading operator code changes in the prototype; but this should indeed be handled in this PR. Will address this by accounting for counter initialization in start functions.

Comment on lines +67 to +73
logger.warning(
"Failed to register out-of-scope callback for block %s; "
"object-store memory for operator %s may be under-counted.",
block_ref,
producer_id,
exc_info=True,
)

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.

Upon further analysis, I think it is very unlikely for core_worker.add_object_out_of_scope_callback to raise in any realistic scenario (and if it does, something is VERY wrong with our system). Therefore, I'll remove the try-except block here entirely.

Comment on lines +187 to +192
# Snapshot input refs before calling bulk_fn. Some bulk_fns (e.g.
# randomize_blocks) forward input ObjectRefs unchanged to the output.
# We only call on_block_produced for genuinely new refs to avoid
# double-counting; forwarded refs stay attributed to their original producer.
input_bundles = self._input_buffer.to_list()
input_refs = {entry.ref for bundle in input_bundles for entry in bundle.blocks}

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.

The input_refs check is to gatekeeping the specific case when the data blocks coming from a InputDataBuffer (not registered in the counter's registered_ids) gets passed into an AllToAllOperator operator that doesn't create new ObjectRefs. And I think it would not be right to register InputDataBuffer Object IDs since they represent preexisting data before execution?

Comment on lines +43 to +46
if id_binary in self._registered_ids:
# Same block already tracked; additional RefBundle slots don't
# change memory consumption.
return

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.

Once the input_refs check handles the InputDataBuffer -> AllToAllOperator case, I don't think there's any realistic scenario where we track the same blocks. Will remove this check!

@rayhhome
rayhhome force-pushed the callback-data-changes branch from 6be9c12 to 54904a1 Compare June 17, 2026 22:28
@rayhhome

Copy link
Copy Markdown
Contributor Author

/gemini review

@justinvyu justinvyu 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! Just one last comment about a test case.

Comment on lines +143 to +150
class TestBlockRefCounterNonOwnedBlocks:
def test_non_owned_block_not_tracked(self, ray_start_regular_shared):
"""on_block_produced gracefully skips blocks not owned by this worker.

When SplitCoordinator runs a streaming executor inside an actor, the
input blocks are owned by the driver. The actor cannot register
out-of-scope callbacks on them, so on_block_produced should catch the
ValueError and leave the usage at zero.

@justinvyu justinvyu Jun 30, 2026 •

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 I don't think this "non owned blocks" is actually testing a real codepath.

I want a test that captures this instead:

[split_iter] = ds.streaming_split(1)

for batch in split_iter.iter_batches(batch_size=None): # 1 block per batch
    # assert usage includes batch
    time.sleep(X)
    del batch
    # assert usage doesn't include batch
    # NOTE: might need to change this to a while loop or something

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.

Ideally we also confirm this with a multi-node training ingest test. Assert that memory usage is accurate when borrowed object refs get freed on other nodes. We can do that in a followup.

@rayhhome rayhhome Jun 30, 2026 •

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.

I think it's not possible to add the described test here since this PR only adds the BlockRefCounter class but does not yet wire it to the operators that use it. The usage assertion step will thus only become meaningful on the next PR ([3/n] #64191). Would it be more appropriate to remove this unit test and add the real-codepath test + multi-node training ingest test in [3/n]?

(Just for documentation purpose: This test was added in commit a308595 and addresses this specific test failure on [3/n]: https://buildkite.com/ray-project/premerge/builds/68898/canvas?jid=019efcec-0454-4901-9501-730e19438028&tab=output (torch_regression_example). When the SplitCoordinator actor runs a StreamingExecutor internally, OutputSplitter.all_inputs_done() calls on_block_produced on driver-owned blocks, which raises ValueError from add_object_out_of_scope_callback.)

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.

Removed this test and the try/except block logic tested, since when externally generated refs arrive as input for the current worker, swallowing the exception and treating it as "expected" can be misleading for future development. Discussed offline and decided to not create this tech debt in the first place.

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

@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 bd9733b. Configure here.

_on_object_freed(id_binary)
return
if not registered:
_on_object_freed(id_binary)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Clear races block registration

Medium Severity

on_block_produced adds the object id and increments _bytes_by_producer under the lock, then registers the Ray callback after releasing the lock. If clear() runs in between, accounting is wiped while registration can still succeed, leaving a live object untracked in _registered_ids and reported usage at zero until it is freed.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit bd9733b. Configure here.

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.

Callback harmlessly no-ops after clear() even in the case of race, so this is not an issue.

@justinvyu justinvyu 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!

self._registered_ids.discard(id_bytes)
self._bytes_by_producer[producer_id] -= size_bytes

registered = self._add_callback_fn(block_ref, _on_object_freed)

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.

can you add a todo here about the "objects that we don't own" issue?

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.

Added!

@justinvyu
justinvyu enabled auto-merge (squash) July 2, 2026 19:58
@justinvyu
justinvyu disabled auto-merge July 2, 2026 19:58
@bveeramani
bveeramani merged commit 17b2241 into ray-project:master Jul 2, 2026
4 checks passed
@rayhhome
rayhhome deleted the callback-data-changes branch July 2, 2026 21:06
bveeramani pushed a commit that referenced this pull request Jul 3, 2026
## Description
Wires `BlockRefCounter` into every operator and the streaming executor.
`ResourceManager` gains the counter as an attribute in this PR, but
`_estimate_object_store_memory_usage` is **not changed** to keep the
scheduling-visible change isolated.
## Implementation
**`physical_operator.py`.** `PhysicalOperator.start()` now accepts
`block_ref_counter` (replaces `set_block_ref_counter()` used in
prototype per review). `DataOpTask.on_data_ready` calls
`on_block_produced` once both the block ref and its metadata are
available.
**`base_physical_operator.py`.** `AllToAllOperator.all_inputs_done`
skips `on_block_produced` for output refs that are unchanged from the
input, avoiding double-counting when `bulk_fn` forwards refs unchanged
(e.g. `randomize_blocks`).
**`streaming_executor_state.py` / `streaming_executor.py`.** Operators
are no longer started inside `build_streaming_topology`. The executor
starts them after `ResourceManager` is constructed so the shared counter
can be passed in. `block_ref_counter.clear()` is called at shutdown
after queues are drained.
**`resource_manager.py`.** Constructs `BlockRefCounter()` and exposes it
via a `block_ref_counter` property.
## Tests
- **`test_operators.py`**: updated to remove `set_block_ref_counter`
calls; adds `op.start(ExecutionOptions())` where missing.
- **`test_streaming_executor.py`**: `_make_data_op_task` helper supplies
default `block_ref_counter` and `producer_id` so existing `DataOpTask`
tests compile.
## Related issues
Depends on #64157 (`BlockRefCounter` implementation).
Related to #63601 (prototype), #63074
(previous manual `BlockRefCounter`).

---------

Signed-off-by: Sirui Huang <[email protected]>
elliot-barn pushed a commit that referenced this pull request Jul 9, 2026
…y Core out-of-scope callbacks (#64157)

## Description
Adds `BlockRefCounter`, which tracks per-operator object-store memory
usage via `CoreWorker::add_object_out_of_scope_callback`
(#64011). A single callback registered at
block-production time fires automatically when all Python `ObjectRef`s
and running-task argument references to that block are released.
## Implementation
**`block_ref_counter.py`.** `on_block_produced(ref, size_bytes,
producer_id)` increments `_bytes_by_producer[producer_id]` and registers
`_on_object_freed`. If registration returns `False` (object already out
of scope), the increment is immediately undone.
## Tests
- **`test_block_ref_counter.py`**: pure-Python unit tests (accounting,
`clear()` semantics, thread safety) plus three live-cluster lifecycle
tests verifying the callback fires only after the last Python ref is
dropped and only after any holding task completes.
## Related issues
Depends on #64011 (Ray Core:
`add_object_out_of_scope_callback` Cython bridge).
Related to #63601 (prototype), #63074
(previous manual `BlockRefCounter`).

---------

Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: elliot-barn <[email protected]>
elliot-barn pushed a commit that referenced this pull request Jul 9, 2026
## Description
Wires `BlockRefCounter` into every operator and the streaming executor.
`ResourceManager` gains the counter as an attribute in this PR, but
`_estimate_object_store_memory_usage` is **not changed** to keep the
scheduling-visible change isolated.
## Implementation
**`physical_operator.py`.** `PhysicalOperator.start()` now accepts
`block_ref_counter` (replaces `set_block_ref_counter()` used in
prototype per review). `DataOpTask.on_data_ready` calls
`on_block_produced` once both the block ref and its metadata are
available.
**`base_physical_operator.py`.** `AllToAllOperator.all_inputs_done`
skips `on_block_produced` for output refs that are unchanged from the
input, avoiding double-counting when `bulk_fn` forwards refs unchanged
(e.g. `randomize_blocks`).
**`streaming_executor_state.py` / `streaming_executor.py`.** Operators
are no longer started inside `build_streaming_topology`. The executor
starts them after `ResourceManager` is constructed so the shared counter
can be passed in. `block_ref_counter.clear()` is called at shutdown
after queues are drained.
**`resource_manager.py`.** Constructs `BlockRefCounter()` and exposes it
via a `block_ref_counter` property.
## Tests
- **`test_operators.py`**: updated to remove `set_block_ref_counter`
calls; adds `op.start(ExecutionOptions())` where missing.
- **`test_streaming_executor.py`**: `_make_data_op_task` helper supplies
default `block_ref_counter` and `producer_id` so existing `DataOpTask`
tests compile.
## Related issues
Depends on #64157 (`BlockRefCounter` implementation).
Related to #63601 (prototype), #63074
(previous manual `BlockRefCounter`).

---------

Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: elliot-barn <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…y Core out-of-scope callbacks (ray-project#64157)

## Description
Adds `BlockRefCounter`, which tracks per-operator object-store memory
usage via `CoreWorker::add_object_out_of_scope_callback`
(ray-project#64011). A single callback registered at
block-production time fires automatically when all Python `ObjectRef`s
and running-task argument references to that block are released.
## Implementation
**`block_ref_counter.py`.** `on_block_produced(ref, size_bytes,
producer_id)` increments `_bytes_by_producer[producer_id]` and registers
`_on_object_freed`. If registration returns `False` (object already out
of scope), the increment is immediately undone.
## Tests
- **`test_block_ref_counter.py`**: pure-Python unit tests (accounting,
`clear()` semantics, thread safety) plus three live-cluster lifecycle
tests verifying the callback fires only after the last Python ref is
dropped and only after any holding task completes.
## Related issues
Depends on ray-project#64011 (Ray Core:
`add_object_out_of_scope_callback` Cython bridge).
Related to ray-project#63601 (prototype), ray-project#63074
(previous manual `BlockRefCounter`).

---------

Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: 400Ping <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…64191)

## Description
Wires `BlockRefCounter` into every operator and the streaming executor.
`ResourceManager` gains the counter as an attribute in this PR, but
`_estimate_object_store_memory_usage` is **not changed** to keep the
scheduling-visible change isolated.
## Implementation
**`physical_operator.py`.** `PhysicalOperator.start()` now accepts
`block_ref_counter` (replaces `set_block_ref_counter()` used in
prototype per review). `DataOpTask.on_data_ready` calls
`on_block_produced` once both the block ref and its metadata are
available.
**`base_physical_operator.py`.** `AllToAllOperator.all_inputs_done`
skips `on_block_produced` for output refs that are unchanged from the
input, avoiding double-counting when `bulk_fn` forwards refs unchanged
(e.g. `randomize_blocks`).
**`streaming_executor_state.py` / `streaming_executor.py`.** Operators
are no longer started inside `build_streaming_topology`. The executor
starts them after `ResourceManager` is constructed so the shared counter
can be passed in. `block_ref_counter.clear()` is called at shutdown
after queues are drained.
**`resource_manager.py`.** Constructs `BlockRefCounter()` and exposes it
via a `block_ref_counter` property.
## Tests
- **`test_operators.py`**: updated to remove `set_block_ref_counter`
calls; adds `op.start(ExecutionOptions())` where missing.
- **`test_streaming_executor.py`**: `_make_data_op_task` helper supplies
default `block_ref_counter` and `producer_id` so existing `DataOpTask`
tests compile.
## Related issues
Depends on ray-project#64157 (`BlockRefCounter` implementation).
Related to ray-project#63601 (prototype), ray-project#63074
(previous manual `BlockRefCounter`).

---------

Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: 400Ping <[email protected]>
marwan116 added a commit to marwan116/ray that referenced this pull request 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]>
matthewdeng pushed a commit that referenced this pull request Sep 22, 2026
… from input to output (#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

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

---------

Signed-off-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) (#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

core Issues that should be addressed in Ray Core 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.

4 participants