Skip to content

[Serve] Stop blocking _to_object_ref on the replica's return value - #65243

Merged
rueian merged 36 commits into
ray-project:masterfrom
rueian:eoakes/serve-gen-peek
Sep 26, 2026
Merged

rueian merged 36 commits into
ray-project:masterfrom
rueian:eoakes/serve-gen-peek

Conversation

@rueian

@rueian rueian commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Continue the #64451 to fix the long-standing issue in serve where _to_object_ref blocks until the underlying result has been produced. (#46893)

Summary

_to_object_ref used to block until the replica produced the user value. After this PR it returns the user ObjectRef as soon as the request is assigned, without fetching the value.

On the default unary path (handle_request_with_rejection), get_rejection_response() peeks that ref with _get_next_ref_n(1) after the replica accepts. That is what makes _to_object_ref non-blocking on the user value.

ObjectRef._ready() is a new separate presence wait (CoreWorker::WaitAsync on the local memory store, no plasma pull). Serve uses it so composition args are not enqueued until the upstream object exists.

@rueian
rueian force-pushed the eoakes/serve-gen-peek branch 4 times, most recently from 63d186a to bbe4acf Compare August 6, 2026 00:00
…to_object_ref

Eagerly peek unary/rejection refs so to_object_ref(_async) returns immediately
instead of waiting for the replica to produce the result.

Co-authored-by: Edward Oakes <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
@rueian
rueian force-pushed the eoakes/serve-gen-peek branch from bbe4acf to 674b6e8 Compare August 6, 2026 00:00
@rueian rueian changed the title Eoakes/serve gen peek serve gen peek Aug 6, 2026
rueian added 2 commits August 5, 2026 17:35
_to_object_ref now returns immediately, so composition must still await
the upstream ref before counting the request toward autoscaling.

Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
@rueian rueian added core Issues that should be addressed in Ray Core go add ONLY when ready to merge, run all tests labels Aug 6, 2026
@rueian
rueian force-pushed the eoakes/serve-gen-peek branch from 1be357c to 475c5f4 Compare August 16, 2026 03:01
@rueian
rueian force-pushed the eoakes/serve-gen-peek branch 2 times, most recently from 106f38d to 51df0a6 Compare August 31, 2026 22:30
Signed-off-by: Rueian Huang <[email protected]>
@rueian
rueian force-pushed the eoakes/serve-gen-peek branch from 51df0a6 to 2716015 Compare August 31, 2026 22:34
@rueian rueian changed the title serve gen peek [WIP] serve gen peek Sep 2, 2026
Signed-off-by: Rueian Huang <[email protected]>
@rueian rueian changed the title [WIP] serve gen peek [Serve] Stop blocking _to_object_ref on the replica's return value Sep 2, 2026

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

High level looks good to me. I am unfamiliar with C changes so have some questions.

from serve side i think change looks good.

@Stack-Attack @suppagoddo This PR will unblock you from doing async inferance in ray serve.

Comment thread python/ray/_raylet.pyx Resolved
Comment thread src/ray/core_worker/core_worker.cc Resolved
Comment thread python/ray/includes/object_ref.pxi Resolved
@@ -215,6 +255,9 @@ def add_done_callback(self, callback: Callable):
self._obj_ref._on_completed(callback) # type: ignore[union-attr]

def cancel(self):
if self._cancel_consume_wait is not None:
self._cancel_consume_wait()

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.

Should this cancel function be dropped (or become a no-op) once the ready callback has already fired?

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 _cancel_consume_wait itself will be a no-op then, but it is a good idea to clear it in the Python on_ready callback directly. Addressed in the latest commit.

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.

Two-read race in cancel(). The io-thread callback now sets _cancel_consume_wait = None. cancel() checks the attribute and then reads it again to call it. A GIL switch between those two reads makes the second read return None, and the call raises TypeError. That happens before ray.cancel runs, so the request is not cancelled. Fix is a local variable: read once, call if not None.

Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
@@ -215,6 +255,9 @@ def add_done_callback(self, callback: Callable):
self._obj_ref._on_completed(callback) # type: ignore[union-attr]

def cancel(self):
if self._cancel_consume_wait is not None:
self._cancel_consume_wait()

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.

Two-read race in cancel(). The io-thread callback now sets _cancel_consume_wait = None. cancel() checks the attribute and then reads it again to call it. A GIL switch between those two reads makes the second read return None, and the call raises TypeError. That happens before ray.cancel runs, so the request is not cancelled. Fix is a local variable: read once, call if not None.

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

@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 the PR, and sorry for the delay! I left some comments and questions, but my main one is on this comment in core_worker.h

The caller must keep a reference to object_id alive until the callback runs; if the last reference is dropped the object can be deleted from the memory store and the wait will never complete.

This feels like we're putting a lot of responsibility on the caller. Do we want to throw an error when the object gets freed instead? Additionally, if the asynchronous wait is invoked on the object, doesn't that automatically mean there has to be at least still a ref around that's preventing the object from being freed?

start_time_s=start_time_s,
curr_time_s=time.time(),
)
return replica_result.to_object_ref(timeout_s=remaining_timeout_s)

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 don't we need the timeout anymore?

@rueian rueian Sep 19, 2026 •

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 is the purpose of this PR, making replica_result.to_object_ref() return immediately by returning the peeked ref.

Comment thread src/ray/core_worker/core_worker.h Outdated
*
* The caller must keep a reference to ``object_id`` alive until the callback
* runs; if the last reference is dropped the object can be deleted from the
* memory store and the wait will never complete.

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.

This behavior is kinda weird for users as it puts extra responsibility on them compared to the synchronous wait. Should we be checking if the object is still alive and throwing an error status 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.

Yeah, we can throw an object loss error.

Comment thread python/ray/_raylet.pyx Resolved
Comment thread src/ray/core_worker/core_worker.cc Outdated
return 0;
}

std::shared_ptr<WaitAsyncState> state = std::make_shared<WaitAsyncState>();

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.

We want to avoid using share_ptr in the code base.

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.

👍

Comment thread src/ray/core_worker/core_worker.cc Resolved
Comment thread python/ray/tests/test_asyncio.py Outdated


@pytest.mark.asyncio
async def test_object_ref_ready_cancel(ray_start_regular_shared):

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.

nit: Same as above, maybe we could make the async nature of the test more explicit in the name.

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.

👌

DrainIoUntilWaitAsyncDone(io_service_, result);
ASSERT_EQ(result.calls, 1);
ASSERT_TRUE(result.status.ok());
}

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.

Could we add a case for inlined objects?

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.

🆗

@@ -94,6 +94,27 @@ TEST(TestMemoryStore, TestReportUnhandledErrors) {
ASSERT_EQ(unhandled_count, 0);
}

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.

Should we add a case for the GetAsync call?

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.

🆗

ASSERT_EQ(result.calls, 1);
ASSERT_TRUE(result.status.ok());
}

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.

Should we add a case for borrowed objects?

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.

🆗

Comment on lines +211 to +213
except asyncio.CancelledError:
cancel()
raise

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.

What might actually trigger the canceled error here? When Ray serve actually cancels the DeploymentResponseBase, does it trigger the cancelled error here?

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.

For example:

@ray.remote
def blocked():
    time.sleep(10**9)

async def main():
    ref = blocked.remote()
    task = asyncio.create_task(ref._ready())
    task.cancel()  # this is what raises CancelledError inside _ready()
    try:
        await task
    except asyncio.CancelledError:
        print("cancelled")

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

Stale Bugbot comment from a previous run.

Comment thread src/ray/core_worker/core_worker.cc Resolved
Signed-off-by: Rueian Huang <[email protected]>
@rueian
rueian force-pushed the eoakes/serve-gen-peek branch from 0915262 to 8edc0c9 Compare September 19, 2026 07:23
Signed-off-by: Rueian Huang <[email protected]>

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

Stale Bugbot comment from a previous run.

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

@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 7f9ff6f. Configure here.

Comment thread src/ray/core_worker/core_worker.cc Resolved
Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
@rueian

rueian commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the PR, and sorry for the delay! I left some comments and questions, but my main one is on this comment in core_worker.h

The caller must keep a reference to object_id alive until the callback runs; if the last reference is dropped the object can be deleted from the memory store and the wait will never complete.

