Skip to content

fix: propagate request cancellation to backend engines - #867

Closed
NJX-njx wants to merge 1 commit into
vllm-project:mainfrom
NJX-njx:fix/634-request-cancellation
Closed

NJX-njx wants to merge 1 commit into
vllm-project:mainfrom
NJX-njx:fix/634-request-cancellation

Conversation

@NJX-njx

@NJX-njx NJX-njx commented Mar 4, 2026

Copy link
Copy Markdown

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:

  • The router kept its connection to the backend open
  • The vLLM engine continued processing the full request
  • Engine logs showed 200 OK instead of Aborted request

With stream: true, cancellation already worked because FastAPI's StreamingResponse naturally propagates generator cancellation.

Solution

Added a disconnect monitor in process_request() that runs as an asyncio background task concurrently with the backend response streaming:

  1. The task polls request.is_disconnected() every ~1 second
  2. When client disconnect is detected, it calls backend_response.close() to abort the backend connection
  3. The closed connection causes vLLM to detect the disconnect and abort the in-flight request
  4. The task is properly cancelled via try/finally when the request completes normally

Changes

  • src/vllm_router/services/request_service/request.py: Added _disconnect_monitor() background task inside process_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 completion

Testing

  • Unit tests pass locally
  • Full integration test requires a running vLLM cluster (demonstrated by sending request via curl and hitting Ctrl-C)

)

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
Copilot AI review requested due to automatic review settings March 4, 2026 10:41
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, 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

  • Request Cancellation Propagation: Implemented client disconnect monitoring for non-streaming requests to ensure cancellation propagates to backend engines, preventing wasteful processing.
  • Disconnect Monitor Background Task: Introduced an asyncio background task, _disconnect_monitor, within process_request() to periodically check for client disconnections.
  • Lifecycle Management: Ensured the _disconnect_monitor task properly closes the backend connection upon client disconnect and is gracefully cancelled when the request completes normally.
  • Unit Testing: Added comprehensive unit tests to verify the correct behavior of the disconnect monitor under various client connection scenarios.

🧠 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
  • src/tests/test_request_cancellation.py
    • Added a new test file containing the TestDisconnectMonitor class.
    • Included tests for verifying backend cancellation when a client disconnects.
    • Included tests for verifying proper task cancellation when a request completes normally without disconnection.
  • src/vllm_router/services/request_service/request.py
    • Imported the asyncio module to support asynchronous operations.
    • Implemented _disconnect_monitor as an asyncio background task within process_request.
    • Added logic to create, manage, and cancel the _disconnect_monitor task to handle client disconnections.
Activity
  • No specific activity (comments, reviews, progress updates) has been recorded for this pull request yet.
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

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

Comment on lines +202 to +205
logger.info(
f"Client disconnected for request {request_id}, "
f"aborting backend connection to {backend_url}"
)

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.

security-medium medium

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.

Suggested change
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}"
)

Comment on lines +30 to +125
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())

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.

medium

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.

Copilot AI 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.

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 asyncio background task in process_request() to poll request.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.

Comment on lines +194 to +208
# 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)

Copilot AI Mar 4, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +206 to +234
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

Copilot AI Mar 4, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines 15 to 23
import json
import os
import time
import uuid
from typing import Optional

import asyncio
import aiohttp

Copilot AI Mar 4, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Comment on lines +23 to +29
import json
import unittest
from unittest.mock import AsyncMock, MagicMock, patch

import pytest


Copilot AI Mar 4, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
import json
import unittest
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
import unittest
from unittest.mock import MagicMock

Copilot uses AI. Check for mistakes.
Comment on lines +33 to +126
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())

Copilot AI Mar 4, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: Cancellations don't propagate through the vLLM router to the engines

3 participants