Skip to content

[Serve] Propagate batch sizing errors without stopping subsequent requests - #66141

Open
ai-yang wants to merge 1 commit into
ray-project:masterfrom
ai-yang:fix/serve-batch-size-exception
Open

ai-yang wants to merge 1 commit into
ray-project:masterfrom
ai-yang:fix/serve-batch-size-exception

Conversation

@ai-yang

@ai-yang ai-yang commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Description

A batch_size_fn exception 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:

.venv/bin/python -c 'import ray,pytest; raise SystemExit(pytest.main(["--import-mode=importlib","-q","python/ray/serve/tests/unit/test_batching.py"]))'
# 120 passed, 4.88s
.venv/bin/python -c 'import ray,pytest; raise SystemExit(pytest.main(["--import-mode=importlib","-q","python/ray/serve/tests/test_batching.py::test_batch_size_fn_stop_iteration"]))'
# 4 passed, 29.23s
.venv/bin/python -m pre_commit run --files python/ray/serve/batching.py python/ray/serve/tests/unit/test_batching.py python/ray/serve/tests/test_batching.py
# All applicable hooks passed.

The four real Serve cases cross both iterator exception types with unary/streaming requests and verify success/error/success. Restoring only base batching.py makes 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.

@ai-yang
ai-yang marked this pull request as ready for review September 13, 2026 05:39
@ai-yang
ai-yang requested a review from a team as a code owner September 13, 2026 05:39

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

@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue community-contribution Contributed by the community labels Sep 13, 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 Sep 27, 2026
@johntaylor-cell johntaylor-cell added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. go add ONLY when ready to merge, run all tests and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Oct 9, 2026
@ai-yang

ai-yang commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

I inspected the failed jobs in Buildkite build 74661 for head 85fc0a330ecf3e52e5834a9938b04c9fc5f07de1:

  • corebuild-py3.10: hash mismatch downloading torch-scatter==2.1.2+cpu.torch.2.9.
  • docgpubuild-py3.10: hash mismatch downloading torch-scatter==2.1.2+cu.12.8.torch.2.9.
  • Serve HAProxy tests: TestProxyStateMetrics::test_proxy_shutdown_duration_metric timed out after 90 seconds waiting for the shutdown-duration metric. Its Bazel test target failed both attempts.

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.

abrarsheikh pushed a commit that referenced this pull request Oct 13, 2026
## 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)

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 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_ok

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.

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:

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.

Please logger.exception(...) here. Execution-stage failures log at L630, but assembly-stage batch_size_fn failures leave nothing in the replica logs.

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.

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)

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.

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.

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.

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.

@ai-yang

ai-yang commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

@abrarsheikh All three inline requests have implementation-specific replies on 4898fd70ac9eea71f4480d4245ce5b23f05682da: the real Serve iterator-exception cases, assembly traceback logging, and the shared exception-conversion helper. Could you re-review that revision and confirm the outstanding threads? No additional code changes or duplicated test claims are included in this follow-up.

@ai-yang
ai-yang force-pushed the fix/serve-batch-size-exception branch from 4898fd7 to 8e14d5b Compare November 13, 2026 16:27

ai-yang commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased as 8e14d5b6 on de4c5765, preserving upstream's queue-arrival timeout accounting as well as the three previously addressed review requests. Fresh runs pass 120 batching unit tests and all 4 real Serve iterator-exception cases; restoring base batching.py causes the 27 targeted recovery regressions to fail. Changed-file pre-commit passes. I reviewed the final diff and ran the relevant tests locally before signing off. The description includes the exact-base wheel and teardown-diagnostic limits.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community go add ONLY when ready to merge, run all tests serve Ray Serve Related Issue unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Serve] A batch_size_fn exception stops batching and hangs subsequent valid requests

3 participants