Repository navigation
Conversation
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 wireResourceManager._estimate_object_store_memory_usage()to read per-producer bytes from it. - Thread an executor-wide
BlockRefCounterthroughPhysicalOperator.start()and intoDataOpTask, registering produced blocks as they are yielded. - Update and extend tests to validate callback-based accounting, including a new
test_block_ref_counter.pytarget 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.
a2cd22a to
6251039
Compare
| # 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. |
There was a problem hiding this comment.
Would it make sense/be simpler to make on_block_produced idempotent?
There was a problem hiding this comment.
Made on_block_produced idempotent on dependent PRs.
| return self._external_consumer_bytes | ||
| return 0 | ||
|
|
||
| usage = op.estimate_object_store_usage(state) |
There was a problem hiding this comment.
Is this dead code now? If so, let's remove it?
There was a problem hiding this comment.
Looks like estimate_object_store_usage is still defined? https://github.com/rayhhome/ray/blob/8beb993d1a84decf1ff26929e6615d6b5572fcf5/python/ray/data/_internal/execution/interfaces/physical_operator.py#L908-L941
| @@ -180,15 +188,16 @@ def _estimate_object_store_memory_usage( | |||
| return self._external_consumer_bytes | |||
There was a problem hiding this comment.
In follow up, I think we should nuke _external_consumer_bytes and clean up DownstreamCapacityBackpressurePolicy
There was a problem hiding this comment.
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.
| @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 |
There was a problem hiding this comment.
Huh? Can't we regular time imported at the top?
There was a problem hiding this comment.
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); " |
There was a problem hiding this comment.
What is RC? Can you write it out in the help
There was a problem hiding this comment.
RC is just ReferenceCounter and is what I used for my own documentation tracking; replaced this with the full name ReferenceCounter.
| cluster_compute: fixed_size_100_cpu_compute.yaml | ||
|
|
||
| run: | ||
| timeout: 1800 |
There was a problem hiding this comment.
This seems way too long given that the convergence timeout is like 30s
There was a problem hiding this comment.
Cutting this down to 300s. Will bump it up if it actually runs longer than this after actual executing on CI.
| Object-store memory is now tracked via BlockRefCounter (one counter shared | ||
| across the whole execution), NOT via queue-size metrics. Each operator's |
There was a problem hiding this comment.
"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.
There was a problem hiding this comment.
Removed implementation specific docstrings.
|
|
||
| # 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] | ||
|
|
There was a problem hiding this comment.
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)
There was a problem hiding this comment.
Makes sense. Applied to avoid testing specific implementation.
| 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. |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Condense the docstrings to give only high-level explanations.
| with counter._lock: | ||
| counter._registered_ids.add(fake_id1) | ||
| counter._bytes_by_producer[o2.id] += 100 |
There was a problem hiding this comment.
This will be super brittle.
Similar to above, could we create some sort of fake BlockRefCounter implementation instead?
There was a problem hiding this comment.
Used the StubBlockRefCounter approach!
6251039 to
8a9caaf
Compare
| @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 |
There was a problem hiding this comment.
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); " |
There was a problem hiding this comment.
RC is just ReferenceCounter and is what I used for my own documentation tracking; replaced this with the full name ReferenceCounter.
| # 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. |
There was a problem hiding this comment.
Made on_block_produced idempotent on dependent PRs.
| return self._external_consumer_bytes | ||
| return 0 | ||
|
|
||
| usage = op.estimate_object_store_usage(state) |
| @@ -180,15 +188,16 @@ def _estimate_object_store_memory_usage( | |||
| return self._external_consumer_bytes | |||
There was a problem hiding this comment.
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.
| cluster_compute: fixed_size_100_cpu_compute.yaml | ||
|
|
||
| run: | ||
| timeout: 1800 |
There was a problem hiding this comment.
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), |
There was a problem hiding this comment.
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.
| Object-store memory is now tracked via BlockRefCounter (one counter shared | ||
| across the whole execution), NOT via queue-size metrics. Each operator's |
There was a problem hiding this comment.
Removed implementation specific docstrings.
|
|
||
| # 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] | ||
|
|
There was a problem hiding this comment.
Makes sense. Applied to avoid testing specific implementation.
| with counter._lock: | ||
| counter._registered_ids.add(fake_id1) | ||
| counter._bytes_by_producer[o2.id] += 100 |
There was a problem hiding this comment.
Used the StubBlockRefCounter approach!
816b626 to
3b47c89
Compare
3b47c89 to
8beb993
Compare
| return self._external_consumer_bytes | ||
| return 0 | ||
|
|
||
| usage = op.estimate_object_store_usage(state) |
There was a problem hiding this comment.
Looks like estimate_object_store_usage is still defined? https://github.com/rayhhome/ray/blob/8beb993d1a84decf1ff26929e6615d6b5572fcf5/python/ray/data/_internal/execution/interfaces/physical_operator.py#L908-L941
|
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 |
8beb993 to
e096219
Compare
e096219 to
47c4df0
Compare
1936a69 to
e21d710
Compare
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit e21d710. Configure here.
2edfb95 to
addb218
Compare
7c44e26 to
7c51eb5
Compare
09f8964 to
4527361
Compare
Signed-off-by: Sirui Huang <[email protected]>
… docstring Signed-off-by: Sirui Huang <[email protected]>
…ounter Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: Sirui Huang <[email protected]>
4527361 to
26784b7
Compare
| def estimate_object_store_usage(self, state) -> ObjectStoreUsage: | ||
| return ObjectStoreUsage(internal=0, outputs=0) | ||
|
|
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Good catch; applied on [5/n].
| # Blocks are attributed to their original producer, not union_op. | ||
| counter.set_usage(input1.id, 1) | ||
| counter.set_usage(input2.id, 1) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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).
| 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 | ||
|
|
There was a problem hiding this comment.
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()
|
Closing this after discussing offline since we'll need to address |

Description
Switches
ResourceManager._estimate_object_store_memory_usageto read fromBlockRefCounter, replacing the manualop.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_usagereads_block_ref_counter.get_object_store_memory_usage(op.id)for output bytes instead of callingop.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_bytescall from the Train-side iterator to keep the memory budget accurate. With callback-based tracking this is no longer needed: the Train worker holds anObjectRef, so the bytes remain attributed until the worker drops the ref and the callback fires.Note:
DownstreamCapacityBackpressurePolicystill reads_external_consumer_bytesfor its own flow-control logic. Removing that dependency is a follow-up.Tests
test_resource_manager.pyandunit/test_resource_manager.py: updated to validate_estimate_object_store_memory_usageagainst callback-based accounting.Related issues
Depends on #64191 (operator wiring).
Related to #63601 (prototype), #63074 (previous manual
BlockRefCounter).