[Frontend][Core] Standardize request error handling with VLLMError hierarchy (#49665)

Signed-off-by: Zach Zhu <zzqshu@126.com>
This commit is contained in:
Zach Zhu
2026-07-29 04:20:40 +00:00
committed by GitHub
parent f37f03db4a
commit 58f9659397
46 changed files with 370 additions and 248 deletions
@@ -8,54 +8,95 @@ PrometheusInstrumentatorMiddleware before being caught by ServerErrorMiddleware.
"""
from argparse import Namespace
from http import HTTPStatus
import httpx
import pytest
from fastapi import FastAPI, HTTPException, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi import HTTPException
from prometheus_client import CollectorRegistry
from prometheus_fastapi_instrumentator import Instrumentator
from vllm.entrypoints.serve.utils.server_utils import exception_handler
from vllm.exceptions import VLLMNotFoundError, VLLMValidationError
from vllm.entrypoints.openai.api_server import build_app
from vllm.exceptions import (
VLLMNotFoundError,
VLLMServerError,
VLLMValidationError,
)
@pytest.fixture
@pytest.fixture(scope="module")
def should_do_global_cleanup_after_test() -> bool:
# This suite never initializes distributed/accelerator state.
return False
def _build_args() -> Namespace:
"""Minimal args for ``build_app``; avoids ``make_arg_parser`` device probing."""
return Namespace(
disable_fastapi_docs=True,
enable_offline_docs=False,
root_path=None,
allowed_origins=["*"],
allow_credentials=False,
allowed_methods=["*"],
allowed_headers=["*"],
api_key=None,
enable_request_id_headers=False,
enable_fault_tolerance=False,
middleware=[],
log_error_stack=False,
)
@pytest.fixture(scope="module")
def registry():
"""Create a fresh Prometheus registry for each test."""
"""Shared Prometheus registry for the module-scoped app."""
return CollectorRegistry()
@pytest.fixture
@pytest.fixture(scope="module")
def app(registry):
"""Create a minimal FastAPI app that mirrors vLLM's exception handler
and Prometheus middleware setup."""
"""Build the real vLLM FastAPI app once and attach probe routes that raise.
app = FastAPI()
Patch the name used by ``attach_router`` (imported into the instrumentator
metrics module), not ``vllm.v1.metrics.prometheus`` alone — that binding is
captured at import time.
"""
import vllm.entrypoints.serve.instrumentator.metrics as metrics_mod
# Mock app state that exception_handler needs
app.state.args = Namespace(log_error_stack=False)
original = metrics_mod.get_prometheus_registry
metrics_mod.get_prometheus_registry = lambda: registry
try:
app = build_app(_build_args(), supported_tasks=())
finally:
metrics_mod.get_prometheus_registry = original
# Register exception handlers exactly as vLLM does in build_app()
app.exception_handler(HTTPException)(_http_exception_handler)
app.exception_handler(RequestValidationError)(_validation_exception_handler)
app.exception_handler(ValueError)(exception_handler)
app.exception_handler(TypeError)(exception_handler)
app.exception_handler(OverflowError)(exception_handler)
app.exception_handler(NotImplementedError)(exception_handler)
app.exception_handler(VLLMValidationError)(exception_handler)
app.exception_handler(VLLMNotFoundError)(exception_handler)
app.exception_handler(Exception)(exception_handler)
@app.get("/raise_http_exception_400")
async def raise_http_exception_400():
raise HTTPException(status_code=400, detail="bad request")
# Instrument with Prometheus (same as vLLM's attach_router)
Instrumentator(
excluded_handlers=["/metrics"],
registry=registry,
).add().instrument(app)
@app.get("/raise_http_exception_404")
async def raise_http_exception_404():
raise HTTPException(status_code=404, detail="not found")
@app.get("/raise_request_validation_error")
async def raise_request_validation_error(n: int):
# Invalid ``n`` triggers FastAPI's RequestValidationError.
return {"n": n}
@app.get("/raise_vllm_validation_error")
async def raise_vllm_validation_error():
raise VLLMValidationError("bad parameter", parameter="temperature")
@app.get("/raise_vllm_not_found_error")
async def raise_vllm_not_found_error():
raise VLLMNotFoundError("model not found")
@app.get("/raise_vllm_server_error")
async def raise_vllm_server_error():
# Bare VLLMServerError goes through vllm_error_handler → 500.
# EngineGenerateError / EngineDeadError are not used here: they call
# terminate_if_errored and need engine/server state.
raise VLLMServerError("internal server failure")
# Test routes that raise different exception types
@app.get("/raise_value_error")
async def raise_value_error():
raise ValueError("invalid input value")
@@ -72,22 +113,6 @@ def app(registry):
async def raise_not_implemented_error():
raise NotImplementedError("feature not supported")
@app.get("/raise_vllm_validation_error")
async def raise_vllm_validation_error():
raise VLLMValidationError("bad parameter", parameter="temperature")
@app.get("/raise_vllm_not_found_error")
async def raise_vllm_not_found_error():
raise VLLMNotFoundError("model not found")
@app.get("/raise_http_exception_400")
async def raise_http_exception_400():
raise HTTPException(status_code=400, detail="bad request")
@app.get("/raise_http_exception_404")
async def raise_http_exception_404():
raise HTTPException(status_code=404, detail="not found")
@app.get("/raise_runtime_error")
async def raise_runtime_error():
raise RuntimeError("unexpected server error")
@@ -99,14 +124,6 @@ def app(registry):
return app
async def _http_exception_handler(req: Request, exc: HTTPException):
return JSONResponse({"error": exc.detail}, status_code=exc.status_code)
async def _validation_exception_handler(req: Request, exc: RequestValidationError):
return JSONResponse({"error": str(exc)}, status_code=HTTPStatus.BAD_REQUEST)
def _get_http_requests_total(registry, method: str, handler: str):
"""Extract the http_requests_total metric values grouped by status.
@@ -128,31 +145,31 @@ def _get_http_requests_total(registry, method: str, handler: str):
@pytest.mark.asyncio
@pytest.mark.parametrize(
"endpoint,expected_status_group,expected_http_code",
"endpoint,expected_status_group,expected_http_code,request_kwargs",
[
# These should record as 4xx in Prometheus
("/raise_value_error", "4xx", 400),
("/raise_type_error", "4xx", 400),
("/raise_overflow_error", "4xx", 400),
("/raise_vllm_validation_error", "4xx", 400),
("/raise_vllm_not_found_error", "4xx", 404),
("/raise_http_exception_400", "4xx", 400),
("/raise_http_exception_404", "4xx", 404),
# NotImplementedError returns 501 which is still 5xx group
("/raise_not_implemented_error", "5xx", 501),
# These should record as 5xx in Prometheus (genuine server errors)
("/raise_runtime_error", "5xx", 500),
# Successful requests should record as 2xx
("/success", "2xx", 200),
("/raise_http_exception_400", "4xx", 400, {}),
("/raise_http_exception_404", "4xx", 404, {}),
("/raise_request_validation_error", "4xx", 400, {"params": {"n": "x"}}),
("/raise_vllm_validation_error", "4xx", 400, {}),
("/raise_vllm_not_found_error", "4xx", 404, {}),
("/raise_vllm_server_error", "5xx", 500, {}),
("/raise_value_error", "4xx", 400, {}),
("/raise_type_error", "4xx", 400, {}),
("/raise_overflow_error", "4xx", 400, {}),
("/raise_not_implemented_error", "5xx", 501, {}),
("/raise_runtime_error", "5xx", 500, {}),
("/success", "2xx", 200, {}),
],
ids=[
"HTTPException(400)->4xx",
"HTTPException(404)->4xx",
"RequestValidationError->4xx",
"VLLMValidationError->4xx",
"VLLMNotFoundError->4xx",
"VLLMServerError->5xx",
"ValueError->4xx",
"TypeError->4xx",
"OverflowError->4xx",
"VLLMValidationError->4xx",
"VLLMNotFoundError->4xx",
"HTTPException(400)->4xx",
"HTTPException(404)->4xx",
"NotImplementedError->5xx",
"RuntimeError->5xx",
"success->2xx",
@@ -164,6 +181,7 @@ async def test_http_requests_total_records_correct_status(
endpoint,
expected_status_group,
expected_http_code,
request_kwargs,
):
"""Verify that http_requests_total records the correct status group.
@@ -177,7 +195,7 @@ async def test_http_requests_total_records_correct_status(
async with httpx.AsyncClient(
transport=transport, base_url="http://testserver"
) as client:
response = await client.get(endpoint)
response = await client.get(endpoint, **request_kwargs)
# Verify the HTTP response code returned to the client is correct
assert response.status_code == expected_http_code, (