Skip to content

[Data] Track Object-store Memory with Centralized BlockRefCounter - #63074

Closed
rayhhome wants to merge 35 commits into
ray-project:masterfrom
rayhhome:ray-huang/union-memory-attribution-v3
Closed

rayhhome wants to merge 35 commits into
ray-project:masterfrom
rayhhome:ray-huang/union-memory-attribution-v3

Conversation

@rayhhome

@rayhhome rayhhome commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Description

Before this PR, ResourceManager.get_op_usage() estimated output-buffer memory by summing size_bytes from BlockMetadata on queued RefBundles — unreliable since metadata can be stale, zero-initialized, or missing.

This PR introduces BlockRefCounter, which tracks the actual ray.ObjectRef-to-(size_bytes, owner_op) mapping for every live block in the pipeline. ResourceManager._estimate_object_store_memory_usage now reads from the counter instead of summing queue metadata.

This is also a prerequisite for a follow-up PR making UnionOperator ineligible for resource budgeting.

How it works

Each block follows a three-step lifecycle:

  • on_block_produced (ref_count=1)
  • on_block_dispatched_to_task (increments ref_count on subsequent dispatches for strict repartition)
  • on_task_completed (decrements ref_count; removes block when it hits zero)

Two helpers on PhysicalOperator — _track_bundle_produced and _track_bundle_consumed — wrap these calls for full RefBundles. The counter is created in ResourceManager.__init__, injected into every operator in StreamingExecutor.execute(), and blocks exiting the pipeline are untracked in _ClosingIterator.get_next().

Operator-specific fixes

  • AggregateNumRows — input blocks consumed in-place were never untracked, and the ray.put output block was never registered. Fixed in _add_input_inner and _get_next_inner.

  • OutputSplitter — _split_block() produces new ObjectRefs that were never registered, the split original was never untracked, and equal=True truncation remainder blocks were never untracked before buffer clear. Fixed by adding _track_bundle_split and untracking remainder blocks before clear_internal_input_queue().

  • HashShufflingOperatorBase — _on_partitioning_done (defined in a for-loop over blocks) was never calling on_task_completed. Fixed by passing block_ref via functools.partial, avoiding the loop-closure problem. HashAggregateOperator and JoinOperator inherit this fix.

  • All other operators — MapOperator (and its subclasses), AllToAllOperator, LimitOperator, ZipOperator, and InputDataBuffer were already correctly wired: task-produced blocks are registered via DataOpTask.on_data_ready, inputs are untracked in task-done callbacks or all_inputs_done, and UnionOperator needs no tracking as a pure passthrough.

Related issues

Related to #62277 (prior attempt using a different method).

Additional information

Tests added:

  • test_block_ref_counter.py — unit tests for the full counter lifecycle (no Ray required).
  • test_resource_manager.py — strengthened with real TaskMetrics fields; covers counter exclusion, cleanup cycle, mem_op_internal/mem_op_outputs coexistence, and strict repartition.
  • test_output_splitter.py — TestOutputSplitterBlockRefCounter: three _track_bundle_split cases and one all_inputs_done truncation test.

@rayhhome rayhhome self-assigned this May 1, 2026
Copilot AI review requested due to automatic review settings May 1, 2026 17:47
@rayhhome rayhhome added the data Ray Data-related issues label May 1, 2026
@rayhhome
rayhhome requested a review from a team as a code owner May 1, 2026 17:47

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 ResourceManager’s object-store memory estimation (previously based on potentially stale/missing BlockMetadata.size_bytes on queued RefBundles) with a centralized BlockRefCounter that tracks live block ObjectRef sizes and producing operators, and updates per-operator memory accounting accordingly.

