Repository navigation
Conversation
MessageQueue.get_one_message raised a stored error before returning messages that were already queued. With gRPC transport and the router on a separate loop, gRPCReplicaResult.consume_messages_from_gen buffers stream chunks ahead of the caller, so a transport failure mid-stream (e.g. the replica dying) dropped every chunk received but not yet read. Return queued messages first and raise the error once the queue is empty, as the docstring already describes. set_error now also wakes pending waiters, so a get_one_message call that is already blocked no longer hangs when an error is set without close(). Signed-off-by: GNITOAHC <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request modifies the MessageQueue in http_util.py to ensure that queued messages are fully drained before a set error is raised, and that pending waiters are woken up when an error is set. It also adds corresponding unit tests to verify this behavior, including handling of transport errors in gRPC replica results. The feedback suggests explicitly checking self._error is None instead of not self._error to avoid potential issues with custom exceptions that might evaluate to False.
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> Signed-off-by: Chao-Ting, Chen <[email protected]>
Signed-off-by: Chao-Ting, Chen <[email protected]>
hikaru-212
left a comment
There was a problem hiding this comment.
I independently verified a cancellation regression against merge-base ef74918f and PR HEAD ef93a768 using a real Serve streaming deployment.
After buffering A and B, I called response.cancel() and confirmed cancellation through gRPC, the server, and the background consumer.
- Parent: Subsequent reads immediately raise
RequestCancelledError. - HEAD: Subsequent reads return A, B, then
RequestCancelledError.
Both sync and async iterators reproduced this.
The transport-error fix is valid, but consume_messages_from_gen() also catches CancelledError, so the new drain-first behavior appears to violate the documented successful-cancellation contract.
Could explicit cancellation retain immediate-error semantics while transport failures still drain buffered messages?
The A/B tests used revision-specific Serve sources and protobuf bindings with a shared Ray 2.58.0 native core.
Draining buffered messages before raising is right for transport failures, but cancelling a streaming response surfaces as asyncio.CancelledError in consume_messages_from_gen, which then went through the same drain-first path. Reads after a successful cancel() returned buffered results before raising RequestCancelledError, violating the DeploymentResponse.cancel contract. Add a discard_messages option to MessageQueue.set_error and use it for CancelledError, restoring the previous immediate-raise behavior for cancellation while transport failures still drain first. Signed-off-by: Chao-Ting, Chen <[email protected]>
Signed-off-by: Chao-Ting, Chen <[email protected]>
|
@hikaru-212 thanks for the careful repro, confirmed and fixed in 1bf954d. |
|
Thanks for the fix! I independently re-ran the real Serve streaming reproducer against HEAD Both sync and async iterators now immediately raise All four focused regression tests passed, including the transport-error draining test. No further correctness issue found within the tested scope. The real Serve verification used the shared Ray 2.58.0 native core. |
|
Hi @jeffreywang88, could you take a look when you have a moment? This fixes |
…67531) ## Summary Corrects the exception that the `DeploymentResponse.cancel` docstring says later operations raise after a successful cancel. This is a docstring-only change. Behavior is unchanged. The docstring sits on `_DeploymentResponseBase`, so `DeploymentResponseGenerator.cancel` inherits the fix. ## Before > - If the request was cancelled before assignment, they'll raise `asyncio.CancelledError` (or a `concurrent.futures.CancelledError` for synchronous methods like `.result()`.). > - If the request was cancelled after assignment, they'll raise `ray.exceptions.TaskCancelledError`. A reader following this writes `except concurrent.futures.CancelledError:` around `.result()`, or `except asyncio.CancelledError:` around `await response`. Neither clause catches what Serve raises. ## What the code does Every path raises `ray.serve.exceptions.RequestCancelledError`, which subclasses `TaskCancelledError` ([exceptions.py#L101](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/exceptions.py#L101)): - **Synchronous, before assignment.** `_fetch_future_result_sync` catches the cancelled routing future's `concurrent.futures.CancelledError` and raises `RequestCancelledError` ([handle.py#L394-L395](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/handle.py#L394-L395)). - **Synchronous, after assignment.** `ActorReplicaResult._process_response` converts `TaskCancelledError` to `RequestCancelledError` ([replica_result.py#L159-L165](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/_private/replica_result.py#L159-L165)). The gRPC replica result does the same for `concurrent.futures.CancelledError` ([replica_result.py#L388-L389](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/_private/replica_result.py#L388-L389)). - **`await`, either side.** The async path surfaces an `asyncio.CancelledError` internally ([replica_result.py#L172](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/_private/replica_result.py#L172)), and `DeploymentResponse.__await__` re-raises it as `RequestCancelledError` when the response was cancelled ([handle.py#L548-L556](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/handle.py#L548-L556)). `DeploymentResponseGenerator.__anext__` does the same ([handle.py#L715-L721](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/handle.py#L715-L721)). `test_handle_cancellation.py` already asserts `RequestCancelledError` for all four cases: sync and async, during assignment and during execution ([L17](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/tests/test_handle_cancellation.py#L17), [L46](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/tests/test_handle_cancellation.py#L46), [L82](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/tests/test_handle_cancellation.py#L82), [L118](https://github.com/ray-project/ray/blob/30ca1d144c9d077177c04acdebbc6486739922bf/python/ray/serve/tests/test_handle_cancellation.py#L118)). ## After > If the request is successfully cancelled, subsequent operations on the response raise `ray.serve.exceptions.RequestCancelledError`. This is the same whether the request was cancelled before or after it was assigned to a replica, and whether you `await` the response or call a synchronous method such as `.result()`. `RequestCancelledError` is a subclass of `ray.exceptions.TaskCancelledError`, so `except TaskCancelledError` also catches it. ## Subsystems Serve (docstrings only) ## Not a duplicate I searched open PRs for `DeploymentResponse cancel`, `RequestCancelledError`, and Serve `handle.py` docstring changes. #66643 edits `handle.py` to let a handler claim an unrouted call, and #67109 and #67210 change cancellation handling in the proxy and gRPC stream paths. None of them changes this docstring or the exception the public `cancel` path raises. ## Testing - `pre-commit run --files python/ray/serve/handle.py` passes, including ruff, black, pydoclint, mypy and pyrefly for Serve, and the Ray docstyle check. - I read each path above on master at 30ca1d1. - I ran a probe script against the released `ray[serve]==2.59.0` wheel, whose cancellation paths match master. It cancels a request queued behind a full replica (`max_ongoing_requests=1`) and one already running on it, from a driver with `.result()` and from inside a deployment with `await`. All four raised `ray.serve.exceptions.RequestCancelledError`, and none was an instance of `asyncio.CancelledError` or `concurrent.futures.CancelledError`. - I didn't run the Serve test suite. The existing tests linked above cover the behavior this docstring now describes. The `docstring-only` label is applied to skip the heavy Serve test suites, and the commit carries an `@rtd-build` line to build the API reference preview. I wrote this with AI assistance (Claude Code). I reviewed every changed line and can defend the change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Douglas Strodtman <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Jadiouo
left a comment
There was a problem hiding this comment.
Thanks @GNITOAHC. Verified at 377b9f9 (merge-base ef74918) with RAY_SERVE_USE_GRPC_BY_DEFAULT=1 and a streaming handle in the driver.
Killing the replica with os._exit after 5 or 50 chunks while the consumer reads slowly: base returns 0 chunks, then ActorUnavailableError. This PR returns all 5 / 50 chunks, then the same error. A fast consumer gets 5 chunks on both. A replica that dies before the first chunk gives 0 on both. Errors raised by the handler itself behave the same on both.
Tests: the new message-queue tests are 5 failed / 4 passed on base and 9 passed here. test_grpc_replica_result.py: 20 passed and 1 failed (the new transport-error test) on base, 21 passed here.
I only tested the handle path, not the gRPC proxy or HTTP streaming.
|
Hi @jeffreywang88, gentle ping on this one. Since my last note, @Jadiouo independently verified the fix by killing a replica mid-stream and all buffered chunks are now delivered before the error, versus 0 on master. If you're busy, could you suggest another Serve reviewer? Thanks! |
…esult Signed-off-by: Chao-Ting, Chen <[email protected]>
| assert self._gen is not None | ||
| async for resp in self._gen: | ||
| self._result_queue.put_nowait(resp) | ||
| except asyncio.CancelledError as e: |
There was a problem hiding this comment.
There's a race condition here: this only discards once the consume task sees the cancel. cancel() runs on the caller's thread, so a next() issued right after it usually reaches the router loop first and returns a buffered chunk.
I'd suggest recording the cancel in cancel() and checking it on read, then dropping discard_messages and this branch:
def cancel(self):
if self._call.cancel():
self._locally_cancelled = True
# _get_internal, queue branch:
if self._locally_cancelled:
raise asyncio.CancelledError()There was a problem hiding this comment.
Thanks!! Switched to your approach in 72e80e8. cancel() now sets _locally_cancelled when _call.cancel() succeeds, and queue reads raise right away. I removed discard_messages. Cancelling an already-finished call still returns the buffered results, and the tests now cover both cases.
| """Results buffered before a stream failure are returned before the error.""" | ||
| loop, _ = create_asyncio_event_loop_in_thread | ||
| replica_result = self._make_failed_streaming_request( | ||
| loop, RuntimeError("stream broke") |
There was a problem hiding this comment.
nit: raise grpc.aio.AioRpcError(grpc.StatusCode.UNAVAILABLE, grpc.aio.Metadata(), grpc.aio.Metadata()) and assert ActorUnavailableError, so the test covers what users actually see when a replica dies.
There was a problem hiding this comment.
Done in 941b84f! The fake now raises AioRpcError(UNAVAILABLE) and the test asserts ActorUnavailableError.
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_message_queue_falsy_error_is_raised(): |
There was a problem hiding this comment.
does this test case simulate a real, possible production failure?
There was a problem hiding this comment.
Actually no, removed it in 80a4921, thanks!
| loop = asyncio.get_running_loop() | ||
| fetch_task = loop.create_task(queue.get_one_message()) | ||
| # Let the task start waiting on the queue before the error is set. | ||
| await asyncio.sleep(0) |
There was a problem hiding this comment.
sleep(0) lets fetch_task start and block in get_one_message() before set_error runs. That's the only order that used to hang cause set_error didn't wake a reader that was already waiting. Without it the task starts after the error is set (which test_message_queue_wait_error already covers). assert not fetch_task.done() checks the task is really waiting.
Discarding buffered results only once consume_messages_from_gen saw the CancelledError left a race: cancel() runs on the caller's thread, so a read issued right after it usually reached the router loop before the consume task observed the cancellation and returned a buffered chunk. Record the cancellation in cancel() when the call is actually cancelled and raise CancelledError from _get_internal on subsequent queue reads. Call.cancel() returns False for a finished call, so cancelling after completion still returns buffered results. Remove the now-unused discard_messages option of MessageQueue.set_error. Signed-off-by: Chao-Ting, Chen <[email protected]>
Raise the error a dying replica actually produces and assert the ActorUnavailableError that callers see, instead of a generic RuntimeError. Signed-off-by: Chao-Ting, Chen <[email protected]>
No exception that reaches MessageQueue.set_error is falsy, so the test did not cover a real failure. The `is not None` check is kept for consistency with the event-clear guard. Signed-off-by: Chao-Ting, Chen <[email protected]>
|
This pull request has been automatically marked as stale because it has not had 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. |
fellowship: 提名 GNITOAHC (ray, 2026-11) 建議等級 2 萬 - [x] 關係人宣告:提名人與被提名者無親屬、僱傭、財務、業務合作或其他可能影響公正判斷之利害關係 - 在兩個月內自己從 Ray Serve 原始碼找到 9 個 bug 並開了 PR,其中 6 個 PR 被 Merged ([Merged PRs](https://github.com/ray-project/ray/pulls?q=is%3Apr+author%3AGNITOAHC+is%3Amerged+merged%3A%3C%3D2026-11-24)) - 開了 Gang Scheduling + Autoscaling 的 Issue 並附上 Repro Script,社群後續依此開 PR 修復,提名人則變成該 PR 的 Reviewer ([#67494](ray-project/ray#67494)) - PR Description 簡潔清楚,讓 Reviewer 清楚理解 PR 解決了什麼問題 ([#66358](ray-project/ray#66358), [#66438](ray-project/ray#66438), [#66616](ray-project/ray#66616), [#66910](ray-project/ray#66910)) - 對於 Maintainer 的 Review 會清楚了解之後回覆 ([#67923 comment](ray-project/ray#67923 (comment)), [#67210 comment](ray-project/ray#67210 (comment)), [#66438 comment](ray-project/ray#66438 (comment)))
Description
MessageQueue.get_one_messageraised a stored error before returning messages that were already queued. With gRPC transport and the router on a separate loop,gRPCReplicaResult.consume_messages_from_genbuffers stream chunks ahead of the caller, so a transport failure mid-stream (e.g. the replica dying) dropped every chunk received but not yet read.Return queued messages first and raise the error once the queue is empty, as the docstring already describes.
set_errornow also wakes pending waiters, so aget_one_messagecall that is already blocked no longer hangs when an error is set withoutclose().Related issues
No existing issue.