Skip to content

[Data] [Core] [4/n] Switch ResourceManager OSM Estimation to use BlockRefCounter - #64192

Closed
rayhhome wants to merge 7 commits into
ray-project:masterfrom
rayhhome:block-ref-counter-resource
Closed

rayhhome wants to merge 7 commits into
ray-project:masterfrom
rayhhome:block-ref-counter-resource

Conversation

@rayhhome

Copy link
Copy Markdown
Contributor

Description

Switches ResourceManager._estimate_object_store_memory_usage to read from BlockRefCounter, replacing the manual op.estimate_object_store_usage(state) path. This is the only change visible to the scheduler; over- or under-counts here cascade into backpressure and OOM/spill decisions.

Implementation

resource_manager.py. _estimate_object_store_memory_usage reads _block_ref_counter.get_object_store_memory_usage(op.id) for output bytes instead of calling op.estimate_object_store_usage(state).

Elimination of explicit external-consumer-bytes tracking

Previously, handing a block to a Train worker required an explicit set_external_consumer_bytes call from the Train-side iterator to keep the memory budget accurate. With callback-based tracking this is no longer needed: the Train worker holds an ObjectRef, so the bytes remain attributed until the worker drops the ref and the callback fires.
Note: DownstreamCapacityBackpressurePolicy still reads _external_consumer_bytes for its own flow-control logic. Removing that dependency is a follow-up.

Tests

  • test_resource_manager.py and unit/test_resource_manager.py: updated to validate _estimate_object_store_memory_usage against callback-based accounting.

Related issues

Depends on #64191 (operator wiring).
Related to #63601 (prototype), #63074 (previous manual BlockRefCounter).

@rayhhome rayhhome self-assigned this Jun 17, 2026
Copilot AI review requested due to automatic review settings June 17, 2026 22:44
@rayhhome
rayhhome requested a review from a team as a code owner June 17, 2026 22:44
@rayhhome rayhhome added core Issues that should be addressed in Ray Core data Ray Data-related issues labels Jun 17, 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-based estimation. This counter is integrated across physical operators, tasks, the resource manager, and the streaming executor, with corresponding updates to the test suite. The review feedback suggests several improvements to make the implementation more robust: preventing double-counting and memory leaks by ignoring duplicate block registrations, defensively ensuring memory usage values do not drop below zero, initializing the operator's block reference counter to a default instance in __init__ to avoid AttributeErrors during testing, and adding a unit test to verify duplicate registration handling.

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 switches Ray Data streaming execution’s object-store memory estimation from per-operator queue/metric-based estimates to centralized, callback-driven accounting via a new BlockRefCounter. This affects scheduler backpressure and spill/OOM decisions by changing how live block bytes are attributed and summed across the pipeline.

Changes:

  • Introduce BlockRefCounter (Ray Core out-of-scope callbacks) and wire ResourceManager._estimate_object_store_memory_usage() to read per-producer bytes from it.
  • Thread an executor-wide BlockRefCounter through PhysicalOperator.start() and into DataOpTask, registering produced blocks as they are yielded.
  • Update and extend tests to validate callback-based accounting, including a new test_block_ref_counter.py target and updated ResourceManager/streaming-executor tests.

Reviewed changes

Copilot reviewed 18 out of 18 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 the centralized ref-counting byte tracker built on Ray Core callbacks.
python/ray/data/_internal/execution/resource_manager.py Switches object store memory estimation to use BlockRefCounter.
python/ray/data/_internal/execution/streaming_executor.py Starts all operators with the shared counter and clears it on shutdown.
python/ray/data/_internal/execution/streaming_executor_state.py Removes operator start() from state setup (moved to executor).
python/ray/data/_internal/execution/interfaces/physical_operator.py Extends PhysicalOperator.start() signature; extends DataOpTask to register produced blocks.
python/ray/data/_internal/execution/operators/map_operator.py Passes counter/producer into DataOpTask; updates start() signature.
python/ray/data/_internal/execution/operators/hash_shuffle.py Updates start() signature; passes counter/producer into finalizing tasks.
python/ray/data/_internal/execution/operators/base_physical_operator.py Avoids double-counting forwarded refs by only registering genuinely new output refs.
python/ray/data/_internal/execution/operators/input_data_buffer.py Updates start() signature to accept the shared counter.
python/ray/data/_internal/execution/operators/union_operator.py Updates start() signature to accept the shared counter.
python/ray/data/_internal/execution/operators/output_splitter.py Updates start() signature to accept the shared counter.
python/ray/data/_internal/execution/operators/actor_pool_map_operator.py Updates start() signature to accept the shared counter.
python/ray/data/tests/test_block_ref_counter.py Adds unit + lifecycle/integration coverage for callback behavior and races.
python/ray/data/BUILD.bazel Adds Bazel py_test target for test_block_ref_counter.
python/ray/data/tests/test_resource_manager.py Updates ResourceManager tests to validate counter-based accounting and union attribution.
python/ray/data/tests/unit/test_resource_manager.py Adjusts unit tests to seed counter attribution directly for union cases.
python/ray/data/tests/test_streaming_executor.py Updates DataOpTask construction in tests with a helper that supplies counter/producer.
python/ray/data/tests/test_operators.py Ensures operators are started in tests where required by new lifecycle.

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

