Repository navigation
[Data] [Core] [1/n] Add dedicated callback thread and Cython API for out-of-scope objects - #64011
Conversation
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 mechanism to register user-defined callbacks that fire when a Ray object goes out of scope or is freed, utilizing a dedicated background thread to avoid blocking the main IO thread. The feedback highlights critical safety improvements, including wrapping the Cython callback instantiation in a try-except block that catches BaseException to prevent process crashes, validating that the Python callback is callable, avoiding a potential use-after-free by capturing the service pointer instead of this in the asynchronous lambda, and adding a defensive nullptr check for the C function pointer.
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 adds a dedicated “object-freed/out-of-scope callback” execution path in Ray Core (C++ + Cython) so Python can register callbacks that fire when an ObjectRef becomes out-of-scope or is explicitly freed, without running Python code while the reference-counter mutex is held.
Changes:
- Introduces a dedicated
instrumented_io_context+ thread (object_freed_callback_service_/object_freed_callback_thread_) for dispatching object-freed callbacks off the main IO thread. - Adds
CoreWorker::AddObjectOutOfScopeOrFreedCallbackoverloads (std::function + C function-pointer) and exposesCoreWorker.add_object_out_of_scope_callback()in Python via Cython. - Adds C++ and Python test coverage for callback behavior, registration semantics, and thread identity.
Reviewed changes
Copilot reviewed 9 out of 9 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| src/ray/core_worker/tests/core_worker_test.cc | Adds unit tests and test plumbing for dedicated callback service/thread behavior. |
| src/ray/core_worker/core_worker.h | Extends CoreWorker constructor + API surface to accept dedicated callback service/thread and expose registration methods. |
| src/ray/core_worker/core_worker.cc | Implements callback registration by posting user callbacks onto the dedicated callback service. |
| src/ray/core_worker/core_worker_shutdown_executor.cc | Stops and joins the dedicated callback thread during graceful shutdown. |
| src/ray/core_worker/core_worker_process.h | Adds process-level dedicated callback io_context, work guard, and thread members. |
| src/ray/core_worker/core_worker_process.cc | Starts the dedicated callback thread and wires the service/thread into CoreWorker construction. |
| python/ray/tests/test_object_out_of_scope_callback.py | Adds live-cluster integration tests for the Python callback API. |
| python/ray/includes/libcoreworker.pxd | Exposes the new C function-pointer overload to Cython. |
| python/ray/_raylet.pyx | Adds the Cython trampoline and Python-facing add_object_out_of_scope_callback method. |
💡 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]>
…allback-core-wiring
Signed-off-by: Sirui Huang <[email protected]>
…allback-core-wiring
Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: Sirui Huang <[email protected]>
…e-wiring Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: Sirui Huang <[email protected]>
| timeout: 600 | ||
| script: python object_store/test_callback_throughput.py | ||
| wait_for_nodes: | ||
| num_nodes: 101 |
There was a problem hiding this comment.
Do we need that many node for this? Seems expensive.
There was a problem hiding this comment.
Cut node count down to 10.
| return np.zeros(OBJECT_SIZE, dtype=np.uint8) | ||
|
|
||
|
|
||
| def test_callback_throughput(num_refs, timeout_s=60): |
There was a problem hiding this comment.
Our old release test benchmarks tends to measure repeated throughput of the same operations as an attempt to find regressions. However, we actually found these tests to be uninformative of actual use cases.
Instead, could you write the test closer to how ray data uses these (e.g. invoke a function that creates the object, pass it to the consumer, then check that its out of scope).
There was a problem hiding this comment.
Makes sense! This benchmark was originally added to measure the callback latency in the edge case of object bursts, but considering the benchmark being mainly used for revealing regressions, it does make more sense for the benchmark to reflect how the system works realistically. Adjusted the benchmark to a more standard producer-consumer pipeline.
| }, | ||
| ], | ||
| } | ||
| json.dump(results, out_file) |
There was a problem hiding this comment.
Finally, could you add the test's output visible on core's preset dashboard. This way we can monitor it.
There was a problem hiding this comment.
Will add it once the PR gets merged!
| results += timeit( | ||
| "object out-of-scope callback fire 1k batch", oos_callback_fire_batch, 1000 | ||
| ) | ||
|
|
There was a problem hiding this comment.
Like the comment for the benchmark test below, we want to move away from testing a feature repeatedly.
There was a problem hiding this comment.
Removed this repetitive microbenchmark completely in the new commit!
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 f462377. Configure here.
Kunchd
left a comment
There was a problem hiding this comment.
Thanks for all the work on this! The final note is that we might want to free the object refs as the consumer task completes instead of all in one go to better reflect data's workload. We can chat more about this offline.
Signed-off-by: Sirui Huang <[email protected]>
… Data execution logic Signed-off-by: Sirui Huang <[email protected]>
…allback-core-wiring
| return total_s | ||
| avg_latency = sum(latencies) / len(latencies) | ||
| print(f" {num_blocks} blocks: avg={avg_latency:.4f}s") | ||
| return avg_latency |
There was a problem hiding this comment.
avg latency might be misleading, could we return the p95 and/or p99 instead?
There was a problem hiding this comment.
Makes sense; switched to p95 in the new commit!
Signed-off-by: Sirui Huang <[email protected]>
rayhhome
left a comment
There was a problem hiding this comment.
Applied suggested change!
| return total_s | ||
| avg_latency = sum(latencies) / len(latencies) | ||
| print(f" {num_blocks} blocks: avg={avg_latency:.4f}s") | ||
| return avg_latency |
There was a problem hiding this comment.
Makes sense; switched to p95 in the new commit!
…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]>
…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]>
…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]>

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 theCoreWorker::AddObjectOutOfScopeOrFreedCallbackAPI along with its Python-facingadd_object_out_of_scope_callbackmethod. The Ray DataBlockRefCounterintegration (the primary consumer of this API) is left for a follow-up PR.Scope.
add_object_out_of_scope_callbackis a private internal API with a single intended caller: Ray Data'sBlockRefCounter. It is not part of the public Ray API and is not intended for general use.Motivation. Ray Data needs to know when an
ObjectRefis 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 asadd_object_out_of_scope_callback. The callback is dispatched on a dedicated thread rather than inline on the IO thread becauseOnObjectOutOfScopeOrFreedfires while holding the RC mutex; calling into Python there would stall the mutex waiting for the GIL, risking deadlock.C++.
CoreWorkerProcessImplgains a dedicatedobject_freed_callback_service_(instrumented_io_context) andobject_freed_callback_thread_, both passed toCoreWorker.CoreWorkerexposes two new overloads ofAddObjectOutOfScopeOrFreedCallback(astd::functionoverload 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 PythonCoreWorker. Acdef void noexcept nogilfunction handles GIL acquisition;Py_INCREFat registration keeps the callback alive across the async gap, andPy_DECREFruns in thefinallyblock when the callback fires (or immediately if registration fails).Related issues
Related to #63601 (initial prototype PR).
Additional information
Call flow.
Tests.
core_worker_test.cc: 6 newTEST_Ftests. 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 5 live-cluster tests. Checks fire ondel ref, false return for already-freed objects, multiple callbacks,ray.internal.free, and exception safety.release/benchmarks/object_store/test_callback_throughput.py: release benchmark measuring p95 callback latency with incremental block release on a 10-node cluster.