Repository navigation
[Serve] Add direct ingress support for Ray Serve - #60118
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces direct ingress support for Ray Serve, a significant feature enabling replicas to be individually addressable. The changes are extensive, touching the controller, replica logic, and adding new components for port management. The implementation is mostly solid and is accompanied by comprehensive tests. My review focuses on improving maintainability by avoiding private member access, enhancing robustness by adding validation and fixing a race condition, and addressing a critical bug in header parsing. I've also noted a potential improvement for the graceful shutdown logic.
| was_error=not healthy, | ||
| status_code=str(status_code), | ||
| ) | ||
| return |
There was a problem hiding this comment.
The logic to extract request_id from headers is not safe. If the SERVE_HTTP_REQUEST_ID_HEADER is missing, headers.get(...) returns None, and calling .decode("utf-8") on None will raise an AttributeError, causing the request to fail. This should be handled gracefully, for example by providing a default value to headers.get().
| was_error=not healthy, | |
| status_code=str(status_code), | |
| ) | |
| return | |
| request_id = ( | |
| headers.get(SERVE_HTTP_REQUEST_ID_HEADER.encode("utf-8"), b"").decode("utf-8") | |
| or generate_request_id() | |
| ) |
| # TODO(abrar): add a validation here to ensure min_port and max_port dont overlap with | ||
| # ray params min_worker_port and max_worker_port. |
There was a problem hiding this comment.
| request_timeout_s = self._parse_request_timeout(headers) | ||
|
|
||
| request_metadata = RequestMetadata( | ||
| request_id=request_id, | ||
| internal_request_id=generate_request_id(), | ||
| call_method="__call__", | ||
| route=self._determine_http_route(scope), | ||
| app_name=self._deployment_id.app_name, | ||
| # TODO(edoakes): populate the multiplexed model ID. |
There was a problem hiding this comment.
There is a race condition in the backpressure logic for direct ingress requests. The check _can_accept_request and the increment of self._num_queued_requests are not atomic. This can lead to more requests being accepted than max_queued_requests under high load, as noted in the code comment.
To fix this, you should introduce a lock to protect the critical section where the number of queued requests is checked and modified.
For example, in Replica.__init__:
self._queued_requests_lock = asyncio.Lock()Then, in _direct_ingress_asgi, wrap the check and increment:
async with self._queued_requests_lock:
if not self._can_accept_request(request_metadata):
# ... drop request
return
self._num_queued_requests += 1And finally, ensure the decrement is also atomic within call_asgi:
async with self._start_request(request_metadata):
async with self._queued_requests_lock:
self._num_queued_requests -= 1
# ... rest of the method| def _get_node_id_to_alive_replica_ids(self) -> Dict[str, Set[str]]: | ||
| node_id_to_alive_replica_ids = defaultdict(set) | ||
| # TODO(abrar): Expose the right APIs in the DeploymentStateManager | ||
| # to get the alive replicas for a deployment. | ||
| for ds in self.deployment_state_manager._deployment_states.values(): | ||
| # here we get all the replicas irrespective of their state | ||
| # unlike in the get_running_replica_infos_for_ingress_deployment | ||
| # where we only get the replicas that are running, because we dont | ||
| # wish to agressively cleanup ports for replicas that are not running | ||
| # and are in the process of being updated or are in the process of | ||
| # being started. | ||
| replicas: List[DeploymentReplica] = ds._replicas.get() | ||
| for replica in replicas: | ||
| node_id: Optional[str] = replica.actor_node_id | ||
| if node_id is None: | ||
| continue | ||
| replica_unique_id = replica.replica_id.unique_id | ||
| node_id_to_alive_replica_ids[node_id].add(replica_unique_id) | ||
| return node_id_to_alive_replica_ids |
There was a problem hiding this comment.
The method _get_node_id_to_alive_replica_ids accesses private members _deployment_states and _replicas of DeploymentStateManager. This breaks encapsulation and makes the code harder to maintain, as noted in the TODO comment. To improve maintainability, a public API should be exposed in DeploymentStateManager to provide this information instead of accessing private attributes directly.
| # if direct ingress is not enabled or the replica is not an ingress replica, | ||
| # we can just call the super method to perform the graceful shutdown. | ||
| await super().perform_graceful_shutdown() | ||
| return | ||
|
|
There was a problem hiding this comment.
The TODO comment highlights a potential issue with the graceful shutdown logic for direct ingress. Relying on a fixed draining period might not be robust if the load balancer (e.g., ALB) continues to send traffic. The suggested improvement in the TODO to use a cooldown period since the last request finished would make the shutdown process more reliable and prevent requests from being dropped during shutdown. It would be good to create a follow-up issue to track this improvement.
There was a problem hiding this comment.
Identical modulo imports
There was a problem hiding this comment.
Integrated parity and OSS, but otherwise identical
There was a problem hiding this comment.
Identical modulo gRPC
| @@ -175,6 +184,15 @@ async def __init__( | |||
| self.cluster_node_info_cache = create_cluster_node_info_cache(self.gcs_client) | |||
| self.cluster_node_info_cache.update() | |||
|
|
|||
| self._direct_ingress_enabled = RAY_SERVE_ENABLE_DIRECT_INGRESS | |||
| @@ -600,6 +620,20 @@ async def run_control_loop_step( | |||
| | self.proxy_state_manager.get_alive_proxy_actor_ids() | |||
| ) | |||
|
|
|||
| # Direct ingress port management | |||
There was a problem hiding this comment.
Test targets are complete with logic ported from parity
There was a problem hiding this comment.
Identical modulo env variables and stubbed out HAProxy
There was a problem hiding this comment.
Identical modulo imports and env variables
There was a problem hiding this comment.
Identical modulo import paths and env variable naming
| @@ -249,6 +267,8 @@ async def __init__( | |||
| ] = [] | |||
| self._refresh_autoscaling_deployments_cache() | |||
|
|
|||
| self._last_broadcasted_target_groups: List[TargetGroup] = [] | |||
|
|
||
| This information is used to setup the load balancer. | ||
| """ | ||
| def _get_proxy_target_groups(self) -> List[TargetGroup]: |
There was a problem hiding this comment.
Keeping the base class OSS logic by renaming the function. Removing the unused parameters. They were only present to match the signature of the override in parity implementation.
| If there are multiple applications with no running replicas, we return | ||
| one target group per application with unique route prefix. | ||
| """ | ||
| proxy_target_groups = self._get_proxy_target_groups() |
There was a problem hiding this comment.
In parity, this was a call to the base class
| ] | ||
|
|
||
| if not apps: | ||
| return proxy_target_groups |
There was a problem hiding this comment.
Divergence. Skipping HAProxy logic
| route_prefix, app_name | ||
| ) | ||
| ) | ||
|
|
There was a problem hiding this comment.
Remainder is identical modulo skipped HAProxy logic and prepended underscore on function names
| @@ -262,6 +277,119 @@ def __init__( | |||
|
|
|||
| self.set_autoscaling_config(autoscaling_config) | |||
|
|
|||
| if self._is_direct_ingress: | |||
c0f4462 to
c939736
Compare
| @@ -1152,9 +1178,123 @@ async def record_routing_stats(self) -> Dict[str, Any]: | |||
| raise e from None | |||
|
|
|||
|
|
|||
| async def send_http_response(message, status_code, send): | |||
| @@ -355,7 +374,14 @@ def should_collect_ongoing_requests(self) -> bool: | |||
| │ └──────────────────────────────┘ │ | |||
| │ │ | |||
| └────────────────────────────────────────────────────────────────┘ | |||
|
|
|||
| @@ -1169,7 +1309,12 @@ async def _on_initialized(self): | |||
| def _on_request_cancelled( | |||
| self, metadata: RequestMetadata, e: asyncio.CancelledError | |||
| ): | |||
| """Recursively cancels child requests.""" | |||
| """Recursively cancel child requests. | |||
| @@ -1179,6 +1324,7 @@ def _on_request_cancelled( | |||
| task.cancel() | |||
|
|
|||
| # Cancel child requests that have already been assigned. | |||
| # This is for gRPC requests and direct ingress requests. | |||
| @@ -1187,6 +1333,16 @@ def _on_request_failed(self, request_metadata: RequestMetadata, e: Exception): | |||
| if ray.util.pdb._is_ray_debugger_post_mortem_enabled(): | |||
| ray.util.pdb._post_mortem() | |||
|
|
|||
| def _can_accept_request(self, request_metadata: RequestMetadata): | |||
| @@ -380,15 +558,35 @@ def enable_custom_autoscaling_metrics( | |||
| def inc_num_ongoing_requests(self, request_metadata: RequestMetadata) -> int: | |||
| """Increment the current total queue length of requests for this replica.""" | |||
| self._num_ongoing_requests += 1 | |||
|
|
|||
| @@ -408,6 +606,72 @@ def record_request_metrics(self, *, route: str, latency_ms: float, was_error: bo | |||
| else: | |||
| self._request_counter.inc(tags={"route": route}) | |||
|
|
|||
| def record_ingress_request_metrics( | |||
| @@ -1206,12 +1600,302 @@ def _wrap_request( | |||
| multiplexed_model_id=request_metadata.multiplexed_model_id, | |||
| grpc_context=request_metadata.grpc_context, | |||
| _ray_trace_ctx=ray_trace_ctx, | |||
| cancel_on_parent_request_cancel=self._ingress | |||
| ) | ||
| ) | ||
|
|
||
| with self._handle_errors_and_metrics(request_metadata) as status_code_callback: | ||
| yield status_code_callback | ||
|
|
||
| async def _dataplane_health_check(self) -> Tuple[bool, str]: |
|
|
||
| return healthy, message | ||
|
|
||
| def get_asgi_tracing_context(self, headers: List[Tuple[bytes, bytes]]): |
There was a problem hiding this comment.
Here to end of file identical
There was a problem hiding this comment.
get_asgi_tracing_context needs to be omitted. Since tracing is not implemented in OSS
c939736 to
c3ff26e
Compare
This adds direct ingress functionality to Ray Serve, allowing replicas to listen directly on ports (HTTP 30000-31000) for incoming traffic. This enables deployments where each replica is individually addressable, which is useful for Kubernetes ingress controllers and load balancers. Key changes: - Add direct ingress HTTP utility for ASGI receive proxying - Add replica response generator for disconnect detection - Add node port manager for per-node port allocation - Add direct ingress support to controller (target groups, port allocation) - Add direct ingress support to replica (ASGI server, graceful shutdown) - Add direct ingress constants and feature flag (RAY_SERVE_ENABLE_DIRECT_INGRESS) - Add integration and unit tests The feature is disabled by default and can be enabled by setting RAY_SERVE_ENABLE_DIRECT_INGRESS=1. Signed-off-by: Seiji Eicher <[email protected]>
…se (ray-project#60092) Signed-off-by: Future-Outlier <[email protected]> Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
…_step Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
The unit test sets the env var via monkeypatch fixture, matching rayturbo. Signed-off-by: Seiji Eicher <[email protected]>
Metrics collection for direct ingress is not critical for the initial port. Signed-off-by: Seiji Eicher <[email protected]>
Leftover from metrics removal - override just called super() with no additional logic. Signed-off-by: Seiji Eicher <[email protected]>
Use ray.util.metrics instead of ray.serve.metrics to avoid reserved tag conflicts (ray.serve.metrics reserves "application", "deployment", etc.). This adds metrics tracking for direct ingress requests: - Request counters with route, method, application, status_code tags - Error counters for both ingress and deployment level - Latency histograms for request processing time - Ongoing requests gauge for autoscaling Signed-off-by: Seiji Eicher <[email protected]>
c3ff26e to
0fb462f
Compare
- Add gRPC server startup alongside HTTP server when gRPC is enabled - Add _direct_ingress_unary_unary handler for gRPC requests - Add _direct_ingress_service_handler_factory for gRPC service handlers - Support Healthz and ListApplications gRPC endpoints - Handle graceful shutdown for gRPC server task Signed-off-by: Seiji Eicher <[email protected]>
0fb462f to
3bf4b65
Compare
| @@ -1548,6 +1559,9 @@ def __init__(self, **kwargs): | |||
| # get node ID | |||
| self._node_id = ray.get_runtime_context().get_node_id() | |||
| self._http_options: Optional[HTTPOptions] = None | |||
| self._grpc_options: Optional[gRPCOptions] = None | |||
| @@ -1612,10 +1626,15 @@ async def allocate_and_start_server(start_server_fn, protocol): | |||
| raise RuntimeError(err_msg) | |||
|
|
|||
| # Fetch configs | |||
| self._http_options = ray.get( | |||
| self._controller_handle.get_http_config.remote(), | |||
| self._http_options, self._grpc_options = ray.get( | |||
| @@ -1639,7 +1658,30 @@ async def start_http_server(port): | |||
| protocol=RequestProtocol.HTTP, | |||
| ) | |||
|
|
|||
| logger.info(f"Started HTTP server on port {self._http_port}") | |||
| # Allocate and start gRPC server if enabled | |||
| await self.shutdown() | ||
| if self._direct_ingress_http_server_task: | ||
| self._direct_ingress_http_server_task.cancel() | ||
| if self._direct_ingress_grpc_server_task: |
|
|
||
| return tracing_ctx | ||
|
|
||
| def get_grpc_tracing_context(self, context: grpc._cython.cygrpc._ServicerContext): |
There was a problem hiding this comment.
Identical modulo set_rpc_span_attributes
There was a problem hiding this comment.
get_grpc_tracing_context needs to be removed
| request_id = ( | ||
| headers.get(SERVE_HTTP_REQUEST_ID_HEADER.encode("utf-8")).decode("utf-8") | ||
| or generate_request_id() | ||
| ) |
There was a problem hiding this comment.
Missing header causes AttributeError when parsing request ID
High Severity
When the x-request-id header is not present in an HTTP request, headers.get(...) returns None, and calling .decode("utf-8") on None raises AttributeError: 'NoneType' object has no attribute 'decode'. The or generate_request_id() fallback never executes because the exception occurs first. This affects all direct ingress HTTP requests that don't include the x-request-id header, which is the common case for most clients.
| msg = ( | ||
| f"Request {request_id} timed out after " | ||
| f"{self._http_options.request_timeout_s}s." | ||
| ) |
There was a problem hiding this comment.
Timeout error message displays wrong timeout value
Low Severity
When a request times out, the error message at line 2295 uses self._http_options.request_timeout_s (the default config value), but the actual timeout applied at line 2267 is request_timeout_s, which may have been overridden by the x-request-timeout-seconds header. If a client sets a custom timeout (e.g., 5 seconds) via header, but the default is 30 seconds, the error message will incorrectly say "timed out after 30s" instead of "5s".
- Add serve_di_test_names.txt with 44 tests to run with DI enabled - Add direct ingress test targets to BUILD.bazel (with _with_grpc variants) - Add "same loop" CI variant with RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD=0 - Port test_handle.py from rayturbo (tests _by_reference option) Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
61155b0 to
a3b80e3
Compare
Add recording of serve_num_http_requests metric in _record_errors_and_metrics when handling direct ingress HTTP requests. This ensures HTTP request metrics are properly tracked when direct ingress is enabled. Signed-off-by: Seiji Eicher <[email protected]>
| request_id = ( | ||
| headers.get(SERVE_HTTP_REQUEST_ID_HEADER.encode("utf-8")).decode("utf-8") | ||
| or generate_request_id() | ||
| ) |
There was a problem hiding this comment.
Request ID extraction crashes when header is missing
High Severity
The request_id extraction calls .decode("utf-8") directly on the result of headers.get(), which returns None when the x-request-id header is not present. This causes an AttributeError: 'NoneType' object has no attribute 'decode' on every HTTP request without the header. Compare with the correct pattern used two lines below for request_disconnect_disabled, which provides a default value b"?0".
| ) | ||
| return port | ||
|
|
||
| raise NoAvailablePortError(self._protocol, self._node_id) |
There was a problem hiding this comment.
Port allocator can assign same port to multiple replicas
Medium Severity
After controller restart, update_port_if_missing adds recovered ports to _allocated_ports but doesn't remove them from _available_ports. When allocate is called for a new replica, it pops from the heap and only checks _blocked_ports, not whether the port is already in _allocated_ports.values(). This can cause the same port to be assigned to multiple replicas, resulting in port conflicts.
Additional Locations (1)
| self.queue.put_nowait(msg) | ||
|
|
||
| def close_queue(self): | ||
| self.queue.close() |
There was a problem hiding this comment.
Method calls nonexistent asyncio.Queue.close() method
Low Severity
The close_queue method calls self.queue.close(), but asyncio.Queue does not have a close() method. If called, this would raise AttributeError: 'Queue' object has no attribute 'close'. The method is currently unused but represents broken code that would fail if invoked.
Remove 9 skip blocks that are no longer needed now that proxy metrics recording has been ported for direct ingress. Keep only the skip for test_proxy_metrics_http_status_code_is_error which still fails. Also remove redundant disable_router_queue_len_throttle fixture since the env var is already set in BUILD.bazel. Signed-off-by: Eugene Kim <[email protected]> Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
There was a problem hiding this comment.
Identical modulo imports
There was a problem hiding this comment.
Skips are identical to parity implementation
| was_error=user_exception is not None, | ||
| ) | ||
|
|
||
| # Record ingress metrics for direct ingress HTTP requests |
There was a problem hiding this comment.
Identical to parity
There was a problem hiding this comment.
Modulo set_http_span_attributes and set_rpc_span_attributes
There was a problem hiding this comment.
Identical modulo env variables and OSS-specific CI dependency setup
There was a problem hiding this comment.
Contents identical to parity modulo proxy/ingress specific items
| if not response_started: | ||
| msg = ( | ||
| f"Request {request_id} timed out after " | ||
| f"{self._http_options.request_timeout_s}s." |
There was a problem hiding this comment.
Timeout error message shows wrong timeout value
Medium Severity
The timeout error message uses self._http_options.request_timeout_s instead of the local request_timeout_s variable. When a client overrides the timeout via the x-request-timeout-seconds header (parsed at line 2181), the actual timeout applied differs from the default HTTP options timeout. The error message will display an incorrect timeout value, confusing users about what timeout actually occurred.
| self.queue.put_nowait(msg) | ||
|
|
||
| def close_queue(self): | ||
| self.queue.close() |
There was a problem hiding this comment.
Dead code calls nonexistent asyncio.Queue method
Low Severity
The close_queue method calls self.queue.close(), but asyncio.Queue does not have a close() method. This would raise AttributeError if invoked. The method is currently unused (no callers found), making it dead code that would fail if ever used.
| port, | ||
| protocol, | ||
| block_port=True, | ||
| ) |
There was a problem hiding this comment.
Port incorrectly blocked on non-port-conflict failures
Medium Severity
The code always passes block_port=True when releasing a port after a server startup failure, regardless of whether the failure was due to port-in-use (is_port_in_use). The is_port_in_use variable is computed at lines 1613-1619 to distinguish port conflicts from other errors, but it's only used for the error message, not for the block_port parameter. This causes ports to be permanently blocked even when failures are unrelated to port conflicts.
| RAY_SERVE_REPLICA_GRPC_MAX_MESSAGE_LENGTH = int( | ||
| # Default max message length in gRPC is 4MB, we keep that default | ||
| os.environ.get("RAY_SERVE_REPLICA_GRPC_MAX_MESSAGE_LENGTH", 4 * 1024 * 1024) | ||
| ) |
There was a problem hiding this comment.
Is this supposed to be added?
|
|
||
| return healthy, message | ||
|
|
||
| def get_asgi_tracing_context(self, headers: List[Tuple[bytes, bytes]]): |
There was a problem hiding this comment.
get_asgi_tracing_context needs to be omitted. Since tracing is not implemented in OSS
|
|
||
| return tracing_ctx | ||
|
|
||
| def get_grpc_tracing_context(self, context: grpc._cython.cygrpc._ServicerContext): |
There was a problem hiding this comment.
get_grpc_tracing_context needs to be removed
| from ray.serve.handle import DeploymentHandle | ||
| from ray.serve.schema import EncodingType, LoggingConfig, ReplicaRank | ||
| from ray.util import metrics as ray_metrics | ||
| from ray.util.tracing.tracing_helper import _is_tracing_enabled |
There was a problem hiding this comment.
i dont think we need this. _is_tracing_enabled is coming from core, which is saperate from serve's tracing
| # TODO(edoakes): populate this. | ||
| multiplexed_model_id="", | ||
| route=self._deployment_id.app_name, | ||
| tracing_context=self.get_grpc_tracing_context(context), |
There was a problem hiding this comment.
set _is_tracing_enabled to None
Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
…ct-ingress-v2 Signed-off-by: Seiji Eicher <[email protected]>
| request_id = ( | ||
| headers.get(SERVE_HTTP_REQUEST_ID_HEADER.encode("utf-8")).decode("utf-8") | ||
| or generate_request_id() | ||
| ) |
There was a problem hiding this comment.
Request ID extraction crashes when header is missing
High Severity
The request_id extraction in _direct_ingress_asgi calls .decode("utf-8") directly on the result of headers.get(). When the x-request-id header is not present, headers.get() returns None, and calling .decode() on None raises AttributeError: 'NoneType' object has no attribute 'decode'. This will crash every HTTP request that doesn't include the request ID header, which is the common case.
| self.queue.put_nowait(msg) | ||
|
|
||
| def close_queue(self): | ||
| self.queue.close() |
There was a problem hiding this comment.
| logger.info( | ||
| f"Recovered {self._protocol} port {port} for replica {replica_id} on node {self._node_id}" | ||
| ) | ||
| return port |
There was a problem hiding this comment.
Recovered ports not removed from available pool
High Severity
The update_port_if_missing method adds a recovered port to _allocated_ports but does not remove it from _available_ports. This can cause the same port to be allocated to multiple replicas. When a new replica calls allocate(), it may pop and assign a port that was already recovered for an existing replica, causing port conflicts and server startup failures.
| msg = ( | ||
| f"Request {request_id} timed out after " | ||
| f"{self._http_options.request_timeout_s}s." | ||
| ) |
There was a problem hiding this comment.
Timeout error message reports wrong timeout value
Low Severity
The timeout error message at line 2274 uses self._http_options.request_timeout_s instead of the actual request_timeout_s value that was used for the timeout (line 2246). When a client sends a custom timeout header, the error message will incorrectly report the default timeout value rather than the actual timeout that was applied, causing confusion during debugging.
| ) = await allocate_and_start_server( | ||
| start_server_fn=start_grpc_server_fn, | ||
| protocol=RequestProtocol.GRPC, | ||
| ) |
There was a problem hiding this comment.
HTTP server not cleaned up when gRPC startup fails
Medium Severity
In _maybe_start_direct_ingress_servers, if the HTTP server starts successfully (lines 1667-1673) but the subsequent gRPC server startup fails after exhausting retries, the HTTP server task continues running and the HTTP port remains allocated. The function raises RuntimeError without canceling self._direct_ingress_http_server_task or releasing the HTTP port, causing a resource leak and orphaned server.
| if isinstance(message, Exception): | ||
| raise message | ||
|
|
||
| return message |
There was a problem hiding this comment.
Duplicated ASGI receive proxy implementations
Medium Severity
The ASGIDIReceiveProxy class in direct_ingress_http_util.py duplicates logic from ASGIReceiveProxy, specifically for _get_default_disconnect_message, queue, and __call__. The _get_default_disconnect_message method is also unused within ASGIDIReceiveProxy. This introduces unnecessary code and increases maintenance overhead.
| ] = [] | ||
| self._refresh_autoscaling_deployments_cache() | ||
|
|
||
| self._last_broadcasted_target_groups: List[TargetGroup] = [] |
There was a problem hiding this comment.
| def get_target_groups( | ||
| self, | ||
| app_name: Optional[str] = None, | ||
| from_proxy_manager: bool = False, |
There was a problem hiding this comment.
|
Skipping new test added by #60270 that does not apply to DI mode |
The test_root_path test validates proxy-dependent behavior where serve_root_path from http_options is handled by the proxy's route matching logic. In direct ingress mode, requests bypass the proxy and go directly to replicas, so this test is not applicable. Signed-off-by: Seiji Eicher <[email protected]>
| request_id = ( | ||
| headers.get(SERVE_HTTP_REQUEST_ID_HEADER.encode("utf-8")).decode("utf-8") | ||
| or generate_request_id() | ||
| ) |
There was a problem hiding this comment.
Null pointer error when request ID header is missing
High Severity
In _direct_ingress_asgi, the code attempts to decode the x-request-id header value without first checking if the header exists. When headers.get(SERVE_HTTP_REQUEST_ID_HEADER.encode("utf-8")) returns None (header not present), calling .decode("utf-8") on None raises an AttributeError. The or generate_request_id() fallback never executes because the exception occurs first. Most HTTP requests won't include this header, causing the direct ingress endpoint to crash.
| msg = ( | ||
| f"Request {request_id} timed out after " | ||
| f"{self._http_options.request_timeout_s}s." | ||
| ) |
There was a problem hiding this comment.
Timeout error message shows wrong timeout value
Low Severity
The timeout error message uses self._http_options.request_timeout_s instead of the actual request_timeout_s value that was used for the timeout. If a client sends a custom timeout via the x-request-timeout-seconds header, the error message will incorrectly display the default HTTP options timeout rather than the actual timeout that was applied.
| logger.info( | ||
| f"Recovered {self._protocol} port {port} for replica {replica_id} on node {self._node_id}" | ||
| ) | ||
| return port |
There was a problem hiding this comment.
Recovered ports not removed from available pool causes conflicts
High Severity
The update_port_if_missing method adds recovered ports to _allocated_ports but fails to remove them from _available_ports. After controller restart, the PortAllocator is reinitialized with all ports in _available_ports. When existing replica ports are recovered via update_port_if_missing, the ports remain in the heap. Subsequent calls to allocate() can return these already-allocated ports to new replicas, causing port conflicts where two replicas believe they own the same port.
| f"{self._http_options.request_timeout_s}s." | ||
| ) | ||
| await send_http_response(msg, 408, send) | ||
| raise asyncio.CancelledError |
There was a problem hiding this comment.
Queue counter leak when request cancelled before processing starts
Medium Severity
When an HTTP request times out or disconnects while waiting on the semaphore in _start_request, the _num_queued_requests counter is incremented at line 2190 but never decremented. The decrement at line 2209 only executes after successfully entering _start_request. When request_task.cancel() is called (lines 2259, 2269), the task is cancelled but not awaited, and CancelledError is immediately raised. If the task was blocked on the semaphore, the decrement never runs. Over time, this counter drift causes the replica to reject all requests due to hitting max_queued_requests.
Additional Locations (1)
| ] = [] | ||
| self._refresh_autoscaling_deployments_cache() | ||
|
|
||
| self._last_broadcasted_target_groups: List[TargetGroup] = [] |
There was a problem hiding this comment.
Unused instance variable never read after initialization
Low Severity
The instance variable _last_broadcasted_target_groups is initialized but never read or used anywhere in the codebase. It appears to be scaffolding for potential future caching/comparison logic (similar to _last_broadcasted_running_replica_infos in deployment_state.py), but since it's not actually used, it's dead code that adds confusion.
| "code": 1005, | ||
| } | ||
| else: | ||
| return {"type": "http.disconnect"} |
There was a problem hiding this comment.
Duplicated disconnect message method across two classes
Low Severity
The _get_default_disconnect_message method in ASGIDIReceiveProxy is an exact character-for-character copy of the same method in ASGIReceiveProxy. Both classes also share identical queue properties and nearly identical __call__ methods. This duplication increases maintenance burden and risks divergent bug fixes.
| "node_id": node_id, | ||
| "node_ip_address": node_ip_address, | ||
| } | ||
| ) |
There was a problem hiding this comment.
Duplicated ingress metrics initialization with proxy code
Low Severity
The methods _init_ingress_request_counter, _init_ingress_request_error_counter, _init_deployment_request_error_counter, _init_ingress_processing_latency_tracker, and _init_ingress_num_ongoing_requests_gauge duplicate the metrics initialization logic from proxy.py. These create identical metric names, descriptions, and tag keys, making maintenance harder.
| request: Any, | ||
| context: grpc._cython.cygrpc._ServicerContext, | ||
| ): | ||
| raise NotImplementedError("unary_stream not implemented.") |
There was a problem hiding this comment.
Stub method raises NotImplementedError in production path
Medium Severity
The _direct_ingress_unary_stream method is wired into the gRPC handler factory and will be called when streaming gRPC requests arrive, but it only raises NotImplementedError. This incomplete implementation exists in a production code path and could surprise users with unexpected errors.
## Summary This PR adds direct ingress functionality to Ray Serve, allowing replicas to listen directly on ports for incoming traffic. This enables deployments where each replica is individually addressable, which is useful for Kubernetes ingress controllers and load balancers. ### Key changes: - Add direct ingress HTTP utility for ASGI receive proxying - Add direct ingress gRPC support (unary-unary handlers, health checks) - Add replica response generator for disconnect detection - Add node port manager for per-node port allocation - Add direct ingress support to controller (target groups, port allocation) - Add direct ingress support to replica (HTTP/gRPC servers, graceful shutdown) - Add direct ingress constants and feature flag (`RAY_SERVE_ENABLE_DIRECT_INGRESS`) - Add integration and unit tests The feature is disabled by default and can be enabled by setting `RAY_SERVE_ENABLE_DIRECT_INGRESS=1`. ## Test plan - [x] Run `test_direct_ingress.py` integration tests - [x] Run `test_direct_ingress_standalone.py` standalone tests - [x] Run `test_controller_direct_ingress.py` unit tests - [x] Benchmarks ## Benchmarks Validated using release image from https://buildkite.com/ray-project/release/builds/76725#019be801-2dc9-45f7-bf1e-3d7ae41ff6d8 and `RAY_SERVE_ENABLE_DIRECT_INGRESS=1`, direct ingress provides 6x reduction in TTFT and 1.8x improvement in throughput. Max concurrency 32/replica, 256 prompts/replica total. ITL 1024 OTL 256. <img width="4171" height="2955" alt="httpproxy_vs_direct_ingress" src="https://github.com/user-attachments/assets/2fddd7df-ad8a-4422-920a-d692993f846c" /> HTTPProxy (baseline) sweep: https://gist.github.com/eicherseiji/630a83a0582aad22fb4655e6464a0038 Direct Ingress (this PR) sweep: https://gist.github.com/eicherseiji/18d326524cbfe48e0353bfa8243bbb28 Toy load balancer used to test Direct Ingress: https://gist.github.com/eicherseiji/cce80555ac2e8d04482483e5f8422509 --------- Signed-off-by: Seiji Eicher <[email protected]> Signed-off-by: Future-Outlier <[email protected]> Signed-off-by: Eugene Kim <[email protected]> Co-authored-by: Han-Ju Chen (Future-Outlier) <[email protected]> Signed-off-by: Adel Nour <[email protected]>
…ve abstract base class (#60198) ## Why are these changes needed? This refactors the Replica class hierarchy to remove `ReplicaBase` in favor of `Replica` for unified gRPC and direct ingress handling. Reference PRs: - #60914 - #59908 - #60118 ## Related issue number N/A ## Checks - [x] I've signed off every commit (by using the -s flag) - [x] I've run `scripts/format.sh` to lint the changes in this PR - [ ] I've included any doc changes needed for https://docs.ray.io/en/master/ - [ ] I've added any new APIs to the API reference - [x] I've made sure the tests are passing - [ ] Testing Strategy - [x] Unit tests - [ ] Release tests - [ ] This PR is not tested :( ## Changes --------- Signed-off-by: Seiji Eicher <[email protected]>
…ve abstract base class (ray-project#60198) ## Why are these changes needed? This refactors the Replica class hierarchy to remove `ReplicaBase` in favor of `Replica` for unified gRPC and direct ingress handling. Reference PRs: - ray-project#60914 - ray-project#59908 - ray-project#60118 ## Related issue number N/A ## Checks - [x] I've signed off every commit (by using the -s flag) - [x] I've run `scripts/format.sh` to lint the changes in this PR - [ ] I've included any doc changes needed for https://docs.ray.io/en/master/ - [ ] I've added any new APIs to the API reference - [x] I've made sure the tests are passing - [ ] Testing Strategy - [x] Unit tests - [ ] Release tests - [ ] This PR is not tested :( ## Changes --------- Signed-off-by: Seiji Eicher <[email protected]>
Summary
This PR adds direct ingress functionality to Ray Serve, allowing replicas to listen directly on ports for incoming traffic. This enables deployments where each replica is individually addressable, which is useful for Kubernetes ingress controllers and load balancers.
Key changes:
RAY_SERVE_ENABLE_DIRECT_INGRESS)The feature is disabled by default and can be enabled by setting
RAY_SERVE_ENABLE_DIRECT_INGRESS=1.Test plan
test_direct_ingress.pyintegration teststest_direct_ingress_standalone.pystandalone teststest_controller_direct_ingress.pyunit testsBenchmarks
Validated using release image from https://buildkite.com/ray-project/release/builds/76725#019be801-2dc9-45f7-bf1e-3d7ae41ff6d8 and

RAY_SERVE_ENABLE_DIRECT_INGRESS=1, direct ingress provides 6x reduction in TTFT and 1.8x improvement in throughput. Max concurrency 32/replica, 256 prompts/replica total. ITL 1024 OTL 256.HTTPProxy (baseline) sweep: https://gist.github.com/eicherseiji/630a83a0582aad22fb4655e6464a0038
Direct Ingress (this PR) sweep: https://gist.github.com/eicherseiji/18d326524cbfe48e0353bfa8243bbb28
Toy load balancer used to test Direct Ingress: https://gist.github.com/eicherseiji/cce80555ac2e8d04482483e5f8422509