Skip to content

[Data] [0/n] Prototyping Track Per-op Object Store Memory with Ray Core Out-of-scope Callbacks - #63601

Closed
rayhhome wants to merge 37 commits into
ray-project:masterfrom
rayhhome:callback-ref-count
Closed

rayhhome wants to merge 37 commits into
ray-project:masterfrom
rayhhome:callback-ref-count

Conversation

@rayhhome

@rayhhome rayhhome commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Description

ResourceManager previously estimated each operator's object-store memory by summing size_bytes from BlockMetadata across 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_ready calls on_block_produced(ref, size_bytes, producer_id). This records the block's size under the producing operator's ID and installs a Ray Core AddObjectOutOfScopeOrFreedCallback on the ObjectRef.

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_usage replaces the old multi-queue sum with a single counter.get_object_store_memory_usage(op.id) call.

Because memory is attributed by ObjectRef identity 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 to ReferenceCounter::AddObjectOutOfScopeOrFreedCallback.

Dedicated callback thread (core_worker_process.h/.cc, reference_counter.h/.cc)

ReferenceCounter previously 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, CoreWorkerProcessImpl now owns a dedicated object_freed_callback_service_ (instrumented_io_context) + thread; ReferenceCounter post()s each callback to it so the IO thread returns immediately. The callback thread shares io_thread_'s attributes (Mac 16 MB stack, signal masking) and is joined in CoreWorkerShutdownExecutor::ExecuteGracefulShutdown after io_thread_.

BlockRefCounter (new file)

Thread-safe counter with three public methods: on_block_produced, get_object_store_memory_usage, and clear. Two design details worth noting:

  • Deduplication: if the same ObjectRef appears in multiple RefBundles (e.g. after randomize_blocks copies bundles), only the first on_block_produced call counts; subsequent calls for the same ID are no-ops.
  • Shutdown safety: 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 + DataOpTask

DataOpTask is the common task wrapper used by all map-style operators. Adding block_ref_counter and producer_id parameters to its constructor means every operator that uses DataOpTask gets counter support for free, without per-operator changes. on_block_produced is called inside on_data_ready behind a None check, so the counter can safely be absent in unit tests that construct DataOpTask directly. In practice the counter is always present at task run time, guaranteed by the executor wiring below.

PhysicalOperator gains a set_block_ref_counter setter used for executor-time injection.

AllToAllOperator.all_inputs_done

AllToAllOperator uses a bulk_fn instead of DataOpTask, so it registers blocks directly. It snapshots input_refs before calling bulk_fn, then calls on_block_produced only for ObjectRefs that are genuinely new in the output. Forwarded refs (such as from randomize_blocks) are skipped and stay attributed to their original producer.

MapOperator, HashShufflingOperator, GPU HashShuffleOperator

Pass block_ref_counter and producer_id through to DataOpTask. These are the only operators that construct DataOpTask directly.

ResourceManager + StreamingExecutor

ResourceManager.__init__ creates the single shared BlockRefCounter for the execution and exposes it via a block_ref_counter property. StreamingExecutor.execute() injects the counter into every operator via set_block_ref_counter after topology construction, then calls counter.clear() on shutdown so late-firing GC callbacks are harmless.

Operators requiring no changes

OutputSplitter, LimitOperator, ZipOperator, and AggregateNumRows all have throttling_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. UnionOperator is eligible but produces no new ObjectRefs, 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), and streaming_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) are null on master — not measured, not assumed. compare() skips null values so no spurious threshold fires; _check_invariants skips null values 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 containing benchmark.py and block_ref_counter_benchmark.py, which they import directly).

Example outputs (local --scale small run)

