Skip to content

[Data] [Core] [1/n] Add dedicated callback thread and Cython API for out-of-scope objects - #64011

Merged
bveeramani merged 41 commits into
ray-project:masterfrom
rayhhome:callback-core-wiring
Jun 29, 2026
Merged

bveeramani merged 41 commits into
ray-project:masterfrom
rayhhome:callback-core-wiring

Conversation

@rayhhome

@rayhhome rayhhome commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

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(id_bytes)

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 5 live-cluster tests. Checks fire on del 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.

rayhhome added 2 commits June 10, 2026 15:26
Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: Sirui Huang <[email protected]>
@rayhhome rayhhome self-assigned this Jun 10, 2026
@rayhhome
rayhhome requested a review from a team as a code owner June 10, 2026 23:50
Copilot AI review requested due to automatic review settings June 10, 2026 23:50
@rayhhome rayhhome added core Issues that should be addressed in Ray Core data Ray Data-related issues go add ONLY when ready to merge, run all tests labels Jun 10, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread python/ray/_raylet.pyx Resolved
Comment thread src/ray/core_worker/core_worker.cc Resolved
Comment thread python/ray/_raylet.pyx Resolved
Comment thread src/ray/core_worker/core_worker.cc Resolved
Comment thread python/ray/_raylet.pyx Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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::AddObjectOutOfScopeOrFreedCallback overloads (std::function + C function-pointer) and exposes CoreWorker.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.

Comment thread python/ray/_raylet.pyx Resolved
Comment thread python/ray/_raylet.pyx Resolved
Signed-off-by: Sirui Huang <[email protected]>
Comment thread python/ray/_raylet.pyx Resolved
Comment thread python/ray/_raylet.pyx Resolved
Comment thread release/release_tests.yaml Outdated
timeout: 600
script: python object_store/test_callback_throughput.py
wait_for_nodes:
num_nodes: 101

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need that many node for this? Seems expensive.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cut node count down to 10.

return np.zeros(OBJECT_SIZE, dtype=np.uint8)


def test_callback_throughput(num_refs, timeout_s=60):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Finally, could you add the test's output visible on core's preset dashboard. This way we can monitor it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will add it once the PR gets merged!

Comment thread python/ray/_private/ray_perf.py Outdated
results += timeit(
"object out-of-scope callback fire 1k batch", oos_callback_fire_batch, 1000
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Like the comment for the benchmark test below, we want to move away from testing a feature repeatedly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed this repetitive microbenchmark completely in the new commit!

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit f462377. Configure here.

Comment thread src/ray/core_worker/core_worker.h Resolved

@Kunchd Kunchd left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

return total_s
avg_latency = sum(latencies) / len(latencies)
print(f" {num_blocks} blocks: avg={avg_latency:.4f}s")
return avg_latency

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

avg latency might be misleading, could we return the p95 and/or p99 instead?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense; switched to p95 in the new commit!

@rayhhome rayhhome left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense; switched to p95 in the new commit!

@bveeramani
bveeramani merged commit 825da92 into ray-project:master Jun 29, 2026
3 checks passed
@rayhhome
rayhhome deleted the callback-core-wiring branch June 29, 2026 23:15
bveeramani pushed a commit that referenced this pull request Jul 2, 2026
…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]>
elliot-barn pushed a commit that referenced this pull request Jul 9, 2026
…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]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…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]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core Issues that should be addressed in Ray Core data Ray Data-related issues go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants