Skip to content

[Data] [Core] [2.5/n] Remove BlockRefCounter.clear() and expand callback throughput benchmark - #64521

Merged
justinvyu merged 26 commits into
ray-project:masterfrom
rayhhome:callback-oos-api
Aug 5, 2026
Merged

justinvyu merged 26 commits into
ray-project:masterfrom
rayhhome:callback-oos-api

Conversation

@rayhhome

@rayhhome rayhhome commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Remove BlockRefCounter.clear() and its shutdown wiring
  • Expand callback throughput release benchmark

Description

Removes BlockRefCounter.clear() and the _block_ref_counter.clear() call in StreamingExecutor.shutdown(). The clear() method was added for deterministic cleanup on executor shutdown, but profiling and benchmarking showed:

  1. Blocks are freed naturally via out-of-scope callbacks when their ObjectRefs go out of scope. Explicit clearing is unnecessary.
  2. Removing clear() had no measurable impact on release test benchmarks.

Also expands test_callback_throughput.py (previously only had an incremental pipeline test) with additional benchmark tests at multiple scales (100 to 10,000 blocks):

  • Registration cost: time to register one out-of-scope callback via BlockRefCounter.on_block_produced
  • Incremental pipeline: blocks produced, consumed, and released one at a time (steady-state)
  • Burst drop: all refs dropped at once without BlockRefCounter, measures time from drop to callback firing
  • Per-callback latency: refs dropped one at a time, measures per-block delay from drop to callback
  • BlockRefCounter burst drop: same as burst drop, but the callback also updates a BlockRefCounter Python dict, matching how BRC is used in production

Benchmark results

Averaged across 4 builds (102169, 101688, 101413, 101369). 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.

Metric (p95) 100 1k 5k 10k
Registration cost (us) 2.33 32.73 2.10 1.93
Incremental pipeline p95 0.35ms 0.63ms 1.23ms 1.15ms
Burst drain p95 7.80ms 76.98ms 574.63ms 986.28ms
Per-callback p95 0.15ms 0.25ms 0.88ms 0.70ms
BRC burst p95 7.83ms 77.45ms 470.73ms 977.90ms

Note: Registration cost at 1k (32.73us) is inflated by 3 of 4 builds showing ~40us, while the 4th shows 1.8us. Other scales are consistently ~2us, likely a warmup outlier rather than a scaling issue.

Related issues

Depends on #64157 (BlockRefCounter implementation).
Related to #63601 (prototype), #63074 (previous manual BlockRefCounter).

@rayhhome rayhhome self-assigned this Jul 2, 2026
@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 Jul 2, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

@rayhhome
rayhhome marked this pull request as ready for review July 2, 2026 23:13
@rayhhome
rayhhome requested a review from a team as a code owner July 2, 2026 23:13
Copilot AI review requested due to automatic review settings July 2, 2026 23:13

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

Adds a symmetric “remove” API for Ray Core’s object out-of-scope/freed callback mechanism so callers (notably Python) can explicitly deregister callbacks and trigger their cleanup logic deterministically, rather than relying on callbacks becoming lazy no-ops.

Changes:

  • Introduces ReferenceCounterInterface::RemoveObjectOutOfScopeOrFreedCallbacks and implements it in ReferenceCounter.
  • Plumbs the API through CoreWorker and exposes it to Python via libcoreworker.pxd and _raylet.pyx.
  • Adds a C++ unit test covering “remove fires once; natural out-of-scope does not fire again”.

Reviewed changes

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
src/ray/core_worker/tests/reference_counter_test.cc Adds a unit test validating removal fires callbacks exactly once.
src/ray/core_worker/reference_counter.h Declares the new removal API on the concrete reference counter.
src/ray/core_worker/reference_counter.cc Implements callback firing + clearing for the new removal API.
src/ray/core_worker/reference_counter_interface.h Adds the new API to the core reference counter interface and documents behavior.
src/ray/core_worker/core_worker.h Declares a CoreWorker wrapper for the new removal API.
src/ray/core_worker/core_worker.cc Implements the CoreWorker wrapper by delegating to the reference counter.
python/ray/includes/libcoreworker.pxd Exposes the CoreWorker removal method to Cython.
python/ray/_raylet.pyx Adds a Python-facing internal method to trigger callback removal/cleanup.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +332 to +334
/// Removes and fires all out-of-scope/freed callbacks for `object_id`.
/// Firing allows per-callback cleanup (e.g. Py_DECREF on the Python side).
/// After this call, no further out-of-scope callbacks will fire for this object.
Comment thread python/ray/_raylet.pyx Outdated
Comment on lines +4304 to +4308
"""Remove and fire all out-of-scope callbacks for the given object.

Firing allows per-callback cleanup (e.g. Py_DECREF). After this
call, no further out-of-scope callbacks will fire for this object.

@rayhhome rayhhome changed the title [Data] [Core] [2.5/n] Add RemoveObjectOutOfScopeOrFreedCallbacks API for Callback Cleanup [Data] [Core] [2.5/n] Unregister Out-of-scope Callback when clear is Called Jul 2, 2026
@rayhhome rayhhome changed the title [Data] [Core] [2.5/n] Unregister Out-of-scope Callback when clear is Called [Data] [Core] [2.5/n] Deregister Out-of-scope Callback when clear is Called Jul 2, 2026
@rayhhome
rayhhome force-pushed the callback-oos-api branch from 200944a to c3a6c68 Compare July 3, 2026 05:37

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

I don't have any big concerns with this PR, but I'm struggling to determine the use case for this. We currently clean up the callback when the object goes out of scope and the callback is invoked. Why is explicit clean up necessary? Could we include the motivation in the PR description?

Comment on lines +895 to +897
for (const auto &callback : it->second.on_object_out_of_scope_or_freed_callbacks) {
callback(object_id);
}

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.

Why is invoking all the callbacks neecessary before removing the callbacks? Doesn't removing the callback mean we don't care about them anymore?

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.

BlockRefCounter's clear() is called when StreamingExecutor calls shutdown(), which happens when a dataset execution ends. In multi-epoch training (or any jobs with many dataset executions), this would be triggered many times. Since the callbacks have Py_DECREF to preserve the _on_object_freed closures, not triggering them would result in minor leaks. What's your take on this?

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 expect object produced within a specific epoch to stay around after the epoch finishes?

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

This PR is mainly for aligning the behavior of clear() with what the function name suggests. In the current implementation, only the Data side dictionary is cleared when clear() is called. The Core callbacks will still be fired when ObjectRefs go out of scope, which seems unintuitive based on what the function is intended to do.

However, I think this does raise the question on whether we need the clear() function at all, considering that no code reads the accounting after the shutdown. Will check this offline and come back with the decision.

Comment on lines +895 to +897
for (const auto &callback : it->second.on_object_out_of_scope_or_freed_callbacks) {
callback(object_id);
}

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.

BlockRefCounter's clear() is called when StreamingExecutor calls shutdown(), which happens when a dataset execution ends. In multi-epoch training (or any jobs with many dataset executions), this would be triggered many times. Since the callbacks have Py_DECREF to preserve the _on_object_freed closures, not triggering them would result in minor leaks. What's your take on this?

@rayhhome
rayhhome requested a review from a team as a code owner July 14, 2026 21:02
@rayhhome
rayhhome requested a review from a team as a code owner July 18, 2026 00:12
Comment thread python/ray/_raylet.pyx Resolved
@rayhhome rayhhome changed the title [Data] [Core] [2.5/n] Deregister Out-of-scope Callback when clear is Called [Data] [Core] [2.5/n] Remove BlockRefCounter.clear() and expand callback throughput benchmark Jul 27, 2026
self._clear_topology_queues_post_shutdown(force, exception)
# Queues have been drained; any remaining Ray Core callbacks that fire
# after this point should be no-ops.
self._block_ref_counter.clear()

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.

If we keep this code and there are 100k callbacks queued up, what actually happens? Does the ray core thread to fire callbacks add some latency on shutdown? Or is it a daemon thread that exits anyways once our main driver process exits?

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.

The callback thread is a daemon thread that exits anyways once our main driver process exits.

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.

Got it, so even if we kept clear(), the callbacks wouldn't block the process exit right?

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.

That's right

Comment on lines -78 to -81
"""Reset all accounting, e.g. on executor shutdown.

Any previously registered Ray Core callbacks firing after clear()
will be silently ignored because _registered_ids is empty.

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.

can you add some note about this in the BlockRefCounter top-level docstring?

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.

Added explanation: the callback-firing thread is a daemon thread in Ray Core and is killed automatically when the driver process exits. Any callbacks firing after shutdown would only decrement counters that are no longer read.

@justinvyu justinvyu 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.

Can you add a summary of the benchmark results in the PR description?

If I have X block frees queued up, what is my expected latency? Aka what is my expected accounting lag?

@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 adding the new benchmarks!

dict mapping id_binary -> per-block drop timestamp.
"""
if isinstance(drop_times, dict):
latencies = [fire_times[id_b] - drop_times[id_b] for id_b in id_binaries]

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.

Is it possible for us to get negative latency here? if the while loop processing the consumer completion can't keep up with the object freeing speed?

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.

I think we'll never see negative latency here; the drop_times timestamps are recorded before their corresponding del ref, and the callback can only fire after the ObjectRef is deleted.

return results


reg = _run_at_scales("Registration cost", test_registration_cost, SCALES)

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 want a new cluster per test? Otherwise subsequent runs might suffer if previous runs aren't cleaned up properly or something broke.

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.

I think it might be unnecessary? each test waits for all its callbacks to fire before returning (except for test_registration_cost, which I patched in new commit), and the tests also use distinct ObjectRefs from each other so there's no cross-contamination.

Signed-off-by: Sirui Huang <[email protected]>

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

Thanks a lot for the reviews! Added a commit addressing them.

Comment on lines -78 to -81
"""Reset all accounting, e.g. on executor shutdown.

Any previously registered Ray Core callbacks firing after clear()
will be silently ignored because _registered_ids is empty.

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.

Added explanation: the callback-firing thread is a daemon thread in Ray Core and is killed automatically when the driver process exits. Any callbacks firing after shutdown would only decrement counters that are no longer read.

self._clear_topology_queues_post_shutdown(force, exception)
# Queues have been drained; any remaining Ray Core callbacks that fire
# after this point should be no-ops.
self._block_ref_counter.clear()

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.

The callback thread is a daemon thread that exits anyways once our main driver process exits.

dict mapping id_binary -> per-block drop timestamp.
"""
if isinstance(drop_times, dict):
latencies = [fire_times[id_b] - drop_times[id_b] for id_b in id_binaries]

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.

I think we'll never see negative latency here; the drop_times timestamps are recorded before their corresponding del ref, and the callback can only fire after the ObjectRef is deleted.

return results


reg = _run_at_scales("Registration cost", test_registration_cost, SCALES)

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.

I think it might be unnecessary? each test waits for all its callbacks to fire before returning (except for test_registration_cost, which I patched in new commit), and the tests also use distinct ObjectRefs from each other so there's no cross-contamination.

@justinvyu
justinvyu merged commit 877314f into ray-project:master Aug 5, 2026
6 checks passed
Artimislyy pushed a commit to Artimislyy/ray that referenced this pull request Aug 11, 2026
…lback throughput benchmark (ray-project#64521)

- Remove `BlockRefCounter.clear()` and its shutdown wiring
- Expand callback throughput release benchmark

---------

Signed-off-by: Sirui Huang <[email protected]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…lback throughput benchmark (ray-project#64521)

- Remove `BlockRefCounter.clear()` and its shutdown wiring
- Expand callback throughput release benchmark

---------

Signed-off-by: Sirui Huang <[email protected]>
Signed-off-by: 400Ping <[email protected]>
marwan116 added a commit to marwan116/ray that referenced this pull request Sep 22, 2026
ray-project#64521 removed `clear()`, but two comments still explain the `_registered_ids`
membership check in terms of it, pointing a reader at a method that is no
longer there. With `clear()` gone the check guards a repeat notification for
an ID that is already gone, so say that instead.

Comment-only, and bundled here because this PR is already editing the file.

Signed-off-by: Marwan Sarieddine <[email protected]>
marwan116 added a commit to marwan116/ray that referenced this pull request Sep 22, 2026
ray-project#64521 removed `clear()`, but two comments still explain the `_registered_ids`
membership check in terms of it, pointing a reader at a method that is no
longer there. With `clear()` gone the check guards a repeat notification for
an ID that is already gone, so say that instead.

Comment-only, and bundled here because this PR is already editing the file.

Signed-off-by: Marwan Sarieddine <[email protected]>
marwan116 added a commit to marwan116/ray that referenced this pull request Sep 22, 2026
Reverts 6dc81a0 to keep this PR to the bug fix alone.

Those two comments do name a method that ray-project#64521 removed, so the cleanup is
correct on master. But it is unrelated to the crash, and on releases/2.57.0 --
the earliest branch this fix has to reach, since BlockRefCounter arrived in
2.57 -- `clear()` still exists. Reworded there, the comments would be wrong.

Leaving them untouched keeps the backport a single hunk-for-hunk cherry-pick
with nothing a backporter has to remember to drop.

Signed-off-by: Marwan Sarieddine <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…lback throughput benchmark (ray-project#64521)

- Remove `BlockRefCounter.clear()` and its shutdown wiring
- Expand callback throughput release benchmark

---------

Signed-off-by: Sirui Huang <[email protected]>
@rayhhome
rayhhome deleted the callback-oos-api branch October 19, 2026 16:41
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