Repository navigation
Conversation
There was a problem hiding this comment.
Code Review
This pull request improves error handling in Ray Serve's batching mechanism. Specifically, it ensures that exceptions raised by the batch sizing function (batch_size_fn) during batch assembly or execution are caught and propagated back to the callers, preventing requests from hanging indefinitely and keeping the batching loop alive. It also adds comprehensive unit tests to verify this behavior. There are no review comments, so I have no feedback to provide.
|
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. |
|
I inspected the failed jobs in Buildkite build 74661 for head
The pipeline also retried the failed jobs. I have not established whether the metric failure reproduces on the base, so I am not classifying it as a flake. Could a maintainer check the dependency/hash failures and advise on a base-versus-head run for the metric case? The unit-test evidence in the PR description is the earlier batching-specific validation, not a new full CI result. |
## Description When a single-input batched handler uses `batch_size_fn`, passing its input by keyword leaves no positional argument for `_compute_batch_size` to read. The resulting `IndexError` escapes batch assembly. A local Serve deployment reproduces positional success, keyword timeout, then another positional timeout because the batching task has stopped. Read the first payload value from the existing flattened argument representation, after `self` has already been removed. This preserves successful positional calls and supports a single explicitly supplied input passed by keyword, including keyword-only parameters. Existing multi-input positional calls remain supported. Multi-input keyword calls and variadic keyword (`**kwargs`) handlers are rejected before queueing because their flattened keyword order is not stable across a batch, and omitting a defaulted input is rejected because there is no explicit value to size. These errors affect only the caller and do not stop the batching worker. General callback-error isolation remains outside this change. The tests exercise functions and bound methods, coroutine and streaming handlers, mixed positional/keyword arrivals in both orders, keyword-only signatures, oversized keyword input recovery, omitted defaults, second-keyword-first ordering, variadic keyword signatures, positional multi-input compatibility, and worker survival after invalid requests. The batching guide describes the supported call forms. ## Related work and attribution This addresses the finding already raised in [the review of #59059](#59059 (comment)); it is not a new discovery. Searches for custom sizing and keyword/kwargs fixes found no matching open PR. #66141 fixes callback-error isolation and explicitly excludes keyword compatibility. #64595 restructures per-model queues but leaves this payload extraction unchanged; it touches the same file and may require rebasing. ## Validation macOS arm64, Python 3.12.14, official Ray `3.0.0.dev0` wheel at `39882c660a6d7b579e39d724ce85d9074d6180fb`, with the branch's current Python Serve sources linked into the environment. Because the branch includes newer master changes, the source and wheel revisions are not exact; the focused suite required a runner-local shim for a newer test-fixture helper. ```bash .venv/bin/python - <<'PYTEST' import ray, pytest raise SystemExit(pytest.main([ '--import-mode=importlib', 'python/ray/serve/tests/unit/test_batching.py', '--tb=short', '-q', ])) PYTEST ``` - 15 keyword regressions from the original change fail on the original implementation; seven review-fix cases fail before their respective fixes. - Full batching unit file: **87 passed**, including 26 cases added by this PR. - Real CPU-only local Serve deployment: positional and keyword requests succeed; invalid omitted-default, multi-input-keyword, and variadic-keyword calls return bounded `TypeError`s; a subsequent valid request succeeds and all batching tasks remain alive. - All hooks applicable to the changed files pass; `git diff --check` passes. Vale is excluded for this documentation path and its environment separately failed to compile on this Mac because the C++ `cassert` header was unavailable. - The test runner prints pending-task teardown diagnostics that were already present in the earlier 61-test baseline; the run exits successfully. The local demo logs include the existing batch-size/ongoing-request advisory and Ray shutdown messages. - Independent Astra Low reviews of each exact review-fix diff found no actionable issues in argument mapping, exception propagation, unresolved futures, cancellation, streaming, or worker survival. No GPU performance, full-Ray suite, docs build, or upstream CI result is claimed. --------- Signed-off-by: Jayesh Suyal <[email protected]> Signed-off-by: YashwanthRanjanSingaravel <[email protected]> Co-authored-by: YashwanthRanjanSingaravel <[email protected]>
| # A sizing callback can fail after requests have been dequeued. | ||
| # Complete those requests and keep the batching loop running. | ||
| for request in batch: | ||
| _set_exception_if_not_done(request.future, e) |
There was a problem hiding this comment.
could you try this test
@pytest.mark.asyncio
@pytest.mark.parametrize("exc_type", [StopIteration, StopAsyncIteration])
@pytest.mark.parametrize("stream", [False, True])
async def test_batch_size_fn_raises_stop_iteration(serve_instance, exc_type, stream):
def batch_size_fn(items):
if "bad" in items:
raise exc_type()
return len(items)
@serve.deployment
class Batcher:
@serve.batch(max_batch_size=4, batch_wait_timeout_s=0.01, batch_size_fn=batch_size_fn)
async def unary(self, items):
return items
@serve.batch(max_batch_size=4, batch_wait_timeout_s=0.01, batch_size_fn=batch_size_fn)
async def streaming(self, items):
yield items
async def call_unary(self, item):
return await self.unary(item)
async def call_streaming(self, item):
async for result in self.streaming(item):
yield result
handle = serve.run(Batcher.bind())
async def call(item):
if stream:
gen = handle.options(stream=True).call_streaming.remote(item)
return [r async for r in gen]
return await handle.call_unary.remote(item)
expected_ok = ["ok"] if stream else "ok"
assert await asyncio.wait_for(call("ok"), timeout=10) == expected_ok
with pytest.raises(Exception) as exc_info:
await asyncio.wait_for(call("bad"), timeout=10)
assert not isinstance(exc_info.value, asyncio.TimeoutError), "Request hung."
assert await asyncio.wait_for(call("ok"), timeout=10) == expected_okThere was a problem hiding this comment.
Addressed in 4898fd70ac9eea71f4480d4245ce5b23f05682da. Added test_batch_size_fn_stop_iteration with both exception types crossed with unary/streaming Serve calls. Each case asserts success, a RuntimeError rather than a hang or normal stream termination, then successful processing of the next request. All four real Serve cases passed; the complete batching unit suite passed 118 tests. The current head also has all six reported checks passing, including Buildkite premerge.
| batch = [] | ||
| try: | ||
| return await self._wait_for_batch(batch) | ||
| except Exception as e: |
There was a problem hiding this comment.
Please logger.exception(...) here. Execution-stage failures log at L630, but assembly-stage batch_size_fn failures leave nothing in the replica logs.
There was a problem hiding this comment.
Addressed in 4898fd70ac9eea71f4480d4245ce5b23f05682da: the assembly exception boundary now calls logger.exception("Batch assembly ran into an unexpected exception."). The sizing-failure regression asserts that a traceback-bearing log record is emitted while queued and later valid requests remain processable.
| try: | ||
| # Recompute after splitting by model ID and removing cancelled requests. | ||
| # Sizing errors must reach the callers just like handler errors. | ||
| computed_batch_size = self._compute_batch_size(batch) |
There was a problem hiding this comment.
If batch_size_fn raises StopIteration here, L633 fails with TypeError when it tries to set it on the future. The callers in this batch then wait forever. Please wrap StopIteration and StopAsyncIteration in a RuntimeError in one small helper, use it here and at L298, and add a unit test for this case.
There was a problem hiding this comment.
Addressed in 4898fd70ac9eea71f4480d4245ce5b23f05682da. The shared synchronous _compute_batch_size helper wraps both StopIteration and StopAsyncIteration in RuntimeError, preserving the cause. Assembly and execution both use this helper. Unit regressions cover both stages, and the four real Serve unary/streaming cases pass. _set_exception_if_not_done retains its existing behavior because streaming completion also uses that path.
|
@abrarsheikh All three inline requests have implementation-specific replies on |
Signed-off-by: Rui <[email protected]>
4898fd7 to
8e14d5b
Compare
|
Rebased as |
Description
A
batch_size_fnexception can leave dequeued requests unresolved and stop subsequent valid requests. For a callback summing string lengths,"ok",None,"ok"changes from success/timeout/timeout to success/TypeError/success.Assembly now fails affected request futures, logs the traceback, and continues consuming requests. Sub-batch sizing and metrics execute inside the existing error boundary. A shared helper converts both iterator exceptions to
RuntimeError, preserving their cause, so errors neither break Future propagation nor masquerade as streaming completion. Cancellation and normal streaming termination retain their behavior.Related issues
Fixes #66140. This updates the existing PR and its three answered review threads; it does not introduce a competing fix.
Additional information
Rebased on
de4c5765b6cf0265f43f9edccf5bd3821f3a9468, preserving upstream's positional/keyword handling and queue-arrival timeout accounting. The change touches only batching and its unit/integration tests. A callback failure rejects the affected batch as a whole because the callback does not identify one offending request.Validation on Linux x86_64, Python 3.11.15, with the official Ray 3.0.0.dev0 wheel for that exact base and local Serve/test sources linked into an isolated environment:
The four real Serve cases cross both iterator exception types with unary/streaming requests and verify success/error/success. Restoring only base
batching.pymakes all 27 targeted error-recovery regressions fail; the candidate was restored byte-for-byte afterward. The unit suite exits successfully with pending-task/event-loop teardown diagnostics. This is local validation, not a full C++ build or upstream CI result.OpenAI Codex assisted with implementation, conflict resolution, and validation.
I reviewed the final diff and ran the relevant tests locally before signing off.