Repository navigation
[Data] [0/n] Prototyping Track Per-op Object Store Memory with Ray Core Out-of-scope Callbacks - #63601
[Data] [0/n] Prototyping Track Per-op Object Store Memory with Ray Core Out-of-scope Callbacks#63601rayhhome wants to merge 37 commits into
Conversation
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]>
There was a problem hiding this comment.
Code Review
This pull request introduces a centralized BlockRefCounter to track object-store memory usage per operator in Ray Data, replacing the previous estimation based on queue metrics. It leverages a new Ray Core callback mechanism, exposed via Cython, that triggers when an object goes out of scope. Key changes include the implementation of the counter with thread-safe accounting and deduplication, integration with ResourceManager for more accurate memory estimation, and updates to physical operators and tasks to report produced blocks. Review feedback highlighted a potential race condition in the counter's registration logic, suggested defensive guards for the counter reference in DataOpTask, and recommended an efficiency improvement in BasePhysicalOperator to avoid redundant buffer iterations.
There was a problem hiding this comment.
Pull request overview
This PR replaces Ray Data’s per-operator object store memory estimation (previously derived from queue BlockMetadata.size_bytes bookkeeping) with a centralized BlockRefCounter that attributes live object-store bytes to the producing operator and automatically releases them via a Ray Core “out-of-scope or freed” callback.
Changes:
- Expose
AddObjectOutOfScopeOrFreedCallbackto Python (core_worker.h/libcoreworker.pxd/_raylet.pyx) and use it from Ray Data. - Add
BlockRefCounterand wire it throughStreamingExecutor→ operators →DataOpTask/AllToAllOperatorfor per-op live byte accounting. - Update/extend tests to validate counter-based accounting and avoid double-counting through passthrough operators like
UnionOperator.
Reviewed changes
Copilot reviewed 15 out of 15 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| src/ray/core_worker/core_worker.h | Adds CoreWorker overload(s) for registering out-of-scope/freed callbacks. |
| python/ray/includes/libcoreworker.pxd | Exposes the new CoreWorker callback registration API to Cython. |
| python/ray/_raylet.pyx | Adds Python-facing CoreWorker.add_object_out_of_scope_callback + C trampoline. |
| python/ray/data/_internal/execution/block_ref_counter.py | Introduces BlockRefCounter and callback-driven decrementing of per-producer bytes. |
| python/ray/data/_internal/execution/interfaces/physical_operator.py | Threads block_ref_counter/producer_id through DataOpTask; registers produced blocks in on_data_ready. |
| python/ray/data/_internal/execution/operators/base_physical_operator.py | Registers newly created bulk outputs (excluding forwarded refs) with the counter. |
| python/ray/data/_internal/execution/operators/map_operator.py | Passes counter + producer id into DataOpTask. |
| python/ray/data/_internal/execution/operators/hash_shuffle.py | Passes counter + producer id into DataOpTask. |
| python/ray/data/_internal/gpu_shuffle/hash_shuffle.py | Passes counter + producer id into DataOpTask. |
| python/ray/data/_internal/execution/resource_manager.py | Switches object-store usage estimation to BlockRefCounter and exposes it via a property. |
| python/ray/data/_internal/execution/streaming_executor.py | Injects the shared counter into all operators and clears it on shutdown. |
| python/ray/data/tests/test_streaming_executor.py | Adds helper to create DataOpTask with default counter/producer id in tests. |
| python/ray/data/tests/test_resource_manager.py | Rewrites tests around counter-based accounting; adds Union double-counting coverage. |
| python/ray/data/tests/test_operators.py | Ensures tests set a counter before calling all_inputs_done on bulk operators. |
| python/ray/data/tests/test_block_ref_counter.py | New unit tests for counter semantics (dedupe/clear/thread-safety) using fake refs. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
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]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Reviewed by Cursor Bugbot for commit edbba9c. Configure here.
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces a centralized BlockRefCounter to track object-store memory usage per operator in Ray Data. It leverages a new Ray Core C++ API AddObjectOutOfScopeOrFreedCallback (exposed via Cython) to trigger callbacks when objects go out of scope, running them on a dedicated background thread to avoid blocking the main IO thread. This counter is integrated into the ResourceManager and physical operators to replace previous queue-size estimation metrics. Feedback on the changes suggests replacing a hard assertion with a None check in BasePhysicalOperator.all_inputs_done when checking for the block reference counter, ensuring consistency with DataOpTask and preventing potential crashes in tests or custom operators.
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.
| for (auto &callback : it->second.on_object_out_of_scope_or_freed_callbacks) { | ||
| // Post to the dedicated service so the callback never runs on the main IO | ||
| // context thread, which must not block waiting for the GIL. | ||
| object_freed_callback_service_.post( |
There was a problem hiding this comment.
You would probably only want to run the callback specific to the user on this thread. The other callbacks might have assumption that they are running on the main io context.
There was a problem hiding this comment.
Additionally, in case of lock contention/deadlock related issues could we also make sure the post to object freed callback for the user callback function doesn't need the mutex_ on reference counter.
|
This pull request has been automatically marked as stale because it has not had 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. |
…out-of-scope objects (#64011) ## Description This PR integrates the C++ infrastructure and Cython bridge from the prototype (#63601). Specifically, it lands the dedicated callback thread (`object_freed_callback_service_`) and the `CoreWorker::AddObjectOutOfScopeOrFreedCallback` API along with its Python-facing `add_object_out_of_scope_callback` method. The Ray Data `BlockRefCounter` integration (the primary consumer of this API) is left for a follow-up PR. **Scope. `add_object_out_of_scope_callback` is a private internal API with a single intended caller: Ray Data's `BlockRefCounter`. It is not part of the public Ray API and is not intended for general use.** **Motivation.** Ray Data needs to know when an `ObjectRef` is no longer held by any task or Python variable so it can release per-operator memory accounting. The right signal is Ray Core's own reference counter — when it drops an object's refcount to zero it has ground-truth knowledge that the bytes are gone. This PR exposes that signal to Python as `add_object_out_of_scope_callback`. The callback is dispatched on a dedicated thread rather than inline on the IO thread because `OnObjectOutOfScopeOrFreed` fires while holding the RC mutex; calling into Python there would stall the mutex waiting for the GIL, risking deadlock. **C++.** `CoreWorkerProcessImpl` gains a dedicated `object_freed_callback_service_` (`instrumented_io_context`) and `object_freed_callback_thread_`, both passed to `CoreWorker`. `CoreWorker` exposes two new overloads of `AddObjectOutOfScopeOrFreedCallback` (a `std::function` overload and a C function-pointer overload for Cython) that each wrap the user callback to post to the dedicated thread rather than run inline. **Cython.** `add_object_out_of_scope_callback(object_ref, callback)` is exposed on the Python `CoreWorker`. A `cdef void noexcept nogil` function handles GIL acquisition; `Py_INCREF` at registration keeps the callback alive across the async gap, and `Py_DECREF` runs in the `finally` block when the callback fires (or immediately if registration fails). ## Related issues Related to #63601 (initial prototype PR). ## Additional information **Call flow.** ``` del ref (Python) → ObjectRef.__dealloc__ → RemoveLocalReference → ReferenceCounter::OnObjectOutOfScopeOrFreed (holds RC mutex) → wrapped lambda posts to object_freed_callback_service_ (no GIL, returns fast) → object_freed_callback_thread_ dequeues and runs: _invoke_object_out_of_scope_callback → with gil: user_callback(ObjectRef) ``` **Tests.** - `core_worker_test.cc`: 6 new `TEST_F` tests. Checks the callback fires on ref drop, false return for already-freed objects, thread identity, the C function-pointer overload, multiple callbacks all fire, and fires exactly once. - `python/ray/tests/test_object_out_of_scope_callback.py`: new test suite with 7 live-cluster tests. Checks fire on `del ref`, false return for already-freed objects, thread identity, multiple callbacks, `ray.internal.free`, exception safety, and fires-exactly-once. --------- Signed-off-by: Sirui Huang <[email protected]>
…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]>
## 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]>
…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]>
## 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]>
…out-of-scope objects (ray-project#64011) ## Description This PR integrates the C++ infrastructure and Cython bridge from the prototype (ray-project#63601). Specifically, it lands the dedicated callback thread (`object_freed_callback_service_`) and the `CoreWorker::AddObjectOutOfScopeOrFreedCallback` API along with its Python-facing `add_object_out_of_scope_callback` method. The Ray Data `BlockRefCounter` integration (the primary consumer of this API) is left for a follow-up PR. **Scope. `add_object_out_of_scope_callback` is a private internal API with a single intended caller: Ray Data's `BlockRefCounter`. It is not part of the public Ray API and is not intended for general use.** **Motivation.** Ray Data needs to know when an `ObjectRef` is no longer held by any task or Python variable so it can release per-operator memory accounting. The right signal is Ray Core's own reference counter — when it drops an object's refcount to zero it has ground-truth knowledge that the bytes are gone. This PR exposes that signal to Python as `add_object_out_of_scope_callback`. The callback is dispatched on a dedicated thread rather than inline on the IO thread because `OnObjectOutOfScopeOrFreed` fires while holding the RC mutex; calling into Python there would stall the mutex waiting for the GIL, risking deadlock. **C++.** `CoreWorkerProcessImpl` gains a dedicated `object_freed_callback_service_` (`instrumented_io_context`) and `object_freed_callback_thread_`, both passed to `CoreWorker`. `CoreWorker` exposes two new overloads of `AddObjectOutOfScopeOrFreedCallback` (a `std::function` overload and a C function-pointer overload for Cython) that each wrap the user callback to post to the dedicated thread rather than run inline. **Cython.** `add_object_out_of_scope_callback(object_ref, callback)` is exposed on the Python `CoreWorker`. A `cdef void noexcept nogil` function handles GIL acquisition; `Py_INCREF` at registration keeps the callback alive across the async gap, and `Py_DECREF` runs in the `finally` block when the callback fires (or immediately if registration fails). ## Related issues Related to ray-project#63601 (initial prototype PR). ## Additional information **Call flow.** ``` del ref (Python) → ObjectRef.__dealloc__ → RemoveLocalReference → ReferenceCounter::OnObjectOutOfScopeOrFreed (holds RC mutex) → wrapped lambda posts to object_freed_callback_service_ (no GIL, returns fast) → object_freed_callback_thread_ dequeues and runs: _invoke_object_out_of_scope_callback → with gil: user_callback(ObjectRef) ``` **Tests.** - `core_worker_test.cc`: 6 new `TEST_F` tests. Checks the callback fires on ref drop, false return for already-freed objects, thread identity, the C function-pointer overload, multiple callbacks all fire, and fires exactly once. - `python/ray/tests/test_object_out_of_scope_callback.py`: new test suite with 7 live-cluster tests. Checks fire on `del ref`, false return for already-freed objects, thread identity, multiple callbacks, `ray.internal.free`, exception safety, and fires-exactly-once. --------- Signed-off-by: Sirui Huang <[email protected]> Signed-off-by: 400Ping <[email protected]>
…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]>
…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
ResourceManagerpreviously estimated each operator's object-store memory by summingsize_bytesfromBlockMetadataacross internal queues, output queues, and pending task inputs/outputs. This was fragile because metadata can be stale, zero, or missing, and every queue boundary needed careful bookkeeping.This PR introduces
BlockRefCounter: a per-execution counter that attributes live bytes to the operator that produced them. Memory is released automatically via a Ray Core callback rather than manual tracking at every handoff.How it works
Step 1 — Register on production. When a block is yielded by a running task,
DataOpTask.on_data_readycallson_block_produced(ref, size_bytes, producer_id). This records the block's size under the producing operator's ID and installs a Ray CoreAddObjectOutOfScopeOrFreedCallbackon theObjectRef.Step 2 — Release automatically. Ray Core fires the callback once the block is no longer held by any Python variable or running task. The callback atomically removes the block's bytes from the producer's total. No "consumed" call is needed at any downstream queue boundary.
Step 3 — Read on demand.
ResourceManager._estimate_object_store_memory_usagereplaces the old multi-queue sum with a singlecounter.get_object_store_memory_usage(op.id)call.Because memory is attributed by
ObjectRefidentity rather than queue position, blocks that transit multiple operators — sitting in an output queue, then consumed as task input — are counted exactly once throughout, always under their original producer.Changes
Ray Core (
_raylet.pyx,core_worker.h/.cc,core_worker_process.h/.cc,core_worker_shutdown_executor.cc,libcoreworker.pxd,reference_counter.h/.cc,BUILD.bazel)Exposes
core_worker.add_object_out_of_scope_callback(ref, fn)to Python and wires it through toReferenceCounter::AddObjectOutOfScopeOrFreedCallback.Dedicated callback thread (
core_worker_process.h/.cc,reference_counter.h/.cc)ReferenceCounterpreviously fired out-of-scope callbacks inline on the IO thread, which handles all ref-count RPCs system-wide — acquiring the Python GIL there risks latency spikes. Instead,CoreWorkerProcessImplnow owns a dedicatedobject_freed_callback_service_(instrumented_io_context) + thread;ReferenceCounterpost()s each callback to it so the IO thread returns immediately. The callback thread sharesio_thread_'s attributes (Mac 16 MB stack, signal masking) and is joined inCoreWorkerShutdownExecutor::ExecuteGracefulShutdownafterio_thread_.BlockRefCounter(new file)Thread-safe counter with three public methods:
on_block_produced,get_object_store_memory_usage, andclear. Two design details worth noting:ObjectRefappears in multipleRefBundles (e.g. afterrandomize_blockscopies bundles), only the firston_block_producedcall counts; subsequent calls for the same ID are no-ops.clear()empties all internal state so callbacks that fire after the executor shuts down (e.g. from GC) are silent no-ops rather than corrupting a stale counter.PhysicalOperator+DataOpTaskDataOpTaskis the common task wrapper used by all map-style operators. Addingblock_ref_counterandproducer_idparameters to its constructor means every operator that usesDataOpTaskgets counter support for free, without per-operator changes.on_block_producedis called insideon_data_readybehind aNonecheck, so the counter can safely be absent in unit tests that constructDataOpTaskdirectly. In practice the counter is always present at task run time, guaranteed by the executor wiring below.PhysicalOperatorgains aset_block_ref_countersetter used for executor-time injection.AllToAllOperator.all_inputs_doneAllToAllOperatoruses abulk_fninstead ofDataOpTask, so it registers blocks directly. It snapshotsinput_refsbefore callingbulk_fn, then callson_block_producedonly forObjectRefs that are genuinely new in the output. Forwarded refs (such as fromrandomize_blocks) are skipped and stay attributed to their original producer.MapOperator,HashShufflingOperator, GPUHashShuffleOperatorPass
block_ref_counterandproducer_idthrough toDataOpTask. These are the only operators that constructDataOpTaskdirectly.ResourceManager+StreamingExecutorResourceManager.__init__creates the single sharedBlockRefCounterfor the execution and exposes it via ablock_ref_counterproperty.StreamingExecutor.execute()injects the counter into every operator viaset_block_ref_counterafter topology construction, then callscounter.clear()on shutdown so late-firing GC callbacks are harmless.Operators requiring no changes
OutputSplitter,LimitOperator,ZipOperator, andAggregateNumRowsall havethrottling_disabled() = True, making them ineligible for resource budgeting. The resource manager never backpressures them, so per-byte accuracy for their blocks does not affect scheduling.UnionOperatoris eligible but produces no newObjectRefs, so its blocks remain attributed to their upstream producers naturally.Benchmarks
Link: https://gist.github.com/rayhhome/cf18e9aab0c93de5c64301f484faf6b1
block_ref_counter_benchmark.py(S1–S4) is a regression suite. It reruns four standard Ray Data workloads and compares pipeline time, peak memory, throughput, and spill against a baseline. It also enforces two hard correctness invariants on every branch (master vs. this PR branch) run: the counter never goes negative, and it drains to zero after the pipeline completes. Scenarios cover the main code paths: backpressure under a slow consumer (S1), raw map throughput at high block rate (S2), an AllToAll sort (S3), andstreaming_split-based training prefetch (S4).All counter-derived metrics (
backpressure_time_s,counter_negative_events,counter_zero_at_end,counter_max_residual_bytes_at_end) arenullon master — not measured, not assumed.compare()skipsnullvalues so no spurious threshold fires;_check_invariantsskipsnullvalues so the health invariants are only evaluated on the branch run.block_ref_counter_accuracy.py(S5–S6) measures whether the new counter tracks live bytes more faithfully than the old queue-based accounting. S5 records, on every scheduling-loop step, how much more the counter reports versus the old queue sum — the delta is bytes correctly held during the cross-operator hand-off window that the old approach released prematurely. S6 runs the same pipeline under an artificially tight object-store cap and checks that better attribution reduces or eliminates spill.The two suites are complementary: the regression benchmark confirms no performance cost; the accuracy benchmark confirms the correctness gain. Both scripts must be run from
release/nightly_tests/dataset/(or any directory containingbenchmark.pyandblock_ref_counter_benchmark.py, which they import directly).Example outputs (local --scale small run)
baseline.json(master — all counter fieldsnull, not measured):{ "s1-fast-producer-slow-consumer": {"time": 1.51, "spill_gb": 0.0, "peak_gb": 0.250, "tput": null, "backpressure_time_s": null, "counter_zero_at_end": null, "counter_peak_bytes": null, "callback_settle_time_s": null, "_brc_callback_registered": false}, "s2-map-throughput": {"time": 2.04, "spill_gb": 0.0, "peak_gb": 0.000, "tput": 490751, "backpressure_time_s": null, "counter_zero_at_end": null, "counter_peak_bytes": null, "callback_settle_time_s": null, "_brc_callback_registered": false}, "s3-sort-alltoall": {"time": 0.61, "spill_gb": 0.0, "peak_gb": 0.000, "tput": null, "backpressure_time_s": null, "counter_zero_at_end": null, "counter_peak_bytes": null, "callback_settle_time_s": null, "_brc_callback_registered": false}, "s4-training-prefetch": {"time": 1.76, "spill_gb": 0.0, "peak_gb": 0.250, "tput": null, "backpressure_time_s": null, "counter_zero_at_end": null, "counter_peak_bytes": null, "callback_settle_time_s": null, "_brc_callback_registered": false} }branch.json(this PR — counter fields populated for S1–S3; S4 usesstreaming_splitso its executor runs inside aSplitCoordinatoractor with its ownDataContext, and the driver-registered callback never fires there):{ "s1-fast-producer-slow-consumer": {"time": 6.59, "spill_gb": 0.0, "peak_gb": 0.063, "tput": null, "backpressure_time_s": 2.00, "counter_zero_at_end": true, "counter_peak_bytes": 33556480, "callback_settle_time_s": 5.11, "_brc_callback_registered": true}, "s2-map-throughput": {"time": 7.02, "spill_gb": 0.0, "peak_gb": 0.000, "tput": 497741, "backpressure_time_s": 2.64, "counter_zero_at_end": true, "counter_peak_bytes": 640000, "callback_settle_time_s": 5.01, "_brc_callback_registered": true}, "s3-sort-alltoall": {"time": 5.24, "spill_gb": 0.0, "peak_gb": 0.000, "tput": null, "backpressure_time_s": 0.13, "counter_zero_at_end": true, "counter_peak_bytes": 4000000, "callback_settle_time_s": 5.01, "_brc_callback_registered": true}, "s4-training-prefetch": {"time": 1.70, "spill_gb": 0.0, "peak_gb": 0.250, "tput": null, "backpressure_time_s": null, "counter_zero_at_end": null, "counter_peak_bytes": null, "callback_settle_time_s": null, "_brc_callback_registered": false} }Note: branch
timeincludes a ~5 s post-shutdown settle poll (callback_settle_time_s);pipeline_time_s = time - callback_settle_time_sis what the regression comparison uses.accuracy-baseline.json(master — counter and accuracy fieldsnull):{ "s5-per-operator-accuracy": {"time": 2.75, "spill_gb": 0.0, "samples_recorded": 0, "counter_minus_shadow_mean_bytes": null, "counter_minus_shadow_max_bytes": null, "counter_zero_at_end": null, "_brc_callback_registered": false}, "s6-memory-constrained-spill": {"time": 29.6, "spill_gb": 0.0, "counter_zero_at_end": null, "_brc_callback_registered": false} }accuracy-branch.json(this PR):{ "s5-per-operator-accuracy": {"time": 7.72, "spill_gb": 0.0, "samples_recorded": 52, "counter_minus_shadow_mean_bytes": 1330885, "counter_minus_shadow_max_bytes": 4194304, "counter_zero_at_end": true, "_brc_callback_registered": true}, "s6-memory-constrained-spill": {"time": 34.2, "spill_gb": 0.0, "counter_zero_at_end": true, "_brc_callback_registered": true} }S5's positive
counter_minus_shadowdelta (~1.3 MB mean, 4 MB max) confirms the counter holds attribution during the cross-operator handoff window that the old queue-based approach released prematurely.python block_ref_counter_benchmark.py compare baseline.json branch.json:python block_ref_counter_benchmark.py compare accuracy-baseline.json accuracy-branch.json— S5/S6 summary (accuracy metrics are branch-only;nullon master means not measured):Related issues
Implements a cleaner alternative to #63074 (manual dispatch/release tracking).
Tests
test_block_ref_counter.py(new): unit tests using a_FakeRefstub (produce/release, multi-producer isolation, deduplication,clear()+ late-callback safety, concurrent callbacks); plusTestBlockRefCounterLifecycleintegration tests against a live Ray cluster that exercise the fulladd_object_out_of_scope_callback→object_freed_callback_service_path with realObjectRefs.test_resource_manager.py:test_update_usageandtest_object_store_usagerewritten around the counter API;test_union_no_double_counting(new) confirms blocks flowing throughUnionOperatorare attributed only to their upstream producers and global usage is not inflated.test_operators.py:test_all_to_all_operatorandtest_all_to_all_estimated_num_output_bundlesupdated to callset_block_ref_counterbeforeall_inputs_done, satisfying the new assert.test_streaming_executor.py:DataOpTaskcall sites updated via a_make_data_op_taskhelper that supplies a default counter and producer ID.