baseline.json (master — all counter fields null, 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 uses streaming_split so its executor runs inside a SplitCoordinator actor with its own DataContext, 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 time includes a ~5 s post-shutdown settle poll (callback_settle_time_s); pipeline_time_s = time - callback_settle_time_s is what the regression comparison uses.

accuracy-baseline.json (master — counter and accuracy fields null):

{
  "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_shadow delta (~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:

Case/Metric                                                 Baseline       Branch     Delta   Status
----------------------------------------------------------------------------------------------------
s1-fast-producer-slow-consumer/pipeline_time_s                  1.5105       1.4807    -2.0%       ok
s1-fast-producer-slow-consumer/object_store_spilled_total_gb    0.0000       0.0000    +0.0%       ok
s1-fast-producer-slow-consumer/object_store_memory_used_peak_gb 0.2501       0.0625   -75.0%       ok
s2-map-throughput/pipeline_time_s                               2.0400       2.0114    -1.4%       ok
s2-map-throughput/object_store_spilled_total_gb                 0.0000       0.0000    +0.0%       ok
s2-map-throughput/object_store_memory_used_peak_gb              0.0003       0.0003    +0.0%       ok
s2-map-throughput/tput                                     490751.4917  497740.5481    +1.4%       ok
s3-sort-alltoall/pipeline_time_s                                0.6144       0.2280   -62.9%       ok
s3-sort-alltoall/object_store_spilled_total_gb                  0.0000       0.0000    +0.0%       ok
s3-sort-alltoall/object_store_memory_used_peak_gb               0.0002       0.0002    +0.0%       ok
s4-training-prefetch/pipeline_time_s                            1.7591       1.7006    -3.3%       ok
s4-training-prefetch/object_store_spilled_total_gb              0.0000       0.0000    +0.0%       ok
s4-training-prefetch/object_store_memory_used_peak_gb           0.2501       0.2501    +0.0%       ok

Result: PASSED

python block_ref_counter_benchmark.py compare accuracy-baseline.json accuracy-branch.json — S5/S6 summary (accuracy metrics are branch-only; null on master means not measured):

Case/Metric                                                 Baseline       Branch     Delta   Status
----------------------------------------------------------------------------------------------------
s5-per-operator-accuracy/pipeline_time_s                        2.7534       2.6963    -2.1%       ok
s5-per-operator-accuracy/object_store_spilled_total_gb          0.0000       0.0000    +0.0%       ok
s5-per-operator-accuracy/object_store_memory_used_peak_gb       0.0294       0.0284    -3.4%       ok
s5-per-operator-accuracy/counter_minus_shadow_mean_bytes          null      1330885       —  (branch only)
s5-per-operator-accuracy/counter_minus_shadow_max_bytes           null      4194304       —  (branch only)
s5-per-operator-accuracy/counter_zero_at_end                      null         true       —  (branch only)
s6-memory-constrained-spill/pipeline_time_s                    29.5909      29.1567    -1.5%       ok
s6-memory-constrained-spill/object_store_spilled_total_gb       0.0000       0.0000    +0.0%       ok
s6-memory-constrained-spill/object_store_memory_used_peak_gb    0.0685       0.0685    +0.0%       ok
s6-memory-constrained-spill/counter_zero_at_end                   null         true       —  (branch only)

Related issues

Implements a cleaner alternative to #63074 (manual dispatch/release tracking).

Tests

  • test_block_ref_counter.py (new): unit tests using a _FakeRef stub (produce/release, multi-producer isolation, deduplication, clear() + late-callback safety, concurrent callbacks); plus TestBlockRefCounterLifecycle integration tests against a live Ray cluster that exercise the full add_object_out_of_scope_callback → object_freed_callback_service_ path with real ObjectRefs.
  • test_resource_manager.py: test_update_usage and test_object_store_usage rewritten around the counter API; test_union_no_double_counting (new) confirms blocks flowing through UnionOperator are attributed only to their upstream producers and global usage is not inflated.
  • test_operators.py: test_all_to_all_operator and test_all_to_all_estimated_num_output_bundles updated to call set_block_ref_counter before all_inputs_done, satisfying the new assert.
  • test_streaming_executor.py: DataOpTask call sites updated via a _make_data_op_task helper that supplies a default counter and producer ID.

@rayhhome rayhhome self-assigned this May 22, 2026
@rayhhome rayhhome added the core Issues that should be addressed in Ray Core label May 22, 2026
@rayhhome
rayhhome requested a review from a team as a code owner May 22, 2026 17:59
Copilot AI review requested due to automatic review settings May 22, 2026 17:59
@rayhhome
rayhhome requested a review from a team as a code owner May 22, 2026 17:59
@rayhhome rayhhome added data Ray Data-related issues go add ONLY when ready to merge, run all tests labels May 22, 2026
Comment thread python/ray/_raylet.pyx Resolved

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

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 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 AddObjectOutOfScopeOrFreedCallback to Python (core_worker.h / libcoreworker.pxd / _raylet.pyx) and use it from Ray Data.
  • Add BlockRefCounter and wire it through StreamingExecutor → operators → DataOpTask / AllToAllOperator for 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.

Comment thread python/ray/_raylet.pyx Resolved
@rayhhome rayhhome changed the title [Data] Track Per-op Object Store Memory with Ray Core Out-of-scope Callbacks [Data] Prototyping Track Per-op Object Store Memory with Ray Core Out-of-scope Callbacks May 22, 2026

@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 2 potential issues.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit edbba9c. Configure here.

@rayhhome

rayhhome commented Jun 3, 2026

Copy link
Copy Markdown
Contributor Author

/gemini review

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

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.

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.

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.

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.

@rayhhome rayhhome changed the title [Data] Prototyping Track Per-op Object Store Memory with Ray Core Out-of-scope Callbacks [Data] [0/n] Prototyping Track Per-op Object Store Memory with Ray Core Out-of-scope Callbacks Jun 10, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

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.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Jun 25, 2026
bveeramani pushed a commit that referenced this pull request Jun 29, 2026
…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]>
@rayhhome

Copy link
Copy Markdown
Contributor Author

Closing this since follow-up stacked PRs have been created (new PR links will be updated here):
[1/n]: #64011;
[2/n]: #64157;
[3/n]: #64191;
[4/n]: #64192.

@rayhhome rayhhome closed this Jun 29, 2026
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]>
bveeramani pushed a commit that referenced this pull request Jul 3, 2026
## 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]>
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]>
elliot-barn pushed a commit that referenced this pull request Jul 9, 2026
## 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]>
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]>
400Ping pushed a commit to 400Ping/ray that referenced this pull request Aug 18, 2026
…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]>
@rayhhome
rayhhome deleted the callback-ref-count 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 stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants