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: identify unsupported Outlines JSON Schema type values

Attila Laszlo Nagy0c0408b1de44
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 588a7f4e1..acd517b79 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
@@ -50,7 +50,11 @@ from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision
from sie_server.adapters.sglang import _server
from sie_server.observability.generation_diagnostics import GenerationStreamTimer
-from sie_server.types.grammar import GrammarSpec
+from sie_server.types.grammar import (
+ OUTLINES_JSON_SCHEMA_TYPE_DIAGNOSTIC,
+ OUTLINES_JSON_SCHEMA_TYPE_MESSAGE,
+ GrammarSpec,
+)
from sie_server.types.inputs import ImageInput, media_bytes
logger = logging.getLogger(__name__)
@@ -158,7 +162,51 @@ def _encode_image_data(images: list[ImageInput] | None) -> list[str] | None:
return encoded
-def _raise_for_sglang_event_error(event: Any, *, grammar: GrammarSpec | None = None, terminal: bool = False) -> None:
+_JSON_SCHEMA_TYPE_DIAGNOSTIC = f"Failed to compile json grammar: {OUTLINES_JSON_SCHEMA_TYPE_DIAGNOSTIC}"
+_MAX_ERROR_BODY_BYTES = 4096
+
+
+def _unique_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for key, value in pairs:
+ if key in result:
+ raise ValueError("SGLang /generate returned duplicate JSON keys")
+ result[key] = value
+ return result
+
+
+async def _raise_for_sglang_http_error(
+ response: httpx.Response, *, grammar: GrammarSpec | None, grammar_backend: str | None
+) -> None:
+ if (
+ response.status_code == 400
+ and grammar_backend == "outlines"
+ and grammar is not None
+ and grammar.kind == "json_schema"
+ ):
+
+ async def read_error() -> bytes:
+ body = bytearray()
+ async for chunk in response.aiter_bytes():
+ if len(body) + len(chunk) > _MAX_ERROR_BODY_BYTES:
+ return b""
+ body.extend(chunk)
+ return bytes(body)
+
+ try:
+ body = await asyncio.wait_for(read_error(), timeout=1.0)
+ payload = json.loads(body, object_pairs_hook=_unique_json_object)
+ except (ValueError, RecursionError, httpx.HTTPError, TimeoutError):
+ pass
+ else:
+ if payload == {"error": {"message": _JSON_SCHEMA_TYPE_DIAGNOSTIC}}:
+ raise GenerationInvalidRequestError("grammar", OUTLINES_JSON_SCHEMA_TYPE_MESSAGE)
+ response.raise_for_status()
+
+
+def _raise_for_sglang_event_error(
+ event: Any, *, grammar: GrammarSpec | None = None, grammar_backend: str | None = None, terminal: bool = False
+) -> None:
"""Reject upstream failures before consuming their text or usage."""
if not isinstance(event, dict):
raise GenerationError("SGLang /generate returned an invalid event")
@@ -170,8 +218,14 @@ def _raise_for_sglang_event_error(event: Any, *, grammar: GrammarSpec | None = N
if finish is not None and kind is None:
raise GenerationError("SGLang /generate returned a malformed finish reason")
if kind == "abort":
- if isinstance(finish, dict) and finish.get("status_code") == 400:
+ if isinstance(finish, dict) and type(finish.get("status_code")) is int and finish["status_code"] == 400:
if grammar is not None:
+ if (
+ grammar_backend == "outlines"
+ and grammar.kind == "json_schema"
+ and finish.get("message") == _JSON_SCHEMA_TYPE_DIAGNOSTIC
+ ):
+ raise GenerationInvalidRequestError("grammar", OUTLINES_JSON_SCHEMA_TYPE_MESSAGE)
raise GenerationInvalidRequestError(
"grammar", f"The generation backend rejected the requested {grammar.kind} grammar"
)
@@ -1254,7 +1308,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
terminal_yielded = False
try:
async with sclient.stream("POST", f"{self._server_url}/generate", json=sbody) as sresp:
- sresp.raise_for_status()
+ await _raise_for_sglang_http_error(sresp, grammar=grammar, grammar_backend=self._grammar_backend)
async for raw_line in sresp.aiter_lines():
line = raw_line.strip()
if line.startswith("data:"):
@@ -1262,10 +1316,10 @@ class SGLangGenerationAdapter(GenerationAdapter):
if not line or line == "[DONE]":
continue
try:
- event = json.loads(line)
+ event = json.loads(line, object_pairs_hook=_unique_json_object)
except json.JSONDecodeError:
continue
- _raise_for_sglang_event_error(event, grammar=grammar)
+ _raise_for_sglang_event_error(event, grammar=grammar, grammar_backend=self._grammar_backend)
idx = event.get("index")
if not isinstance(idx, int) or isinstance(idx, bool) or not 0 <= idx < return_count:
raise GenerationError("SGLang /generate returned an invalid candidate index")
@@ -1387,9 +1441,10 @@ class SGLangGenerationAdapter(GenerationAdapter):
if top_logprobs is not None and top_logprobs > 0:
nbody["top_logprobs_num"] = top_logprobs
nclient = await self._get_or_create_http_client()
- nresp = await nclient.post(f"{self._server_url}/generate", json=nbody)
- nresp.raise_for_status()
- results = nresp.json()
+ async with nclient.stream("POST", f"{self._server_url}/generate", json=nbody) as nresp:
+ await _raise_for_sglang_http_error(nresp, grammar=grammar, grammar_backend=self._grammar_backend)
+ await nresp.aread()
+ results = nresp.json(object_pairs_hook=_unique_json_object)
# SGLang returns a list of ``n`` result objects for ``n > 1``;
# tolerate a single dict defensively.
if isinstance(results, dict):
@@ -1397,7 +1452,9 @@ class SGLangGenerationAdapter(GenerationAdapter):
if not isinstance(results, list):
raise GenerationError("SGLang /generate returned an invalid candidate list")
for result in results:
- _raise_for_sglang_event_error(result, grammar=grammar, terminal=True)
+ _raise_for_sglang_event_error(
+ result, grammar=grammar, grammar_backend=self._grammar_backend, terminal=True
+ )
if len(results) != gen_count:
raise GenerationError("SGLang /generate returned an incorrect candidate count")
if rank:
@@ -1527,10 +1584,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
terminal_yielded = False
try:
async with client.stream("POST", f"{self._server_url}/generate", json=body) as response:
- if response.status_code != 200:
- await response.aread()
- logger.error("SGLang /generate stream error %d", response.status_code)
- response.raise_for_status()
+ await _raise_for_sglang_http_error(response, grammar=grammar, grammar_backend=self._grammar_backend)
last_cumulative_text = ""
first_yield_done = False
@@ -1553,12 +1607,12 @@ class SGLangGenerationAdapter(GenerationAdapter):
if not line or line == "[DONE]":
continue
try:
- event = json.loads(line)
+ event = json.loads(line, object_pairs_hook=_unique_json_object)
except json.JSONDecodeError:
logger.warning("SGLang stream: skipping non-JSON line")
continue
- _raise_for_sglang_event_error(event, grammar=grammar)
+ _raise_for_sglang_event_error(event, grammar=grammar, grammar_backend=self._grammar_backend)
chunk = _chunk_from_sglang_event(
event,
previous_cumulative_text=last_cumulative_text,
diff --git a/packages/sie_server/src/sie_server/processors/grammar_compile.py b/packages/sie_server/src/sie_server/processors/grammar_compile.py
index e285ac119..5946a7def 100644
--- a/packages/sie_server/src/sie_server/processors/grammar_compile.py
+++ b/packages/sie_server/src/sie_server/processors/grammar_compile.py
@@ -53,7 +53,12 @@ import json
import logging
from typing import Any
-from sie_server.types.grammar import GrammarSpec, GrammarValidationError
+from sie_server.types.grammar import (
+ OUTLINES_JSON_SCHEMA_TYPE_DIAGNOSTIC,
+ OUTLINES_JSON_SCHEMA_TYPE_MESSAGE,
+ GrammarSpec,
+ GrammarValidationError,
+)
logger = logging.getLogger(__name__)
@@ -178,9 +183,7 @@ def compile_outlines(tokenizer: Any, grammar: GrammarSpec) -> Any:
Blocking — callers must wrap in :func:`asyncio.to_thread` (see
:class:`StreamingProcessor`). Raises
- :class:`GrammarValidationError` with ``code="grammar_compile_failed"``
- on any Outlines exception, wrapping the original error message for
- the gateway-side chunk envelope.
+ :class:`GrammarValidationError` with a client-safe diagnostic.
The returned value is a sentinel object that :class:`GrammarLRU`
stores. Currently ``True`` for the SGLang path; a future
@@ -225,11 +228,16 @@ def compile_outlines(tokenizer: Any, grammar: GrammarSpec) -> Any:
except GrammarValidationError:
raise
except Exception as exc:
- # Wrap the Outlines-internal error message so the chunk envelope
- # surfaces something actionable. Don't include the full schema
- # in the message — schemas are sometimes private.
+ if (
+ grammar.kind == "json_schema"
+ and isinstance(exc, ValueError)
+ and exc.args == (OUTLINES_JSON_SCHEMA_TYPE_DIAGNOSTIC,)
+ ):
+ raise GrammarValidationError(
+ OUTLINES_JSON_SCHEMA_TYPE_MESSAGE, code="invalid_request", param="grammar"
+ ) from exc
raise GrammarValidationError(
- f"outlines compile failed: {exc}",
+ "outlines compile failed",
code="grammar_compile_failed",
param="grammar",
) from exc
diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.py
index 20b1dc37f..64704ade2 100644
--- a/packages/sie_server/src/sie_server/processors/streaming.py
+++ b/packages/sie_server/src/sie_server/processors/streaming.py
@@ -83,7 +83,12 @@ from sie_server.processors.tool_call_grammar import (
normalize_tool_choice,
)
from sie_server.processors.tool_call_parser import ToolCallFormat, parse_tool_call_stream
-from sie_server.types.grammar import GrammarSpec, GrammarValidationError, hash_grammar
+from sie_server.types.grammar import (
+ OUTLINES_JSON_SCHEMA_TYPE_MESSAGE,
+ GrammarSpec,
+ GrammarValidationError,
+ hash_grammar,
+)
from sie_server.types.inputs import ImageInput
# Module-level shim around :func:`asyncio.wait_for`. Tests monkey-patch
@@ -3632,7 +3637,7 @@ class StreamingProcessor:
# follower settles its own work item rather than hanging
# until ack_wait and triggering redelivery.
await _wait_for(future_to_await, timeout=_GRAMMAR_FOLLOWER_TIMEOUT_S)
- except Exception: # noqa: BLE001
+ except Exception as exc: # noqa: BLE001
# Leader's compile failed, was cancelled, or did not
# resolve in time; surface the same terminal-error path.
logger.warning(
@@ -3641,13 +3646,21 @@ class StreamingProcessor:
attempt_id,
exc_info=True,
)
+ known_type_refusal = (
+ grammar.kind == "json_schema"
+ and isinstance(exc, GrammarValidationError)
+ and exc.code == "invalid_request"
+ and exc.args == (OUTLINES_JSON_SCHEMA_TYPE_MESSAGE,)
+ )
await self._terminal_error_then_settle(
reply_subject,
request_id=request_id,
attempt_id=attempt_id,
seq=0,
- code="grammar_compile_failed",
- message=_INTERNAL_GRAMMAR_COMPILE_MESSAGE,
+ code="invalid_request" if known_type_refusal else "grammar_compile_failed",
+ message=OUTLINES_JSON_SCHEMA_TYPE_MESSAGE
+ if known_type_refusal
+ else _INTERNAL_GRAMMAR_COMPILE_MESSAGE,
msg=msg,
)
return False
diff --git a/packages/sie_server/src/sie_server/types/grammar.py b/packages/sie_server/src/sie_server/types/grammar.py
index 8b072c46b..21acdae0b 100644
--- a/packages/sie_server/src/sie_server/types/grammar.py
+++ b/packages/sie_server/src/sie_server/types/grammar.py
@@ -39,6 +39,12 @@ from typing import Literal
# building cache keys don't import the cache module just for the tag.
GrammarKind = Literal["json_schema", "regex", "ebnf"]
+OUTLINES_JSON_SCHEMA_TYPE_DIAGNOSTIC = "'type' must be a string"
+OUTLINES_JSON_SCHEMA_TYPE_MESSAGE = (
+ "JSON Schema 'type' must be a string for this backend. Type arrays are unsupported; "
+ "express unions, including null, with 'anyOf' branches."
+)
+
@dataclass(frozen=True)
class GrammarSpec:
diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.py
index 698e780cd..0818992cc 100644
--- a/packages/sie_server/tests/adapters/test_sglang_generation.py
+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py
@@ -21,6 +21,7 @@ from pathlib import Path
from typing import Any, Self
from unittest.mock import AsyncMock, MagicMock, patch
+import httpx
import pytest
from sie_server.adapters._generation_base import (
GenerationChunk,
@@ -38,9 +39,11 @@ from sie_server.adapters.sglang.generation import (
_mamba_scheduler_strategy_value,
_p_unsafe_from_verdict_logprobs,
_parse_sglang_generate_response,
+ _raise_for_sglang_event_error,
+ _raise_for_sglang_http_error,
_thresholded_verdict,
)
-from sie_server.types.grammar import GrammarSpec
+from sie_server.types.grammar import OUTLINES_JSON_SCHEMA_TYPE_MESSAGE, GrammarSpec
from sie_server.types.inputs import InvalidMediaError
@@ -500,7 +503,9 @@ def test_generate_n_gt_one_fans_out_into_candidates(mock_async_client: MagicMock
resp.json = MagicMock(return_value=sglang_results)
resp.raise_for_status = MagicMock()
client_instance = _make_client_with_stream(_FakeStreamingResponse([]))
- client_instance.post = AsyncMock(return_value=resp)
+ resp.aread = AsyncMock()
+ resp.__aenter__ = AsyncMock(return_value=resp)
+ client_instance.stream.return_value = resp
mock_async_client.return_value = client_instance
adapter._server_url = "http://localhost:30005"
@@ -524,7 +529,7 @@ def test_generate_n_gt_one_fans_out_into_candidates(mock_async_client: MagicMock
assert term.prompt_tokens == 4
assert term.completion_tokens == 25
# The request asked SGLang for n candidates, non-streaming.
- body = client_instance.post.call_args.kwargs["json"]
+ body = client_instance.stream.call_args.kwargs["json"]
assert body["sampling_params"]["n"] == 2
assert body["stream"] is False
@@ -680,7 +685,9 @@ def test_generate_best_of_ranks_by_logprob_and_trims(mock_async_client: MagicMoc
resp.json = MagicMock(return_value=sglang_results)
resp.raise_for_status = MagicMock()
client_instance = _make_client_with_stream(_FakeStreamingResponse([]))
- client_instance.post = AsyncMock(return_value=resp)
+ resp.aread = AsyncMock()
+ resp.__aenter__ = AsyncMock(return_value=resp)
+ client_instance.stream.return_value = resp
mock_async_client.return_value = client_instance
adapter._server_url = "http://localhost:30005"
@@ -695,7 +702,7 @@ def test_generate_best_of_ranks_by_logprob_and_trims(mock_async_client: MagicMoc
assert term.candidates is not None
assert len(term.candidates) == 1 # trimmed to n
assert term.candidates[0]["text"] == " best" # highest cumulative logprob (-0.2)
- body = client_instance.post.call_args.kwargs["json"]
+ body = client_instance.stream.call_args.kwargs["json"]
assert body["sampling_params"]["n"] == 3 # over-generated best_of
assert body["return_logprob"] is True # ranking needs logprobs
@@ -1845,7 +1852,9 @@ def test_generate_n_gt_one_non_streaming_emits_per_candidate_logprobs(mock_async
resp.json = MagicMock(return_value=sglang_results)
resp.raise_for_status = MagicMock()
client_instance = _make_client_with_stream(_FakeStreamingResponse([]))
- client_instance.post = AsyncMock(return_value=resp)
+ resp.aread = AsyncMock()
+ resp.__aenter__ = AsyncMock(return_value=resp)
+ client_instance.stream.return_value = resp
mock_async_client.return_value = client_instance
adapter._server_url = "http://localhost:30005"
@@ -1900,7 +1909,9 @@ def test_generate_n_gt_one_non_streaming_omits_logprobs_when_not_requested(
resp.json = MagicMock(return_value=sglang_results)
resp.raise_for_status = MagicMock()
client_instance = _make_client_with_stream(_FakeStreamingResponse([]))
- client_instance.post = AsyncMock(return_value=resp)
+ resp.aread = AsyncMock()
+ resp.__aenter__ = AsyncMock(return_value=resp)
+ client_instance.stream.return_value = resp
mock_async_client.return_value = client_instance
adapter._server_url = "http://localhost:30005"
@@ -2375,7 +2386,10 @@ def test_backend_grammar_abort_never_emits_placeholder_or_usage(
{"text": "valid", "meta_info": {"finish_reason": {"type": "stop"}}},
abort,
]
- client.post = AsyncMock(return_value=response)
+ response.aread = AsyncMock()
+ response.__aenter__ = AsyncMock(return_value=response)
+ if not stream:
+ client.stream.return_value = response
mock_async_client.return_value = client
adapter._server_url = "http://localhost:30005"
chunks = []
@@ -2477,7 +2491,9 @@ def test_buffered_candidates_require_exact_count_before_ranking(
{"text": "value", "meta_info": {"finish_reason": {"type": "stop"}}} for _ in range(count)
]
client = _make_client_with_stream(_FakeStreamingResponse([]))
- client.post = AsyncMock(return_value=response)
+ response.aread = AsyncMock()
+ response.__aenter__ = AsyncMock(return_value=response)
+ client.stream.return_value = response
mock_async_client.return_value = client
adapter._server_url = "http://localhost:30005"
chunks = []
@@ -2637,3 +2653,167 @@ def test_guard_first_sampled_verdict_requires_complete_evidence() -> None:
assert _p_unsafe_from_verdict_logprobs((incomplete_yes, later_safe)) is None
missing_sampled = {"token": "Yes", "top_logprobs": [_lp("Yes", -0.1), _lp("No", -3)]}
assert _p_unsafe_from_verdict_logprobs((missing_sampled, later_safe)) is None
+
+
+_TYPE_DIAGNOSTIC = "Failed to compile json grammar: 'type' must be a string"
+_TYPE_GRAMMAR = GrammarSpec(kind="json_schema", value={"type": ["string", "null"]})
+
+
+ ("n", "stream", "best_of"), [(1, False, None), (1, True, None), (2, True, None), (2, False, None), (1, False, 2)]
+)
[email protected]("transport", ["http", "abort"])
+async def test_outlines_type_refusal_across_generate_paths(adapter, n, stream, best_of, transport) -> None:
+ abort = {
+ "text": "[]",
+ "meta_info": {
+ "prompt_tokens": 1,
+ "completion_tokens": 1,
+ "finish_reason": {"type": "abort", "status_code": 400, "message": _TYPE_DIAGNOSTIC},
+ },
+ }
+
+ def respond(request: httpx.Request) -> httpx.Response:
+ body = json.loads(request.content)
+ if transport == "http":
+ return httpx.Response(400, json={"error": {"message": _TYPE_DIAGNOSTIC}})
+ if body["stream"]:
+ return httpx.Response(200, text="data: " + json.dumps(abort) + "\n\n")
+ return httpx.Response(200, json=[abort] * body["sampling_params"]["n"])
+
+ chunks = []
+ async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client:
+ adapter._http_client = client
+ adapter._server_url = "http://localhost:30005"
+ with pytest.raises(GenerationInvalidRequestError) as error:
+ async for chunk in adapter.generate(
+ prompt="Optional value", max_new_tokens=8, n=n, stream=stream, best_of=best_of, grammar=_TYPE_GRAMMAR
+ ):
+ chunks.append(chunk)
+ assert error.value.code == "invalid_request"
+ assert error.value.param == "grammar"
+ assert str(error.value) == OUTLINES_JSON_SCHEMA_TYPE_MESSAGE
+ assert chunks == []
+
+
+ ("backend", "grammar", "status", "message"),
+ [
+ ("xgrammar", _TYPE_GRAMMAR, 400, _TYPE_DIAGNOSTIC),
+ (None, _TYPE_GRAMMAR, 400, _TYPE_DIAGNOSTIC),
+ ("outlines", None, 400, _TYPE_DIAGNOSTIC),
+ ("outlines", GrammarSpec(kind="regex", value=".*"), 400, _TYPE_DIAGNOSTIC),
+ ("outlines", _TYPE_GRAMMAR, 500, _TYPE_DIAGNOSTIC),
+ ("outlines", _TYPE_GRAMMAR, 400.0, _TYPE_DIAGNOSTIC),
+ ("outlines", _TYPE_GRAMMAR, "400", _TYPE_DIAGNOSTIC),
+ ("outlines", _TYPE_GRAMMAR, 400, _TYPE_DIAGNOSTIC + " secret"),
+ ("outlines", _TYPE_GRAMMAR, 400, "secret " + _TYPE_DIAGNOSTIC),
+ ("outlines", _TYPE_GRAMMAR, 400, [_TYPE_DIAGNOSTIC]),
+ ("outlines", _TYPE_GRAMMAR, 400, "x" * 8192),
+ ],
+)
+def test_abort_type_refusal_requires_exact_diagnostic_and_context(backend, grammar, status, message) -> None:
+ event = {"meta_info": {"finish_reason": {"type": "abort", "status_code": status, "message": message}}}
+ with pytest.raises(GenerationError) as error:
+ _raise_for_sglang_event_error(event, grammar=grammar, grammar_backend=backend)
+ assert str(error.value) != OUTLINES_JSON_SCHEMA_TYPE_MESSAGE
+ assert "secret" not in str(error.value)
+ assert _TYPE_DIAGNOSTIC not in str(error.value)
+
+
+def test_unqualified_in_band_error_is_not_a_type_refusal() -> None:
+ with pytest.raises(GenerationError) as error:
+ _raise_for_sglang_event_error(
+ {"error": {"message": _TYPE_DIAGNOSTIC}}, grammar=_TYPE_GRAMMAR, grammar_backend="outlines"
+ )
+ assert error.value.code == "inference_error"
+
+
+ "body",
+ [
+ b"not json",
+ b'{"detail":"Failed to compile json grammar: \'type\' must be a string"}',
+ b'{"error":{"message":"Failed to compile json grammar: \'type\' must be a string","message":"secret"}}',
+ b'{"error":{"message":"secret","message":"Failed to compile json grammar: \'type\' must be a string"}}',
+ json.dumps({"error": {"message": _TYPE_DIAGNOSTIC, "schema": "secret"}}).encode(),
+ json.dumps({"error": {"message": _TYPE_DIAGNOSTIC + " secret"}}).encode(),
+ json.dumps({"error": {"message": [_TYPE_DIAGNOSTIC]}}).encode(),
+ json.dumps({"error": {"message": _TYPE_DIAGNOSTIC}}).encode() + b" " * 4096,
+ b"[" * 2000 + b"]" * 2000,
+ ],
+)
+async def test_http_type_refusal_rejects_unknown_malformed_or_oversized_body(body) -> None:
+ response = httpx.Response(400, content=body, request=httpx.Request("POST", "http://localhost/generate"))
+ with pytest.raises(httpx.HTTPStatusError) as error:
+ await _raise_for_sglang_http_error(response, grammar=_TYPE_GRAMMAR, grammar_backend="outlines")
+ assert "secret" not in str(error.value)
+ assert _TYPE_DIAGNOSTIC not in str(error.value)
+
+
+ ("status", "backend", "grammar"),
+ [
+ (500, "outlines", _TYPE_GRAMMAR),
+ (502, "outlines", _TYPE_GRAMMAR),
+ (400, "xgrammar", _TYPE_GRAMMAR),
+ (400, "outlines", None),
+ (400, "outlines", GrammarSpec(kind="regex", value=".*")),
+ ],
+)
+async def test_http_type_refusal_requires_status_backend_and_grammar(status, backend, grammar) -> None:
+ response = httpx.Response(
+ status,
+ json={"error": {"message": _TYPE_DIAGNOSTIC}},
+ request=httpx.Request("POST", "http://localhost/generate"),
+ )
+ with pytest.raises(httpx.HTTPStatusError):
+ await _raise_for_sglang_http_error(response, grammar=grammar, grammar_backend=backend)
+
+
[email protected]("mode", ["oversized", "timeout", "cancel"])
+ ("n", "stream", "best_of"), [(1, False, None), (2, True, None), (2, False, None), (1, False, 2)]
+)
+async def test_http_error_read_is_bounded_and_closes_stream(adapter, mode, n, stream, best_of) -> None:
+ closed = asyncio.Event()
+ started = asyncio.Event()
+ reads = []
+
+ class ErrorStream(httpx.AsyncByteStream):
+ async def __aiter__(self):
+ started.set()
+ if mode == "oversized":
+ reads.append(1)
+ yield b" " * 4097
+ raise AssertionError("oversized body must not be drained")
+ await asyncio.Event().wait()
+ yield b""
+
+ async def aclose(self):
+ closed.set()
+
+ async with httpx.AsyncClient(
+ transport=httpx.MockTransport(lambda _: httpx.Response(400, stream=ErrorStream()))
+ ) as client:
+ adapter._http_client = client
+ adapter._server_url = "http://localhost:30005"
+ iterator = adapter.generate(
+ prompt="Optional value", max_new_tokens=8, grammar=_TYPE_GRAMMAR, n=n, stream=stream, best_of=best_of
+ )
+ task = asyncio.create_task(anext(iterator))
+ await started.wait()
+ if mode == "cancel":
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ else:
+ with pytest.raises(httpx.HTTPStatusError):
+ await asyncio.wait_for(task, timeout=3)
+ await iterator.aclose()
+ assert closed.is_set()
+ assert reads == ([1] if mode == "oversized" else [])
diff --git a/packages/sie_server/tests/api/test_generate.py b/packages/sie_server/tests/api/test_generate.py
index 9d0ae4159..24ad45441 100644
--- a/packages/sie_server/tests/api/test_generate.py
+++ b/packages/sie_server/tests/api/test_generate.py
@@ -24,6 +24,7 @@ from sie_server.adapters._generation_base import (
GenerationDrainingError,
GenerationError,
GenerationInputTooLongError,
+ GenerationInvalidRequestError,
GenerationUnsupportedFieldError,
)
from sie_server.adapters._spec import AdapterSpec
@@ -41,7 +42,7 @@ from sie_server.config.model import (
Tasks,
)
from sie_server.core.registry import ModelRegistry
-from sie_server.types.grammar import GrammarSpec
+from sie_server.types.grammar import OUTLINES_JSON_SCHEMA_TYPE_MESSAGE, GrammarSpec
from sie_server.types.inputs import ImageInput
_GEMMA_OPEN = "<" + "|channel" + ">" + "thought\n"
@@ -1518,6 +1519,22 @@ class TestGenerateEndpoint:
assert response.json()["detail"]["param"] == "top_k"
assert adapter.events == ["preflight"]
+ def test_backend_type_refusal_is_actual_buffered_400(self, client: TestClient, registry: MagicMock) -> None:
+ adapter = _PreflightAdapter(
+ GenerationInvalidRequestError("grammar", OUTLINES_JSON_SCHEMA_TYPE_MESSAGE), raise_during_generate=True
+ )
+ registry.get.return_value = adapter
+ response = client.post(
+ "/v1/generate/Qwen__Qwen3-4B-Instruct", json={"prompt": "Optional value", "max_new_tokens": 8}
+ )
+ assert response.status_code == 400
+ assert response.json()["detail"] == {
+ "code": "invalid_request",
+ "message": OUTLINES_JSON_SCHEMA_TYPE_MESSAGE,
+ "param": "grammar",
+ }
+ assert adapter.events == ["preflight", "generate"]
+
def test_preflight_input_too_long_is_exact_400(
self,
client: TestClient,
diff --git a/packages/sie_server/tests/processors/test_grammar_compile.py b/packages/sie_server/tests/processors/test_grammar_compile.py
index 1794e0c6a..d99f934f1 100644
--- a/packages/sie_server/tests/processors/test_grammar_compile.py
+++ b/packages/sie_server/tests/processors/test_grammar_compile.py
@@ -12,7 +12,7 @@ from typing import Any, ClassVar
import pytest
from sie_server.processors import grammar_compile
-from sie_server.types.grammar import GrammarSpec, GrammarValidationError
+from sie_server.types.grammar import OUTLINES_JSON_SCHEMA_TYPE_MESSAGE, GrammarSpec, GrammarValidationError
class _V5Tokenizer:
@@ -283,3 +283,66 @@ def test_already_adapted_tokenizer_passes_through(
assert out is True
_, tok_arg = regex_calls[0]
assert tok_arg is adapted
+
+
[email protected]("type_value", [["string", "null"], {}, None, 1, True])
+def test_compile_known_nonstring_type_diagnostic_is_client_refusal(monkeypatch, type_value) -> None:
+ def reject(*_):
+ raise ValueError("'type' must be a string")
+
+ monkeypatch.setattr(grammar_compile, "_FACTORIES", (reject, reject))
+ with pytest.raises(GrammarValidationError) as error:
+ grammar_compile.compile_outlines(
+ _AdaptedTokenizer(), GrammarSpec(kind="json_schema", value={"type": type_value})
+ )
+ assert error.value.code == "invalid_request"
+ assert error.value.param == "grammar"
+ assert str(error.value) == OUTLINES_JSON_SCHEMA_TYPE_MESSAGE
+
+
[email protected]("kind", ["json_schema", "regex"])
+ "failure",
+ [
+ ValueError("'type' must be a string secret"),
+ ValueError("secret 'type' must be a string"),
+ ValueError("secret" * 4096),
+ RuntimeError("'type' must be a string"),
+ ],
+)
+def test_compile_unknown_diagnostic_is_sanitized(monkeypatch, kind, failure) -> None:
+ def reject(*_):
+ raise failure
+
+ monkeypatch.setattr(grammar_compile, "_FACTORIES", (reject, reject))
+ grammar = GrammarSpec(kind=kind, value={} if kind == "json_schema" else ".*")
+ with pytest.raises(GrammarValidationError) as error:
+ grammar_compile.compile_outlines(_AdaptedTokenizer(), grammar)
+ assert error.value.code == "grammar_compile_failed"
+ assert str(error.value) == "outlines compile failed"
+
+
+def test_regex_diagnostic_does_not_gain_json_schema_refusal(monkeypatch) -> None:
+ def reject(*_):
+ raise ValueError("'type' must be a string")
+
+ monkeypatch.setattr(grammar_compile, "_FACTORIES", (reject, reject))
+ with pytest.raises(GrammarValidationError) as error:
+ grammar_compile.compile_outlines(_AdaptedTokenizer(), GrammarSpec(kind="regex", value=".*"))
+ assert error.value.code == "grammar_compile_failed"
+
+
+ "schema",
+ [
+ {"type": "string"},
+ {"type": "null"},
+ {"anyOf": [{"type": "string"}, {"type": "null"}]},
+ {"type": ["string", "null"]},
+ ],
+)
+def test_compile_does_not_reject_or_rewrite_schema_shapes(monkeypatch, schema) -> None:
+ json_calls = []
+ _install_stubs(monkeypatch, json_calls=json_calls, regex_calls=[])
+ assert grammar_compile.compile_outlines(_StubTokenizer(), GrammarSpec(kind="json_schema", value=schema)) is True
+ assert json_calls[0][0] == grammar_compile.json.dumps(schema, sort_keys=True)
diff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.py
index 341191db2..f0dfd0376 100644
--- a/packages/sie_server/tests/processors/test_streaming.py
+++ b/packages/sie_server/tests/processors/test_streaming.py
@@ -29,6 +29,7 @@ from sie_server.adapters._generation_base import (
GenerationChunk,
GenerationError,
GenerationInputTooLongError,
+ GenerationInvalidRequestError,
GenerationUnsupportedFieldError,
)
from sie_server.adapters._spec import AdapterSpec
@@ -38,7 +39,7 @@ from sie_server.config.model import ModelConfig
from sie_server.observability import worker_telemetry as worker_metrics
from sie_server.processors import streaming as streaming_mod
from sie_server.processors.streaming import StreamingProcessor, _ValidationError
-from sie_server.types.grammar import GrammarSpec
+from sie_server.types.grammar import OUTLINES_JSON_SCHEMA_TYPE_MESSAGE, GrammarSpec, GrammarValidationError
_GEMMA_OPEN = "<" + "|channel" + ">" + "thought\n"
_GEMMA_CLOSE = "<" + "channel|" + ">"
@@ -4084,3 +4085,90 @@ async def test_native_raw_prompt_is_preserved_with_served_template_settings(
assert adapter.dispatched_parameters is not None
assert adapter.dispatched_parameters["prompt"] == prompt
render.assert_not_called()
+
+
+async def test_known_type_refusal_is_identical_for_preflight_leader_and_follower(monkeypatch) -> None:
+ loop = asyncio.get_running_loop()
+ started = asyncio.Event()
+ following = asyncio.Event()
+ release = threading.Event()
+ real_wait_for = streaming_mod._wait_for
+
+ def reject(_tok, _grammar):
+ loop.call_soon_threadsafe(started.set)
+ if not release.wait(timeout=5):
+ raise AssertionError("compile was not released")
+ raise GrammarValidationError(OUTLINES_JSON_SCHEMA_TYPE_MESSAGE, code="invalid_request", param="grammar")
+
+ calls = _patch_compile(monkeypatch, reject)
+ registry = _make_registry(_FakeGenAdapter([]))
+ registry.get_config.side_effect = KeyError("no config")
+ nc = AsyncMock()
+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")
+ grammar = GrammarSpec(kind="json_schema", value={"type": ["string", "null"]})
+ messages = [_make_msg(_make_work_item()) for _ in range(2)]
+
+ def wait_for(awaitable, *, timeout):
+ if any(awaitable is future for future in proc._grammar_inflight.values()):
+ following.set()
+ return real_wait_for(awaitable, timeout=timeout)
+
+ monkeypatch.setattr(streaming_mod, "_wait_for", wait_for)
+
+ async def run(index):
+ return await proc._ensure_grammar_ready(
+ grammar,
+ model_id="test/model",
+ reply_subject="_INBOX.test",
+ request_id=f"req-{index}",
+ attempt_id=f"att-{index}",
+ msg=messages[index],
+ )
+
+ leader = asyncio.create_task(run(0))
+ try:
+ await asyncio.wait_for(started.wait(), timeout=3)
+ follower = asyncio.create_task(run(1))
+ await asyncio.wait_for(following.wait(), timeout=3)
+ finally:
+ release.set()
+ assert await asyncio.gather(leader, follower) == [False, False]
+ assert len(calls) == 1
+ terminals = [msgpack.unpackb(call.args[1], raw=False) for call in nc.publish.call_args_list]
+ assert len(terminals) == 2
+ for index, terminal in enumerate(terminals):
+ assert terminal["error"] == {"code": "invalid_request", "message": OUTLINES_JSON_SCHEMA_TYPE_MESSAGE}
+ assert terminal["request_id"] == f"req-{index}"
+ assert terminal["attempt_id"] == f"att-{index}"
+ assert terminal["finish_reason"] == "error"
+ assert terminal.get("prompt_tokens") is None
+ assert terminal.get("completion_tokens") is None
+ messages[index].ack.assert_awaited_once()
+ messages[index].nak.assert_not_awaited()
+ assert proc._grammar_inflight == {}
+
+
+async def test_backend_type_refusal_survives_worker_terminal_and_settlement(monkeypatch) -> None:
+ nc = AsyncMock()
+ adapter = _PreflightGenAdapter(
+ GenerationInvalidRequestError("grammar", OUTLINES_JSON_SCHEMA_TYPE_MESSAGE), raise_during_generate=True
+ )
+ registry = _make_registry(adapter)
+ registry.get_config.return_value = _make_generation_config()
+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")
+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))
+ message = _make_msg(_make_work_item())
+ await proc.process(message, "test/model")
+ terminal = _decode_chunks(nc)[-1]
+ assert terminal["error"] == {
+ "code": "invalid_request",
+ "message": OUTLINES_JSON_SCHEMA_TYPE_MESSAGE,
+ "param": "grammar",
+ }
+ assert terminal["finish_reason"] == "error"
+ assert terminal.get("prompt_tokens") is None
+ assert terminal.get("completion_tokens") is None
+ message.ack.assert_awaited_once()
+ assert adapter.close_calls == 1