[Mini-VLLM] Cut non-OpenAI surfaces, dead kernels, Mistral stack

- Remove Anthropic, Cohere, SageMaker, decisions, structured-decisions,
  rl, render-launcher and batch entrypoints; keep scale-out token routes
- Drop the Swagger static bundle and the /docs, /redoc routes
- Delete device-keyed tuning configs for fused_moe, quant utils, mamba
  select-state and helion; no sm86 entry ever existed for any of them
- Remove ten unused rope variants plus the fbgemm_fp8 and fp_quant
  quantizers and their config, metrics and loader plumbing
- Cut the CPU device build: csrc/cpu, cpu_extension.cmake, cpu
  requirements and the setup.py cpu target path
- Delete 29 environment variables nothing reads and 14 chat-template
  fallbacks for models this fork no longer registers
- Remove nine dead CUDA ops (deepseek_v4, kimi_k3, minimax, muse_spark,
  dsv3 gemm) with their kernels, bindings, wrappers and CMake entries
- Delete the connector test suites that targeted removed connectors
- Cut the Mistral tokenizer and parser stack, its tests, and the
  mistral_common and ijson dependency pins
- Restore the Qwen4Exp registry rows and nvidia/mtp.py that an earlier
  cut deleted while keeping the model tree

Co-authored-by: Hinata <hinata@idihore.id>
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-10-19 17:10:56 +07:00
co-authored by Hinata
parent bd70a61c20
commit 2066d3143f
1086 changed files with 122 additions and 291919 deletions
@@ -2,7 +2,6 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import multiprocessing
import os
import socket
import threading
import time
@@ -410,198 +409,3 @@ def test_external_process_monitoring(api_server_args):
mock_coordinator.shutdown()
time.sleep(0.2)
WORKER_RUNTIME_SECONDS = prev_worker_runtime
def test_rust_frontend_launch_log_redacts_credentials(monkeypatch):
"""The Rust frontend command carries every non-default arg as JSON.
Credentials must not reach the log line."""
import subprocess as subprocess_mod
from vllm.entrypoints.launchers.cli_args import make_arg_parser
from vllm.utils.argparse_utils import FlexibleArgumentParser
from vllm.v1.utils import RustFrontendProcessManager
hf_token = "hf_TESTTOKEN123"
api_key = "sk-TESTKEY456"
args = make_arg_parser(FlexibleArgumentParser()).parse_args(
["--model", "org/model", "--hf-token", hf_token, "--api-key", api_key]
)
class _FakeProc:
pid = 4321
returncode = 0
def poll(self):
return 0
def wait(self, timeout=None):
return 0
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
input_listener = make_zmq_listener("tcp://127.0.0.1:0", zmq.ROUTER)
output_listener = make_zmq_listener("tcp://127.0.0.1:0", zmq.PULL)
try:
monkeypatch.setattr(subprocess_mod, "Popen", lambda *a, **kw: _FakeProc())
with patch("vllm.v1.utils.logger.info") as log_info:
RustFrontendProcessManager(
binary_path="/nonexistent/vllm-rs",
sock=sock,
args=args,
input_listener=input_listener,
output_listener=output_listener,
engine_start_index=0,
engine_count=1,
data_parallel_size=1,
)
finally:
sock.close()
log_format, *log_args = log_info.call_args.args
message = log_format % tuple(log_args)
assert "Launching Rust frontend:" in message
assert hf_token not in message
assert api_key not in message
assert '"hf_token": "***"' in message
assert '"api_key": "***"' in message
def test_rust_frontend_uses_config_model_as_model_tag(monkeypatch, caplog, tmp_path):
"""Config-only model selection must be forwarded to the Rust frontend."""
import subprocess as subprocess_mod
from vllm.entrypoints.launchers.cli_args import make_arg_parser
from vllm.utils.argparse_utils import FlexibleArgumentParser
from vllm.v1.utils import RustFrontendProcessManager
config_path = tmp_path / "config.yml"
config_path.write_text("model: org/model\n")
args = make_arg_parser(FlexibleArgumentParser()).parse_args(
["--config", str(config_path)]
)
assert args.model == "org/model"
assert args.model_tag is None
class _FakeProc:
pid = 4321
returncode = 0
def poll(self):
return 0
def wait(self, timeout=None):
return 0
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
input_listener = make_zmq_listener("tcp://127.0.0.1:0", zmq.ROUTER)
output_listener = make_zmq_listener("tcp://127.0.0.1:0", zmq.PULL)
try:
monkeypatch.setattr(subprocess_mod, "Popen", lambda *a, **kw: _FakeProc())
with caplog.at_level("INFO", logger="vllm.v1.utils"):
RustFrontendProcessManager(
binary_path="/nonexistent/vllm-rs",
sock=sock,
args=args,
input_listener=input_listener,
output_listener=output_listener,
engine_start_index=0,
engine_count=1,
data_parallel_size=1,
)
finally:
sock.close()
assert '"model_tag": "org/model"' in caplog.text
def test_rust_frontend_inherits_grpc_listener(monkeypatch):
"""The Python-bound gRPC socket is passed to Rust like the HTTP one."""
import subprocess as subprocess_mod
from vllm.entrypoints.launchers.cli_args import make_arg_parser
from vllm.utils.argparse_utils import FlexibleArgumentParser
from vllm.v1.utils import RustFrontendProcessManager
args = make_arg_parser(FlexibleArgumentParser()).parse_args(
["--model", "org/model", "--grpc-port", "50051"]
)
class _FakeProc:
pid = 4321
returncode = 0
def poll(self):
return 0
def wait(self, timeout=None):
return 0
popen_calls = []
def fake_popen(cmd, **kwargs):
popen_calls.append((cmd, kwargs))
return _FakeProc()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
grpc_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
input_listener = make_zmq_listener("tcp://127.0.0.1:0", zmq.ROUTER)
output_listener = make_zmq_listener("tcp://127.0.0.1:0", zmq.PULL)
input_fd = input_listener.socket.fileno()
output_fd = output_listener.socket.fileno()
try:
monkeypatch.setattr(subprocess_mod, "Popen", fake_popen)
RustFrontendProcessManager(
binary_path="/nonexistent/vllm-rs",
sock=sock,
args=args,
input_listener=input_listener,
output_listener=output_listener,
engine_start_index=0,
engine_count=1,
data_parallel_size=1,
grpc_sock=grpc_sock,
)
[(cmd, kwargs)] = popen_calls
grpc_fd = grpc_sock.fileno()
flag_index = cmd.index("--grpc-listen-fd")
assert cmd[flag_index + 1] == str(grpc_fd)
assert list(kwargs["pass_fds"]) == [
sock.fileno(),
input_fd,
output_fd,
grpc_fd,
]
finally:
sock.close()
grpc_sock.close()
def test_rust_frontend_spawn_failure_cleans_up_listeners(tmp_path):
"""No child owns the listeners when Popen fails, so the parent removes them."""
from vllm.entrypoints.launchers.cli_args import make_arg_parser
from vllm.utils.argparse_utils import FlexibleArgumentParser
from vllm.v1.utils import RustFrontendProcessManager
args = make_arg_parser(FlexibleArgumentParser()).parse_args(
["--model", "org/model"]
)
input_listener = make_zmq_listener(f"ipc://{tmp_path}/input.sock", zmq.ROUTER)
output_listener = make_zmq_listener(f"ipc://{tmp_path}/output.sock", zmq.PULL)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
with pytest.raises(FileNotFoundError):
RustFrontendProcessManager(
binary_path=str(tmp_path / "missing-vllm-rs"),
sock=sock,
args=args,
input_listener=input_listener,
output_listener=output_listener,
engine_start_index=0,
engine_count=1,
data_parallel_size=1,
)
finally:
sock.close()
for listener in (input_listener, output_listener):
assert listener.socket.fileno() == -1
assert not os.path.exists(listener.address.removeprefix("ipc://"))
@@ -1,2 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
@@ -1,84 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from argparse import Namespace
import pytest
from starlette.datastructures import State
import vllm.entrypoints.launchers.render.app_state as app_state_mod
from vllm.config import ModelConfig, VllmConfig
from vllm.entrypoints.launchers.cli_args import make_arg_parser
from vllm.utils.argparse_utils import FlexibleArgumentParser
class _CaptureKwargs:
"""Stands in for OnlineRenderer/OnlineDerenderer; records init kwargs."""
captured: list[dict]
def __init__(self, **kwargs):
type(self).captured.append(kwargs)
def warmup(self):
pass
def _render_cli_args(*argv: str) -> Namespace:
"""Parse ``argv`` the way ``vllm launch render`` does, so new serve flags
carry their defaults instead of needing a hand-maintained ``Namespace``."""
args = make_arg_parser(FlexibleArgumentParser()).parse_args(list(argv))
if args.model_tag is not None:
args.model = args.model_tag
return args
@pytest.mark.asyncio
async def test_render_app_state_uses_config_resolved_reasoning_parser(monkeypatch):
"""gpt_oss defaults its reasoning parser through verify_and_update_config;
the render server must pick up that resolved value like the main API
server does, otherwise harmony markup leaks unparsed into derender output.
"""
model_config = ModelConfig("openai/gpt-oss-20b")
vllm_config = VllmConfig(model_config=model_config)
assert vllm_config.structured_outputs_config.reasoning_parser == "openai_gptoss"
class _Renderer(_CaptureKwargs):
captured = []
class _Derenderer(_CaptureKwargs):
captured = []
async def _noop_async(*args, **kwargs):
return None
monkeypatch.setattr(app_state_mod, "renderer_from_config", lambda cfg: object())
monkeypatch.setattr(app_state_mod, "OnlineRenderer", _Renderer)
monkeypatch.setattr(app_state_mod, "OnlineDerenderer", _Derenderer)
monkeypatch.setattr(app_state_mod, "ServingTokenization", lambda *a, **kw: object())
monkeypatch.setattr(app_state_mod, "init_render_state", lambda *a, **kw: None)
monkeypatch.setattr(app_state_mod, "init_endpoint_plugins_state", _noop_async)
args = _render_cli_args("openai/gpt-oss-20b")
await app_state_mod.init_render_app_state(vllm_config, State(), args)
assert _Renderer.captured[0]["reasoning_parser"] == "openai_gptoss"
assert _Derenderer.captured[0]["reasoning_parser"] == "openai_gptoss"
def test_explicit_reasoning_parser_flag_wins_over_model_default():
"""An explicit --reasoning-parser must survive VllmConfig construction
for models that define their own default (gpt_oss); the default only
applies when the resolved value is empty."""
from vllm.engine.arg_utils import AsyncEngineArgs
engine_args = AsyncEngineArgs(
model="openai/gpt-oss-20b", reasoning_parser="deepseek_r1"
)
model_config = engine_args.create_model_config()
vllm_config = VllmConfig(
model_config=model_config,
structured_outputs_config=engine_args.create_structured_outputs_config(),
)
assert vllm_config.structured_outputs_config.reasoning_parser == "deepseek_r1"
+2 -133
View File
@@ -2,11 +2,9 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
from types import SimpleNamespace
import pytest
import vllm.entrypoints.launchers.cli_args as cli_args_module
from tests.utils import VLLM_PATH
from vllm.engine.arg_utils import AsyncEngineArgs
from vllm.entrypoints.launchers.cli_args import (
@@ -180,73 +178,6 @@ def test_multiple_valid_inputs(serve_parser):
### Tests for serve argument validation that run prior to loading
@pytest.mark.parametrize(
"port, extra_args",
[
(50051, []),
(0, ["--port", "0"]),
(50051, ["--port", "50051", "--uds", "/tmp/vllm.sock"]),
],
)
def test_rust_grpc_port_accepts_frontend_launch(
vllm_parser, monkeypatch, port, extra_args
):
monkeypatch.setenv("VLLM_USE_RUST_FRONTEND", "1")
args = vllm_parser.parse_args(
[
"serve",
"--grpc-port",
str(port),
"--data-parallel-size",
"8",
"--data-parallel-size-local",
"4",
"--data-parallel-start-rank",
"4",
"--data-parallel-hybrid-lb",
*extra_args,
]
)
validate_parsed_serve_args(args)
assert args.grpc_port == port
@pytest.mark.parametrize(
"rust_enabled, extra_args, port",
[
(False, [], 50051),
(False, ["--grpc"], 50051),
(True, ["--grpc"], 50051),
(True, ["--headless"], 50051),
(True, ["--api-server-count", "0"], 50051),
(True, ["--api-server-count", "-1"], 50051),
(True, ["--data-parallel-multi-port-external-lb"], 50051),
(True, ["--port", "50051"], 50051),
(True, [], -1),
(True, [], 65536),
],
)
def test_rust_grpc_port_rejects_incompatible_launch(
vllm_parser, monkeypatch, rust_enabled, extra_args, port
):
monkeypatch.setenv("VLLM_USE_RUST_FRONTEND", "1" if rust_enabled else "0")
args = vllm_parser.parse_args(["serve", "--grpc-port", str(port), *extra_args])
error = (
"--grpc and --grpc-port are mutually exclusive"
if "--grpc" in extra_args
else "--grpc-port"
)
with pytest.raises(ValueError, match=error):
validate_parsed_serve_args(args)
def test_rust_grpc_port_requires_serve_subcommand(monkeypatch):
"""Direct Python render/API entrypoints must reject a Rust-only listener."""
monkeypatch.setenv("VLLM_USE_RUST_FRONTEND", "1")
parser = make_arg_parser(FlexibleArgumentParser())
args = parser.parse_args(["--grpc-port", "50051"])
with pytest.raises(ValueError, match="--grpc-port requires"):
validate_parsed_serve_args(args)
def test_enable_auto_choice_fails_without_tool_call_parser(serve_parser):
@@ -263,7 +194,7 @@ def test_enable_auto_choice_passes_with_tool_call_parser(serve_parser):
args=[
"--enable-auto-tool-choice",
"--tool-call-parser",
"mistral",
"qwen3_coder",
]
)
validate_parsed_serve_args(args)
@@ -280,7 +211,7 @@ def test_auto_tool_choice_with_reasoning_parser_passes(serve_parser):
args=[
"--enable-auto-tool-choice",
"--tool-call-parser",
"mistral",
"qwen3_coder",
"--reasoning-parser",
"deepseek_r1",
]
@@ -333,48 +264,6 @@ def test_per_request_metrics_requires_log_stats(serve_parser):
validate_parsed_serve_args(args)
def _build_launch_render_parser():
"""Mirror `vllm launch render`.
`vllm/entrypoints/cli/main.py` parses subcommands with ``dest="subparser"``,
and `LaunchSubcommandBase.add_cli_args` builds the component parser with
`make_arg_parser`, so a launch component carries serve args under
``args.subparser == "launch"``.
"""
vllm_parser = FlexibleArgumentParser()
subparsers = vllm_parser.add_subparsers(required=False, dest="subparser")
launch_parser = subparsers.add_parser("launch")
launch_subparsers = launch_parser.add_subparsers(
required=True, dest="launch_component"
)
render_parser = launch_subparsers.add_parser("render")
make_arg_parser(render_parser)
return vllm_parser
@pytest.fixture
def launch_render_parser():
return _build_launch_render_parser()
@pytest.mark.parametrize(
"cli_args, error",
[
(["--enable-auto-tool-choice"], TypeError),
(["--grpc-port", "50051"], ValueError),
],
)
def test_launch_render_validates_serve_args(
launch_render_parser, monkeypatch, cli_args, error
):
"""`vllm launch render` reuses the serve parser, so it gets the serve checks"""
monkeypatch.setenv("VLLM_USE_RUST_FRONTEND", "1")
args = launch_render_parser.parse_args(args=["launch", "render", *cli_args])
assert args.subparser == "launch"
with pytest.raises(error):
validate_parsed_serve_args(args)
def test_subcommand_without_serve_args_skips_validation():
"""A subcommand that does not use the serve parser is still skipped"""
vllm_parser = FlexibleArgumentParser()
@@ -456,26 +345,6 @@ def test_default_chat_template_kwargs_default_none(serve_parser):
assert args.default_chat_template_kwargs is None
@pytest.mark.parametrize(
"default_kwargs,cohere_format,expected",
[
(None, "cmd3", {"cohere_format": "cmd3"}),
(
{"cohere_format": "cmd4", "custom": True},
"cmd3",
{"cohere_format": "cmd4", "custom": True},
),
],
)
def test_resolve_default_chat_template_kwargs(default_kwargs, cohere_format, expected):
args = SimpleNamespace(
default_chat_template_kwargs=default_kwargs,
cohere_format=cohere_format,
)
assert cli_args_module.resolve_default_chat_template_kwargs(args) == expected
def test_default_chat_template_kwargs_invalid_json(serve_parser):
"""Ensure invalid JSON raises an error."""
with pytest.raises(SystemExit):
@@ -1,956 +0,0 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
import subprocess
import tempfile
import threading
from collections.abc import Generator
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
import vllm.envs as envs
from vllm.assets.audio import AudioAsset
from vllm.connections import HTTPConnection
from vllm.entrypoints.launchers.run_batch import (
BatchRequestOutput,
download_bytes_from_url,
upload_data,
)
from vllm.exceptions import VLLMValidationError
from vllm.utils.mem_constants import MiB_bytes
CHAT_MODEL_NAME = "hmellor/tiny-random-LlamaForCausalLM"
EMBEDDING_MODEL_NAME = "intfloat/multilingual-e5-small"
RERANKER_MODEL_NAME = "BAAI/bge-reranker-v2-m3"
REASONING_MODEL_NAME = "Qwen/Qwen3-0.6B"
SPEECH_LARGE_MODEL_NAME = "openai/whisper-large-v3"
SPEECH_SMALL_MODEL_NAME = "openai/whisper-small"
INPUT_BATCH = "\n".join(
json.dumps(req)
for req in [
{
"custom_id": "request-1",
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": CHAT_MODEL_NAME,
"messages": [
{
"role": "system",
"content": "You are a helpful assistant.",
},
{"role": "user", "content": "Hello world!"},
],
"max_tokens": 1000,
},
},
{
"custom_id": "request-2",
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": CHAT_MODEL_NAME,
"messages": [
{
"role": "system",
"content": "You are an unhelpful assistant.",
},
{"role": "user", "content": "Hello world!"},
],
"max_tokens": 1000,
},
},
{
"custom_id": "request-3",
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": "NonExistModel",
"messages": [
{
"role": "system",
"content": "You are an unhelpful assistant.",
},
{"role": "user", "content": "Hello world!"},
],
"max_tokens": 1000,
},
},
{
"custom_id": "request-4",
"method": "POST",
"url": "/bad_url",
"body": {
"model": CHAT_MODEL_NAME,
"messages": [
{
"role": "system",
"content": "You are an unhelpful assistant.",
},
{"role": "user", "content": "Hello world!"},
],
"max_tokens": 1000,
},
},
{
"custom_id": "request-5",
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"stream": "True",
"model": CHAT_MODEL_NAME,
"messages": [
{
"role": "system",
"content": "You are an unhelpful assistant.",
},
{"role": "user", "content": "Hello world!"},
],
"max_tokens": 1000,
},
},
]
)
INVALID_INPUT_BATCH = "\n".join(
json.dumps(req)
for req in [
{
"invalid_field": "request-1",
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": CHAT_MODEL_NAME,
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello world!"},
],
"max_tokens": 1000,
},
},
{
"custom_id": "request-2",
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": CHAT_MODEL_NAME,
"messages": [
{"role": "system", "content": "You are an unhelpful assistant."},
{"role": "user", "content": "Hello world!"},
],
"max_tokens": 1000,
},
},
]
)
INPUT_EMBEDDING_BATCH = "\n".join(
json.dumps(req)
for req in [
{
"custom_id": "request-1",
"method": "POST",
"url": "/v1/embeddings",
"body": {
"model": EMBEDDING_MODEL_NAME,
"input": "You are a helpful assistant.",
},
},
{
"custom_id": "request-2",
"method": "POST",
"url": "/v1/embeddings",
"body": {
"model": EMBEDDING_MODEL_NAME,
"input": "You are an unhelpful assistant.",
},
},
{
"custom_id": "request-3",
"method": "POST",
"url": "/v1/embeddings",
"body": {
"model": EMBEDDING_MODEL_NAME,
"input": "Hello world!",
},
},
{
"custom_id": "request-4",
"method": "POST",
"url": "/v1/embeddings",
"body": {
"model": "NonExistModel",
"input": "Hello world!",
},
},
]
)
_SCORE_RERANK_DOCUMENTS = [
"The capital of Brazil is Brasilia.",
"The capital of France is Paris.",
]
INPUT_SCORE_BATCH = "\n".join(
json.dumps(req)
for req in [
{
"custom_id": "request-1",
"method": "POST",
"url": "/score",
"body": {
"model": RERANKER_MODEL_NAME,
"queries": "What is the capital of France?",
"documents": _SCORE_RERANK_DOCUMENTS,
},
},
{
"custom_id": "request-2",
"method": "POST",
"url": "/v1/score",
"body": {
"model": RERANKER_MODEL_NAME,
"queries": "What is the capital of France?",
"documents": _SCORE_RERANK_DOCUMENTS,
},
},
]
)
INPUT_RERANK_BATCH = "\n".join(
json.dumps(req)
for req in [
{
"custom_id": "request-1",
"method": "POST",
"url": "/rerank",
"body": {
"model": RERANKER_MODEL_NAME,
"query": "What is the capital of France?",
"documents": _SCORE_RERANK_DOCUMENTS,
},
},
{
"custom_id": "request-2",
"method": "POST",
"url": "/v1/rerank",
"body": {
"model": RERANKER_MODEL_NAME,
"query": "What is the capital of France?",
"documents": _SCORE_RERANK_DOCUMENTS,
},
},
{
"custom_id": "request-2",
"method": "POST",
"url": "/v2/rerank",
"body": {
"model": RERANKER_MODEL_NAME,
"query": "What is the capital of France?",
"documents": _SCORE_RERANK_DOCUMENTS,
},
},
]
)
INPUT_REASONING_BATCH = "\n".join(
json.dumps(req)
for req in [
{
"custom_id": "request-1",
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": REASONING_MODEL_NAME,
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Solve this math problem: 2+2=?"},
],
},
},
{
"custom_id": "request-2",
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": REASONING_MODEL_NAME,
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is the capital of France?"},
],
},
},
]
)
MINIMAL_WAV_BASE64 = "UklGRigAAABXQVZFZm10IBAAAAABAAEAgD4AAAB9AAACABAAZGF0YQQAAAAAAP9/"
_EXACT_LIMIT_AUDIO = b"a" * MiB_bytes
_OVERSIZED_BASE64_AUDIO = "A" * (4 * ((MiB_bytes + 2) // 3))
_OVERSIZED_HTTP_AUDIO = b"b" * (MiB_bytes + 1)
class _BatchHTTPServer(ThreadingHTTPServer):
request_paths: list[str]
class _BatchHTTPHandler(BaseHTTPRequestHandler):
def do_GET(self) -> None:
server = self.server
assert isinstance(server, _BatchHTTPServer)
server.request_paths.append(self.path)
if self.path == "/exact-limit":
self._send_body(_EXACT_LIMIT_AUDIO)
return
if self.path == "/oversized-chunked":
self.send_response(200)
self.end_headers()
self._write_body(_OVERSIZED_HTTP_AUDIO)
return
self.send_error(404, "Unknown batch HTTP test path")
def _send_body(self, body: bytes) -> None:
self.send_response(200)
self.send_header("Content-Type", "application/octet-stream")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self._write_body(body)
def _write_body(self, body: bytes) -> None:
try:
for offset in range(0, len(body), 64 * 1024):
self.wfile.write(body[offset : offset + 64 * 1024])
except (BrokenPipeError, ConnectionResetError):
self.close_connection = True
def log_message(self, fmt: str, *args: object) -> None:
return
@pytest.fixture
def batch_http_server() -> Generator[_BatchHTTPServer, None, None]:
server = _BatchHTTPServer(("127.0.0.1", 0), _BatchHTTPHandler)
server.request_paths = []
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
yield server
finally:
server.shutdown()
thread.join()
server.server_close()
def _batch_http_url(server: _BatchHTTPServer, path: str) -> str:
return f"http://localhost:{server.server_port}{path}"
async def _close_async_connection(connection: HTTPConnection) -> None:
if connection._async_client is not None:
await connection._async_client.close()
INPUT_TRANSCRIPTION_BATCH = (
json.dumps(
{
"custom_id": "request-1",
"method": "POST",
"url": "/v1/audio/transcriptions",
"body": {
"model": SPEECH_LARGE_MODEL_NAME,
"file_url": f"data:audio/wav;base64,{MINIMAL_WAV_BASE64}",
"response_format": "json",
},
}
)
+ "\n"
)
INPUT_TRANSCRIPTION_HTTP_BATCH = (
json.dumps(
{
"custom_id": "request-1",
"method": "POST",
"url": "/v1/audio/transcriptions",
"body": {
"model": SPEECH_LARGE_MODEL_NAME,
"file_url": AudioAsset("mary_had_lamb").url,
"language": "en",
"response_format": "json",
},
}
)
+ "\n"
)
INPUT_TRANSLATION_BATCH = (
json.dumps(
{
"custom_id": "request-1",
"method": "POST",
"url": "/v1/audio/translations",
"body": {
"model": SPEECH_SMALL_MODEL_NAME,
"file_url": AudioAsset("mary_had_lamb").url,
"response_format": "text",
"language": "it",
"to_language": "en",
"temperature": 0.0,
},
}
)
+ "\n"
)
WEATHER_TOOL = {
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
},
},
"required": ["location"],
},
},
}
INPUT_TOOL_CALLING_BATCH = json.dumps(
{
"custom_id": "request-1",
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": REASONING_MODEL_NAME,
"messages": [
{"role": "user", "content": "What is the weather in San Francisco?"},
],
"tools": [WEATHER_TOOL],
"tool_choice": "required",
"max_tokens": 1000,
},
}
)
def test_empty_file():
with (
tempfile.NamedTemporaryFile("w") as input_file,
tempfile.NamedTemporaryFile("r") as output_file,
):
input_file.write("")
input_file.flush()
proc = subprocess.Popen(
[
"vllm",
"run-batch",
"-i",
input_file.name,
"-o",
output_file.name,
"--model",
EMBEDDING_MODEL_NAME,
],
)
proc.communicate()
proc.wait()
assert proc.returncode == 0, f"{proc=}"
contents = output_file.read()
assert contents.strip() == ""
def test_completions():
with (
tempfile.NamedTemporaryFile("w") as input_file,
tempfile.NamedTemporaryFile("r") as output_file,
):
input_file.write(INPUT_BATCH)
input_file.flush()
proc = subprocess.Popen(
[
"vllm",
"run-batch",
"-i",
input_file.name,
"-o",
output_file.name,
"--model",
CHAT_MODEL_NAME,
],
)
proc.communicate()
proc.wait()
assert proc.returncode == 0, f"{proc=}"
contents = output_file.read()
for line in contents.strip().split("\n"):
# Ensure that the output format conforms to the openai api.
# Validation should throw if the schema is wrong.
BatchRequestOutput.model_validate_json(line)
def test_completions_invalid_input():
"""Ensure that we fail when the input doesn't conform to the openai api."""
with (
tempfile.NamedTemporaryFile("w") as input_file,
tempfile.NamedTemporaryFile("r") as output_file,
):
input_file.write(INVALID_INPUT_BATCH)
input_file.flush()
proc = subprocess.Popen(
[
"vllm",
"run-batch",
"-i",
input_file.name,
"-o",
output_file.name,
"--model",
CHAT_MODEL_NAME,
],
)
proc.communicate()
proc.wait()
assert proc.returncode != 0, f"{proc=}"
def test_embeddings():
with (
tempfile.NamedTemporaryFile("w") as input_file,
tempfile.NamedTemporaryFile("r") as output_file,
):
input_file.write(INPUT_EMBEDDING_BATCH)
input_file.flush()
proc = subprocess.Popen(
[
"vllm",
"run-batch",
"-i",
input_file.name,
"-o",
output_file.name,
"--model",
EMBEDDING_MODEL_NAME,
],
)
proc.communicate()
proc.wait()
assert proc.returncode == 0, f"{proc=}"
contents = output_file.read()
for line in contents.strip().split("\n"):
# Ensure that the output format conforms to the openai api.
# Validation should throw if the schema is wrong.
BatchRequestOutput.model_validate_json(line)
@pytest.mark.parametrize("input_batch", [INPUT_SCORE_BATCH, INPUT_RERANK_BATCH])
def test_score(input_batch):
with (
tempfile.NamedTemporaryFile("w") as input_file,
tempfile.NamedTemporaryFile("r") as output_file,
):
input_file.write(input_batch)
input_file.flush()
proc = subprocess.Popen(
[
"vllm",
"run-batch",
"-i",
input_file.name,
"-o",
output_file.name,
"--model",
RERANKER_MODEL_NAME,
],
)
proc.communicate()
proc.wait()
assert proc.returncode == 0, f"{proc=}"
contents = output_file.read()
for line in contents.strip().split("\n"):
# Ensure that the output format conforms to the openai api.
# Validation should throw if the schema is wrong.
BatchRequestOutput.model_validate_json(line)
# Ensure that there is no error in the response.
line_dict = json.loads(line)
assert isinstance(line_dict, dict)
assert line_dict["error"] is None
def test_reasoning_parser():
"""Test that reasoning_parser parameter works correctly in run_batch."""
with (
tempfile.NamedTemporaryFile("w") as input_file,
tempfile.NamedTemporaryFile("r") as output_file,
):
input_file.write(INPUT_REASONING_BATCH)
input_file.flush()
proc = subprocess.Popen(
[
"vllm",
"run-batch",
"-i",
input_file.name,
"-o",
output_file.name,
"--model",
REASONING_MODEL_NAME,
"--reasoning-parser",
"qwen3",
],
)
proc.communicate()
proc.wait()
assert proc.returncode == 0, f"{proc=}"
contents = output_file.read()
for line in contents.strip().split("\n"):
# Ensure that the output format conforms to the openai api.
# Validation should throw if the schema is wrong.
BatchRequestOutput.model_validate_json(line)
# Ensure that there is no error in the response.
line_dict = json.loads(line)
assert isinstance(line_dict, dict)
assert line_dict["error"] is None
# Check that reasoning is present and not empty
reasoning = line_dict["response"]["body"]["choices"][0]["message"][
"reasoning"
]
assert reasoning is not None
assert len(reasoning) > 0
def test_tool_calling():
"""Test that tool calling works correctly in run_batch.
Verifies that requests with tools return tool_calls in the response.
"""
with (
tempfile.NamedTemporaryFile("w") as input_file,
tempfile.NamedTemporaryFile("r") as output_file,
):
input_file.write(INPUT_TOOL_CALLING_BATCH)
input_file.flush()
proc = subprocess.Popen(
[
"vllm",
"run-batch",
"-i",
input_file.name,
"-o",
output_file.name,
"--model",
REASONING_MODEL_NAME,
"--enable-auto-tool-choice",
"--tool-call-parser",
"hermes",
],
)
proc.communicate()
proc.wait()
assert proc.returncode == 0, f"{proc=}"
contents = output_file.read()
for line in contents.strip().split("\n"):
if not line.strip(): # Skip empty lines
continue
# Ensure that the output format conforms to the openai api.
# Validation should throw if the schema is wrong.
BatchRequestOutput.model_validate_json(line)
# Ensure that there is no error in the response.
line_dict = json.loads(line)
assert isinstance(line_dict, dict)
assert line_dict["error"] is None
# Check that tool_calls are present in the response
# With tool_choice="required", the model must call a tool
response_body = line_dict["response"]["body"]
assert response_body is not None
message = response_body["choices"][0]["message"]
assert "tool_calls" in message
tool_calls = message.get("tool_calls")
# With tool_choice="required", tool_calls must be present and non-empty
assert tool_calls is not None
assert isinstance(tool_calls, list)
assert len(tool_calls) > 0
# Verify tool_calls have the expected structure
for tool_call in tool_calls:
assert "id" in tool_call
assert "type" in tool_call
assert tool_call["type"] == "function"
assert "function" in tool_call
assert "name" in tool_call["function"]
assert "arguments" in tool_call["function"]
# Verify the tool name matches our tool definition
assert tool_call["function"]["name"] == "get_current_weather"
# ---------------------------------------------------------------------------
# Unit tests for download_bytes_from_url SSRF protection
# ---------------------------------------------------------------------------
def _make_aiohttp_mocks(response_data: bytes = b"fake-data", status: int = 200):
"""Create mock objects that simulate aiohttp.ClientSession context managers."""
async def iter_chunked(chunk_size: int):
del chunk_size
yield response_data
mock_resp = MagicMock()
mock_resp.status = status
mock_resp.content_length = len(response_data)
mock_resp.content.iter_chunked = iter_chunked
mock_resp.read = AsyncMock(return_value=response_data)
mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)
mock_resp.__aexit__ = AsyncMock(return_value=False)
mock_session = MagicMock()
mock_session.get = MagicMock(return_value=mock_resp)
mock_session.__aenter__ = AsyncMock(return_value=mock_session)
mock_session.__aexit__ = AsyncMock(return_value=False)
return mock_session
@pytest.mark.asyncio
async def test_download_bytes_data_url_bypasses_domain_check():
"""data: URLs must work regardless of the domain allowlist."""
data_url = f"data:audio/wav;base64,{MINIMAL_WAV_BASE64}"
result = await download_bytes_from_url(
data_url, allowed_media_domains=["example.com"]
)
assert isinstance(result, bytes)
assert len(result) > 0
@pytest.mark.asyncio
async def test_download_bytes_rejects_disallowed_domain():
"""HTTP URLs whose hostname is not in the allowlist must be rejected."""
url = "https://evil.internal/secret"
with pytest.raises(VLLMValidationError, match="allowed domains") as exc_info:
await download_bytes_from_url(url, allowed_media_domains=["example.com"])
# URL validation failures carry structured metadata for the frontend.
assert exc_info.value.parameter == "url"
assert exc_info.value.value == "evil.internal"
@pytest.mark.asyncio
async def test_download_bytes_rejects_unsupported_scheme():
"""Unsupported URL schemes are rejected with structured metadata."""
with pytest.raises(VLLMValidationError, match="Unsupported URL scheme") as exc_info:
await download_bytes_from_url("ftp://example.com/file")
assert exc_info.value.parameter == "url"
assert exc_info.value.value == "ftp"
@pytest.mark.asyncio
async def test_download_bytes_rejects_cloud_metadata_ip():
"""Cloud metadata endpoints must be blocked when an allowlist is set."""
url = "http://169.254.169.254/latest/meta-data/"
with pytest.raises(VLLMValidationError, match="allowed domains"):
await download_bytes_from_url(url, allowed_media_domains=["example.com"])
@pytest.mark.asyncio
async def test_download_bytes_rejects_internal_ip():
"""Private-range IPs must be blocked when an allowlist is set."""
for internal_url in [
"http://10.0.0.1/secret",
"http://192.168.1.1/admin",
"http://127.0.0.1:8080/internal",
]:
with pytest.raises(VLLMValidationError, match="allowed domains"):
await download_bytes_from_url(
internal_url, allowed_media_domains=["example.com"]
)
@pytest.mark.asyncio
async def test_download_bytes_allows_permitted_domain():
"""HTTP URLs whose hostname IS in the allowlist must be fetched."""
url = "https://example.com/audio.wav"
expected = b"audio-bytes"
mock_session = _make_aiohttp_mocks(expected)
with patch(
"vllm.entrypoints.launchers.run_batch.aiohttp.ClientSession",
return_value=mock_session,
):
result = await download_bytes_from_url(
url, allowed_media_domains=["example.com"]
)
assert result == expected
@pytest.mark.asyncio
async def test_download_bytes_no_allowlist_permits_any_domain():
"""Without an allowlist all HTTP URLs must be attempted (backward compat)."""
url = "https://any-domain.example.org/file.wav"
expected = b"some-data"
mock_session = _make_aiohttp_mocks(expected)
with patch(
"vllm.entrypoints.launchers.run_batch.aiohttp.ClientSession",
return_value=mock_session,
):
result = await download_bytes_from_url(url, allowed_media_domains=None)
assert result == expected
@pytest.mark.asyncio
async def test_download_bytes_empty_allowlist_denies_all():
"""An empty allowlist must deny all HTTP URLs (least privilege)."""
url = "https://any-domain.example.org/file.wav"
with pytest.raises(VLLMValidationError, match="allowed domains"):
await download_bytes_from_url(url, allowed_media_domains=[])
@pytest.mark.asyncio
async def test_download_bytes_unsupported_scheme():
"""Unsupported URL schemes must be rejected regardless of allowlist."""
with pytest.raises(VLLMValidationError, match="Unsupported URL scheme"):
await download_bytes_from_url("ftp://example.com/file.wav")
with pytest.raises(VLLMValidationError, match="Unsupported URL scheme"):
await download_bytes_from_url(
"ftp://example.com/file.wav",
allowed_media_domains=["example.com"],
)
@pytest.mark.asyncio
async def test_download_bytes_backslash_bypass():
"""Backslash-@ URL confusion must not bypass the allowlist.
urllib3.parse_url() and aiohttp/yarl disagree on backslash-before-@.
The fix normalizes through urllib3 before handing to aiohttp.
"""
bypass_url = "http://allowed.example.com\\@evil.internal/secret"
with pytest.raises(VLLMValidationError, match="allowed domains"):
await download_bytes_from_url(
bypass_url, allowed_media_domains=["evil.internal"]
)
@pytest.mark.asyncio
async def test_download_bytes_allows_http_body_at_audio_limit(
monkeypatch: pytest.MonkeyPatch,
batch_http_server: _BatchHTTPServer,
):
monkeypatch.setattr(envs, "VLLM_MAX_AUDIO_CLIP_FILESIZE_MB", 1)
connection = HTTPConnection()
monkeypatch.setattr(
"vllm.entrypoints.launchers.run_batch.global_http_connection",
connection,
)
try:
result = await download_bytes_from_url(
_batch_http_url(batch_http_server, "/exact-limit")
)
assert result == _EXACT_LIMIT_AUDIO
finally:
await _close_async_connection(connection)
# ---------------------------------------------------------------------------
# Unit tests for upload_data retry behavior
# ---------------------------------------------------------------------------
def _make_aiohttp_put_session(status: int = 200, body_text: str = ""):
"""Mock an aiohttp.ClientSession whose PUT returns the given status."""
mock_resp = MagicMock()
mock_resp.status = status
mock_resp.text = AsyncMock(return_value=body_text)
mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)
mock_resp.__aexit__ = AsyncMock(return_value=False)
mock_session = MagicMock()
mock_session.put = MagicMock(return_value=mock_resp)
mock_session.__aenter__ = AsyncMock(return_value=mock_session)
mock_session.__aexit__ = AsyncMock(return_value=False)
return mock_session
@pytest.mark.asyncio
@pytest.mark.parametrize("status", [200, 201, 204])
@pytest.mark.parametrize("from_file", [False, True])
async def test_upload_data_uploads_once_on_success(status, from_file, tmp_path):
"""Successful PUT responses must not retry either upload path."""
session = _make_aiohttp_put_session(status=status)
data_or_file = "payload"
if from_file:
path = tmp_path / "output.jsonl"
path.write_text(data_or_file, encoding="utf-8")
data_or_file = str(path)
with (
patch(
"vllm.entrypoints.launchers.run_batch.aiohttp.ClientSession",
return_value=session,
),
patch(
"vllm.entrypoints.launchers.run_batch.asyncio.sleep",
new_callable=AsyncMock,
) as sleep,
):
await upload_data(
"https://example.com/output.jsonl", data_or_file, from_file=from_file
)
assert session.put.call_count == 1
sleep.assert_not_awaited()
@pytest.mark.asyncio
async def test_upload_data_error_includes_awaited_response_body():
"""A failed upload must surface the awaited response body, not a coroutine."""
session = _make_aiohttp_put_session(status=500, body_text="server-error-detail")
with (
patch(
"vllm.entrypoints.launchers.run_batch.aiohttp.ClientSession",
return_value=session,
),
patch(
"vllm.entrypoints.launchers.run_batch.asyncio.sleep",
AsyncMock(),
),
pytest.raises(Exception) as exc_info,
):
await upload_data(
"https://example.com/output.jsonl", "payload", from_file=False
)
message = str(exc_info.value)
assert "server-error-detail" in message
assert "coroutine" not in message