Repository navigation
[Serve] Stop blocking _to_object_ref on the replica's return value - #65243
Conversation
63d186a to
bbe4acf
Compare
…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]>
bbe4acf to
674b6e8
Compare
_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]>
Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
1be357c to
475c5f4
Compare
Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
106f38d to
51df0a6
Compare
Signed-off-by: Rueian Huang <[email protected]>
51df0a6 to
2716015
Compare
Signed-off-by: Rueian Huang <[email protected]>
abrarsheikh
left a comment
There was a problem hiding this comment.
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.
| @@ -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() | |||
There was a problem hiding this comment.
Should this cancel function be dropped (or become a no-op) once the ready callback has already fired?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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() | |||
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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_idalive 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) |
There was a problem hiding this comment.
Why don't we need the timeout anymore?
There was a problem hiding this comment.
That is the purpose of this PR, making replica_result.to_object_ref() return immediately by returning the peeked ref.
| * | ||
| * 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. |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Yeah, we can throw an object loss error.
| return 0; | ||
| } | ||
|
|
||
| std::shared_ptr<WaitAsyncState> state = std::make_shared<WaitAsyncState>(); |
There was a problem hiding this comment.
We want to avoid using share_ptr in the code base.
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_object_ref_ready_cancel(ray_start_regular_shared): |
There was a problem hiding this comment.
nit: Same as above, maybe we could make the async nature of the test more explicit in the name.
| DrainIoUntilWaitAsyncDone(io_service_, result); | ||
| ASSERT_EQ(result.calls, 1); | ||
| ASSERT_TRUE(result.status.ok()); | ||
| } |
There was a problem hiding this comment.
Could we add a case for inlined objects?
| @@ -94,6 +94,27 @@ TEST(TestMemoryStore, TestReportUnhandledErrors) { | |||
| ASSERT_EQ(unhandled_count, 0); | |||
| } | |||
|
|
|||
There was a problem hiding this comment.
Should we add a case for the GetAsync call?
| ASSERT_EQ(result.calls, 1); | ||
| ASSERT_TRUE(result.status.ok()); | ||
| } | ||
|
|
There was a problem hiding this comment.
Should we add a case for borrowed objects?
| except asyncio.CancelledError: | ||
| cancel() | ||
| raise |
There was a problem hiding this comment.
What might actually trigger the canceled error here? When Ray serve actually cancels the DeploymentResponseBase, does it trigger the cancelled error here?
There was a problem hiding this comment.
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")Signed-off-by: Rueian Huang <[email protected]>
0915262 to
8edc0c9
Compare
Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 7f9ff6f. Configure here.
Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
Signed-off-by: Rueian Huang <[email protected]>
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
left a comment
There was a problem hiding this comment.
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.
…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]>
…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]>

Continue the #64451 to fix the long-standing issue in serve where
_to_object_refblocks until the underlying result has been produced. (#46893)Summary
_to_object_refused to block until the replica produced the user value. After this PR it returns the userObjectRefas 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_refnon-blocking on the user value.ObjectRef._ready()is a new separate presence wait (CoreWorker::WaitAsyncon the local memory store, no plasma pull). Serve uses it so composition args are not enqueued until the upstream object exists.