Changes:

  • Introduces BlockRefCounter and wires it through StreamingExecutor, ResourceManager, DataOpTask, and multiple operators to register/unregister blocks as they’re produced/consumed.
  • Updates object-store memory estimation to use the centralized counter (plus pending task output bytes), and untracks blocks as they exit the pipeline.
  • Adds/updates unit tests to validate counter lifecycle and OutputSplitter/ResourceManager integration.

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
python/ray/data/_internal/execution/block_ref_counter.py Adds centralized ref-counted tracking of live block bytes by producing operator.
python/ray/data/_internal/execution/interfaces/physical_operator.py Adds counter plumbing to DataOpTask and helper methods on PhysicalOperator to track produced/consumed bundles.
python/ray/data/_internal/execution/resource_manager.py Switches object-store usage estimation to use BlockRefCounter + pending task output bytes.
python/ray/data/_internal/execution/streaming_executor.py Injects the counter into all operators and untracks blocks as they are returned to the user iterator.
python/ray/data/_internal/execution/operators/base_physical_operator.py Tracks produced bulk outputs and untracks bulk inputs for AllToAllOperator.
python/ray/data/_internal/execution/operators/map_operator.py Tracks dispatch-to-task and consumption of task inputs; passes counter into DataOpTask.
python/ray/data/_internal/execution/operators/hash_shuffle.py Fixes closure capture and untracks shuffle input blocks on task completion; passes counter into DataOpTask finalization.
python/ray/data/_internal/execution/operators/output_splitter.py Adds split tracking for newly created refs and untracks truncated remainder refs.
python/ray/data/_internal/execution/operators/zip_operator.py Tracks produced zip outputs and untracks consumed zip inputs.
python/ray/data/_internal/execution/operators/limit_operator.py Tracks newly produced sliced block refs and untracks dropped (non-forwarded) inputs.
python/ray/data/_internal/execution/operators/input_data_buffer.py Registers blocks yielded from the input buffer with the counter.
python/ray/data/_internal/execution/operators/aggregate_num_rows.py Untracks in-place consumed inputs and tracks the produced output block.
python/ray/data/tests/test_block_ref_counter.py New unit tests for ref counter lifecycle/refcount semantics.
python/ray/data/tests/test_resource_manager.py Updates tests to validate mem_op_internal vs mem_op_outputs behavior using the counter.
python/ray/data/tests/test_output_splitter.py Adds unit tests for OutputSplitter’s counter integration and truncation untracking.

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

Comment on lines +183 to +193
# NOTE: We don't account object store memory use from intermediate `bulk_fn`
# outputs (e.g., map outputs for map-reduce).
output_buffer, self._stats = self._bulk_fn(self._input_buffer.to_list(), ctx)
for bundle in output_buffer:
self._track_bundle_produced(bundle)
self._output_buffer = FIFOBundleQueue(output_buffer)

while self._input_buffer.has_next():
refs = self._input_buffer.get_next()
self._metrics.on_input_dequeued(refs, input_index=0)
self._track_bundle_consumed(refs)

Copilot AI May 1, 2026

Copy link

Choose a reason for hiding this comment

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

AllToAllOperator.all_inputs_done() now unconditionally calls _track_bundle_produced() on every output bundle and _track_bundle_consumed() on every input bundle. This will assert/crash for AllToAll transforms that forward existing block ObjectRefs (e.g., randomize_blocks shuffles RefBundles but reuses the same block refs), because on_block_produced will be called for already-tracked refs and then inputs will be untracked even though the same refs are still live in outputs. Consider diffing input vs output refs: only call on_block_produced for new refs not present in inputs, and only call on_task_completed for input refs that are not forwarded into outputs (leave forwarded refs attributed to their original producer).

Suggested change
# NOTE: We don't account object store memory use from intermediate `bulk_fn`
# outputs (e.g., map outputs for map-reduce).
output_buffer, self._stats = self._bulk_fn(self._input_buffer.to_list(), ctx)
for bundle in output_buffer:
self._track_bundle_produced(bundle)
self._output_buffer = FIFOBundleQueue(output_buffer)
while self._input_buffer.has_next():
refs = self._input_buffer.get_next()
self._metrics.on_input_dequeued(refs, input_index=0)
self._track_bundle_consumed(refs)
input_bundles = self._input_buffer.to_list()
input_block_refs = {
block_ref
for bundle in input_bundles
for block_ref, _ in bundle.blocks
}
# NOTE: We don't account object store memory use from intermediate `bulk_fn`
# outputs (e.g., map outputs for map-reduce).
output_buffer, self._stats = self._bulk_fn(input_bundles, ctx)
output_block_refs = {
block_ref
for bundle in output_buffer
for block_ref, _ in bundle.blocks
}
for bundle in output_buffer:
bundle_block_refs = {block_ref for block_ref, _ in bundle.blocks}
if bundle_block_refs.isdisjoint(input_block_refs):
self._track_bundle_produced(bundle)
self._output_buffer = FIFOBundleQueue(output_buffer)
while self._input_buffer.has_next():
refs = self._input_buffer.get_next()
self._metrics.on_input_dequeued(refs, input_index=0)
refs_block_refs = {block_ref for block_ref, _ in refs.blocks}
if refs_block_refs.isdisjoint(output_block_refs):
self._track_bundle_consumed(refs)

