← Back to Pull requests

fix(api): abort non-streaming vLLM requests when the client disconnects #5694

Closed
unknown closed this pull request without merging on Oct 16, 2026 09:04 UTC
View on GitHub
unknown unknown commented on Oct 16, 2026 05:08 UTC
Author

What happens

#5549 stops a vLLM request when an SSE client disconnects. A non-streaming /v1/chat/completions or /v1/completions request whose HTTP client has gone (a client-side timeout, a cancelled call, a closed connection) is not aborted. Starlette does not cancel the handler on disconnect, so generation can continue consuming model capacity after the client leaves. The explicit abort endpoint (POST /v1/models/{uid}/requests/{id}/abort) still works, but only for a caller that still has the request id.

On a real GPU (RTX 4090 24 GB, vLLM 0.31.0, Qwen3-8B-FP8 served by xinference-local), with a chat request asking to count to 3000 (max_tokens=3000, ignore_eos=True, chat_template_kwargs={"enable_thinking": False}):

| request | on dfa2021 | with this PR |
|---|---|---|
| streaming, client closes after 4 lines (control) | probe reported 0.0 s; abort logged | probe reported 0.0 s; abort logged |
| non-streaming, client times out after 1 s | still busy at the end of the 90 s window; no abort logged | last busy sample at 0.6 s; abort logged |
| non-streaming, explicit abort endpoint (control) | 200 {"msg":"DONE"}; last busy sample at 0.6 s | same |

The probe sleeps 0.5 s between samples and reports the time of the last sample with GPU utilisation above 5%, or 0.0 if none was seen. These are not precise idle or completion times.

Cause

The non-streaming branches of create_completion and create_chat_completion (xinference/api/restful_api.py) do a bare await model.generate(...) / await model.chat(...). Nothing watches the connection, so the vLLM request tracking never sees the request interrupted.

Change

  • New helper _run_non_streaming_request beside the SSE abort helpers. Both endpoints use it when model.is_vllm_backend() is true, the condition under which the request id is passed to the model; the existing P/D routers, whose is_vllm_backend() is always true, use it too. It runs the model call as a task and races it against a listener that waits for http.disconnect on the request's receive channel (the body has already been read).

  • If generation finishes first, including when both are ready, the response, errors and metrics are as before.

  • If the disconnect wins, the helper reports it (report_client_disconnect), aborts the request through _SSERequestAbortController.abort() (shielded, now with an optional timeout on the abort operation: 5 s here, none for SSE), cancels and joins the generation task, and returns an empty 499 (nothing can be delivered). This is one abort invocation by the helper on the selected model reference; total teardown is cooperative and can exceed five seconds.

  • If the handler itself is cancelled, it waits for shielded cleanup and re-raises the cancellation. If the cleanup task becomes cancelled while joining generation, the wait terminates and cancellation is re-raised. A failing receive propagates instead of being treated as a disconnect.

  • Direct non-vLLM ModelActor paths, streaming, the explicit abort endpoint and its DONE/NO_OP/NOT_FOUND outcomes, and the actor's serve-count release are unchanged.
  • No documentation change: this extends the cleanup #5549 added for streaming to the non-streaming path.

    Tests

    New file xinference/api/tests/test_non_streaming_request_abort.py (28 cases: 19 ASGI/protocol cases, eight direct-helper cases and one shutdown subprocess; no sockets):

  • both endpoints, with and without the audit middleware: a disconnect during generation aborts once, stops generation and logs a 499; a connected request keeps its response bytes, its Content-Type and X-Request-ID headers and the #5690 token metrics; injected backend errors keep the 500/429 mapping;

  • a P/D-router-shaped model reference gets the abort on the router through the completion route, using the real router predicate and a mocked abort method;

  • generation that finishes at the same time as a disconnect wins (success, error, cancellation);

  • abort failure and abort timeout, repeated handler cancellation, cancellation during cleanup, cancellation of the cleanup task while it joins generation, and a failing receive;

  • concurrent requests with independent ids and serve counts, and an explicit abort racing a disconnect;

  • Uvicorn h11's connection_lost, exercised with a mocked transport.
  • Outside-sandbox comparison with the e5b0acc test file on base dfa2021: 16 cases failed and 12 passed, with one additional teardown error in the concurrent-ids case:

  • the four disconnect route cases, the P/D router case, the h11 connection loss and the concurrent-ids case fail because nothing aborts the request (the concurrent case times out waiting for an abort and leaves tasks for teardown);

  • eight tie and cleanup cases fail with AttributeError because the helper is absent; the shutdown subprocess fails to import it with ImportError;

  • the connected and error controls pass.
  • The cleanup-task case runs its scenario in a subprocess, allowing up to 600 s for startup and imports to print ready, then 20 s for the scenario and interpreter shutdown. In my outside-sandbox runs of the updated test file with the two-line cancellation fix removed, it failed with subprocess.TimeoutExpired on Linux Python 3.12 and Windows Python 3.14 instead of hanging the test run.

    The 429 case injects a rate-limit error; it does not exhaust the admission limit. The P/D case checks routing with a stub, not P/D engine teardown. httptools, abort-before-registration, reused-id timing and separate supervisor/worker RPC teardown are not covered by this file.

    I ran these outside the sandbox on e5b0acc (Python 3.12, CPU torch, Linux under WSL; vLLM not installed):

  • PYTHONPATH=. ~/venvs/xi/bin/python -m pytest -p no:cacheprovider xinference/api/tests/test_non_streaming_request_abort.py -q --timeout=300: 28 passed, twice.

  • xinference/api/tests/test_llm_request_abort.py and xinference/model/llm/vllm/tests/test_abort.py: 33 passed.

  • All of xinference/api/tests: 787 passed, 67 skipped, 1 failed. That failure, test_anthropic_compat.py::test_pdf_requests_share_the_ocr_lock_and_render_once, also fails on dfa2021 (759 passed, 67 skipped, 1 failed).

  • uvx pre-commit run --files xinference/api/restful_api.py xinference/api/tests/test_non_streaming_request_abort.py: black, end-of-file, trailing-whitespace, ruff, isort, mypy and codespell pass.
  • The GPU table comes from my own probe (not part of this PR) against xinference-local with the model launched through the REST API (enforce_eager, max_model_len=8192, gpu_memory_utilization=0.85), on dfa2021, first unchanged and then with this change's restful_api.py before the two-line fix for cancellation of the cleanup task.

    AI assistance: the bug was found and the fix drafted with AI tools (OpenAI Codex, Claude Code).

    🤖 Generated with Claude Code

    https://claude.ai/code/session_019TTGAv6fe859ebbCLLfLHP

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: Jackmeson1 Review duration: 236m
    All Vouch review confidence checks passed
    Residual risk 0.25 = Change Risk (0.57) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.57 · 650 lines diff across 8 files
    0.57
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    1 comments
    "Review active on #5694"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 57% (MEDIUM) · Higher = larger blast radius
    57%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 56.8% · Lower = rushed or shallow review
    56.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 24.7% · Safe to merge
    24.7%