Repository navigation
Conversation
_choose_replica_for_request awaits the pending request's future with no bound. A request waits with no error while every replica is at capacity. It also waits while the deployment has no replicas, for example when a scaled-to-zero deployment can't schedule a new replica. HTTPOptions.request_timeout_s applies to the HTTP proxy only and also counts processing time. Add request_routing_timeout_s to RequestRouterConfig. When set, a request that isn't assigned a replica within the timeout raises TimeoutError. The timeout does not cover the time the replica takes to handle the request. The default of None keeps the current behavior. RequestRouterConfig equality includes the new field, so a timeout-only config change is broadcast to routers. Closes ray-project#40995 Signed-off-by: codechrl <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces a new configuration option, request_routing_timeout_s, allowing users to set a timeout for assigning requests to replicas in Ray Serve. Key changes include updates to RequestRouterConfig, the protobuf definition, documentation, and the request routing logic to handle and raise a timeout error when the limit is exceeded. The review feedback highlights a potential memory leak in the queue cleanup logic due to head-of-line blocking and suggests filtering the queues in-place. Additionally, it recommends raising asyncio.TimeoutError instead of the built-in TimeoutError to ensure backward compatibility with Python versions prior to 3.11, along with corresponding updates to the unit tests.
| raise TimeoutError( | ||
| f"Failed to route request to a replica of {self._deployment_id} " | ||
| f"within {self.request_routing_timeout_s}s." | ||
| ) from None |
There was a problem hiding this comment.
In Python versions prior to 3.11, asyncio.TimeoutError and the built-in TimeoutError are distinct exception classes (with different inheritance hierarchies). Since this is an asynchronous API and callers typically expect asyncio.TimeoutError when awaiting async operations, raising asyncio.TimeoutError is more idiomatic and ensures backward compatibility for callers catching asyncio.TimeoutError on Python 3.8 - 3.10.
| raise TimeoutError( | |
| f"Failed to route request to a replica of {self._deployment_id} " | |
| f"within {self.request_routing_timeout_s}s." | |
| ) from None | |
| raise asyncio.TimeoutError( | |
| f"Failed to route request to a replica of {self._deployment_id} " | |
| f"within {self.request_routing_timeout_s}s." | |
| ) from None |
There was a problem hiding this comment.
Builtin TimeoutError is intentional. The HTTP/gRPC proxies map isinstance(exc, TimeoutError) to 408/DEADLINE_EXCEEDED (http_util.py, grpc_util.py), and handle.py re-raises asyncio.TimeoutError as the builtin for the same reason. On 3.10, asyncio.TimeoutError isn't a subclass of the builtin, so switching would turn the 408 into a 500.
| loop = get_or_create_event_loop() | ||
|
|
||
| task = loop.create_task(s._choose_replica_for_request(fake_pending_request())) | ||
| with pytest.raises(TimeoutError, match="Failed to route request to a replica"): |
There was a problem hiding this comment.
There was a problem hiding this comment.
The router raises the builtin TimeoutError on purpose (see the thread on request_router.py), so the test stays as is.
| s.update_replicas([r1]) | ||
|
|
||
| task = loop.create_task(s._choose_replica_for_request(fake_pending_request())) | ||
| with pytest.raises(TimeoutError, match="Failed to route request to a replica"): |
There was a problem hiding this comment.
There was a problem hiding this comment.
Same as above: the builtin TimeoutError is intentional, so the test stays as is.
The lazy cleanup only pops a done prefix, so a request that timed out behind a still-pending one stayed queued. Remove it by identity on timeout, cancel its future explicitly, and leave the optional request_routing_timeout_s proto field unset when it is None, matching retry_after_s. Signed-off-by: codechrl <[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. |
|
@codechrl Please fix the premerge test failure. Please rebase. And I found a few things from testing this:
|
Move the timeout into AsyncioRouter so retries, choose_replica with _reserve=False and CapacityQueueRouter share a single deadline. Raise RequestRoutingTimeoutError (a TimeoutError subclass) and map it to 408 and DEADLINE_EXCEEDED with its own message. Register the ConsistentHashRouter routing task per request so a timed-out request stops it, and record the queued request before the scale-from-zero metrics push. Signed-off-by: codechrl <[email protected]>
…e-request-routing-timeout-v2 # Conflicts: # doc/source/serve/api/index.md
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 515da64. Configure here.
|
@codechrl Please address bot comment and the premerge test failure |
A rejected request is re-inserted into the pending queues while its earlier entry can still be queued, so removal by identity must not stop at the first match. Otherwise one copy keeps num_pending_requests inflated. Signed-off-by: codechrl <[email protected]>
|
@codechrl premerge still fails the serve mypy hook: router.py:1064-1089 use the routing result without handling |
) ## Description `AutoscalingConfig.target_ongoing_requests` is typed `Optional[PositiveFloat]`, so `None` passes validation, both in `@serve.deployment(autoscaling_config=...)` and as `target_ongoing_requests: null` in a config file. The readers I checked all expect a number: the default policy computes `config.get_target_ongoing_requests() * num_running_replicas` (`autoscaling_policy.py:337`), the config-file override path compares `max_ongoing_requests < get_target_ongoing_requests()` (`application_state.py:2087`), and the autoscaling state sets a gauge to it (`autoscaling_state.py:662`). The first raises a `TypeError` on every controller loop iteration. The `Optional` type and the `None` mapping in `from_proto` date from the rename in #43454, when `None` meant "fall back to `target_num_ongoing_requests_per_replica`". #46392 removed that field and the fallback, so `None` has had no meaning since. The failure is not limited to the misconfigured app. I deployed a healthy app, then an app with `target_ongoing_requests=None`, then a second healthy app, on a local cluster on master. The controller logged 2,217 `TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'` errors in about 4 minutes. The second healthy app never showed up in the controller log, and `serve.status()` did not return before the script was stopped after 4 minutes. This was one run, with the script below. Why one deployment's policy exception stalls the whole loop is a separate question that this PR does not change. Behavior change: `@serve.deployment(autoscaling_config={..., "target_ongoing_requests": None})` now raises `ValidationError` when the class is decorated, instead of being accepted. A `null` in a config file still passes schema parsing, because the schema keeps `autoscaling_config` as a plain dict, and the app fails when it is built, as it already did on master, now with a `ValidationError` from `AutoscalingConfig`. One setup that works today would break: a deployment defined in Python with a custom autoscaling policy that never reads this field. The gauge skips `None`, and the `application_state.py` comparison only runs for config files, so that setup runs with `None` on master. A proto with 0.0, which a client cannot set on purpose because the field must be positive, now gets the default of 2 instead of `None`. A config object that already holds `None` and is restored by unpickling is not revalidated (checked with `cloudpickle`), so it behaves as on master. Changes: - `config.py`: type the field as `PositiveFloat`, so `None` is rejected when an `AutoscalingConfig` is built (when the class is decorated, or when a config-file app is built): `target_ongoing_requests: Input should be a valid number [type=float_type, input_value=None, input_type=NoneType]`. - `_private/config.py`: `from_proto` replaced a 0.0 `target_ongoing_requests`, the proto3 default when the field is not set, with `None`. It now drops the key so the field default (2) applies, the same way the `request_router_config` fields above it are handled. ## Related issues None. I searched issues and PRs for "target_ongoing_requests None", "target_ongoing_requests null" and "autoscaling NoneType" and found no report. Open PRs that edit `serve/config.py` or `_private/config.py` (#67507, #67440, #66855, #66798, #66580, #66512) do not change this field's type or its `from_proto` handling. ## Additional information Tests added to `python/ray/serve/tests/unit/test_config.py`: - `test_target_ongoing_requests_none_rejected`: `AutoscalingConfig(target_ongoing_requests=None)`, and the same value passed through `DeploymentConfig`, raise `ValidationError`. - `test_target_ongoing_requests_proto_default`: a proto without the field gives the default of 2, and a value of 7 survives a proto round trip. Commands, run locally on macOS arm64 with the nightly wheel, `setup-dev.py` and Pydantic 2.14.2: - `pytest python/ray/serve/tests/unit/test_config.py -k target_ongoing`: 3 passed (the two new tests and the existing `test_target_ongoing_requests`). On master 541bd56: the two new tests fail. - `pytest` on `test_config.py`, `test_schema.py`, `test_autoscaling_policy.py`, `test_application_state.py`, `test_deployment_state.py` and `test_autoscaling_metrics_merge.py`, all in `python/ray/serve/tests/unit/`: 751 passed, 12 skipped. - `pre-commit run` on the changed files: passed. <details><summary>Repro script (run on master)</summary> ```python import time, ray from ray import serve from ray.serve.api import _run ray.init(num_cpus=8, include_dashboard=False, log_to_driver=False) @serve.deployment(ray_actor_options={"num_cpus": 0}) class Ok: def __call__(self): return "ok" @serve.deployment(autoscaling_config={"min_replicas": 1, "max_replicas": 3, "target_ongoing_requests": None}, ray_actor_options={"num_cpus": 0}) class Bad: def __call__(self): return "bad" serve.run(Ok.bind(), name="ok1", route_prefix="/ok1") _run(Bad.bind(), name="bad", route_prefix="/bad", _blocking=False) time.sleep(3) _run(Ok.bind(), name="ok2", route_prefix="/ok2", _blocking=False) time.sleep(15) st = serve.status().applications print({k: str(v.status) for k, v in st.items()}) serve.shutdown(); ray.shutdown() ``` </details> Signed-off-by: William Guo <[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. |
…ting-timeout-v2 Signed-off-by: codechrl <[email protected]> # Conflicts: # python/ray/serve/_private/router.py # python/ray/serve/tests/unit/test_http_util.py
_wait_for_routing returned Any, so replica stayed Optional[RunningReplica] after routing and the serve mypy hook flagged every use of it in _route_and_send_request_once. Make it generic over the awaited value. Signed-off-by: codechrl <[email protected]>
|
Thanks @codechrl, mypy and premerge pass now. A few remaining items:
In the description, the scaled-to-zero bullet (on master via ray-project/ray#67087) and the |
…ting-timeout-v2 # Conflicts: # python/ray/serve/tests/unit/test_grpc_util.py
…tError on 3.10 - Pop the done prefix of the pending queues on each timeout and compact them only once timeouts could fill half the queue. - On Python < 3.11, re-raise an asyncio.TimeoutError raised by the request router itself; only an expired deadline becomes RequestRoutingTimeoutError. - Share routing-task bookkeeping between RequestRouter and ConsistentHashRouter, and test the consistent-hash routing-task restart. Signed-off-by: codechrl <[email protected]>
|
Thanks. Pushed:
Merged master, description updated. |

Description
_choose_replica_for_requestawaits the pending request's future with no bound. A request waits with no error while every replica is at capacity. It also waits while the deployment has no replicas, for example when a scaled-to-zero deployment can't schedule a new replica.HTTPOptions.request_timeout_sapplies to the HTTP proxy only and also counts processing time. ADeploymentHandlecaller can bound assignment only per call, by wrapping_to_object_ref()inasyncio.wait_forand cancelling the response on timeout._to_object_ref()returns on assignment since #65243.This adds
request_routing_timeout_stoRequestRouterConfig. It follows the same path as the backoff fields:serve.proto, thenAsyncioRouter. The defaultNonekeeps the current behavior.The timeout lives in
AsyncioRouteras one deadline per request. It starts on the first routing attempt, after the arguments resolve, and retries after a replica rejects the request don't restart it. It coversassign_request,choose_replicawith and without reservation, andCapacityQueueRouter. Time spent inreserve_slotor probing counts toward the deadline but isn't interrupted.RequestRoutingTimeoutError, aTimeoutErrorsubclass, is raised. The HTTP proxy returns 408 and the gRPC proxyDEADLINE_EXCEEDED, both with the error's own message.handle.pyre-raises the error, so Python 3.11+ no longer rewrites it toTimed out resolving to ObjectRef..asyncio.TimeoutErrorraised by the request router itself propagates; only an expired routing deadline becomesRequestRoutingTimeoutError.ConsistentHashRoutershares the base router's routing-task helpers and registers its routing task per request, so a timed-out request stops it.__eq__and__hash__include the field.broadcast_deployment_config_if_changedcompares configs with==, so a timeout-only change would otherwise never reach the routers.optional, so an unset value doesn't come back as0.0.performance.mdsays so.Related issues
Closes #40995
Additional information
Not a duplicate: no open or closed PR references #40995. #64399 (open) adds
max_request_retriesfor #61017. It bounds the retry loops that run after a replica rejects a request. It doesn't bound the wait inside_choose_replica_for_request. Both PRs add field 9 toRequestRouterConfiginserve.proto, so whichever merges second needs to renumber.Tests:
test_router.py:TestRequestRoutingTimeoutcovers the single deadline across retries, the done-prefix pop and the half-queue compaction, routing skipping timed-out entries,_reserve=False, a router's ownTimeoutError/asyncio.TimeoutErrorpropagating, and the routing task stopping with every replica at capacity.test_consistent_hash_router.py: a timed-out request stops its routing task, and with one replica, cancelled routing tasks are replaced so a queued third request is still routed.test_http_util.pyandtest_grpc_util.py: 408 andDEADLINE_EXCEEDEDuse the error's message, including when wrapped inRayTaskError.test_config.py: proto round trip forNoneand1.5, and equality.Each new test fails with its source hunk reverted. Ran with this branch's
python/ray/servemerged with current master on the nightly wheel, Python 3.11: 410 passed, 6 skipped, 1 failed. The failingtest_configproto round trip is because the wheel's generatedserve_pb2lacks the new field. The 3.10 branch of_wait_for_routingwas checked on CPython 3.9 and 3.10 with a standalone script. Not run: the suite on Python 3.10 and 3.12+, a liveCapacityQueueRouter, HAProxy.Disclaimer: this PR was prepared with the assistance of an AI agent (Claude Code). All code and test changes were reviewed by the author before submission.