[Bugfix][Structured Output] Cap JSON schema nesting to prevent 500s and API-server stalls (#60036)

Signed-off-by: Mazukiri <maihoangduc04@gmail.com>
Signed-off-by: sfeng33 <4florafeng@gmail.com>
Co-authored-by: Flora Feng <4florafeng@gmail.com>
This commit is contained in:
Mai Hoàng Đức
2026-10-06 00:06:59 +00:00
committed by GitHub
co-authored by Flora Feng
parent fa423b614c
commit 5cd8a2626b
11 changed files with 259 additions and 8 deletions
+8 -1
View File
@@ -230,7 +230,11 @@ def validate_structural_tag_response_format(
def validate_structural_tag_payload(payload: Any, *, parameter: str) -> None:
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
from vllm.sampling_params import (
SamplingParams,
StructuredOutputsParams,
check_json_nesting,
)
from vllm.v1.structured_output.backend_xgrammar import validate_xgrammar_grammar
if isinstance(payload, str) and not payload:
@@ -239,6 +243,9 @@ def validate_structural_tag_payload(payload: Any, *, parameter: str) -> None:
parameter=parameter,
)
if isinstance(payload, str):
# Raised here so the error is not reported as a malformed tag below
check_json_nesting(payload, structural_tag=True)
try:
validate_xgrammar_grammar(
SamplingParams(
+7 -1
View File
@@ -42,7 +42,11 @@ from vllm.parser.engine.adapters import ParserEngineToolAdapter
from vllm.parser.metrics import record_tool_parser_invocation
from vllm.parser.utils import count_history_tool_calls
from vllm.reasoning.abs_reasoning_parsers import ReasoningParser
from vllm.sampling_params import SamplingParams, StructuredOutputsParams
from vllm.sampling_params import (
SamplingParams,
StructuredOutputsParams,
check_json_nesting,
)
from vllm.tokenizers import TokenizerLike
from vllm.tool_parsers.abstract_tool_parser import Tool, ToolParser
from vllm.tool_parsers.streaming import (
@@ -274,6 +278,7 @@ def structured_outputs_to_format(params: StructuredOutputsParams) -> Format | No
if params.json is not None:
schema = params.json
if isinstance(schema, str):
check_json_nesting(schema)
schema = json.loads(schema)
return JSONSchemaFormat(json_schema=schema)
if params.regex is not None:
@@ -295,6 +300,7 @@ def structured_outputs_to_format(params: StructuredOutputsParams) -> Format | No
raise VLLMValidationError("Invalid grammar specification.") from e
return GrammarFormat(grammar=grammar)
if params.structural_tag is not None:
check_json_nesting(params.structural_tag, structural_tag=True)
s_tag = json.loads(params.structural_tag)
if "structures" in s_tag:
# LegacyStructuralTagResponseFormat
+3 -1
View File
@@ -45,7 +45,7 @@ from vllm.reasoning.cohere_command_reasoning_parser import (
BaseCohereCommandReasoningParser,
)
from vllm.renderers.cohere import POSITION_TO_SOURCE_KEY
from vllm.sampling_params import StructuredOutputsParams
from vllm.sampling_params import StructuredOutputsParams, check_json_nesting
from vllm.tool_parsers.cohere_command_tool_parser import BaseCohereCommandToolParser
if TYPE_CHECKING:
@@ -127,6 +127,7 @@ def collect_tool_schema(tool_schema: list[CohereNormalizedTool]) -> str:
tool_dictionary: dict[str, str] = {}
for tool in tool_schema:
tool_name = tool["name"]
check_json_nesting(tool["parameters"])
tool_parameters = dict(tool["parameters"])
json_schema: dict[str, Any] = {
"type": "object",
@@ -404,6 +405,7 @@ def _schema_dict_from_structured_outputs(
if isinstance(raw, str):
if not raw.strip():
raise ValueError("structured_outputs.json cannot be empty.")
check_json_nesting(raw)
try:
raw = json.loads(raw)
except json.JSONDecodeError as e:
+2 -1
View File
@@ -48,7 +48,7 @@ from vllm.parser.engine.parser_engine_config import (
ParserState,
Transition,
)
from vllm.sampling_params import StructuredOutputsParams
from vllm.sampling_params import StructuredOutputsParams, check_json_nesting
from vllm.utils.mistral import is_mistral_tokenizer
if TYPE_CHECKING:
@@ -381,6 +381,7 @@ class MistralParser(ParserEngine):
json_schema = _DEFAULT_JSON_SCHEMA
elif request.structured_outputs.json is not None:
if isinstance(request.structured_outputs.json, str):
check_json_nesting(request.structured_outputs.json)
json_schema = json.loads(request.structured_outputs.json)
else:
json_schema = request.structured_outputs.json
+58
View File
@@ -33,6 +33,15 @@ MAX_LOGPROB_TOKEN_IDS = 128
"""Upper bound on `SamplingParams.logprob_token_ids` list length. Must match
the per-request row width allocated by the sampler's `LogprobTokenIdsState`."""
MAX_STRUCTURED_OUTPUT_JSON_NESTING = 64
"""Upper bound on nested objects and arrays in a structured-output JSON schema
or structural tag. Grammar conversion runs on the API server and its cost grows
steeply with nesting. OpenAI allows 10 levels of schema nesting."""
STRUCTURAL_TAG_WRAPPER_NESTING = 16
"""Extra nesting allowed for a structural tag, which wraps its JSON schemas in
tag structure (up to 15 levels for tool-call tags generated by tool parsers)."""
def _verify_num_sequences(value: int, parameter_name: str) -> None:
if not isinstance(value, int):
@@ -202,6 +211,52 @@ class RequestOutputKind(Enum):
FINAL_ONLY = 2
def _exceeds_json_nesting(spec: str | dict[str, Any], limit: int) -> bool:
"""Whether a JSON document nests objects and arrays deeper than `limit`."""
if isinstance(spec, str):
try:
spec = json_mod.loads(spec)
except RecursionError:
return True
except ValueError:
# Malformed JSON is reported by the backend validation.
return False
level: list[Any] = [spec]
for _ in range(limit):
level = [
child
for node in level
if isinstance(node, (dict, list))
for child in (node.values() if isinstance(node, dict) else node)
if isinstance(child, (dict, list))
]
if not level:
return False
return True
def check_json_nesting(
spec: str | dict[str, Any] | None, *, structural_tag: bool = False
) -> None:
"""Reject a JSON schema nested more than `MAX_STRUCTURED_OUTPUT_JSON_NESTING`
levels deep, or a structural tag nested deeper than that plus
`STRUCTURAL_TAG_WRAPPER_NESTING`.
Raises:
VLLMValidationError: If `spec` is nested too deeply.
"""
limit = MAX_STRUCTURED_OUTPUT_JSON_NESTING
if structural_tag:
limit += STRUCTURAL_TAG_WRAPPER_NESTING
if spec and _exceeds_json_nesting(spec, limit):
raise VLLMValidationError(
"The JSON schema is nested too deeply: objects and arrays may nest at "
f"most {MAX_STRUCTURED_OUTPUT_JSON_NESTING} levels"
)
def _is_non_tekken_mistral(tokenizer: TokenizerLike) -> bool:
return is_mistral_tokenizer(tokenizer) and not tokenizer.is_tekken
@@ -1230,6 +1285,9 @@ class SamplingParams(
raise VLLMValidationError(
"structured_outputs.json cannot be an empty string"
)
# Reject deep nesting before any backend walks or converts the schema
check_json_nesting(self.structured_outputs.json)
check_json_nesting(self.structured_outputs.structural_tag, structural_tag=True)
# Reject json_object=False early to avoid engine-side crashes
if self.structured_outputs.json_object is False:
raise VLLMValidationError(
@@ -10,7 +10,7 @@ import torch
import vllm.envs
from vllm.exceptions import VLLMValidationError
from vllm.logger import init_logger
from vllm.sampling_params import SamplingParams
from vllm.sampling_params import SamplingParams, check_json_nesting
from vllm.utils.import_utils import LazyLoader
from vllm.utils.mistral import is_mistral_tokenizer
from vllm.v1.structured_output.backend_types import (
@@ -392,6 +392,7 @@ def validate_xgrammar_grammar(sampling_params: SamplingParams) -> None:
return
if so_params.json:
check_json_nesting(so_params.json)
if isinstance(so_params.json, str):
try:
schema = json.loads(so_params.json)
@@ -426,6 +427,7 @@ def validate_xgrammar_grammar(sampling_params: SamplingParams) -> None:
return
if so_params.structural_tag:
check_json_nesting(so_params.structural_tag, structural_tag=True)
try:
s_tag = json.loads(so_params.structural_tag)