@rayhhome
rayhhome force-pushed the block-ref-counter-resource branch from a2cd22a to 6251039 Compare June 18, 2026 00:17
Comment on lines +187 to +190
# 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Would it make sense/be simpler to make on_block_produced idempotent?

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.

Made on_block_produced idempotent on dependent PRs.

return self._external_consumer_bytes
return 0

usage = op.estimate_object_store_usage(state)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Is this dead code now? If so, let's remove it?

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!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@@ -180,15 +188,16 @@ def _estimate_object_store_memory_usage(
return self._external_consumer_bytes

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

In follow up, I think we should nuke _external_consumer_bytes and clean up DownstreamCapacityBackpressurePolicy

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 can make the follow up PR [5/n] of the stack PR. Will start working on it once Ray Core callback wiring is integrated and we can start running actual tests. Will post the PR link here when it's up.

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.

[5/n] is here: #64456.

@ray.remote(num_cpus=1)
def _hold_block(block_ref, sleep_s: float) -> None:
"""Hold block_ref as a task argument for sleep_s seconds, then return."""
import time as _time

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Huh? Can't we regular time imported at the top?

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.

Forgot to change this; applied in new commit.

type=int,
default=100,
help="Number of concurrent tasks / blocks in the burst. "
"Latency scales with this value (RC mutex serializes callbacks); "

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What is RC? Can you write it out in the help

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.

RC is just ReferenceCounter and is what I used for my own documentation tracking; replaced this with the full name ReferenceCounter.

Comment thread release/release_data_tests.yaml Outdated
cluster_compute: fixed_size_100_cpu_compute.yaml

run:
timeout: 1800

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This seems way too long given that the convergence timeout is like 30s

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.

Cutting this down to 300s. Will bump it up if it actually runs longer than this after actual executing on CI.

Comment on lines +213 to +214
Object-store memory is now tracked via BlockRefCounter (one counter shared
across the whole execution), NOT via queue-size metrics. Each operator's

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

"Object-store memory is now tracked via BlockRefCounter, NOT via queue-size metrics"

I think you can either drop all of the docstring changes or drop the comparison to queue-size metrics.

The comment makes sense in the context of this PR, but won't make sense when someone reads it 2 years from 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.

Removed implementation specific docstrings.

Comment on lines +262 to +269

# Seed the counter so each eligible op reports its expected counter bytes.
for op in [o2, o3]:
if mock_counter_bytes[op]:
resource_manager.block_ref_counter._bytes_by_producer[
op.id
] = mock_counter_bytes[op]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I know these tests already heavily break abstraction barriers, but at least for this new part we're adding I think we should avoid doing that.

In specific, rather than mutating internal attributes, I think we could create a stub implementation. Could look like this:

class BaseBlockRefCounter(abc.ABC)
    @abc.abstractmethod
    def on_block_produced(...):
        ...

    ... # etc


# In test file
class StubBlockRefCounter(BaseBlockRefCounter):
    def __init__(self, bytes_by_producer):
         self._bytes_by_producer = bytes_by_producer

    def on_block_produced(self, ...):
        pass. # No-op. Just uses the specificed values

    def get_object_store_memory_usage(...):
         return self._bytes_by_producer.get(producer_id)

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.

Makes sense. Applied to avoid testing specific implementation.

Comment on lines +300 to +303
Memory is attributed to the operator that called on_block_produced and
released automatically via the Ray Core out-of-scope callback. This test
drives the counter directly (bypassing Ray Core) to verify the integration
between ResourceManager._estimate_object_store_memory_usage and the counter.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can we avoid documenting too much of the implementation details in the tests and keep the tests focused on the high-level behavior under test?

This kind of stuff goes stale over time

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.

Condense the docstrings to give only high-level explanations.

Comment on lines +330 to +332
with counter._lock:
counter._registered_ids.add(fake_id1)
counter._bytes_by_producer[o2.id] += 100

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This will be super brittle.

Similar to above, could we create some sort of fake BlockRefCounter implementation instead?

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.

Used the StubBlockRefCounter approach!

@rayhhome
rayhhome force-pushed the block-ref-counter-resource branch from 6251039 to 8a9caaf Compare June 23, 2026 01:29

@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 all comments; also, would it be helpful to rebase this and all previous PRs on top of #64011? It would allow for running and passing microcheck, premerge, and release tests.

@ray.remote(num_cpus=1)
def _hold_block(block_ref, sleep_s: float) -> None:
"""Hold block_ref as a task argument for sleep_s seconds, then return."""
import time as _time

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.

Forgot to change this; applied in new commit.

type=int,
default=100,
help="Number of concurrent tasks / blocks in the burst. "
"Latency scales with this value (RC mutex serializes callbacks); "

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.

RC is just ReferenceCounter and is what I used for my own documentation tracking; replaced this with the full name ReferenceCounter.

Comment on lines +187 to +190
# 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.

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.

Made on_block_produced idempotent on dependent PRs.

return self._external_consumer_bytes
return 0

usage = op.estimate_object_store_usage(state)

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!

@@ -180,15 +188,16 @@ def _estimate_object_store_memory_usage(
return self._external_consumer_bytes

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 can make the follow up PR [5/n] of the stack PR. Will start working on it once Ray Core callback wiring is integrated and we can start running actual tests. Will post the PR link here when it's up.

Comment thread release/release_data_tests.yaml Outdated
cluster_compute: fixed_size_100_cpu_compute.yaml

run:
timeout: 1800

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.

Cutting this down to 300s. Will bump it up if it actually runs longer than this after actual executing on CI.

)

return {
"callback_settle_time_s": round(settle_time_s, 4),

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 don't yet have the exact settle time now since this PR depends on the Ray Core callback wiring PR. A close estimate would be the oos_callback_fire_batch microbenchmark on #64011. Running it now and will post the result here.

Also, would it be more helpful for me to stack the three Data side PRs on the Ray Core PR? Then I'll be able to run this benchmark.

Comment on lines +213 to +214
Object-store memory is now tracked via BlockRefCounter (one counter shared
across the whole execution), NOT via queue-size metrics. Each operator's

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 implementation specific docstrings.

Comment on lines +262 to +269

# Seed the counter so each eligible op reports its expected counter bytes.
for op in [o2, o3]:
if mock_counter_bytes[op]:
resource_manager.block_ref_counter._bytes_by_producer[
op.id
] = mock_counter_bytes[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.

Makes sense. Applied to avoid testing specific implementation.

Comment on lines +330 to +332
with counter._lock:
counter._registered_ids.add(fake_id1)
counter._bytes_by_producer[o2.id] += 100

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.

Used the StubBlockRefCounter approach!

@rayhhome
rayhhome force-pushed the block-ref-counter-resource branch from 816b626 to 3b47c89 Compare June 23, 2026 01:46
@rayhhome
rayhhome requested a review from a team as a code owner June 23, 2026 01:46
@rayhhome
rayhhome force-pushed the block-ref-counter-resource branch from 3b47c89 to 8beb993 Compare June 23, 2026 01:52
return self._external_consumer_bytes
return 0

usage = op.estimate_object_store_usage(state)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@bveeramani

Copy link
Copy Markdown
Member

If you haven't already, can you also confirm that the release test passes?

Also, seems a bit weird that we're adding the convergence release test in this PR. Think it'd make more sense to add to either 2/n or as a followup. Doesn't seem directly related to ResourceManager

@rayhhome
rayhhome force-pushed the block-ref-counter-resource branch from 8beb993 to e096219 Compare June 25, 2026 02:49
@rayhhome
rayhhome requested a review from a team as a code owner June 25, 2026 02:49
@rayhhome
rayhhome force-pushed the block-ref-counter-resource branch from e096219 to 47c4df0 Compare June 25, 2026 03:39
@rayhhome
rayhhome force-pushed the block-ref-counter-resource branch 5 times, most recently from 1936a69 to e21d710 Compare June 26, 2026 23:04

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

@rayhhome
rayhhome force-pushed the block-ref-counter-resource branch 2 times, most recently from 2edfb95 to addb218 Compare June 29, 2026 22:54
@rayhhome rayhhome added the go add ONLY when ready to merge, run all tests label Jun 29, 2026
@rayhhome
rayhhome force-pushed the block-ref-counter-resource branch from 7c44e26 to 7c51eb5 Compare June 30, 2026 20:15
@rayhhome
rayhhome force-pushed the block-ref-counter-resource branch 2 times, most recently from 09f8964 to 4527361 Compare July 2, 2026 21:21
@rayhhome
rayhhome force-pushed the block-ref-counter-resource branch from 4527361 to 26784b7 Compare July 3, 2026 05:37
@bveeramani bveeramani self-assigned this Jul 6, 2026
Comment on lines -425 to -427
def estimate_object_store_usage(self, state) -> ObjectStoreUsage:
return ObjectStoreUsage(internal=0, outputs=0)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

On second review, I remember that this was a performance optimization You-Cheng added.

To avoid adding a regression, should we reintroduce PhysicalOperator.estimate_object_store_usage and keep this override? The base PhysicalOperator.estimate_object_store_usage implementation could use BlockRefCounter.get_object_store_memory_usage similar to how we're currently doing

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.

Good catch; applied on [5/n].

Comment on lines +158 to +160
# Blocks are attributed to their original producer, not union_op.
counter.set_usage(input1.id, 1)
counter.set_usage(input2.id, 1)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

For the tests in this file -- would it make sense to just directly call on_block_produced since it's an actual public method, rather than this test-only set_usage method?

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.

Switched to using on_block_produced to better reflect actual class usage.


assert completed_ops_usage == ExecutionResources(cpu=8, object_store_memory=400)

def test_external_consumer_bytes_attributed_to_terminal_operator(

@bveeramani bveeramani Jul 7, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we still need test that bytes taken from the DAG but haven't been freed are still accounted for/is there another test for 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.

We no longer attribute _external_consumer_bytes to get_op_usage() so the original test would fail. BlockRefCounter now tracks total byte usage automatically via live ObjectRefs, so I think test_object_store_usage covers the general case.

Added a reverse test on [5/n] test_external_consumer_bytes_not_double_counted to ensure that all bytes are accounted for but not double counted (the external consumer bytes in particular).

Comment on lines +39 to +47
class StubBlockRefCounter(BlockRefCounter):
"""Test double for BlockRefCounter with directly settable per-operator usage."""

def __init__(self):
super().__init__(add_object_out_of_scope_callback=lambda *_: True)

def set_usage(self, producer_id: str, bytes: int) -> None:
self._bytes_by_producer[producer_id] = bytes

@bveeramani bveeramani Jul 7, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nit: Rather than assuming BlockRefCounter has an attribute named _bytes_by_producer, should we just stub the entire interface? Would be more robust since you don't have to make assumptions about the implementation

class StubBlockRefCounter(BlockRefCounter):

    def __init__(self):
        self._bytes_by_producer = defaultdict(int)

    def on_block_produced(
        self,
        block_ref: "ray.ObjectRef",
        size_bytes: int,
        producer_id: str,
    ) -> None:
       self._bytes_by_producer[producer_id] += size_bytes

    def get_object_store_memory_usage(self, producer_id: str) -> int:
            return self._bytes_by_producer[producer_id]

    def set_object_store_memory_usage(self, producer_id: str, nbytes: int) -> None:
            self._bytes_by_producer[producer_id] = nbytes

    def clear(self) -> None:
        self._bytes_by_producer.clear()

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.

Applied on [5/n]!

@rayhhome

Copy link
Copy Markdown
Contributor Author

Closing this after discussing offline since we'll need to address BlockRefCounter's impact on DownstreamCapacityBackpressurePolicy together with the ResourceManager. Continuing on [5/n]: #64456.

@rayhhome rayhhome closed this Jul 10, 2026
@rayhhome
rayhhome deleted the block-ref-counter-resource branch October 19, 2026 16:41
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.

3 participants