Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

fix(sglang): bound JSON number digits in XGrammar json_schema grammars (#467)

svonava7f3666dd785a
diff --git a/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml b/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml
index 5edde14c5..6074af201 100644
--- a/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3.8-27B-FP8.yaml
@@ -24,6 +24,10 @@ inputs:
# also compiles JSON-schema grammars without free whitespace, so greedy
# decoding cannot pad a reply with indentation or run to the output cap in
# spaces.
+# Every profile also bounds each JSON number to 19 integer and 19 fractional
+# digits (``json_number_max_digits``). XGrammar leaves digit runs unbounded, so
+# a greedy decode that starts repeating a digit (``8214263.0000...``) ran to
+# the output cap on 2 of 30 page-image extractions on the batch profile.
tasks:
generate:
# Keep the bare route conservative. Native context is exposed only through
@@ -70,6 +74,7 @@ profiles:
disable_cuda_graph: true
attention_backend: flashinfer
grammar_backend: xgrammar
+ json_number_max_digits: 19
tool_call_parser: qwen3_coder
speculative:
enabled: false
@@ -121,6 +126,7 @@ profiles:
served_model_name: Qwen/Qwen3.8-27B-FP8
attention_backend: fa3
grammar_backend: xgrammar
+ json_number_max_digits: 19
tool_call_parser: qwen3_coder
extra_env:
SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
@@ -172,6 +178,7 @@ profiles:
served_model_name: Qwen/Qwen3.8-27B-FP8
attention_backend: fa3
grammar_backend: xgrammar
+ json_number_max_digits: 19
tool_call_parser: qwen3_coder
extra_env:
SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
@@ -222,6 +229,7 @@ profiles:
served_model_name: Qwen/Qwen3.8-27B-FP8
attention_backend: fa3
grammar_backend: xgrammar
+ json_number_max_digits: 19
tool_call_parser: qwen3_coder
extra_env:
SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
@@ -287,6 +295,7 @@ profiles:
served_model_name: Qwen/Qwen3.8-27B-FP8
attention_backend: fa3
grammar_backend: xgrammar
+ json_number_max_digits: 19
reasoning_parser: qwen3
tool_call_parser: qwen3_coder
extra_env:
@@ -352,6 +361,7 @@ profiles:
served_model_name: Qwen/Qwen3.8-27B-FP8
attention_backend: fa3
grammar_backend: xgrammar
+ json_number_max_digits: 19
tool_call_parser: qwen3_coder
extra_env:
SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
@@ -403,6 +413,7 @@ profiles:
served_model_name: Qwen/Qwen3.8-27B-FP8
attention_backend: fa3
grammar_backend: xgrammar
+ json_number_max_digits: 19
tool_call_parser: qwen3_coder
extra_env:
SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
@@ -450,6 +461,7 @@ profiles:
served_model_name: Qwen/Qwen3.8-27B-FP8
attention_backend: flashinfer
grammar_backend: xgrammar
+ json_number_max_digits: 19
tool_call_parser: qwen3_coder
extra_env:
SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
@@ -499,6 +511,7 @@ profiles:
served_model_name: Qwen/Qwen3.8-27B-FP8
attention_backend: flashinfer
grammar_backend: xgrammar
+ json_number_max_digits: 19
tool_call_parser: qwen3_coder
extra_env:
SIE_SGLANG_SINGLE_IMAGE_MAX_PIXELS: "3211264"
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/_compat/sitecustomize.py b/packages/sie_server/src/sie_server/adapters/sglang/_compat/sitecustomize.py
index f1d909712..d8b25849b 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/_compat/sitecustomize.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/_compat/sitecustomize.py
@@ -18,12 +18,18 @@ The same hook redacts multimodal load failures: SGLang raises
serving layer then logs with a traceback. The redacted error is a
``ValueError`` because that is the only exception SGLang's ``/generate`` turns
into a 400 response; the adapter maps its fixed message to ``invalid_request``.
+
+When the adapter sets ``SIE_SGLANG_JSON_NUMBER_MAX_DIGITS``, the hook also
+bounds the digit runs of numbers in XGrammar's JSON-schema grammars (see the
+section at the end of this module).
"""
from __future__ import annotations
import builtins
import copy
+import importlib
+import json
import os
import sys
from collections.abc import Mapping, Sequence
@@ -145,3 +151,261 @@ def _install_mm_process_config_compat() -> None:
if os.environ.get("SIE_SGLANG_MM_PROCESS_CONFIG_COMPAT") == "1":
_install_mm_process_config_compat()
+
+
+# --- JSON number digit bound ---------------------------------------------
+#
+# XGrammar compiles numeric JSON-schema values to digit runs of unbounded
+# length. Under greedy decoding a model that settles into repeating a digit
+# (``8214263.000000...``) has nothing to stop it before ``max_new_tokens``, and
+# the reply is truncated JSON. XGrammar has no option for this and SGLang 0.5.20
+# compiles the schema itself, so this hook bounds the digit runs where SGLang
+# asks XGrammar for the grammar. Once a number holds the maximum digits, the
+# grammar lets the model only close it.
+#
+# Two steps cover every numeric schema. First the schema is rewritten: a
+# numeric schema bounded on one side gains a wide bound on the other, which
+# XGrammar compiles to a finite range pattern (see bound_json_schema_numbers
+# for the one case left alone), and an unbounded one becomes a reference to one
+# of two injected definitions. Then the grammar XGrammar
+# builds is edited: the rules for those two definitions, and the shared
+# ``basic_integer`` and ``basic_number`` rules that untyped values use, get
+# digit-bounded bodies.
+
+_XGRAMMAR_COMPILER_MODULE = "xgrammar.compiler"
+_XGRAMMAR_GRAMMAR_MODULE = "xgrammar.grammar"
+_JSON_DIGITS_MARKER = "_sie_json_number_max_digits"
+_JSON_DIGITS_IMPORT_HOOK_MARKER = "_sie_json_number_max_digits_deferred"
+JSON_NUMBER_MAX_DIGITS_ENV = "SIE_SGLANG_JSON_NUMBER_MAX_DIGITS"
+
+# Injected definitions. XGrammar names the rule for ``#/$defs/<name>``
+# ``defs_<name>``, and keeps only letters, ``_``, ``-`` and ``.`` of the name.
+_INTEGER_DEF = "SieBoundedJsonInteger"
+_NUMBER_DEF = "SieBoundedJsonNumber"
+_INTEGER_RULES = ("basic_integer", f"defs_{_INTEGER_DEF}")
+_NUMBER_RULES = ("basic_number", f"defs_{_NUMBER_DEF}")
+_INT64_MAX = 2**63 - 1
+_NUMBER_UPPER_BOUND = 1e15
+
+_SUBSCHEMA_KEYS = frozenset(
+ {
+ "additionalProperties",
+ "additionalItems",
+ "contains",
+ "else",
+ "if",
+ "items",
+ "not",
+ "propertyNames",
+ "then",
+ "unevaluatedItems",
+ "unevaluatedProperties",
+ }
+)
+_SUBSCHEMA_LIST_KEYS = frozenset({"allOf", "anyOf", "items", "oneOf", "prefixItems"})
+_SUBSCHEMA_MAP_KEYS = frozenset({"$defs", "definitions", "dependentSchemas", "patternProperties", "properties"})
+_NUMERIC_KEYS = frozenset({"exclusiveMaximum", "exclusiveMinimum", "maximum", "minimum", "multipleOf"})
+_LOWER_KEYS = ("minimum", "exclusiveMinimum")
+_UPPER_KEYS = ("maximum", "exclusiveMaximum")
+
+
+def bound_json_schema_numbers(schema: Any, max_digits: int) -> Any:
+ """Return ``schema`` rewritten so XGrammar can bound every numeric value.
+
+ A numeric schema with ``enum`` or ``const``, or with both a lower and an
+ upper bound, is already finite and is left alone. An integer bounded on one
+ side gains the other side at the largest ``max_digits``-digit magnitude,
+ capped at the int64 range XGrammar reads. A number with only a lower bound
+ gains ``maximum: 1e15``; one with only an upper bound keeps XGrammar's own
+ pattern, whose fraction XGrammar already limits to six digits. A numeric
+ schema with no bound is replaced by a reference to an injected ``integer``
+ or ``number`` definition whose rule :func:`bound_json_number_rules` then
+ bounds; in a ``type`` list the other types stay as an ``anyOf``
+ alternative. The input is not modified, and a schema without a numeric type
+ comes back unchanged.
+ """
+ if not isinstance(schema, dict):
+ return schema
+ used: set[str] = set()
+ out = _rewrite_schema(schema, max_digits, used)
+ if used:
+ defs = dict(out.get("$defs") or {})
+ for name in sorted(used):
+ defs[name] = {"type": "integer" if name == _INTEGER_DEF else "number"}
+ out["$defs"] = defs
+ return out
+
+
+def _rewrite_schema(node: Any, max_digits: int, used: set[str]) -> Any:
+ if not isinstance(node, dict):
+ return node
+ out: dict[str, Any] = {}
+ for key, value in node.items():
+ if key in _SUBSCHEMA_MAP_KEYS and isinstance(value, dict):
+ out[key] = {name: _rewrite_schema(sub, max_digits, used) for name, sub in value.items()}
+ elif key in _SUBSCHEMA_LIST_KEYS and isinstance(value, list):
+ out[key] = [_rewrite_schema(sub, max_digits, used) for sub in value]
+ elif key in _SUBSCHEMA_KEYS and isinstance(value, dict):
+ out[key] = _rewrite_schema(value, max_digits, used)
+ else:
+ out[key] = value
+ return _bound_numeric_node(out, max_digits, used)
+
+
+def _bound_numeric_node(node: dict[str, Any], max_digits: int, used: set[str]) -> dict[str, Any]:
+ types = node.get("type")
+ type_list = list(types) if isinstance(types, list) else [types]
+ if "number" in type_list:
+ definition = _NUMBER_DEF
+ elif "integer" in type_list:
+ definition = _INTEGER_DEF
+ else:
+ return node
+ if "enum" in node or "const" in node:
+ return node
+ has_lower = any(key in node for key in _LOWER_KEYS)
+ has_upper = any(key in node for key in _UPPER_KEYS)
+ if has_lower and has_upper:
+ return node
+ if definition == _INTEGER_DEF and (has_lower or has_upper):
+ bound = min(10**max_digits - 1, _INT64_MAX)
+ return node | ({"maximum": bound} if has_lower else {"minimum": -bound})
+ if has_lower:
+ # XGrammar's float range pattern mis-compiles wide ranges: with an upper
+ # bound of 1e19 it rejects most in-range values. 1e15 is the widest
+ # bound measured to compile correctly, and it also fixes the fractions
+ # below 1 that a lower bound alone rejects.
+ return node | {"maximum": _NUMBER_UPPER_BOUND}
+ if has_upper:
+ # Adding a lower bound here makes XGrammar accept values above a
+ # ``maximum: 0``, so an upper-bounded number keeps XGrammar's own pattern.
+ return node
+ used.add(definition)
+ reference = {"$ref": f"#/$defs/{definition}"}
+ others = [t for t in type_list if t not in ("number", "integer")]
+ if not others:
+ # Keep keywords that constrain nothing (``description``, ``title``)
+ # off the reference; a sibling keyword would stop XGrammar resolving
+ # the node as a bare reference.
+ return reference
+ rest = {key: value for key, value in node.items() if key not in _NUMERIC_KEYS}
+ rest["type"] = others if len(others) > 1 else others[0]
+ return {"anyOf": [reference, rest]}
+
+
+def bound_json_number_rules(ebnf: str, max_digits: int) -> str:
+ """Give XGrammar's numeric rules digit-bounded bodies.
+
+ The rules are the shared ``basic_integer`` and ``basic_number`` and the
+ rules for the definitions :func:`bound_json_schema_numbers` injects. The
+ bodies keep JSON's number shape and bound only the digit runs: at most
+ ``max_digits`` integer digits, at most ``max_digits`` fractional digits, and
+ at most three exponent digits. Every other rule, including digit runs that
+ come from a string ``pattern``, is unchanged.
+ """
+ tail = max_digits - 1
+ integer = f'(("0") | ("-"? [1-9] [0-9]{{0,{tail}}}))'
+ number = f'(("-"? ("0" | [1-9] [0-9]{{0,{tail}}}) ("." [0-9]{{1,{max_digits}}})? ([eE] [+\\-]? [0-9]{{1,3}})?))'
+ replacements = dict.fromkeys(_INTEGER_RULES, integer) | dict.fromkeys(_NUMBER_RULES, number)
+ lines = []
+ for line in ebnf.splitlines():
+ name, separator, _ = line.partition(" ::= ")
+ if separator and name in replacements:
+ line = f"{name} ::= {replacements[name]}"
+ lines.append(line)
+ return "\n".join(lines) + "\n"
+
+
+def json_number_max_digits_from_env() -> int | None:
+ """Return the configured digit bound, or None when the hook is off."""
+ raw = os.environ.get(JSON_NUMBER_MAX_DIGITS_ENV)
+ if not raw:
+ return None
+ if not raw.isdigit() or int(raw) <= 0:
+ raise ValueError(f"{JSON_NUMBER_MAX_DIGITS_ENV} must be a positive integer, got {raw!r}")
+ return int(raw)
+
+
+def _bounded_schema(schema: Any, max_digits: int) -> Any:
+ """Rewrite a schema given as text or a dict; anything else passes through for XGrammar to handle."""
+ if isinstance(schema, dict):
+ return bound_json_schema_numbers(schema, max_digits)
+ if isinstance(schema, (str, bytes)):
+ try:
+ parsed = json.loads(schema)
+ except ValueError:
+ return schema
+ return json.dumps(bound_json_schema_numbers(parsed, max_digits)) if isinstance(parsed, dict) else schema
+ return schema
+
+
+def _patch_xgrammar_compiler_module(module: ModuleType, max_digits: int) -> None:
+ compiler_class = getattr(module, "GrammarCompiler", None)
+ if compiler_class is None:
+ raise RuntimeError(f"{_XGRAMMAR_COMPILER_MODULE} does not expose GrammarCompiler")
+ if getattr(compiler_class, _JSON_DIGITS_MARKER, False):
+ return
+ grammar_class = importlib.import_module(_XGRAMMAR_GRAMMAR_MODULE).Grammar
+ original_compile = compiler_class.compile_json_schema
+
+ @wraps(original_compile)
+ def compile_json_schema(
+ self: Any,
+ schema: Any,
+ *,
+ any_whitespace: bool = True,
+ indent: int | None = None,
+ separators: tuple[str, str] | None = None,
+ strict_mode: bool = True,
+ max_whitespace_cnt: int | None = None,
+ ) -> Any:
+ grammar = grammar_class.from_json_schema(
+ _bounded_schema(schema, max_digits),
+ any_whitespace=any_whitespace,
+ indent=indent,
+ separators=separators,
+ strict_mode=strict_mode,
+ max_whitespace_cnt=max_whitespace_cnt,
+ )
+ return self.compile_grammar(bound_json_number_rules(str(grammar), max_digits))
+
+ compiler_class.compile_json_schema = compile_json_schema
+ setattr(compiler_class, _JSON_DIGITS_MARKER, True)
+
+
+def _install_json_number_max_digits() -> None:
+ max_digits = json_number_max_digits_from_env()
+ if max_digits is None:
+ return
+ loaded = sys.modules.get(_XGRAMMAR_COMPILER_MODULE)
+ if isinstance(loaded, ModuleType) and hasattr(loaded, "GrammarCompiler"):
+ _patch_xgrammar_compiler_module(loaded, max_digits)
+ return
+
+ current_import = builtins.__import__
+ if getattr(current_import, _JSON_DIGITS_IMPORT_HOOK_MARKER, False):
+ return
+
+ def deferred_import(
+ name: str,
+ globals: Mapping[str, object] | None = None,
+ locals: Mapping[str, object] | None = None,
+ fromlist: Sequence[str] | None = (),
+ level: int = 0,
+ ) -> ModuleType:
+ module = current_import(name, globals, locals, fromlist, level)
+ loaded_module = sys.modules.get(_XGRAMMAR_COMPILER_MODULE)
+ if not isinstance(loaded_module, ModuleType) or not hasattr(loaded_module, "GrammarCompiler"):
+ return module
+ try:
+ _patch_xgrammar_compiler_module(loaded_module, max_digits)
+ finally:
+ if builtins.__import__ is deferred_import:
+ setattr(builtins, "__import__", current_import) # noqa: B010
+ return module
+
+ setattr(deferred_import, _JSON_DIGITS_IMPORT_HOOK_MARKER, True)
+ setattr(builtins, "__import__", deferred_import) # noqa: B010
+
+
+_install_json_number_max_digits()
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
index 1bd88f864..d2b5ba07e 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
@@ -168,6 +168,22 @@ def _resolve_profile_startup_timeout(declared: float | None, *, tensor_parallel_
return _server.resolve_startup_timeout(declared)
+_JSON_NUMBER_MAX_DIGITS_ENV = "SIE_SGLANG_JSON_NUMBER_MAX_DIGITS"
+
+
+def _validate_json_number_max_digits(value: Any, grammar_backend: str | None) -> int | None:
+ """Return a usable JSON number digit bound, or None when the profile sets none."""
+ if value is None:
+ return None
+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
+ msg = f"json_number_max_digits must be a positive integer, got {value!r}"
+ raise ValueError(msg)
+ if grammar_backend != "xgrammar":
+ msg = f"json_number_max_digits bounds XGrammar's JSON grammars and needs grammar_backend 'xgrammar', got {grammar_backend!r}"
+ raise ValueError(msg)
+ return value
+
+
def _mamba_strategy_value(extra_launch_args: list[str], flag: str) -> str | None:
"""Return the value passed to the mamba strategy ``flag``, or ``None``.
@@ -486,9 +502,17 @@ class SGLangGenerationAdapter(GenerationAdapter):
# "decide from the width", or off at every width for an adapter whose
# profiles were sized on an engine that never captured it.
disable_piecewise_cuda_graph: bool | None = None,
+ # Upper bound on the digits a JSON-schema grammar lets a number carry,
+ # in its integer part and in its fraction. XGrammar leaves both
+ # unbounded, so a greedy decode that starts repeating a digit runs to
+ # ``max_new_tokens``. None keeps the backend's unbounded numbers; the
+ # bound needs the ``xgrammar`` backend, which the child's sitecustomize
+ # patches.
+ json_number_max_digits: int | None = None,
**kwargs: Any, # accept extra args from loader for compatibility
) -> None:
_ = kwargs
+ self._json_number_max_digits = _validate_json_number_max_digits(json_number_max_digits, grammar_backend)
self._model_name_or_path = str(model_name_or_path)
self._max_seq_length = max_seq_length
self._mem_fraction_static = mem_fraction_static
@@ -865,6 +889,8 @@ class SGLangGenerationAdapter(GenerationAdapter):
# auto-imports sitecustomize from PYTHONPATH during child startup.
extra_env["PYTHONPATH"] = os.pathsep.join(self._compat_pythonpath_entries())
extra_env["SIE_SGLANG_MM_PROCESS_CONFIG_COMPAT"] = "1"
+ if self._json_number_max_digits is not None:
+ extra_env[_JSON_NUMBER_MAX_DIGITS_ENV] = str(self._json_number_max_digits)
logger.warning(
"Resolved SGLang generation command: %s",
" ".join(shlex.quote(str(arg)) for arg in cmd),
diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.py
index 90f2c3dc5..06a4bfa0b 100644
--- a/packages/sie_server/tests/adapters/test_sglang_generation.py
+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py
@@ -209,6 +209,58 @@ def test_load_drops_is_embedding(
assert child_env["PYTHONPATH"].split(os.pathsep)[0] == str(expected_compat_dir)
[email protected]("digits", [None, 19])
+@patch("sie_server.adapters.sglang._server.subprocess.Popen")
+@patch("sie_server.adapters.sglang._server.requests.get")
+@patch("sie_server.adapters.sglang._server.find_free_port")
+def test_load_passes_json_number_max_digits_to_the_child(
+ mock_find_port: MagicMock,
+ mock_requests_get: MagicMock,
+ mock_popen: MagicMock,
+ monkeypatch: pytest.MonkeyPatch,
+ digits: int | None,
+) -> None:
+ monkeypatch.delenv("SIE_SGLANG_JSON_NUMBER_MAX_DIGITS", raising=False)
+ mock_find_port.return_value = 30005
+ mock_process = MagicMock()
+ mock_process.poll.return_value = None
+ mock_popen.return_value = mock_process
+ mock_requests_get.return_value = MagicMock(status_code=200)
+ adapter = SGLangGenerationAdapter(
+ model_name_or_path="Qwen/Qwen3-4B-Instruct",
+ grammar_backend="xgrammar",
+ json_number_max_digits=digits,
+ )
+
+ adapter.load("cuda:0")
+
+ child_env = mock_popen.call_args.kwargs["env"]
+ if digits is None:
+ assert "SIE_SGLANG_JSON_NUMBER_MAX_DIGITS" not in child_env
+ else:
+ assert child_env["SIE_SGLANG_JSON_NUMBER_MAX_DIGITS"] == "19"
+
+
+ ("digits", "backend", "message"),
+ [
+ (0, "xgrammar", "positive integer"),
+ (-1, "xgrammar", "positive integer"),
+ (True, "xgrammar", "positive integer"),
+ ("19", "xgrammar", "positive integer"),
+ (19, "outlines", "needs grammar_backend 'xgrammar'"),
+ (19, None, "needs grammar_backend 'xgrammar'"),
+ ],
+)
+def test_json_number_max_digits_rejects_unusable_settings(digits: object, backend: str | None, message: str) -> None:
+ with pytest.raises(ValueError, match=message):
+ SGLangGenerationAdapter(
+ model_name_or_path="Qwen/Qwen3-4B-Instruct",
+ grammar_backend=backend,
+ json_number_max_digits=digits, # type: ignore[arg-type]
+ )
+
+
@patch("sie_server.adapters.sglang._server.subprocess.Popen")
@patch("sie_server.adapters.sglang._server.requests.get")
@patch("sie_server.adapters.sglang._server.find_free_port")
diff --git a/packages/sie_server/tests/adapters/test_sglang_json_grammar_limits.py b/packages/sie_server/tests/adapters/test_sglang_json_grammar_limits.py
new file mode 100644
index 000000000..386565b15
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_sglang_json_grammar_limits.py
@@ -0,0 +1,258 @@
+"""The JSON number digit bound applied by the SGLang child's sitecustomize hook."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+from types import ModuleType
+
+import pytest
+
+_COMPAT_DIR = Path(__file__).resolve().parents[2] / "src/sie_server/adapters/sglang/_compat"
+
+# ``str(Grammar.from_json_schema(...))`` from XGrammar 0.2.1 for a schema with an
+# unbounded integer, an unbounded number, and a digit-only string pattern.
+_XGRAMMAR_EBNF = r"""basic_integer ::= (("0") | (basic_integer_1 [1-9] [0-9]*))
+basic_number ::= ((basic_number_1 basic_number_7 basic_number_3 basic_number_6))
+root_prop_2 ::= (("\"" root_prop_2_1 "\""))
+root ::= (("{" "\"n\"" ": " basic_integer ", " "\"x\"" ": " basic_number ", " "\"s\"" ": " root_prop_2 "}"))
+basic_integer_1 ::= ("" | ("-"))
+basic_number_1 ::= ("" | ("-"))
+basic_number_2 ::= (([0-9] basic_number_2) | ([0-9]))
+basic_number_3 ::= ("" | ("." basic_number_2))
+root_prop_2_1 ::= (([0-9] root_prop_2_1) | ([0-9]))
+"""
+
+
+def _load_sitecustomize() -> ModuleType:
+ spec = importlib.util.spec_from_file_location("sie_sglang_sitecustomize", _COMPAT_DIR / "sitecustomize.py")
+ assert spec is not None
+ assert spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def test_bound_json_number_rules_bounds_only_the_shared_number_rules() -> None:
+ sitecustomize = _load_sitecustomize()
+
+ bounded = sitecustomize.bound_json_number_rules(_XGRAMMAR_EBNF, 19)
+
+ rules = dict(line.split(" ::= ", 1) for line in bounded.splitlines())
+ assert rules["basic_integer"] == '(("0") | ("-"? [1-9] [0-9]{0,18}))'
+ assert rules["basic_number"] == (r'(("-"? ("0" | [1-9] [0-9]{0,18}) ("." [0-9]{1,19})? ([eE] [+\-]? [0-9]{1,3})?))')
+ # A string pattern compiles to the same digit recursion as a number; only
+ # the shared numeric rules may change.
+ original = dict(line.split(" ::= ", 1) for line in _XGRAMMAR_EBNF.splitlines())
+ for name in original.keys() - {"basic_integer", "basic_number"}:
+ assert rules[name] == original[name], name
+
+
+def test_bound_json_number_rules_bounds_the_injected_definition_rules() -> None:
+ sitecustomize = _load_sitecustomize()
+ ebnf = (
+ "root ::= ((defs_SieBoundedJsonInteger defs_SieBoundedJsonNumber))\n"
+ 'defs_SieBoundedJsonInteger ::= (("0") | (defs_SieBoundedJsonInteger_1 [1-9] [0-9]*))\n'
+ "defs_SieBoundedJsonNumber ::= ((defs_SieBoundedJsonNumber_1 defs_SieBoundedJsonNumber_7))\n"
+ )
+
+ rules = dict(line.split(" ::= ", 1) for line in sitecustomize.bound_json_number_rules(ebnf, 5).splitlines())
+
+ assert rules["defs_SieBoundedJsonInteger"] == '(("0") | ("-"? [1-9] [0-9]{0,4}))'
+ assert rules["defs_SieBoundedJsonNumber"].startswith('(("-"? ("0" | [1-9] [0-9]{0,4}) ("." [0-9]{1,5})?')
+
+
+_INT = {"$ref": "#/$defs/SieBoundedJsonInteger"}
+_NUM = {"$ref": "#/$defs/SieBoundedJsonNumber"}
+_DEFS = {"SieBoundedJsonInteger": {"type": "integer"}, "SieBoundedJsonNumber": {"type": "number"}}
+
+
+def test_bound_json_schema_numbers_references_every_unbounded_numeric_schema() -> None:
+ sitecustomize = _load_sitecustomize()
+ schema = {
+ "type": "object",
+ "properties": {
+ "year": {"type": ["integer", "null"], "description": "four digits"},
+ "price": {"type": "number", "description": "USD"},
+ "tags": {"type": "array", "items": {"type": "number"}},
+ "either": {"anyOf": [{"$ref": "#/$defs/Count"}, {"type": "string"}]},
+ },
+ "$defs": {"Count": {"type": "integer", "title": "count"}},
+ }
+ original = json.loads(json.dumps(schema))
+
+ bounded = sitecustomize.bound_json_schema_numbers(schema, 19)
+
+ assert schema == original
+ assert bounded["properties"]["year"] == {"anyOf": [_INT, {"type": "null", "description": "four digits"}]}
+ assert bounded["properties"]["price"] == _NUM
+ assert bounded["properties"]["tags"] == {"type": "array", "items": _NUM}
+ assert bounded["properties"]["either"] == schema["properties"]["either"]
+ assert bounded["$defs"] == {"Count": _INT} | _DEFS
+
+
+ ("numeric", "expected"),
+ [
+ ({"type": "integer", "minimum": 0}, {"type": "integer", "minimum": 0, "maximum": 2**63 - 1}),
+ (
+ {"type": "integer", "exclusiveMaximum": 10},
+ {"type": "integer", "exclusiveMaximum": 10, "minimum": -(2**63 - 1)},
+ ),
+ ({"type": "number", "minimum": 0}, {"type": "number", "minimum": 0, "maximum": 1e15}),
+ ({"type": "number", "exclusiveMinimum": 0}, {"type": "number", "exclusiveMinimum": 0, "maximum": 1e15}),
+ ({"type": "number", "maximum": 100}, {"type": "number", "maximum": 100}),
+ ({"type": "integer", "minimum": 1, "maximum": 5}, {"type": "integer", "minimum": 1, "maximum": 5}),
+ ({"type": "number", "enum": [1.5, 2.5]}, {"type": "number", "enum": [1.5, 2.5]}),
+ ({"type": "integer", "const": 3}, {"type": "integer", "const": 3}),
+ ({"type": "string", "pattern": "^[0-9]+$"}, {"type": "string", "pattern": "^[0-9]+$"}),
+ ],
+)
+def test_bound_json_schema_numbers_handles_bounded_and_finite_schemas(numeric: dict, expected: dict) -> None:
+ sitecustomize = _load_sitecustomize()
+
+ bounded = sitecustomize.bound_json_schema_numbers({"type": "object", "properties": {"v": numeric}}, 19)
+
+ assert bounded == {"type": "object", "properties": {"v": expected}}
+
+
+def test_bound_json_schema_numbers_integer_bound_follows_the_digit_limit() -> None:
+ sitecustomize = _load_sitecustomize()
+
+ bounded = sitecustomize.bound_json_schema_numbers({"type": "integer", "minimum": 0}, 4)
+
+ assert bounded == {"type": "integer", "minimum": 0, "maximum": 9999}
+
+
+def test_bound_json_schema_numbers_rewrites_a_numeric_root() -> None:
+ sitecustomize = _load_sitecustomize()
+
+ assert sitecustomize.bound_json_schema_numbers({"type": "number"}, 19) == _NUM | {
+ "$defs": {"SieBoundedJsonNumber": {"type": "number"}}
+ }
+ assert sitecustomize.bound_json_schema_numbers(True, 19) is True
+
+
+def test_bound_json_number_rules_leaves_a_grammar_without_numbers_alone() -> None:
+ sitecustomize = _load_sitecustomize()
+ ebnf = 'root ::= (("{" "\\"a\\"" ": " basic_string "}"))\nbasic_string ::= (("\\"" [a-z]* "\\""))\n'
+
+ assert sitecustomize.bound_json_number_rules(ebnf, 19) == ebnf
+
+
+def _fake_xgrammar(root: Path) -> None:
+ package = root / "xgrammar"
+ package.mkdir(parents=True)
+ (package / "__init__.py").write_text("from .compiler import GrammarCompiler\n", encoding="utf-8")
+ (package / "grammar.py").write_text(
+ f"""EBNF = {_XGRAMMAR_EBNF!r}
+CALLS = []
+
+
+class Grammar:
+ @classmethod
+ def from_json_schema(cls, schema, **kwargs):
+ CALLS.append(("from_json_schema", schema, kwargs))
+ return cls()
+
+ def __str__(self):
+ return EBNF
+""",
+ encoding="utf-8",
+ )
+ (package / "compiler.py").write_text(
+ """from .grammar import CALLS, Grammar
+
+
+class GrammarCompiler:
+ def compile_json_schema(
+ self, schema, *, any_whitespace=True, indent=None, separators=None, strict_mode=True, max_whitespace_cnt=None
+ ):
+ CALLS.append(("compile_json_schema", schema, {"any_whitespace": any_whitespace, "max_whitespace_cnt": max_whitespace_cnt}))
+ return "json"
+
+ def compile_grammar(self, ebnf):
+ CALLS.append(("compile_grammar", ebnf, {}))
+ return "ebnf"
+""",
+ encoding="utf-8",
+ )
+
+
+def _run_child(tmp_path: Path, script: str, **env_overrides: str) -> subprocess.CompletedProcess[str]:
+ fake_root = tmp_path / "fake"
+ _fake_xgrammar(fake_root)
+ env = {k: v for k, v in os.environ.items() if k != "SIE_SGLANG_JSON_NUMBER_MAX_DIGITS"}
+ env["PYTHONPATH"] = os.pathsep.join((str(_COMPAT_DIR), str(fake_root)))
+ env.update(env_overrides)
+ return subprocess.run( # noqa: S603 - executes the fixed local interpreter
+ [sys.executable, "-c", script],
+ env=env,
+ capture_output=True,
+ text=True,
+ timeout=15,
+ check=False,
+ )
+
+
+_CHILD_SCRIPT = """import json
+from xgrammar import GrammarCompiler
+from xgrammar.grammar import CALLS
+
+compiler = GrammarCompiler()
+results = [
+ compiler.compile_json_schema(schema='{"type": "object"}', any_whitespace=False),
+ compiler.compile_json_schema('{"type": "object"}', any_whitespace=True, max_whitespace_cnt=4),
+]
+print(json.dumps({
+ "patched": bool(getattr(GrammarCompiler, "_sie_json_number_max_digits", False)),
+ "results": results,
+ "calls": CALLS,
+}))
+"""
+
+
+def _child_report(completed: subprocess.CompletedProcess[str]) -> dict:
+ assert completed.returncode == 0, completed.stderr
+ assert "Error in sitecustomize" not in completed.stderr
+ return json.loads(completed.stdout)
+
+
+def test_json_number_hook_is_inert_without_configuration(tmp_path: Path) -> None:
+ report = _child_report(_run_child(tmp_path, _CHILD_SCRIPT))
+
+ assert report["patched"] is False
+ assert report["results"] == ["json", "json"]
+ assert [call[0] for call in report["calls"]] == ["compile_json_schema", "compile_json_schema"]
+
+
+def test_json_number_hook_compiles_the_digit_bounded_grammar(tmp_path: Path) -> None:
+ report = _child_report(_run_child(tmp_path, _CHILD_SCRIPT, SIE_SGLANG_JSON_NUMBER_MAX_DIGITS="19"))
+
+ assert report["patched"] is True
+ assert report["results"] == ["ebnf", "ebnf"]
+ # The schema and every formatting option reach XGrammar's own converter.
+ conversions = [call for call in report["calls"] if call[0] == "from_json_schema"]
+ assert [call[1] for call in conversions] == ['{"type": "object"}', '{"type": "object"}']
+ assert [call[2] for call in conversions] == [
+ {"any_whitespace": False, "indent": None, "separators": None, "strict_mode": True, "max_whitespace_cnt": None},
+ {"any_whitespace": True, "indent": None, "separators": None, "strict_mode": True, "max_whitespace_cnt": 4},
+ ]
+ compiled = [call[1] for call in report["calls"] if call[0] == "compile_grammar"]
+ assert compiled == [sitecustomize_bound(19), sitecustomize_bound(19)]
+
+
+def sitecustomize_bound(max_digits: int) -> str:
+ return _load_sitecustomize().bound_json_number_rules(_XGRAMMAR_EBNF, max_digits)
+
+
[email protected]("value", ["0", "-3", "many", "1.5"])
+def test_json_number_hook_rejects_invalid_bounds(tmp_path: Path, value: str) -> None:
+ completed = _run_child(tmp_path, "import xgrammar\n", SIE_SGLANG_JSON_NUMBER_MAX_DIGITS=value)
+
+ assert "Error in sitecustomize" in completed.stderr
+ assert "SIE_SGLANG_JSON_NUMBER_MAX_DIGITS must be a positive integer" in completed.stderr
diff --git a/packages/sie_server/tests/config/test_qwen38_generation_profiles.py b/packages/sie_server/tests/config/test_qwen38_generation_profiles.py
index fed522c37..74787acea 100644
--- a/packages/sie_server/tests/config/test_qwen38_generation_profiles.py
+++ b/packages/sie_server/tests/config/test_qwen38_generation_profiles.py
@@ -299,3 +299,14 @@ def test_qwen38_reads_one_page_at_document_resolution_with_compact_json() -> Non
# The bare route still fits one full-resolution page and the whole output cap.
assert 3136 + output_cap < window
+
+
+def test_qwen38_json_grammars_bound_number_digits() -> None:
+ # XGrammar's unbounded digit runs let a temperature-0 decode loop to the
+ # output cap; every launch, including each grammar twin, bounds them.
+ config = load_model_config(_MODEL_PATH)
+
+ for name in config.profiles:
+ profile = config.resolve_profile(name)
+ assert profile.loadtime["grammar_backend"] == "xgrammar", name
+ assert profile.loadtime["json_number_max_digits"] == 19, name