Repository navigation
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]>
…mutex 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 dedicated event loop and thread (object_free_rpc_service_) for handling FreeObjectOnNodes gRPC calls asynchronously, keeping them off the main I/O and callback services. It also refactors ReferenceCounter to defer out-of-scope work (callbacks and gRPC frees) outside of its internal mutex lock using a new RAII guard MutexLockWithOOSDrain. The feedback highlights a potential bug where using absl::MutexLock instead of MutexLockWithOOSDrain could trap deferred work, and suggests several optimizations to avoid copying locations sets by passing them by value and utilizing std::move.
There was a problem hiding this comment.
🟡 Changes recommended
Deferred out-of-scope work can remain un-drained on remaining absl::MutexLock code paths (and shutdown currently stops the new service in a way that may abandon queued frees).
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
This PR reduces lock contention in ReferenceCounter::OnObjectOutOfScopeOrFreed by deferring slow work (FreeObjectOnNodes gRPC broadcasts and out-of-scope callbacks) until after mutex_ is released, and adds a dedicated object_free_rpc_service_ event loop/thread to keep those gRPC frees off the main IO and callback services.
Changes:
- Introduces deferred out-of-scope work collection/draining via
DeferredOOSWork+MutexLockWithOOSDrain, moving callbacks and free broadcasts out from underReferenceCounter::mutex_. - Adds
object_free_rpc_service_/object_free_rpc_thread_and routesFreeObjectOnNodesAsyncwork onto it. - Updates unit tests and a Python thread-count test to account for the new dedicated thread.
File summaries
| File | Description |
|---|---|
| src/ray/core_worker/tests/core_worker_test.cc | Wires a new object_free_rpc_service_ into the CoreWorker test fixture. |
| src/ray/core_worker/reference_counter.h | Adds deferred-work structs and a custom mutex guard that drains deferred work after unlock. |
| src/ray/core_worker/reference_counter.cc | Switches key entrypoints to MutexLockWithOOSDrain and defers out-of-scope callbacks/free broadcasts. |
| src/ray/core_worker/core_worker.h | Extends CoreWorker constructor/fields to include the new RPC-free io_context/thread. |
| src/ray/core_worker/core_worker.cc | Plumbs the new constructor parameters into CoreWorker initialization. |
| src/ray/core_worker/core_worker_shutdown_executor.cc | Stops and joins the new object-free RPC service/thread during graceful shutdown. |
| src/ray/core_worker/core_worker_process.h | Adds the new dedicated io_context/work-guard/thread to the worker process. |
| src/ray/core_worker/core_worker_process.cc | Starts the new thread and posts FreeObjectOnNodesAsync onto the dedicated service. |
| python/ray/tests/test_basic.py | Updates expected worker thread counts to include the additional dedicated thread. |
Review details
- Files reviewed: 9/9 changed files
- Comments generated: 2
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
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 b35fd7f. Configure here.
Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: Sirui Huang <[email protected]>
There was a problem hiding this comment.
🔵 Needs a closer look
A release-build silent correctness hazard exists because RAY_DCHECK(oos_drain_active_) does not fail-fast under NDEBUG, which can strand deferred out-of-scope work if any call path misses the new guard.
Review details
Suppressed comments (1)
src/ray/core_worker/reference_counter.cc:855
RAY_DCHECK(oos_drain_active_)only logs (non-fatal) in release builds (NDEBUG), which would stranddeferred_oos_work_indefinitely if any caller ever reaches this path while holdingmutex_via a plainabsl::MutexLock. Since that would silently skip out-of-scope callbacks and free broadcasts, this should be fail-fast in all builds (or otherwise provide a safe fallback).
// Collect work that does not need mutex_ (gRPC frees, callbacks) into
// deferred_oos_work_. MutexLockWithOOSDrain swaps it out and executes
// it after releasing the lock.
RAY_DCHECK(oos_drain_active_)
<< "OnObjectOutOfScopeOrFreed requires the caller to hold mutex_ via "
"MutexLockWithOOSDrain, not absl::MutexLock. Otherwise the callbacks "
"and gRPC frees queued here are stranded until some later guarded "
"call drains them.";
DeferredOOSWork work;
- Files reviewed: 10/10 changed files
- Comments generated: 0 new
- Review effort level: Lite
… from input to output (#66369) ## Description A Ray Train job dies before it reads a single row. Its input pipeline shuffles a dataset that was already materialized: ```python ds = ray.data.range(100, override_num_blocks=10).materialize() ds = ds.randomize_block_order() (it,) = ds.streaming_split(1, equal=True) list(it.iter_rows()) ``` ``` (SplitCoordinator pid=42263) Split 0 epoch 0 get() failed after 0 rows: Cannot register an out-of-scope/freed callback for object 6f1bcddfc6570c62…: it is not owned by this worker (it may be owned by another worker, or have no ownership record). These callbacks can only be registered by the owner. ``` ### Why it happens `BlockRefCounter` tracks object-store memory. To do that, it asks Ray Core to call it back when a block is freed. Only the block's owner may register that callback, and the owner is the process that created the block. `streaming_split` runs the plan inside a `SplitCoordinator` actor. But the blocks were created earlier, by `materialize()` on the caller. The same holds for any `InputData` source, such as `from_arrow` or `from_pandas`. ``` caller SplitCoordinator actor ────────────── ────────────────────── materialize() ── refs ──▶ randomize_block_order → … → split(N) owns B1..B10 owns nothing it was handed ``` `AllToAllOperator.all_inputs_done` registered a callback for every block it sent downstream. That is right for sort, shuffle and repartition. Their output blocks come from reduce tasks the operator itself submitted, so it owns them. It is wrong for `RandomizeBlocks`. That operator creates no blocks. It reorders its input bundles and returns the same refs. So the actor asks Ray Core to watch blocks the caller owns, Ray Core refuses, and the execution fails. ### The fix Register a block only when its ref was not among the operator's inputs: ```python input_refs = {entry.ref for b in input_bundles for entry in b.blocks} ... for bundle in output_buffer: for entry in bundle.blocks: if entry.ref in input_refs: continue self._block_ref_counter.on_block_produced(...) ``` Returned refs are skipped. New ones are still registered. `OutputSplitter` already uses the same test on `_split_block` output. **Why not `RefBundle.owns_blocks`?** That flag says whether the blocks may be destroyed, not who made them. The shuffle, sort and split-repartition schedulers copy it from their input onto blocks their own reduce tasks made (`input_owned = all(b.owns_blocks for b in refs)` at `pull_based_shuffle_task_scheduler.py:50`, used at `:145`). A filter on that flag would drop real blocks from the counter whenever the source is `from_*` or `materialize`, and under-report their memory. Bugbot caught this in the first version of this PR. ### Where it came from #64157 added `BlockRefCounter` to the operators in 2.57, and the crash has been there since. It was reported from a Ray Train job on 2.58.0. That job's input pipeline is `from_arrow → repartition → materialize → randomize_block_order → map_batches → repartition → streaming_split`, and all four splits fail at 0 rows. ## Related issues None open. I searched ray-project/ray for open PRs and issues mentioning `BlockRefCounter`, `owns_blocks`, `streaming_split materialized`, and the error text "Cannot register an out-of-scope callback". Two open PRs touch the counter: #65878 (consumer-held bytes) and #65220 (deferring gRPC frees). Neither changes this registration path, and no open issue tracks the crash, so this is not duplicate work. ## Additional information **Tests.** `test_streaming_split_over_materialized_all_to_all` reproduces the failure end to end. The two tests in `test_operators.py` cover both sides of the check; the second fails if the check uses `owns_blocks`, which is what the first version of this PR did. ``` $ PYTHONPATH=python/ray/data/tests python -m pytest \ python/ray/data/tests/test_streaming_integration.py \ -k test_streaming_split_over_materialized_all_to_all -q 1 passed, 25 deselected in 9.28s # fails on master with the error above $ PYTHONPATH=python/ray/data/tests python -m pytest \ python/ray/data/tests/test_operators.py \ python/ray/data/tests/test_randomize_block_order.py \ python/ray/data/tests/unit/test_block_ref_counter.py \ python/ray/data/tests/unit/test_resource_manager.py -q 29 passed in 16.10s $ PYTHONPATH=python/ray/data/tests python -m pytest \ python/ray/data/tests/test_streaming_integration.py -k streaming_split -q 13 passed, 13 deselected in 68.67s ``` The last command needs #66366 applied locally. On master, `request_remaining=True` in `rate_based_cluster_autoscaler.py` raises `TypeError: 'bool' object is not iterable` in the autoscaling coordinator, which makes these tests flaky. **CI.** The `buildkite/premerge` failure here is that same master bug. All three pyrefly errors are in `rate_based_cluster_autoscaler.py`, a file this PR does not touch. #66366 and #66370 both fix it, and this PR is unblocked once either one lands. **AI assistance was used** for the diagnosis, the patch, and this description. --------- Signed-off-by: Marwan Sarieddine <[email protected]> Co-authored-by: Ayush Kumar <[email protected]>
… from input to output (ray-project#66369) ## Description A Ray Train job dies before it reads a single row. Its input pipeline shuffles a dataset that was already materialized: ```python ds = ray.data.range(100, override_num_blocks=10).materialize() ds = ds.randomize_block_order() (it,) = ds.streaming_split(1, equal=True) list(it.iter_rows()) ``` ``` (SplitCoordinator pid=42263) Split 0 epoch 0 get() failed after 0 rows: Cannot register an out-of-scope/freed callback for object 6f1bcddfc6570c62…: it is not owned by this worker (it may be owned by another worker, or have no ownership record). These callbacks can only be registered by the owner. ``` ### Why it happens `BlockRefCounter` tracks object-store memory. To do that, it asks Ray Core to call it back when a block is freed. Only the block's owner may register that callback, and the owner is the process that created the block. `streaming_split` runs the plan inside a `SplitCoordinator` actor. But the blocks were created earlier, by `materialize()` on the caller. The same holds for any `InputData` source, such as `from_arrow` or `from_pandas`. ``` caller SplitCoordinator actor ────────────── ────────────────────── materialize() ── refs ──▶ randomize_block_order → … → split(N) owns B1..B10 owns nothing it was handed ``` `AllToAllOperator.all_inputs_done` registered a callback for every block it sent downstream. That is right for sort, shuffle and repartition. Their output blocks come from reduce tasks the operator itself submitted, so it owns them. It is wrong for `RandomizeBlocks`. That operator creates no blocks. It reorders its input bundles and returns the same refs. So the actor asks Ray Core to watch blocks the caller owns, Ray Core refuses, and the execution fails. ### The fix Register a block only when its ref was not among the operator's inputs: ```python input_refs = {entry.ref for b in input_bundles for entry in b.blocks} ... for bundle in output_buffer: for entry in bundle.blocks: if entry.ref in input_refs: continue self._block_ref_counter.on_block_produced(...) ``` Returned refs are skipped. New ones are still registered. `OutputSplitter` already uses the same test on `_split_block` output. **Why not `RefBundle.owns_blocks`?** That flag says whether the blocks may be destroyed, not who made them. The shuffle, sort and split-repartition schedulers copy it from their input onto blocks their own reduce tasks made (`input_owned = all(b.owns_blocks for b in refs)` at `pull_based_shuffle_task_scheduler.py:50`, used at `:145`). A filter on that flag would drop real blocks from the counter whenever the source is `from_*` or `materialize`, and under-report their memory. Bugbot caught this in the first version of this PR. ### Where it came from ray-project#64157 added `BlockRefCounter` to the operators in 2.57, and the crash has been there since. It was reported from a Ray Train job on 2.58.0. That job's input pipeline is `from_arrow → repartition → materialize → randomize_block_order → map_batches → repartition → streaming_split`, and all four splits fail at 0 rows. ## Related issues None open. I searched ray-project/ray for open PRs and issues mentioning `BlockRefCounter`, `owns_blocks`, `streaming_split materialized`, and the error text "Cannot register an out-of-scope callback". Two open PRs touch the counter: ray-project#65878 (consumer-held bytes) and ray-project#65220 (deferring gRPC frees). Neither changes this registration path, and no open issue tracks the crash, so this is not duplicate work. ## Additional information **Tests.** `test_streaming_split_over_materialized_all_to_all` reproduces the failure end to end. The two tests in `test_operators.py` cover both sides of the check; the second fails if the check uses `owns_blocks`, which is what the first version of this PR did. ``` $ PYTHONPATH=python/ray/data/tests python -m pytest \ python/ray/data/tests/test_streaming_integration.py \ -k test_streaming_split_over_materialized_all_to_all -q 1 passed, 25 deselected in 9.28s # fails on master with the error above $ PYTHONPATH=python/ray/data/tests python -m pytest \ python/ray/data/tests/test_operators.py \ python/ray/data/tests/test_randomize_block_order.py \ python/ray/data/tests/unit/test_block_ref_counter.py \ python/ray/data/tests/unit/test_resource_manager.py -q 29 passed in 16.10s $ PYTHONPATH=python/ray/data/tests python -m pytest \ python/ray/data/tests/test_streaming_integration.py -k streaming_split -q 13 passed, 13 deselected in 68.67s ``` The last command needs ray-project#66366 applied locally. On master, `request_remaining=True` in `rate_based_cluster_autoscaler.py` raises `TypeError: 'bool' object is not iterable` in the autoscaling coordinator, which makes these tests flaky. **CI.** The `buildkite/premerge` failure here is that same master bug. All three pyrefly errors are in `rate_based_cluster_autoscaler.py`, a file this PR does not touch. ray-project#66366 and ray-project#66370 both fix it, and this PR is unblocked once either one lands. **AI assistance was used** for the diagnosis, the patch, and this description. --------- Signed-off-by: Marwan Sarieddine <[email protected]> Co-authored-by: Ayush Kumar <[email protected]>
… from input to output (ray-project#66369) ## Description A Ray Train job dies before it reads a single row. Its input pipeline shuffles a dataset that was already materialized: ```python ds = ray.data.range(100, override_num_blocks=10).materialize() ds = ds.randomize_block_order() (it,) = ds.streaming_split(1, equal=True) list(it.iter_rows()) ``` ``` (SplitCoordinator pid=42263) Split 0 epoch 0 get() failed after 0 rows: Cannot register an out-of-scope/freed callback for object 6f1bcddfc6570c62…: it is not owned by this worker (it may be owned by another worker, or have no ownership record). These callbacks can only be registered by the owner. ``` ### Why it happens `BlockRefCounter` tracks object-store memory. To do that, it asks Ray Core to call it back when a block is freed. Only the block's owner may register that callback, and the owner is the process that created the block. `streaming_split` runs the plan inside a `SplitCoordinator` actor. But the blocks were created earlier, by `materialize()` on the caller. The same holds for any `InputData` source, such as `from_arrow` or `from_pandas`. ``` caller SplitCoordinator actor ────────────── ────────────────────── materialize() ── refs ──▶ randomize_block_order → … → split(N) owns B1..B10 owns nothing it was handed ``` `AllToAllOperator.all_inputs_done` registered a callback for every block it sent downstream. That is right for sort, shuffle and repartition. Their output blocks come from reduce tasks the operator itself submitted, so it owns them. It is wrong for `RandomizeBlocks`. That operator creates no blocks. It reorders its input bundles and returns the same refs. So the actor asks Ray Core to watch blocks the caller owns, Ray Core refuses, and the execution fails. ### The fix Register a block only when its ref was not among the operator's inputs: ```python input_refs = {entry.ref for b in input_bundles for entry in b.blocks} ... for bundle in output_buffer: for entry in bundle.blocks: if entry.ref in input_refs: continue self._block_ref_counter.on_block_produced(...) ``` Returned refs are skipped. New ones are still registered. `OutputSplitter` already uses the same test on `_split_block` output. **Why not `RefBundle.owns_blocks`?** That flag says whether the blocks may be destroyed, not who made them. The shuffle, sort and split-repartition schedulers copy it from their input onto blocks their own reduce tasks made (`input_owned = all(b.owns_blocks for b in refs)` at `pull_based_shuffle_task_scheduler.py:50`, used at `:145`). A filter on that flag would drop real blocks from the counter whenever the source is `from_*` or `materialize`, and under-report their memory. Bugbot caught this in the first version of this PR. ### Where it came from ray-project#64157 added `BlockRefCounter` to the operators in 2.57, and the crash has been there since. It was reported from a Ray Train job on 2.58.0. That job's input pipeline is `from_arrow → repartition → materialize → randomize_block_order → map_batches → repartition → streaming_split`, and all four splits fail at 0 rows. ## Related issues None open. I searched ray-project/ray for open PRs and issues mentioning `BlockRefCounter`, `owns_blocks`, `streaming_split materialized`, and the error text "Cannot register an out-of-scope callback". Two open PRs touch the counter: ray-project#65878 (consumer-held bytes) and ray-project#65220 (deferring gRPC frees). Neither changes this registration path, and no open issue tracks the crash, so this is not duplicate work. ## Additional information **Tests.** `test_streaming_split_over_materialized_all_to_all` reproduces the failure end to end. The two tests in `test_operators.py` cover both sides of the check; the second fails if the check uses `owns_blocks`, which is what the first version of this PR did. ``` $ PYTHONPATH=python/ray/data/tests python -m pytest \ python/ray/data/tests/test_streaming_integration.py \ -k test_streaming_split_over_materialized_all_to_all -q 1 passed, 25 deselected in 9.28s # fails on master with the error above $ PYTHONPATH=python/ray/data/tests python -m pytest \ python/ray/data/tests/test_operators.py \ python/ray/data/tests/test_randomize_block_order.py \ python/ray/data/tests/unit/test_block_ref_counter.py \ python/ray/data/tests/unit/test_resource_manager.py -q 29 passed in 16.10s $ PYTHONPATH=python/ray/data/tests python -m pytest \ python/ray/data/tests/test_streaming_integration.py -k streaming_split -q 13 passed, 13 deselected in 68.67s ``` The last command needs ray-project#66366 applied locally. On master, `request_remaining=True` in `rate_based_cluster_autoscaler.py` raises `TypeError: 'bool' object is not iterable` in the autoscaling coordinator, which makes these tests flaky. **CI.** The `buildkite/premerge` failure here is that same master bug. All three pyrefly errors are in `rate_based_cluster_autoscaler.py`, a file this PR does not touch. ray-project#66366 and ray-project#66370 both fix it, and this PR is unblocked once either one lands. **AI assistance was used** for the diagnosis, the patch, and this description. --------- Signed-off-by: Marwan Sarieddine <[email protected]> Co-authored-by: Ayush Kumar <[email protected]>
|
Closing this pr. So far no substantive evidence suggests that the issue mentioned in the pr description impacted any practical workloads. |

Description
Move
free_object_on_nodes_async_(gRPC free broadcast) and out-of-scope callbacks outside ofmutex_inReferenceCounter::OnObjectOutOfScopeOrFreed. Previously, when manyObjectRefsare freed simultaneously (e.g., LIMIT operators, UDF failures), the gRPC calls (~70% ofRemoveLocalReferenceruntime) and callbacks (~7%) executed undermutex_, forcing 10,000 concurrent frees to serialize into ~1s of lock contention.This change:
BlockRefCounterupdates ASAP);object_free_rpc_service_thread, keeping them off bothio_service_(gRPC handlers, GCS) andobject_freed_callback_service_(lightweight BRC callbacks).How the speedup works
FreeObjectOnNodesAsyncsends gRPC RPCs to remote nodes to free their copies of an object. Previously it ran undermutex_insideOnObjectOutOfScopeOrFreed, so eachRemoveLocalReferenceheld the lock for ~80us (18us ref counting + 56us gRPC). When Python frees 10k refs, each ref's__dealloc__callsRemoveLocalReferencesequentially, and the next ref can't start until the current ref's gRPC finishes. With this change, the lock is released after ref counting (~18us) and the gRPC is posted to a dedicated thread, so the main thread immediately moves to the next ref while gRPC calls run in parallel.Benchmark results
Compared against baseline (master, averaged across 4 builds). Each latency metric measures the time from ref drop to individual callback firing. p50, p95, p99, and max are all recorded by the benchmark, but p95 is selected here for horizontal comparison.
Pipeline p95 (steady-state, one ref at a time) is unchanged, as expected.
Per-callback p95 (individual
del refto callback latency) regressed at large scales (0.7ms to 3.1ms at 10k) because callback posting now happens after mutex release + deferred work swap instead of immediately under mutex. This is a tradeoff: individual callback latency is slightly higher, but total burst drain time is 3-4x faster.Related issues
Related to #64521 (callback throughput benchmark).
Related to #64456 (BlockRefCounter-based memory tracking).