Repository navigation
[Data] [Core] [3/n] Wire BlockRefCounter into Operators - #64191
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 via Ray Core callbacks, integrating it across various physical operators and the streaming executor. The feedback focuses on enhancing the robustness of this counter: first, by replacing the set-based tracking of registered IDs with a dictionary to handle duplicate registrations and prevent memory leaks; second, by skipping tracking for zero-sized blocks to reduce overhead; third, by initializing the counter to a default instance in PhysicalOperator to avoid potential AttributeErrors in tests; and finally, by adding proper type annotations to the overridden start methods across all operator subclasses to ensure 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.
There was a problem hiding this comment.
Pull request overview
This PR introduces a centralized BlockRefCounter to track per-operator object store memory via Ray Core out-of-scope callbacks, wiring it through operator startup and the streaming executor lifecycle.
Changes:
- Add
BlockRefCounterimplementation + comprehensive unit/integration tests and Bazel target. - Plumb a shared counter from
ResourceManagerintoPhysicalOperator.start()and intoDataOpTaskso blocks are accounted once metadata is available. - Avoid double-counting for AllToAll bulk transforms that forward input refs unchanged; clear accounting on executor shutdown after queues are drained.
Reviewed changes
Copilot reviewed 16 out of 16 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| python/ray/data/tests/test_streaming_executor.py | Adds a helper to construct DataOpTask with default BlockRefCounter/producer_id for existing tests. |
| python/ray/data/tests/test_operators.py | Updates operator tests to call start() explicitly where required. |
| python/ray/data/tests/test_block_ref_counter.py | New test suite for BlockRefCounter accounting, clear(), thread-safety, and lifecycle integration. |
| python/ray/data/BUILD.bazel | Registers the new test_block_ref_counter Bazel py_test. |
| python/ray/data/_internal/execution/streaming_executor.py | Starts all operators with a shared counter and clears the counter at shutdown after draining queues. |
| python/ray/data/_internal/execution/streaming_executor_state.py | Stops starting operators during topology construction (executor does it after ResourceManager exists). |
| python/ray/data/_internal/execution/resource_manager.py | Constructs and exposes an executor-wide BlockRefCounter. |
| python/ray/data/_internal/execution/operators/union_operator.py | Updates start() signature to accept/forward block_ref_counter. |
| python/ray/data/_internal/execution/operators/output_splitter.py | Updates start() signature to accept/forward block_ref_counter. |
| python/ray/data/_internal/execution/operators/map_operator.py | Updates start() signature; plumbs counter + producer id into DataOpTask. |
| python/ray/data/_internal/execution/operators/input_data_buffer.py | Updates start() signature to accept/forward block_ref_counter. |
| python/ray/data/_internal/execution/operators/hash_shuffle.py | Updates start() signature; plumbs counter + producer id into finalization DataOpTask. |
| python/ray/data/_internal/execution/operators/base_physical_operator.py | Prevents double-counting in AllToAll by skipping forwarded input refs. |
| python/ray/data/_internal/execution/operators/actor_pool_map_operator.py | Updates start() signature to accept/forward block_ref_counter. |
| python/ray/data/_internal/execution/interfaces/physical_operator.py | Extends PhysicalOperator.start() and DataOpTask to accept a shared counter + producer id; DataOpTask accounts blocks when metadata is ready. |
| python/ray/data/_internal/execution/block_ref_counter.py | Adds the BlockRefCounter implementation using Ray Core out-of-scope callbacks. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| block_ref_counter: Optional[BlockRefCounter], | ||
| producer_id: str, |
There was a problem hiding this comment.
An alternative implementation could be to make callers responsible for updating the reference counter with output_ready_callback rather than making it DataOpTask's responsibility.
Advantage is that it would reduce the amount we pass through block_ref_counter and simplify the DataOpTask interface, though I imagine it might also introduce a moderate amount of duplication.
Will defer you to about what's cleaner
There was a problem hiding this comment.
I think the main caveat for using the alternative approach is, if we are to add new operators that use DataOpTask, there is non-zero possibility for future developers to omit updating the reference counter. Passing the block_ref_counter through to DataOpTask will prevent this since on_data_ready calls it by default.
| self, | ||
| task_index: int, | ||
| streaming_gen: ObjectRefGenerator, | ||
| block_ref_counter: Optional[BlockRefCounter], |
There was a problem hiding this comment.
When can this ever be None? We only create DataOpTasks once execution has already started, so I feel like we shouldn't allow it
There was a problem hiding this comment.
Didn't apply this in the combined PR since this would many extra test changes; will now add them since we've split into smaller PRs.
| def start( | ||
| self, | ||
| options: ExecutionOptions, | ||
| block_ref_counter: Optional[BlockRefCounter] = None, |
There was a problem hiding this comment.
Similar comment -- can this ever actually be None? We control when start gets called, and we make it so that start always gets called with a non-None value.
Making this just block_ref_counter: BlockRefCounter would make the code easier to reason about
There was a problem hiding this comment.
Made block_ref_counter non-optional.
| @property | ||
| def block_ref_counter(self) -> BlockRefCounter: | ||
| """The centralized block reference counter for this executor.""" | ||
| return self._block_ref_counter | ||
|
|
There was a problem hiding this comment.
We can probably simplify the dataflow here.
Currently, it's like:
- Executor creates ResourceManager
- ResourceManager constructs counter
- Executor gets counter from ResourceManager
- Executor passes counter from ResourceManager to Operators
I think it'd be clearer as
- Executor constructs counter
- Executor passes counter to ResourceManager as constructor dependency
- Executor passes counter to operators in
start
There was a problem hiding this comment.
If we do this, we can also avoid expanding the ResourceManager interface with the block_ref_coutner proeprty
There was a problem hiding this comment.
Makes sense; creating the reference counter in StreamingExecutor now.
| kwargs.setdefault("block_ref_counter", BlockRefCounter()) | ||
| kwargs.setdefault("producer_id", "test_op") |
There was a problem hiding this comment.
Here and below -- I think the tests would be clearer if we just inlined these parameters and didn't introduce the _make_data_op_task layer of indirection
| # outputs (e.g., map outputs for map-reduce). | ||
| output_buffer, self._stats = self._bulk_fn(self._input_buffer.to_list(), ctx) | ||
|
|
||
| # Snapshot input refs before calling bulk_fn. Some bulk_fns (e.g. |
There was a problem hiding this comment.
Would it make sense/be simpler if we made on_block_produced idempotent?
There was a problem hiding this comment.
Made on_block_produced idempotent in the dependent PR; now we're able to remove the input_refs check!
95bcd52 to
2c2cb41
Compare
2c2cb41 to
154704b
Compare
rayhhome
left a comment
There was a problem hiding this comment.
Addressed comments!
| block_ref_counter: Optional[BlockRefCounter], | ||
| producer_id: str, |
There was a problem hiding this comment.
I think the main caveat for using the alternative approach is, if we are to add new operators that use DataOpTask, there is non-zero possibility for future developers to omit updating the reference counter. Passing the block_ref_counter through to DataOpTask will prevent this since on_data_ready calls it by default.
| self, | ||
| task_index: int, | ||
| streaming_gen: ObjectRefGenerator, | ||
| block_ref_counter: Optional[BlockRefCounter], |
There was a problem hiding this comment.
Didn't apply this in the combined PR since this would many extra test changes; will now add them since we've split into smaller PRs.
| def start( | ||
| self, | ||
| options: ExecutionOptions, | ||
| block_ref_counter: Optional[BlockRefCounter] = None, |
There was a problem hiding this comment.
Made block_ref_counter non-optional.
| # outputs (e.g., map outputs for map-reduce). | ||
| output_buffer, self._stats = self._bulk_fn(self._input_buffer.to_list(), ctx) | ||
|
|
||
| # Snapshot input refs before calling bulk_fn. Some bulk_fns (e.g. |
There was a problem hiding this comment.
Made on_block_produced idempotent in the dependent PR; now we're able to remove the input_refs check!
| @property | ||
| def block_ref_counter(self) -> BlockRefCounter: | ||
| """The centralized block reference counter for this executor.""" | ||
| return self._block_ref_counter | ||
|
|
There was a problem hiding this comment.
Makes sense; creating the reference counter in StreamingExecutor now.
|
I double checked and found that I missed some operators that generated new blocks and I added
In particular, |
4fe4bb0 to
7eeb784
Compare
a0171c1 to
e620314
Compare
38c52a4 to
57a15c3
Compare
9650f83 to
48e7065
Compare
515e075 to
49f5732
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 e2f5a6b. Configure here.
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]>
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]>
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]>
…oduced Signed-off-by: Sirui Huang <[email protected]>
7208d2d to
9b64096
Compare
justinvyu
left a comment
There was a problem hiding this comment.
Thanks, good work!
One nit, feel free to address after merging.
| ExecutionOptions(), | ||
| lambda: total_resources, | ||
| DataContext.get_current(), | ||
| BlockRefCounter(add_object_out_of_scope_callback=lambda *_: True), |
There was a problem hiding this comment.
Can we just patch global_worker.core_worker.add_object_out_of_scope_callback instead of this weird override argument in the BlockRefCounter?
See monkeypatch setattr / unittest mock patch
There was a problem hiding this comment.
Oh, I recommended this to Ray.
IMO an explicit dependency seam is more maintainable than monkeypatching internals.
If we monkeypatch global_worker.core_worker.add_object_out_of_scope_callback, we're making assumptions about the implementation details like where the function is defined or what its signature is like. If we monkeypatch, a developer can correctly change the implementation details of on_block_produced and unintentionally break the tests
BlockRefCounter (recently added in ray-project#64191) is a required constructor argument on DataOpTask (physical_operator.py:138-139) and on PhysicalOperator.start (physical_operator.py:775). V2's ShuffleReduceOp passes ``block_ref_counter=self._block_ref_counter, producer_id=self.id`` into every DataOpTask, but ShuffleReduceOpV3 was authored before that change landed and never got updated -- the first reducer dispatch would raise TypeError under a real executor run. Fix: * shuffle_reduce_operator_v3.py: pass ``block_ref_counter`` + ``producer_id`` to DataOpTask, matching v2. * test_shuffle_v3_smoke.py: PhysicalOperator.start also requires a BlockRefCounter now; construct one and pass to every op's start. ShuffleMapOpV3 uses MetadataOpTask (which does not depend on BlockRefCounter), so no map-side change needed. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> Signed-off-by: Yuanzhuo Yang <[email protected]>
… tests Follow-up to the master merge: build_streaming_topology now requires a BlockRefCounter (ray-project#64191); pass noop_counter() like the other tests. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: xgui <[email protected]>
## 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]>
…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]>

Description
Wires
BlockRefCounterinto every operator and the streaming executor.ResourceManagergains the counter as an attribute in this PR, but_estimate_object_store_memory_usageis not changed to keep the scheduling-visible change isolated.Implementation
physical_operator.py.PhysicalOperator.start()now acceptsblock_ref_counter(replacesset_block_ref_counter()used in prototype per review).DataOpTask.on_data_readycallson_block_producedonce both the block ref and its metadata are available.base_physical_operator.py.AllToAllOperator.all_inputs_doneskipson_block_producedfor output refs that are unchanged from the input, avoiding double-counting whenbulk_fnforwards refs unchanged (e.g.randomize_blocks).streaming_executor_state.py/streaming_executor.py. Operators are no longer started insidebuild_streaming_topology. The executor starts them afterResourceManageris constructed so the shared counter can be passed in.block_ref_counter.clear()is called at shutdown after queues are drained.resource_manager.py. ConstructsBlockRefCounter()and exposes it via ablock_ref_counterproperty.Tests
test_operators.py: updated to removeset_block_ref_countercalls; addsop.start(ExecutionOptions())where missing.test_streaming_executor.py:_make_data_op_taskhelper supplies defaultblock_ref_counterandproducer_idso existingDataOpTasktests compile.Related issues
Depends on #64157 (
BlockRefCounterimplementation).Related to #63601 (prototype), #63074 (previous manual
BlockRefCounter).