This feels like we're putting a lot of responsibility on the caller. Do we want to throw an error when the object gets freed instead? Additionally, if the asynchronous wait is invoked on the object, doesn't that automatically mean there has to be at least still a ref around that's preventing the object from being freed?

During an offline discussion with @Kunchd, we found that to throw an error when the object gets freed, we need to subscribe to reference counting on _on_ready registration, but that can hurt performance because it incurs lock contention between a Python thread and a core worker thread. Unless we took another route to put background checks on other threads for each serve ref with _on_ready registration, which is also not appealing.

Given that Ray Serve keeps the ref for the whole wait, we decided we won't throw an error when the object gets freed, aligning with the existing _on_completed.

@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 documenting our conversation offline! The rest of the code looks good. If we ever plan on making the wair async API public. We should consider raising the error if a wait was invoked on an object ref that's gone out of scope.

@rueian
rueian enabled auto-merge (squash) September 25, 2026 22:20
@rueian
rueian merged commit c1cd00a into ray-project:master Sep 26, 2026
7 checks passed
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…ay-project#65243)

Continue the ray-project#64451 to fix the
long-standing issue in serve where `_to_object_ref` blocks until the
underlying result has been produced.
(ray-project#46893)

## Summary

`_to_object_ref` used to block until the replica produced the user
value. After this PR it returns the user `ObjectRef` as soon as the
request is assigned, without fetching the value.

On the default unary path (`handle_request_with_rejection`),
`get_rejection_response()` peeks that ref with `_get_next_ref_n(1)`
after the replica accepts. That is what makes `_to_object_ref`
non-blocking on the user value.

`ObjectRef._ready()` is a new separate presence wait
(`CoreWorker::WaitAsync` on the local memory store, no plasma pull).
Serve uses it so composition args are not enqueued until the upstream
object exists.

---------

Signed-off-by: Rueian Huang <[email protected]>
Co-authored-by: Edward Oakes <[email protected]>
sai-miduthuri added a commit that referenced this pull request Nov 10, 2026
…rent stack before py calls (#67132) (#68023)

## Description

Cherry-pick of #67132 (master commit
6077a8a) onto `releases/2.59.2`.

#64772, which is in 2.59, re-anchors CPython 3.14's stack-protection
bounds to the async actor's fiber stack on each task switch, to fix a
memory leak. But the re-anchor runs after `task_execution_handler` has
already made a Python call on the new fiber. That call can see the stale
bounds and raise a spurious `RecursionError`, which crashes the actor
worker with `Check failed: objects_valid 1 return objects expected, 1
returned. Object at idx 0 was not stored.` This is #66399 (P1).

#67132 re-anchors the boundary to the current stack before any Python
call in `task_execution_handler`.

## Related issues

Related to #67132 and #66399. The same pick for 2.60.1 is #67996.

## Additional information

### Cherry-pick details

Applied cleanly with `git cherry-pick -x`. It has the same 2 files,
+287/-106, and the same `git patch-id --stable` as the master commit.

No prerequisite commits are missing:

- #64772 is on this branch; it merged to master before the 2.59 branch
cut.
- `_raylet.pyx` differs from master at 6077a8a by #66514, #65243 and
#65487, which aren't on this branch. None of them touches
`task_execution_handler`, the only function #67132 changes.
- `test_asyncio.py` differs from master by tests that #66576 and #65243
add. #67132's two tests go after
`test_async_actor_finalizes_objects_dropped_on_fiber`, which this branch
has from #64772.

Not a duplicate: this branch doesn't contain #67132, and no PR against
`releases/2.59.2` references it.

### Testing

| Command | Result |
|---|---|
| `pre-commit run --files python/ray/_raylet.pyx
python/ray/tests/test_asyncio.py` | Passed, including cython-lint |

I didn't run the tests locally. `_raylet.pyx` needs a full Ray build,
which wasn't practical on my machine.

Both new tests in `test_asyncio.py` skip below CPython 3.14. Premerge CI
on this branch runs the core Python tests on 3.10, and postmerge also on
3.12, so it runs the rest of `test_asyncio.py` against the changed
`task_execution_handler`, but not these two tests.

AI assistance was used to prepare this cherry-pick.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: davik <[email protected]>
Signed-off-by: Sai Miduthuri <[email protected]>
Co-authored-by: Kunchen (David) Dai <[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 go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants