Repository navigation
Conversation
) When a client disconnects during a request (especially non-streaming), the router now detects the disconnection and closes its connection to the backend engine, causing vLLM to abort the in-flight request. Previously, cancelling a non-streaming request (e.g., Ctrl-C on curl) would not propagate to the backend, causing vLLM to continue processing the request wastefully. Implementation: - Added an asyncio background task in process_request() that polls request.is_disconnected() every second - When disconnect is detected, calls backend_response.close() to abort the backend connection - Task is properly cancelled when the request completes normally Tests: - test_disconnect_monitor_cancels_backend: verifies backend is closed on client disconnect - test_disconnect_monitor_cancelled_on_normal_completion: verifies no action on normal completion
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request addresses a critical issue where client cancellations for non-streaming requests were not propagated to the backend vLLM engine, leading to inefficient resource utilization. The solution introduces a robust mechanism to detect client disconnections and proactively terminate backend processing, ensuring that resources are not wasted on abandoned requests. This significantly improves the router's efficiency and responsiveness to client behavior. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request introduces a mechanism to propagate client-side request cancellations to the backend engine for non-streaming requests, using an asyncio background task to monitor client disconnection and close backend connections, thereby preventing wasteful processing. However, a medium-severity log injection vulnerability was identified in the new logging logic, as untrusted input from the X-Request-Id header is logged without proper sanitization. Additionally, while the core logic is verified, the tests could be improved by directly testing the implementation code rather than a copy, enhancing their robustness.
| logger.info( | ||
| f"Client disconnected for request {request_id}, " | ||
| f"aborting backend connection to {backend_url}" | ||
| ) |
There was a problem hiding this comment.
The request_id is derived from the user-supplied X-Request-Id header and is logged without sanitization. If the default text logger is used (which is the case when log_format is not set to 'json'), an attacker can inject newline characters into the header to forge log entries or disrupt log analysis. This can be used to mislead auditors or interfere with monitoring systems that rely on log parsing.
| logger.info( | |
| f"Client disconnected for request {request_id}, " | |
| f"aborting backend connection to {backend_url}" | |
| ) | |
| logger.info( | |
| f"Client disconnected for request {request_id.replace('\n', ' ').replace('\r', ' ')}, " | |
| f"aborting backend connection to {backend_url}" | |
| ) |
| class TestDisconnectMonitor(unittest.TestCase): | ||
| """Test the disconnect monitoring logic in process_request.""" | ||
|
|
||
| def test_disconnect_monitor_cancels_backend(self): | ||
| """ | ||
| Simulate a client disconnect and verify that the backend response | ||
| gets closed, which propagates cancellation to the engine. | ||
| """ | ||
|
|
||
| async def _run(): | ||
| # Mock objects | ||
| mock_response = MagicMock() | ||
| mock_response.close = MagicMock() | ||
|
|
||
| # Simulate disconnect after 0.1s | ||
| call_count = 0 | ||
|
|
||
| async def mock_is_disconnected(): | ||
| nonlocal call_count | ||
| call_count += 1 | ||
| # Return False first, then True to simulate disconnect | ||
| return call_count > 1 | ||
|
|
||
| mock_request = MagicMock() | ||
| mock_request.is_disconnected = mock_is_disconnected | ||
|
|
||
| # Create the disconnect monitor task | ||
| async def _disconnect_monitor(): | ||
| try: | ||
| while True: | ||
| if await mock_request.is_disconnected(): | ||
| mock_response.close() | ||
| return | ||
| await asyncio.sleep(0.05) | ||
| except asyncio.CancelledError: | ||
| pass | ||
|
|
||
| task = asyncio.create_task(_disconnect_monitor()) | ||
|
|
||
| # Wait for the task to detect disconnect | ||
| await asyncio.sleep(0.2) | ||
|
|
||
| # Verify the backend response was closed | ||
| mock_response.close.assert_called_once() | ||
|
|
||
| # Clean up | ||
| if not task.done(): | ||
| task.cancel() | ||
| try: | ||
| await task | ||
| except asyncio.CancelledError: | ||
| pass | ||
|
|
||
| asyncio.run(_run()) | ||
|
|
||
| def test_disconnect_monitor_cancelled_on_normal_completion(self): | ||
| """ | ||
| Verify that the disconnect monitor task is properly cancelled | ||
| when the request completes normally (client stays connected). | ||
| """ | ||
|
|
||
| async def _run(): | ||
| mock_response = MagicMock() | ||
| mock_response.close = MagicMock() | ||
|
|
||
| # Client never disconnects | ||
| async def mock_is_disconnected(): | ||
| return False | ||
|
|
||
| mock_request = MagicMock() | ||
| mock_request.is_disconnected = mock_is_disconnected | ||
|
|
||
| async def _disconnect_monitor(): | ||
| try: | ||
| while True: | ||
| if await mock_request.is_disconnected(): | ||
| mock_response.close() | ||
| return | ||
| await asyncio.sleep(0.05) | ||
| except asyncio.CancelledError: | ||
| pass | ||
|
|
||
| task = asyncio.create_task(_disconnect_monitor()) | ||
|
|
||
| # Simulate normal request completion - cancel the task | ||
| await asyncio.sleep(0.05) | ||
| task.cancel() | ||
| try: | ||
| await task | ||
| except asyncio.CancelledError: | ||
| pass | ||
|
|
||
| # Verify backend response was NOT closed | ||
| mock_response.close.assert_not_called() | ||
|
|
||
| asyncio.run(_run()) |
There was a problem hiding this comment.
The tests in TestDisconnectMonitor currently duplicate the implementation of the _disconnect_monitor function from src/vllm_router/services/request_service/request.py. This is not ideal as it makes the tests brittle; if the production code for _disconnect_monitor changes, these tests might not reflect that change, potentially leading to a false sense of security.
To make the tests more robust and maintainable, I suggest refactoring _disconnect_monitor into a standalone (non-nested) helper function in request.py. This will allow you to import it directly into your test file and test the actual production code.
Example of refactoring in request.py:
# In src/vllm_router/services/request_service/request.py
async def _disconnect_monitor_task(request: Request, backend_response, request_id: str, backend_url: str):
"""Monitors for client disconnect and aborts the backend request."""
try:
while True:
if await request.is_disconnected():
logger.info(
f"Client disconnected for request {request_id}, "
f"aborting backend connection to {backend_url}"
)
backend_response.close()
return
await asyncio.sleep(1.0)
except asyncio.CancelledError:
pass
async def process_request(...):
# ...
disconnect_task = asyncio.create_task(
_disconnect_monitor_task(request, backend_response, request_id, backend_url)
)
# ...Then, you could update your test to import and use this function directly, ensuring you are always testing the real implementation.
There was a problem hiding this comment.
Pull request overview
This PR aims to ensure client disconnect/cancellation for non-streaming requests propagates from the router to backend vLLM engines by closing the backend connection when the client disconnects.
Changes:
- Add an
asynciobackground task inprocess_request()to pollrequest.is_disconnected()and close the backend response on disconnect. - Add a new test module intended to validate request-cancellation propagation behavior.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 5 comments.
| File | Description |
|---|---|
src/vllm_router/services/request_service/request.py |
Adds a disconnect-monitor background task to abort the backend aiohttp response when the client disconnects. |
src/tests/test_request_cancellation.py |
Adds unit tests intended to validate the disconnect-monitor behavior. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| # Start a background task that monitors client disconnection | ||
| # and closes the backend connection to propagate cancellation. | ||
| # This is critical for non-streaming requests where the backend | ||
| # may spend a long time processing before sending any response. | ||
| async def _disconnect_monitor(): | ||
| try: | ||
| while True: | ||
| if await request.is_disconnected(): | ||
| logger.info( | ||
| f"Client disconnected for request {request_id}, " | ||
| f"aborting backend connection to {backend_url}" | ||
| ) | ||
| backend_response.close() | ||
| return | ||
| await asyncio.sleep(1.0) |
There was a problem hiding this comment.
The disconnect monitor is started only after aiohttp_client_wrapper().request(... ) yields backend_response (i.e., after the backend has sent response headers). If the backend doesn't send headers until it finishes the non-streaming computation (common for JSON responses), the router will still be blocked waiting for headers and won't detect client disconnects during that period. Consider running the aiohttp request itself in a task and racing it against a disconnect monitor (cancel/close the request task on disconnect) so cancellation can be propagated even while waiting for the initial response.
| backend_response.close() | ||
| return | ||
| await asyncio.sleep(1.0) | ||
| except asyncio.CancelledError: | ||
| pass | ||
|
|
||
| disconnect_task = asyncio.create_task(_disconnect_monitor()) | ||
|
|
||
| try: | ||
| # Yield headers and status code first. | ||
| yield backend_response.headers, backend_response.status | ||
| # Stream response content. | ||
| async for chunk in backend_response.content.iter_any(): | ||
| total_len += len(chunk) | ||
| if not first_token: | ||
| first_token = True | ||
| request.app.state.request_stats_monitor.on_request_response( | ||
| backend_url, request_id, time.time() | ||
| ) | ||
| # For non-streaming requests, collect the full response | ||
| if full_response is not None: | ||
| full_response.extend(chunk) | ||
| yield chunk | ||
| finally: | ||
| disconnect_task.cancel() | ||
| try: | ||
| await disconnect_task | ||
| except asyncio.CancelledError: | ||
| pass |
There was a problem hiding this comment.
When the client disconnects and _disconnect_monitor() calls backend_response.close(), the async for chunk in backend_response.content.iter_any() loop is likely to raise an aiohttp connection/payload exception. Right now this will be caught by the outer except Exception and counted/logged as a router error (and potentially mark traces as errored), even though it's an expected cancellation path. Consider treating “client disconnected” as a normal termination: e.g., set a flag in the monitor and, when catching aiohttp read/connection errors or asyncio.CancelledError, check await request.is_disconnected() / the flag and exit without incrementing request_errors_total.
| import json | ||
| import os | ||
| import time | ||
| import uuid | ||
| from typing import Optional | ||
|
|
||
| import asyncio | ||
| import aiohttp | ||
|
|
There was a problem hiding this comment.
Import ordering will fail the repo’s isort pre-commit hook: asyncio is a stdlib import but it’s inserted after from typing import Optional. Run isort (or reorder imports) so all stdlib imports are grouped/sorted before third-party imports like aiohttp.
| import json | ||
| import unittest | ||
| from unittest.mock import AsyncMock, MagicMock, patch | ||
|
|
||
| import pytest | ||
|
|
||
|
|
There was a problem hiding this comment.
This test file has multiple unused imports (json, AsyncMock, patch, pytest). The repo runs Ruff on src/tests/ (see .pre-commit-config.yaml), so these will trigger F401 and fail CI/pre-commit. Remove the unused imports or use them in the tests.
| import json | |
| import unittest | |
| from unittest.mock import AsyncMock, MagicMock, patch | |
| import pytest | |
| import unittest | |
| from unittest.mock import MagicMock |
| def test_disconnect_monitor_cancels_backend(self): | ||
| """ | ||
| Simulate a client disconnect and verify that the backend response | ||
| gets closed, which propagates cancellation to the engine. | ||
| """ | ||
|
|
||
| async def _run(): | ||
| # Mock objects | ||
| mock_response = MagicMock() | ||
| mock_response.close = MagicMock() | ||
|
|
||
| # Simulate disconnect after 0.1s | ||
| call_count = 0 | ||
|
|
||
| async def mock_is_disconnected(): | ||
| nonlocal call_count | ||
| call_count += 1 | ||
| # Return False first, then True to simulate disconnect | ||
| return call_count > 1 | ||
|
|
||
| mock_request = MagicMock() | ||
| mock_request.is_disconnected = mock_is_disconnected | ||
|
|
||
| # Create the disconnect monitor task | ||
| async def _disconnect_monitor(): | ||
| try: | ||
| while True: | ||
| if await mock_request.is_disconnected(): | ||
| mock_response.close() | ||
| return | ||
| await asyncio.sleep(0.05) | ||
| except asyncio.CancelledError: | ||
| pass | ||
|
|
||
| task = asyncio.create_task(_disconnect_monitor()) | ||
|
|
||
| # Wait for the task to detect disconnect | ||
| await asyncio.sleep(0.2) | ||
|
|
||
| # Verify the backend response was closed | ||
| mock_response.close.assert_called_once() | ||
|
|
||
| # Clean up | ||
| if not task.done(): | ||
| task.cancel() | ||
| try: | ||
| await task | ||
| except asyncio.CancelledError: | ||
| pass | ||
|
|
||
| asyncio.run(_run()) | ||
|
|
||
| def test_disconnect_monitor_cancelled_on_normal_completion(self): | ||
| """ | ||
| Verify that the disconnect monitor task is properly cancelled | ||
| when the request completes normally (client stays connected). | ||
| """ | ||
|
|
||
| async def _run(): | ||
| mock_response = MagicMock() | ||
| mock_response.close = MagicMock() | ||
|
|
||
| # Client never disconnects | ||
| async def mock_is_disconnected(): | ||
| return False | ||
|
|
||
| mock_request = MagicMock() | ||
| mock_request.is_disconnected = mock_is_disconnected | ||
|
|
||
| async def _disconnect_monitor(): | ||
| try: | ||
| while True: | ||
| if await mock_request.is_disconnected(): | ||
| mock_response.close() | ||
| return | ||
| await asyncio.sleep(0.05) | ||
| except asyncio.CancelledError: | ||
| pass | ||
|
|
||
| task = asyncio.create_task(_disconnect_monitor()) | ||
|
|
||
| # Simulate normal request completion - cancel the task | ||
| await asyncio.sleep(0.05) | ||
| task.cancel() | ||
| try: | ||
| await task | ||
| except asyncio.CancelledError: | ||
| pass | ||
|
|
||
| # Verify backend response was NOT closed | ||
| mock_response.close.assert_not_called() | ||
|
|
||
| asyncio.run(_run()) | ||
|
|
There was a problem hiding this comment.
The tests currently re-implement _disconnect_monitor() locally instead of exercising the new logic inside process_request(). As written, they only validate that an asyncio task can call close() and be cancelled, but they don’t prove that process_request() closes the real backend_response when request.is_disconnected() flips to true (or that it’s cancelled on normal completion). Consider testing process_request() directly by mocking request.is_disconnected(), request.app.state.aiohttp_client_wrapper().request(...) / backend_response.content.iter_any(), and asserting backend_response.close() is called (and not called) in the two cases.
Summary
Closes #634
Fixes the bug where cancelling a non-streaming request (e.g., Ctrl-C on curl) does not propagate to the backend vLLM engine, causing it to continue processing the request wastefully.
Problem
When
stream: false(or omitted), if the client disconnects mid-request:200 OKinstead ofAborted requestWith
stream: true, cancellation already worked because FastAPI's StreamingResponse naturally propagates generator cancellation.Solution
Added a disconnect monitor in
process_request()that runs as anasynciobackground task concurrently with the backend response streaming:request.is_disconnected()every ~1 secondbackend_response.close()to abort the backend connectiontry/finallywhen the request completes normallyChanges
src/vllm_router/services/request_service/request.py: Added_disconnect_monitor()background task insideprocess_request(), with proper lifecycle management (cancel on completion, handle gracefully)src/tests/test_request_cancellation.py: Unit tests verifying the disconnect monitor correctly closes backend on disconnect and does nothing on normal completionTesting
curland hitting Ctrl-C)