Copilot uses AI. Check for mistakes.

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.

Great catch! randomize_blocks seems to be the only bulk function that would introduce this problem. Currently, applying the suggested change to control the scope of this PR, but, in a future PR, we should let the bulk functions own a distinct property that states whether it reuses the same refs or not.

@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 for Ray Data blocks. It replaces the previous estimation logic in the ResourceManager with an incremental tracking system that attributes memory usage to the producing PhysicalOperator. The counter is integrated across various operators, including Map, Zip, Limit, and HashShuffle, to monitor block lifecycles from production to task completion. Unit tests for the new counter and updated integration tests for the resource manager and output splitter are included. I have no feedback to provide.

rayhhome added 4 commits May 5, 2026 17:15
…t ownership + track id instead of full op + Rename on_task_completed to on_block_released

Signed-off-by: Sirui Huang <[email protected]>

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

Addressed issues pointed out in the previous review!


This means:
- blocks in queues (not yet dispatched): counted once toward their owner
- blocks held by N concurrent tasks (strict repartition): counted once

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.

Sorry for the ambiguous comment; the "counted once" was supposed to indicate size_bytes only counted once even with N concurrent tasks. Improved the description in the new commit.

Comment on lines +286 to +289
if self._block_ref_counter is not None:
self._block_ref_counter.on_block_produced(
self._pending_block_ref, meta.size_bytes or 0, self._owner_op
)

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's possible to put it inside the task callbacks. However, since map_operator, execution/operators/hash_shuffle, gpu_shuffle/hash_shuffle each has their own callbacks, we'll have to repeat this code block for all of them if we want to make the change.

I think the tradeoff here is OpTasks's being conceptually clean versus code repetition + future-proof failsafe. What your take on this?

Comment on lines +195 to +199
# Snapshot input refs before calling bulk_fn. Some bulk_fns (e.g.
# randomize_blocks) reuse input ObjectRefs unchanged — diffing against
# output_refs prevents double-registering already-tracked refs and
# incorrectly untracking forwarded refs.
input_refs = {ref for bundle in self._input_buffer for ref, _ 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.

Yea, currently randomize_blocks is the only bulk_fn that reuses input ObjectRefs. Initially I considered using an additional flag for AllToAllOperator, but eventually ruled against integrating it now because it was a relatively large change and not directly needed for this PR.

Do we want to do this as a followup? The current code does not self-document and this might lead to mistakes when future developers add new bulk functions.

# references, and Ray won't be able to reconstruct downstream objects.
bundle = self._input_data[self._input_data_index]
self._input_data_index += 1
self._track_bundle_produced(bundle)

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.

We also need this for the correctness of block lifecycles: when on_task_completed is called on downstream operators, it asserts that the block exists in _entries. To make this true, we need to call on_block_produced for InputDataBuffer first.

Added a comment to make this more straightforward.

Comment on lines +58 to +68
Sets ref_count = 1 on the first call. Duplicate calls for the same
ObjectRef (e.g. from_pandas_refs([ref, ref])) increment ref_count and
queue_holds without double-counting size_bytes.
"""
with self._lock:
if block_ref in self._entries:
entry = self._entries[block_ref]
entry.ref_count += 1
entry.queue_holds += 1
return
self._entries[block_ref] = _BlockEntry(

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's true that when a block gets produced, its ref_count starts off as 1 because we are considering the queue as a holder of this block. This is to maintain the following invariant: a block can be released once its refcount hits 0. There are a few operators (such as LimitOperator and OutputSplitter) that can drop blocks from a queue before it was dispatched. By starting ref_count at 1 (counting the queue slot as a holder), on_block_released can handle both task completions and queue drops through the same path: the entry is removed whenever ref_count reaches 0.

Meanwhile, queue_holds counts how many queue slots currently hold the block ref, and ref_count - queue_holds gives the number of in-flight task references. The total ref_count is thus the sum of both.

Comment on lines +58 to +68
Sets ref_count = 1 on the first call. Duplicate calls for the same
ObjectRef (e.g. from_pandas_refs([ref, ref])) increment ref_count and
queue_holds without double-counting size_bytes.
"""
with self._lock:
if block_ref in self._entries:
entry = self._entries[block_ref]
entry.ref_count += 1
entry.queue_holds += 1
return
self._entries[block_ref] = _BlockEntry(

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.

Based on the above logic, if we are to apply the approach of filtering duplicate blocks out, we'll need a separate path (e.g. on_block_drop_from_queue) to handle this edge case, because even with ref_count = 1, on_block_released will be called twice because there are two references to the same block because it's called once per bundle.

There are some alternatives:

  • No-op in on_block_released when ref_count hits 0: works, but does hide actual double-release bugs.

  • New on_block_drop_from_queue method: there's another edge case--when two bundles hold the same block reference, and one drops before the other one dispatches, ref_count = 0 would hit 0 before the second bundle is able to dispatch. This means we'll need mechanism to track if there are other entities still holding the block (which queue_holds does). In this case, we only made the logic more complex compared to what we have.

  • Deduplication in _track_bundle_consumed: two bundles holding the same block call _track_bundle_consumed separately, so it doesn't resolve the edge case for InputDataBuffer ([b1][b1]).

Not sure if there are other better alternatives, but these are all that I can think of right now.

# operator's output usage.
self._output_operator = terminal_operator_from_topology(topology)

self._block_ref_counter = BlockRefCounter()

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.

ResourceManager is created after physical operator construction time. If we're to pass it at physical operator construction time, we have to move it into planner, which is out of scope of this PR. This change is worth doing since it removes None guards and makes it explicit which operator depends on it, but should be deferred to a later PR.

Comment on lines +194 to +196
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.

Comment on lines +419 to +420
# Strict repartition: the same block is dispatched to two downstream tasks.
# The block must remain live (and attributed to o2) until BOTH tasks complete.

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.

Yes, this is the only place where slices of the same underlying block are used across tasks. on_block_queue_slot_added is added to handle this edge case. Other operators with similar behaviors (such as OutputSplitter) still launches tasks to materialize new ObjectRefs for the splits.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 63b4c9c. Configure here.

counter = resource_manager.block_ref_counter
mock_counter_bytes[o1] = 999 # non-zero to actually exercise the exclusion
for op, size in mock_counter_bytes.items():
counter.on_block_produced(object(), size, op)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Tests register blocks with operator object instead of operator id

High Severity

counter.on_block_produced(object(), size, op) passes the operator object as producer_id, but _estimate_object_store_memory_usage queries with op.id (a UUID string). Since these keys don't match, get_object_store_memory_usage always returns 0, causing the test assertions (which expect mock_counter_bytes[op] to be included) to fail.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 63b4c9c. Configure here.

self.counter.on_block_produced(ref, 100, self.op)
self.counter.on_block_released(ref)
with pytest.raises(AssertionError, match="double completion"):
self.counter.on_block_released(ref)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Test match pattern doesn't match actual error message

Medium Severity

pytest.raises(AssertionError, match="double completion") won't match the actual error message which contains "double release". The assertion is raised correctly but pytest will fail because the regex pattern doesn't match the exception text.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 63b4c9c. Configure here.

@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label May 23, 2026
@github-actions

github-actions Bot commented Jun 6, 2026

Copy link
Copy Markdown

This pull request has been automatically closed because there has been no more activity in the 14 days
since being marked stale.

Please feel free to reopen or open a new pull request if you'd still like this to be addressed.

Again, you can always ask for help on our discussion forum or Ray's public slack channel.

Thanks again for your contribution!

@rayhhome

Copy link
Copy Markdown
Contributor Author

This PR was closed in favor of #63601.

@rayhhome
rayhhome deleted the ray-huang/union-memory-attribution-v3 branch June 29, 2026 23:34
bveeramani pushed a commit that referenced this pull request Jul 2, 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]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants