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(generation): verify strict structured output and serve grammars on grammar-safe profiles (#399)

Krisztian Gajdar5e2ae504b031
diff --git a/packages/sie_gateway/src/handlers/grammar.rs b/packages/sie_gateway/src/handlers/grammar.rs
index a96522497..33bbf8ad6 100644
--- a/packages/sie_gateway/src/handlers/grammar.rs
+++ b/packages/sie_gateway/src/handlers/grammar.rs
@@ -12,6 +12,8 @@
//! * JSON Schema reject-list (``$dynamicRef``, ``if/then/else``,
//! ``unevaluatedProperties``, ``dependentSchemas``)
//! * Mutual exclusivity of ``json_schema`` and ``regex``
+//! * ``strict: true`` only on ``json_schema`` and ``regex`` grammars, whose
+//! finished output the worker verifies
//!
//! All failures return a 400 :class:`Response` carrying the OpenAI
//! error envelope with ``code`` (``grammar_invalid`` |
@@ -293,6 +295,13 @@ pub fn parse_grammar(v: &Value) -> GrammarParseResult {
oai_code::INVALID_REQUEST,
));
}
+ if strict == Some(true) {
+ return GrammarParseResult::Err(bad_request(
+ "'grammar.strict' is not supported for EBNF grammars".to_string(),
+ "grammar.strict",
+ oai_code::UNSUPPORTED_FIELD,
+ ));
+ }
GrammarParseResult::Ok(GrammarSpec::Ebnf {
value: ebnf.to_string(),
label,
@@ -1178,6 +1187,20 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn test_parse_grammar_rejects_strict_ebnf() {
+ let v = json!({"ebnf": "root ::= \"yes\" | \"no\"", "strict": true});
+ let body = err_or_panic(parse_grammar(&v)).await;
+ assert_eq!(body["error"]["param"], "grammar.strict");
+ assert_eq!(body["error"]["code"], "unsupported_field");
+
+ let v = json!({"ebnf": "root ::= \"yes\" | \"no\"", "strict": false});
+ match ok_or_panic(parse_grammar(&v)) {
+ GrammarSpec::Ebnf { strict, .. } => assert_eq!(strict, Some(false)),
+ other => panic!("expected Ebnf, got {other:?}"),
+ }
+ }
+
// ── capability gate ────────────────────────────────────────────
#[tokio::test]
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index d44929605..f1448aa5f 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -1947,7 +1947,19 @@ async fn resolve_routing(
let mut dispatch_model = model_name.clone();
if generation_intent == Some(GenerationRequestIntent::Grammar) {
- route_grammar_to_profile(&state.model_registry, &mut dispatch_model);
+ if let Err(unavailable) =
+ route_grammar_to_profile(&state.model_registry, &mut dispatch_model)
+ {
+ return Err(Box::new(endpoint_error_response(
+ endpoint,
+ StatusCode::BAD_REQUEST,
+ err_code::INVALID_REQUEST,
+ oai_type::INVALID_REQUEST,
+ oai_code::UNSUPPORTED_FIELD,
+ Some("grammar"),
+ unavailable.message(&model),
+ )));
+ }
}
// #3441 ordering: a model this data plane does not have is answered by the
// populated-registry `MODEL_NOT_FOUND` 404 BEFORE the governed lookup runs.
@@ -6965,9 +6977,11 @@ async fn resolve_generation_route(
/// dispatched profile does not serve. The rewritten (DISPATCH) id governs only
/// the NATS subject + work item; the caller keeps the requested (DISPLAY) id for
/// the response body, success metrics, and audit log. Invoke ONLY when a grammar
-/// is present. Degrades to the requested id when no profile is declared or the
-/// variant is absent (the cluster still serves on the requested profile — never
-/// hang/5xx).
+/// is present. Keeps the requested id when no profile is declared. A declared
+/// grammar profile whose variant is absent from the registry returns
+/// [`GrammarProfileUnavailable`]: serving the grammar on the requested profile
+/// would bypass the grammar backend, so callers reject the request with
+/// ``400 unsupported_field`` instead.
///
/// Both grammar-capable surfaces (``/v1/generate`` and ``/v1/chat/completions``)
/// now route *before* their capability/LoRA gates so those validate against the
@@ -6983,7 +6997,7 @@ async fn resolve_generation_route(
pub fn route_grammar_to_profile(
registry: &crate::state::model_registry::ModelRegistry,
model: &mut String,
-) {
+) -> Result<(), GrammarProfileUnavailable> {
use crate::state::model_registry::GrammarRoute;
match registry.grammar_route_variant(model) {
GrammarRoute::Rewrite(variant) => {
@@ -6993,18 +7007,36 @@ pub fn route_grammar_to_profile(
"routing grammar-constrained request to non-speculative profile variant"
);
*model = variant;
+ Ok(())
}
- GrammarRoute::Keep => {}
+ GrammarRoute::Keep => Ok(()),
GrammarRoute::MissingVariant(grammar_profile) => {
- tracing::warn!(
+ tracing::error!(
base = %model,
grammar_profile = %grammar_profile,
- "declared grammar_profile variant not in registry; serving grammar on the requested profile"
+ "declared grammar_profile variant not in registry; rejecting grammar-constrained request"
);
+ Err(GrammarProfileUnavailable { grammar_profile })
}
}
}
+/// A model routes grammar-constrained requests to a profile variant that the
+/// registry does not hold.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct GrammarProfileUnavailable {
+ pub grammar_profile: String,
+}
+
+impl GrammarProfileUnavailable {
+ fn message(&self, display_model: &str) -> String {
+ format!(
+ "grammar-constrained generation for model '{display_model}' requires profile '{}', which is not served",
+ self.grammar_profile
+ )
+ }
+}
+
#[utoipa::path(
post,
path = "/v1/chat/completions",
@@ -7136,7 +7168,20 @@ async fn proxy_chat_inner(
// grammar is present and a variant exists. See ``route_grammar_to_profile``.
let mut dispatch_model = model_name.clone();
if params.grammar.is_some() {
- route_grammar_to_profile(&state.model_registry, &mut dispatch_model);
+ if let Err(unavailable) =
+ route_grammar_to_profile(&state.model_registry, &mut dispatch_model)
+ {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(json_openai_error(
+ unavailable.message(&model_name),
+ oai_type::INVALID_REQUEST,
+ Some("response_format"),
+ oai_code::UNSUPPORTED_FIELD,
+ )),
+ )
+ .into_response();
+ }
}
// -- per-request max_output_tokens cap from model config + grammar capability.
@@ -21392,7 +21437,7 @@ mod tests {
) -> (String, String) {
let display = requested.to_string();
let mut dispatch = display.clone();
- route_grammar_to_profile(registry, &mut dispatch);
+ route_grammar_to_profile(registry, &mut dispatch).expect("grammar route resolves");
(display, dispatch)
}
@@ -21551,12 +21596,9 @@ mod tests {
));
}
- #[test]
- fn test_grammar_variant_absent_degrades_to_base() {
- // Safety contract: a declared `grammar_profile` whose variant is not in
- // the registry degrades to the base model (never hang / 5xx). Here
- // `grammar_profile: ghost` names a profile that is not defined, so no
- // `org/g3:ghost` variant entry is minted and routing keeps the base.
+ /// A model whose declared `grammar_profile: ghost` names a profile that is
+ /// not defined, so no `org/g3:ghost` variant entry is minted.
+ fn ghost_grammar_registry() -> crate::state::model_registry::ModelRegistry {
use crate::types::model::{ModelConfig, ProfileConfig};
use std::collections::HashMap as StdHashMap;
@@ -21576,8 +21618,10 @@ mod tests {
extends: None,
},
);
- let tasks: serde_yaml::Value =
- serde_yaml::from_str("generate:\n grammar_profile: ghost\n").unwrap();
+ let tasks: serde_yaml::Value = serde_yaml::from_str(
+ "generate:\n grammar_profile: ghost\n capabilities:\n grammar: [json_schema]\n",
+ )
+ .unwrap();
registry
.add_model_config(ModelConfig {
name: "org/g3".to_string(),
@@ -21591,6 +21635,15 @@ mod tests {
tasks: Some(tasks),
})
.unwrap();
+ registry
+ }
+
+ #[test]
+ fn test_grammar_variant_absent_rejects_instead_of_serving_base() {
+ // Safety contract: a declared `grammar_profile` whose variant is not in
+ // the registry is refused, because the requested profile does not
+ // honour the grammar backend.
+ let registry = ghost_grammar_registry();
// The declared (but undefined) profile is still surfaced...
assert_eq!(
@@ -21600,12 +21653,75 @@ mod tests {
.as_deref(),
Some("ghost"),
);
- // ...yet routing degrades to base because `org/g3:ghost` does not exist.
- let (display, dispatch) = route_like_handler(&registry, "org/g3");
- assert_eq!(display, "org/g3");
+ // ...and routing refuses because `org/g3:ghost` does not exist. The
+ // dispatch id is left untouched.
+ let mut dispatch = "org/g3".to_string();
+ let unavailable = route_grammar_to_profile(&registry, &mut dispatch)
+ .expect_err("a missing grammar-safe variant must not serve the grammar");
+ assert_eq!(unavailable.grammar_profile, "ghost");
assert_eq!(dispatch, "org/g3");
}
+ #[tokio::test]
+ async fn test_grammar_variant_absent_rejects_native_and_chat_requests() {
+ let pool_manager = Arc::new(PoolManager::new(vec!["l4".to_string()]));
+ pool_manager.create_default_pool().await;
+ let mut state = admission_test_state(pool_manager);
+ state.model_registry = Arc::new(ghost_grammar_registry());
+ let probe = Arc::new(GenerationTargetProbe::default());
+ state.work_publisher = Some(probe.clone());
+ let state = Arc::new(state);
+
+ let native = proxy_request(
+ State(Arc::clone(&state)),
+ json_request(
+ "/v1/generate/org%2Fg3",
+ serde_json::json!({
+ "prompt": "hello",
+ "max_new_tokens": 4,
+ "grammar": {"json_schema": {"type": "object"}}
+ }),
+ ),
+ "generate",
+ )
+ .await;
+ let chat = proxy_chat(
+ State(Arc::clone(&state)),
+ json_request(
+ "/v1/chat/completions",
+ serde_json::json!({
+ "model": "org/g3",
+ "messages": [{"role": "user", "content": "hello"}],
+ "max_tokens": 4,
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {"name": "answer", "schema": {"type": "object"}}
+ }
+ }),
+ ),
+ )
+ .await;
+
+ for (response, param) in [(native, "grammar"), (chat, "response_format")] {
+ assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{param}");
+ let body = to_bytes(response.into_body(), 16 * 1024).await.unwrap();
+ let value: Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ value["error"]["code"],
+ oai_code::UNSUPPORTED_FIELD,
+ "{param}"
+ );
+ assert_eq!(value["error"]["param"], param);
+ assert!(
+ value["error"]["message"]
+ .as_str()
+ .is_some_and(|message| message.contains("'ghost'")),
+ "{value}"
+ );
+ }
+ assert_eq!(probe.target_count(), 0);
+ }
+
// ── /v1/chat/completions parsing + body composition ────────────
fn _chat_body_min(model: &str) -> serde_json::Value {
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.md
index b4046b00b..3ef4079cb 100644
--- a/packages/sie_sdk/README.md
+++ b/packages/sie_sdk/README.md
@@ -341,7 +341,7 @@ When a batch response carries fewer items than were sent, `encode` and
items that did come back (match them by `id`), and `missing_ids` names
the dropped items when every submitted item carried an `id`.
-One generation-specific error is terminal and never retried:
+Two generation-specific errors are terminal and never retried:
- `empty_model_output` — the generation finished nominally but produced
no visible output text (for example, private reasoning consumed the
@@ -349,6 +349,15 @@ One generation-specific error is terminal and never retried:
is not re-run. Surfaces as `ServerError` with
`code == "empty_model_output"`; on streaming calls it is raised
mid-stream with the gateway request id attached for correlation.
+- `MODEL_OUTPUT_PARSE_ERROR` — a strict grammar (`grammar.strict` or
+ `response_format.json_schema.strict` set to `true`) was not satisfied:
+ the finished output of a `json_schema` grammar did not parse or
+ validate, or a `regex` grammar did not match the whole output. The
+ message names the failing JSON path and keyword. Streaming calls have
+ already received the text deltas when the error arrives on the
+ terminal event. Truncated (`length`) completions are returned
+ unverified, and `strict: true` on an `ebnf` grammar is rejected with
+ `400 unsupported_field`.
## Handling resource exhaustion
diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.json
index 708dcec7c..224e37e43 100644
--- a/packages/sie_server/openapi.json
+++ b/packages/sie_server/openapi.json
@@ -3271,6 +3271,7 @@
}
],
"default": null,
+ "description": "EBNF output cannot be verified, so true is rejected with 400 unsupported_field",
"title": "Strict"
}
},
@@ -3344,6 +3345,7 @@
}
],
"default": null,
+ "description": "When true, the finished output must parse as JSON and validate against json_schema; otherwise the request fails with MODEL_OUTPUT_PARSE_ERROR",
"title": "Strict"
}
},
@@ -3384,6 +3386,7 @@
}
],
"default": null,
+ "description": "When true, the finished output must match regex in full; otherwise the request fails with MODEL_OUTPUT_PARSE_ERROR",
"title": "Strict"
}
},
diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.toml
index 4b09b6b6d..988191589 100644
--- a/packages/sie_server/pyproject.toml
+++ b/packages/sie_server/pyproject.toml
@@ -83,6 +83,12 @@ dependencies = [
"pillow>=12.2.0",
"numpy>=2,<3",
"torchvision>=0.18,<1", # Required by some HF models (e.g., nvidia/llama-nemoretriever)
+ # Strict structured-output verification (processors/strict_grammar.py):
+ # JSON Schema validation with local-only $ref resolution, and a
+ # backtracking regex engine that supports match timeouts.
+ "jsonschema>=4.23,<5",
+ "referencing>=0.36,<1",
+ "regex>=2024.11.6",
# Config
"pyyaml>=6,<7",
"pydantic>=2.9,<3",
diff --git a/packages/sie_server/src/sie_server/adapters/mlx/generation.py b/packages/sie_server/src/sie_server/adapters/mlx/generation.py
index 576dee4d4..2b0279678 100644
--- a/packages/sie_server/src/sie_server/adapters/mlx/generation.py
+++ b/packages/sie_server/src/sie_server/adapters/mlx/generation.py
@@ -34,7 +34,7 @@ import os
import subprocess
import tempfile
import time
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Mapping
from pathlib import Path
from typing import Any, cast
@@ -87,6 +87,14 @@ _MLX_SAMPLING_KEYS: frozenset[str] = frozenset(
)
+def _reject_grammar(grammar: object) -> None:
+ if grammar is not None:
+ raise GenerationUnsupportedFieldError(
+ "grammar",
+ "structured-output grammars are not supported by the MLX generation backend",
+ )
+
+
def normalize_mlx_seed(seed: int) -> int:
"""Convert a signed i64 seed to MLX's equivalent uint64 bit pattern."""
if isinstance(seed, bool) or not isinstance(seed, int) or not -(1 << 63) <= seed <= (1 << 63) - 1:
@@ -322,6 +330,11 @@ class MLXGenerationAdapter(GenerationAdapter):
if self._server_url is None:
raise RuntimeError(ERR_NOT_LOADED)
+ def preflight_generate(self, parameters: Mapping[str, Any], *, stream: bool) -> None:
+ """Reject controls that ``mlx_lm.server`` cannot honour before dispatch."""
+ _ = stream
+ _reject_grammar(parameters.get("grammar"))
+
def _build_sampling_body(
self,
prompt: str,
@@ -385,9 +398,10 @@ class MLXGenerationAdapter(GenerationAdapter):
top_logprobs: int | None = None,
images: list[ImageInput] | None = None,
videos: list[VideoInput] | None = None,
- **kwargs: Any, # tolerate SGLang-only kwargs (grammar, n, best_of, stream, …)
+ **kwargs: Any, # tolerate SGLang-only kwargs (n, best_of, stream, …); grammar is rejected
) -> AsyncIterator[GenerationChunk]:
self._check_loaded()
+ _reject_grammar(kwargs.get("grammar"))
# Vision is deferred on the Mac MLX path (mlx-vlm would need its own
# transformers>=5.5 process — see the implementation plan §9). Fail loud
# rather than silently dropping the images and returning a wrong answer.
diff --git a/packages/sie_server/src/sie_server/api/generate.py b/packages/sie_server/src/sie_server/api/generate.py
index 1130aecd9..525c6d2ad 100644
--- a/packages/sie_server/src/sie_server/api/generate.py
+++ b/packages/sie_server/src/sie_server/api/generate.py
@@ -80,9 +80,11 @@ from sie_server.adapters._generation_base import (
)
from sie_server.api.helpers import ModelStateChecker, oom_retry_after_from_registry, read_bounded_request_body
from sie_server.api.validation import validate_machine_profile_header, validate_signed_i64
+from sie_server.core.grammar_routing import resolve_grammar_serving_model
from sie_server.core.runtime_options import apply_generation_runtime_options
from sie_server.core.tokenizer import image_first_chat_message, load_tokenizer
from sie_server.observability.tracing import tracer
+from sie_server.processors.strict_grammar import enforce_strict_grammar
from sie_server.types.grammar import GrammarSpec
from sie_server.types.inputs import ImageInput
from sie_server.types.openapi import (
@@ -589,6 +591,12 @@ def _parse_native_grammar(value: Any) -> GrammarSpec | None:
raise _bad_request(f"'grammar.{kind}' must be a string", param=f"grammar.{kind}")
if len(payload) > limit:
raise _bad_request(f"{kind} length {len(payload)} exceeds limit ({limit})", param=f"grammar.{kind}")
+ if kind == "ebnf" and strict is True:
+ raise _bad_request(
+ "'grammar.strict' is not supported for EBNF grammars",
+ param="grammar.strict",
+ code="unsupported_field",
+ )
return GrammarSpec(kind=cast("Any", kind), value=payload, label=label, strict=strict)
@@ -820,6 +828,7 @@ async def _stream_generate_events(
start_inside=thinking_starts_in_prompt,
reasoning_format=reasoning_format,
)
+ chunks = enforce_strict_grammar(chunks, grammar)
async for chunk in chunks:
if chunk.done:
saw_terminal = True
@@ -1093,16 +1102,22 @@ async def generate(
registry = http_request.app.state.registry
device = registry.device
+ serving_key = registry_key
+ if grammar is not None:
+ try:
+ serving_key = resolve_grammar_serving_model(registry, registry_key)
+ except GenerationError as exc:
+ raise _generation_http_exception(exc, registry) from exc
# Standard model-state gates: 404 if unknown, 503 if loading/unloading,
# 502 if a terminal load failure is in cooldown.
- checker = ModelStateChecker(registry, registry_key, span)
+ checker = ModelStateChecker(registry, serving_key, span)
checker.check_exists()
checker.check_not_failed()
checker.check_not_unloading()
checker.check_not_loading()
- config = registry.get_config(registry_key)
+ config = registry.get_config(serving_key)
# Enforce the gateway-side cap mirror: max_new_tokens ≤
# tasks.generate.max_output_tokens. Worker-authoritative so the
# local-dev route reports the same 400 the gateway would.
@@ -1219,8 +1234,8 @@ async def generate(
# Do not start a potentially expensive model load until the complete
# request has passed validation.
await checker.ensure_loaded(device)
- adapter = registry.get(registry_key)
- registry.touch_lru(registry_key)
+ adapter = registry.get(serving_key)
+ registry.touch_lru(serving_key)
if not isinstance(adapter, GenerationAdapter):
raise _bad_request(
f"Model '{model}' adapter does not support generate (not a GenerationAdapter)",
@@ -1307,6 +1322,7 @@ async def generate(
start_inside=thinking_starts_in_prompt,
reasoning_format=reasoning_format,
)
+ chunks = enforce_strict_grammar(chunks, grammar)
result = await collect_generation(chunks)
except GenerationError as exc:
raise _generation_http_exception(exc, registry) from exc
@@ -1364,8 +1380,9 @@ async def generate(
# ``model`` against it; echoing the path-encoded form broke that
# round-trip. ``config.name`` == ``registry_key`` (denormalized
# path param) — prefer the config value as the source of truth and
- # fall back to ``registry_key`` defensively.
- canonical_model = getattr(config, "name", None) or registry_key
+ # fall back to ``registry_key`` defensively. A grammar request served
+ # by its grammar-safe profile still reports the requested model.
+ canonical_model = registry_key if serving_key != registry_key else getattr(config, "name", None) or registry_key
return JSONResponse(
content={
"model": canonical_model,
diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.py
index f14478386..b8a9c1dfd 100644
--- a/packages/sie_server/src/sie_server/api/openai_local.py
+++ b/packages/sie_server/src/sie_server/api/openai_local.py
@@ -37,6 +37,7 @@ from fastapi.responses import JSONResponse, Response, StreamingResponse
from sie_sdk.queue_types import denormalize_model_id
from sie_server.adapters._generation_base import (
+ GenerationUnsupportedFieldError,
ReasoningFormat,
ThinkingBlockStripper,
aclose_with_error_precedence,
@@ -50,6 +51,7 @@ from sie_server.api.options import resolve_runtime_options
from sie_server.api.score import score_usage_from_output
from sie_server.api.validation import validate_machine_profile_header, validate_signed_i64
from sie_server.config.model import validate_chat_template_kwargs
+from sie_server.core.grammar_routing import resolve_grammar_serving_model
from sie_server.core.inference_output import ScoreOutput
from sie_server.core.score_cost import MAX_SCORE_ITEMS, build_score_prepared_items
from sie_server.core.timing import RequestTiming
@@ -61,6 +63,12 @@ from sie_server.core.video_frames import (
)
from sie_server.observability.tracing import tracer
from sie_server.processors.streaming import _decode_data_uri_image
+from sie_server.processors.strict_grammar import (
+ MODEL_OUTPUT_PARSE_ERROR,
+ first_output_violation,
+ unverifiable_schema_keyword,
+)
+from sie_server.types.grammar import GrammarSpec
from sie_server.types.inputs import Item, item_size_error
from sie_server.types.responses import ErrorCode
@@ -261,14 +269,19 @@ def _translated_upstream_status(upstream_status: int) -> int:
return status.HTTP_502_BAD_GATEWAY
-def _upstream_error_event(message: str = "upstream stream error") -> bytes:
+def _upstream_error_event(
+ message: str = "upstream stream error",
+ *,
+ code: str = "upstream_error",
+ error_type: str = "upstream_error",
+) -> bytes:
payload = json.dumps(
{
"error": {
"message": message,
- "type": "upstream_error",
+ "type": error_type,
"param": None,
- "code": "upstream_error",
+ "code": code,
}
},
separators=(",", ":"),
@@ -276,6 +289,55 @@ def _upstream_error_event(message: str = "upstream stream error") -> bytes:
return f"data: {payload}\n\ndata: [DONE]\n\n".encode()
+def _response_format_constrains_decoding(response_format: Any) -> bool:
+ return isinstance(response_format, dict) and response_format.get("type") not in (None, "text")
+
+
+def _strict_response_format_grammar(response_format: Any) -> GrammarSpec | None:
+ """Return the JSON Schema grammar a strict ``response_format`` requires."""
+ if not isinstance(response_format, dict) or response_format.get("type") != "json_schema":
+ return None
+ json_schema = response_format.get("json_schema")
+ if not isinstance(json_schema, dict) or json_schema.get("strict") is not True:
+ return None
+ schema = json_schema.get("schema")
+ if not isinstance(schema, dict):
+ return None
+ return GrammarSpec(kind="json_schema", value=schema, strict=True)
+
+
+async def _strict_output_violation(grammar: GrammarSpec, outputs: list[str]) -> str | None:
+ if not outputs:
+ return None
+ return await asyncio.to_thread(first_output_violation, grammar, outputs)
+
+
+def _completed_choice_contents(payload: dict[str, Any]) -> list[str]:
+ """Return the visible content of each naturally completed, non-tool choice."""
+ outputs: list[str] = []
+ choices = payload.get("choices")
+ if not isinstance(choices, list):
+ return outputs
+ for choice in choices:
+ if not isinstance(choice, dict) or choice.get("finish_reason") != "stop":
+ continue
+ message = choice.get("message")
+ if not isinstance(message, dict) or message.get("tool_calls"):
+ continue
+ content = message.get("content")
+ outputs.append(content if isinstance(content, str) else "")
+ return outputs
+
+
+def _strict_output_error_response(message: str) -> JSONResponse:
+ return openai_error_response(
+ HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail={"code": MODEL_OUTPUT_PARSE_ERROR, "message": message},
+ )
+ )
+
+
def _validate_optional_positive_int(body: dict[str, Any], field: str) -> int | None:
value = body.get(field)
if value is None:
@@ -761,8 +823,11 @@ async def _sanitize_sse_stream(
initial_inside_thinking: bool,
reasoning_format: ReasoningFormat,
slot: asyncio.Semaphore | None,
+ strict_grammar: GrammarSpec | None = None,
) -> AsyncIterator[bytes]:
states: dict[int, ThinkingBlockStripper] = {}
+ strict_contents: dict[int, list[str]] = {}
+ strict_tool_choices: set[int] = set()
buffered = bytearray()
received = 0
saw_done = False
@@ -804,6 +869,21 @@ async def _sanitize_sse_stream(
states=states,
terminal=False,
)
+ if strict_grammar is not None:
+ violation = await _stream_strict_violation(
+ sanitized,
+ strict_grammar,
+ contents=strict_contents,
+ tool_choices=strict_tool_choices,
+ )
+ if violation is not None:
+ terminal_outcome_selected = True
+ yield _upstream_error_event(
+ violation,
+ code=MODEL_OUTPUT_PARSE_ERROR,
+ error_type="server_error",
+ )
+ return
encoded = json.dumps(sanitized, separators=(",", ":"), ensure_ascii=False).encode()
yield b"data: " + encoded + b"\n"
@@ -843,6 +923,36 @@ async def _sanitize_sse_stream(
slot.release()
+async def _stream_strict_violation(
+ payload: dict[str, Any],
+ grammar: GrammarSpec,
+ *,
+ contents: dict[int, list[str]],
+ tool_choices: set[int],
+) -> str | None:
+ """Accumulate streamed choice content and verify each choice that stops."""
+ choices = payload.get("choices")
+ if not isinstance(choices, list):
+ return None
+ completed: list[str] = []
+ for position, choice in enumerate(choices):
+ if not isinstance(choice, dict):
+ continue
+ choice_obj = cast("dict[str, Any]", choice)
+ raw_index = choice_obj.get("index", position)
+ index = raw_index if isinstance(raw_index, int) and not isinstance(raw_index, bool) else position
+ delta = choice_obj.get("delta")
+ if isinstance(delta, dict):
+ content = delta.get("content")
+ if isinstance(content, str) and content:
+ contents.setdefault(index, []).append(content)
+ if delta.get("tool_calls"):
+ tool_choices.add(index)
+ if choice_obj.get("finish_reason") == "stop" and index not in tool_choices:
+ completed.append("".join(contents.get(index, ())))
+ return await _strict_output_violation(grammar, completed)
+
+
# -- /v1/chat/completions (proxy to the managed generation child) ------------
@@ -906,6 +1016,18 @@ async def _chat_completions(
registry = http_request.app.state.registry
device = registry.device
registry_key = denormalize_model_id(model)
+ if _response_format_constrains_decoding(body.get("response_format")):
+ try:
+ registry_key = resolve_grammar_serving_model(registry, registry_key)
+ except GenerationUnsupportedFieldError as exc:
+ raise _bad_request(str(exc), param="response_format", code="unsupported_field") from exc
+ strict_grammar = _strict_response_format_grammar(body.get("response_format"))
+ if strict_grammar is not None and (keyword := unverifiable_schema_keyword(strict_grammar.value)) is not None:
+ raise _bad_request(
+ f"'{keyword}' is not supported in a strict response_format schema",
+ param="response_format",
+ code="unsupported_field",
+ )
with tracer.start_as_current_span("chat_completions") as span:
span.set_attribute("model", model)
@@ -1054,6 +1176,7 @@ async def _chat_completions(
initial_inside_thinking=initial_inside_thinking,
reasoning_format=reasoning_format,
slot=slot,
+ strict_grammar=strict_grammar,
),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
@@ -1094,6 +1217,10 @@ async def _chat_completions(
except (ValueError, TypeError, json.JSONDecodeError):
logger.warning("generation child returned an invalid chat response", exc_info=True)
return _upstream_error_response("generation child returned an invalid response")
+ if strict_grammar is not None:
+ violation = await _strict_output_violation(strict_grammar, _completed_choice_contents(payload))
+ if violation is not None:
+ return _strict_output_error_response(violation)
return JSONResponse(content=payload)
diff --git a/packages/sie_server/src/sie_server/core/grammar_routing.py b/packages/sie_server/src/sie_server/core/grammar_routing.py
new file mode 100644
index 000000000..e2087b1b8
--- /dev/null
+++ b/packages/sie_server/src/sie_server/core/grammar_routing.py
@@ -0,0 +1,172 @@
+"""Grammar-profile admission shared by every worker generation ingress.
+
+A model may declare ``tasks.generate.grammar_profile``, and a profile may
+declare a profile-scoped ``grammar_profile``, naming the sibling profile that
+honours decode-time grammar enforcement. Speculative decoding bypasses the
+grammar backend, so a grammar-constrained request must run on that sibling.
+
+The gateway rewrites the dispatch model before queue publication. The direct
+HTTP routes and the queue worker resolve the same rewrite here, so a
+constrained request runs on a grammar-safe profile whichever ingress it used.
+The rules mirror the gateway's ``ModelRegistry::grammar_route_variant``:
+
+- a model without a declared grammar profile keeps its id;
+- a default profile that is already grammar compatible keeps its id;
+- a request that names the grammar-safe variant keeps its id;
+- a variant that directly extends the grammar profile and is grammar
+ compatible keeps its id;
+- otherwise the request moves to ``{base}:{grammar_profile}``, and fails with
+ ``unsupported_field`` when that variant is not served.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Mapping
+from typing import Any, Protocol
+
+from sie_server.adapters._generation_base import GenerationUnsupportedFieldError
+
+logger = logging.getLogger(__name__)
+
+_RAW_SPECULATIVE_FLAGS = frozenset({"--enable-multi-layer-eagle", "--config"})
+_GRAMMAR_SAFE_EXTRA_LAUNCH_ARGS = ("--quantization", "fp8")
+
+
+class ModelConfigSource(Protocol):
+ def has_model(self, name: str) -> bool: ...
+
+ def get_config(self, name: str) -> Any: ...
+
+
+def resolve_grammar_serving_model(registry: ModelConfigSource, model_id: str) -> str:
+ """Return the registered model id that serves a grammar-constrained request.
+
+ Call only when the request carries a grammar. An unknown ``model_id`` is
+ returned unchanged so the caller's own not-found handling applies.
+
+ Raises:
+ GenerationUnsupportedFieldError: The model routes grammar requests to a
+ profile that this worker does not serve.
+ """
+ target = _grammar_target(registry, model_id)
+ if target is None:
+ return model_id
+ base_id, grammar_profile = target
+ if model_id == base_id and _profile_is_grammar_compatible(registry.get_config(base_id), "default", grammar_profile):
+ return model_id
+ target_id = f"{base_id}:{grammar_profile}"
+ if model_id == target_id:
+ return model_id
+ if registry.has_model(target_id):
+ return target_id
+ logger.error(
+ "model %s routes grammar-constrained generation to %s, which is not served; rejecting the request",
+ model_id,
+ target_id,
+ )
+ raise GenerationUnsupportedFieldError(
+ "grammar",
+ f"grammar-constrained generation for model '{model_id}' requires profile "
+ f"'{grammar_profile}', which is not served",
+ )
+
+
+def _grammar_target(registry: ModelConfigSource, model_id: str) -> tuple[str, str] | None:
+ if not registry.has_model(model_id):
+ return None
+ config = registry.get_config(model_id)
+ source = getattr(config, "synthetic_profile_variant_source", None)
+ if not isinstance(source, tuple):
+ grammar_profile = _model_grammar_profile(config)
+ return None if grammar_profile is None else (model_id, grammar_profile)
+ base_id, source_profile = source
+ if not registry.has_model(base_id):
+ return _variant_only_target(config, base_id, source_profile)
+ base = registry.get_config(base_id)
+ profiles: Mapping[str, Any] = base.profiles
+ if any(profile.grammar_profile == source_profile for profile in profiles.values()):
+ return base_id, source_profile
+ source_config = profiles.get(source_profile)
+ if source_config is None:
+ return None
+ if source_config.grammar_profile is not None:
+ return base_id, source_config.grammar_profile
+ grammar_profile = _model_grammar_profile(base)
+ if grammar_profile is None:
+ return None
+ if source_config.extends == grammar_profile and _profile_is_grammar_compatible(
+ base, source_profile, grammar_profile
+ ):
+ return base_id, source_profile
+ return base_id, grammar_profile
+
+
+def _variant_only_target(config: Any, base_id: str, source_profile: str) -> tuple[str, str] | None:
+ """Resolve a variant whose base model is not registered on this worker.
+
+ Without sibling profiles only the variant's own resolved launch shape is
+ available, so an explicitly non-speculative variant is kept and any other
+ variant routes to its declared grammar profile.
+ """
+ own_profile = config.profiles.get("default")
+ scoped = getattr(own_profile, "grammar_profile", None)
+ if isinstance(scoped, str):
+ return base_id, scoped
+ grammar_profile = _model_grammar_profile(config)
+ if grammar_profile is None:
+ return None
+ if _explicitly_disables_speculation(config.resolve_profile("default")):
+ return base_id, source_profile
+ return base_id, grammar_profile
+
+
+def _model_grammar_profile(config: Any) -> str | None:
+ generate = getattr(getattr(config, "tasks", None), "generate", None)
+ grammar_profile = getattr(generate, "grammar_profile", None)
+ return grammar_profile if isinstance(grammar_profile, str) else None
+
+
+def _profile_is_grammar_compatible(config: Any, profile: str, grammar_profile: str) -> bool:
+ try:
+ candidate = config.resolve_profile(profile)
+ grammar = config.resolve_profile(grammar_profile)
+ except ValueError:
+ return False
+ return (
+ candidate.adapter_path == grammar.adapter_path
+ and _explicitly_disables_speculation(candidate)
+ and candidate.loadtime.get("grammar_backend") == grammar.loadtime.get("grammar_backend")
+ and _extra_launch_args_are_compatible(candidate.loadtime, grammar.loadtime)
+ )
+
+
+def _explicitly_disables_speculation(profile: Any) -> bool:
+ speculative = profile.loadtime.get("speculative")
+ return (
+ isinstance(speculative, Mapping)
+ and speculative.get("enabled") is False
+ and _has_no_raw_speculative_overrides(profile.loadtime)
+ )
+
+
+def _has_no_raw_speculative_overrides(loadtime: Mapping[str, Any]) -> bool:
+ args = loadtime.get("extra_launch_args")
+ if args is None:
+ return True
+ if not isinstance(args, list | tuple):
+ return False
+ for arg in args:
+ if not isinstance(arg, str):
+ return False
+ flag = arg.split("=", 1)[0]
+ if flag.startswith("--speculative-") or flag in _RAW_SPECULATIVE_FLAGS:
+ return False
+ return True
+
+
+def _extra_launch_args_are_compatible(candidate: Mapping[str, Any], grammar: Mapping[str, Any]) -> bool:
+ candidate_args = candidate.get("extra_launch_args")
+ if candidate_args == grammar.get("extra_launch_args"):
+ return True
+ return isinstance(candidate_args, list | tuple) and tuple(candidate_args) == _GRAMMAR_SAFE_EXTRA_LAUNCH_ARGS
diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.py
index ebf993c2e..7bde90200 100644
--- a/packages/sie_server/src/sie_server/processors/streaming.py
+++ b/packages/sie_server/src/sie_server/processors/streaming.py
@@ -71,6 +71,7 @@ from sie_server.adapters._generation_base import (
)
from sie_server.api.helpers import oom_retry_after_from_registry
from sie_server.config.model import validate_chat_template_kwargs
+from sie_server.core.grammar_routing import resolve_grammar_serving_model
from sie_server.core.runtime_options import apply_generation_runtime_options
from sie_server.core.text_tokens import estimate_tokens_from_chars
from sie_server.core.tokenizer import image_first_chat_message, load_tokenizer
@@ -83,6 +84,7 @@ from sie_server.observability import worker_telemetry as _metrics
from sie_server.observability.lifecycle import current_lifecycle, observe_generation
from sie_server.processors.grammar_cache import GrammarLRU
from sie_server.processors.grammar_compile import compile_outlines
+from sie_server.processors.strict_grammar import enforce_strict_grammar
from sie_server.processors.tool_call_grammar import (
ToolChoiceError,
build_tool_choice_grammar,
@@ -1670,6 +1672,22 @@ class StreamingProcessor:
)
return
+ if (self._extract_generate_params(wi) or {}).get("grammar") is not None:
+ try:
+ model_id = resolve_grammar_serving_model(self._registry, model_id)
+ except GenerationError as exc:
+ await self._terminal_error_then_settle(
+ reply_subject,
+ request_id=request_id,
+ attempt_id=attempt_id,
+ seq=0,
+ code=exc.code,
+ message=client_safe_generation_error_message(exc.code, str(exc)),
+ param=client_safe_generation_error_param(exc),
+ msg=msg,
+ )
+ return
+
# Lazy-load the model on first request. NAK for redelivery if
# load fails or the model isn't registered for this worker.
try:
@@ -2177,6 +2195,7 @@ class StreamingProcessor:
tool_call_format=tool_call_format,
parallel_tool_calls=parallel_tool_calls,
)
+ chunks_iter = enforce_strict_grammar(chunks_iter, grammar)
# Bounded chunk queue + a single publisher task drains it. If the
# queue fills up, the iterator-driver triggers transport_failure.
@@ -3099,6 +3118,11 @@ class StreamingProcessor:
)
label_raw = grammar_raw.get("label")
strict_raw = grammar_raw.get("strict")
+ if kind_raw == "ebnf" and strict_raw is True:
+ return _ValidationError(
+ code="unsupported_field",
+ message="'grammar.strict' is not supported for EBNF grammars",
+ )
grammar = GrammarSpec(
kind=kind_raw,
value=value,
diff --git a/packages/sie_server/src/sie_server/processors/strict_grammar.py b/packages/sie_server/src/sie_server/processors/strict_grammar.py
new file mode 100644
index 000000000..37b1b7f5a
--- /dev/null
+++ b/packages/sie_server/src/sie_server/processors/strict_grammar.py
@@ -0,0 +1,319 @@
+"""Terminal output validation for strict structured-output grammars.
+
+The engine's grammar backend constrains decoding. A request that also sets
+``strict: true`` requires the completed output to satisfy the grammar: a
+``json_schema`` output must parse as JSON and validate against the schema, and
+a ``regex`` output must match the pattern in full. No verifier exists for the
+backend's EBNF dialects, so ingress rejects ``strict: true`` on ``ebnf``
+grammars instead of accepting a guarantee it cannot check.
+
+Validation runs on the visible text of every choice that stopped naturally
+without a tool call. A violation replaces the terminal with a typed
+``MODEL_OUTPUT_PARSE_ERROR`` terminal, which every generation ingress already
+surfaces as an error. Choices that finished with ``length`` or a tool call, and
+``cancelled`` or ``error`` terminals, are not verified.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import time
+from collections.abc import AsyncIterator, Iterable, Iterator, Mapping, Sequence
+from contextvars import ContextVar
+from dataclasses import replace
+from functools import lru_cache
+from typing import Any
+
+import regex
+from jsonschema import Draft202012Validator, ValidationError, validators
+from referencing import Registry, Resource
+from referencing.exceptions import NoSuchResource
+
+from sie_server.adapters._generation_base import GenerationChunk, aclose_with_error_precedence
+from sie_server.types.grammar import GrammarSpec
+
+logger = logging.getLogger(__name__)
+
+MODEL_OUTPUT_PARSE_ERROR = "MODEL_OUTPUT_PARSE_ERROR"
+VERIFIABLE_GRAMMAR_KINDS = frozenset({"json_schema", "regex"})
+
+# Upper bound on the wall time spent evaluating caller-supplied patterns for
+# one output. Patterns run on the backtracking ``regex`` engine, whose timeout
+# keeps a pathological pattern from pinning the worker.
+_PATTERN_BUDGET_S = 2.0
+_MAX_PATH_CHARS = 200
+_UNVERIFIABLE_MESSAGE = "generated output could not be verified against the requested grammar"
+# A shared ``tool_calls`` terminal can still close choices that stopped
+# without a tool call; per-choice eligibility is decided in ``_terminal_outputs``.
+_VERIFIED_TERMINAL_REASONS = frozenset({"stop", "tool_calls"})
+
+_UNVERIFIABLE_SCHEMA_KEYWORDS = ("unevaluatedProperties",)
+_SCHEMA_MAP_KEYWORDS = frozenset(
+ {"properties", "patternProperties", "$defs", "definitions", "dependencies", "dependentRequired", "dependentSchemas"}
+)
+_DATA_KEYWORDS = frozenset({"const", "default", "enum", "examples"})
+
+_pattern_deadline: ContextVar[float] = ContextVar("strict_grammar_pattern_deadline")
+
+
+def _refuse_retrieval(uri: str) -> Resource:
+ raise NoSuchResource(ref=uri)
+
+
+# Schemas are caller-supplied: only references inside the schema resolve, and
+# the verifier never fetches a remote document.
+_LOCAL_REFERENCES = Registry(retrieve=_refuse_retrieval)
+
+
+def requires_output_validation(grammar: GrammarSpec | None) -> bool:
+ """Return whether ``grammar`` asks for a verified output."""
+ return grammar is not None and grammar.strict is True and grammar.kind in VERIFIABLE_GRAMMAR_KINDS
+
+
+def output_violation(grammar: GrammarSpec, text: str) -> str | None:
+ """Return a client-safe violation message, or ``None`` when ``text`` conforms."""
+ token = _pattern_deadline.set(time.monotonic() + _PATTERN_BUDGET_S)
+ try:
+ if grammar.kind == "json_schema" and isinstance(grammar.value, dict):
+ return _json_schema_violation(grammar.value, text)
+ if grammar.kind == "regex" and isinstance(grammar.value, str):
+ return _regex_violation(grammar.value, text)
+ return _UNVERIFIABLE_MESSAGE
+ except Exception: # noqa: BLE001 - a grammar the verifier cannot evaluate fails closed
+ logger.warning("strict grammar verification failed for kind=%s", grammar.kind, exc_info=True)
+ return _UNVERIFIABLE_MESSAGE
+ finally:
+ _pattern_deadline.reset(token)
+
+
+def first_output_violation(grammar: GrammarSpec, outputs: Iterable[str]) -> str | None:
+ """Return the first violation across ``outputs`` (one per choice)."""
+ for text in outputs:
+ violation = output_violation(grammar, text)
+ if violation is not None:
+ return violation
+ return None
+
+
+def enforce_strict_grammar(
+ chunks: AsyncIterator[GenerationChunk],
+ grammar: GrammarSpec | None,
+) -> AsyncIterator[GenerationChunk]:
+ """Return ``chunks`` with strict-grammar terminal validation applied.
+
+ Apply this to the visible stream, after reasoning suppression and
+ tool-call parsing. Non-strict grammars return ``chunks`` unchanged.
+ """
+ if grammar is None or not requires_output_validation(grammar):
+ return chunks
+ return _validated_chunks(chunks, grammar)
+
+
+async def _validated_chunks(
+ chunks: AsyncIterator[GenerationChunk],
+ grammar: GrammarSpec,
+) -> AsyncIterator[GenerationChunk]:
+ texts: dict[int, list[str]] = {}
+ choice_finish_reasons: dict[int, str] = {}
+ tool_call_choices: set[int] = set()
+ terminal_outcome_selected = False
+ try:
+ async for chunk in chunks:
+ if chunk.text_delta:
+ texts.setdefault(chunk.choice_index, []).append(chunk.text_delta)
+ if chunk.tool_call_delta is not None:
+ tool_call_choices.add(chunk.choice_index)
+ if not chunk.done and chunk.finish_reason is not None:
+ choice_finish_reasons[chunk.choice_index] = chunk.finish_reason
+ if chunk.done:
+ if chunk.error_code is None and (chunk.finish_reason or "stop") in _VERIFIED_TERMINAL_REASONS:
+ outputs = _terminal_outputs(chunk, texts, choice_finish_reasons, tool_call_choices)
+ violation = await asyncio.to_thread(first_output_violation, grammar, outputs)
+ if violation is not None:
+ chunk = replace(
+ chunk,
+ finish_reason="error",
+ error_code=MODEL_OUTPUT_PARSE_ERROR,
+ error_message=violation,
+ )
+ terminal_outcome_selected = True
+ yield chunk
+ if not terminal_outcome_selected:
+ # Consumers settle an iterator that ends without a terminal as a
+ # natural stop, so the accumulated output is verified here.
+ implicit_stop = GenerationChunk(text_delta="", done=True)
+ outputs = _terminal_outputs(implicit_stop, texts, choice_finish_reasons, tool_call_choices)
+ violation = await asyncio.to_thread(first_output_violation, grammar, outputs)
+ if violation is not None:
+ terminal_outcome_selected = True
+ yield replace(
+ implicit_stop,
+ finish_reason="error",
+ error_code=MODEL_OUTPUT_PARSE_ERROR,
+ error_message=violation,
+ )
+ finally:
+ await aclose_with_error_precedence(
+ chunks,
+ outcome_selected=terminal_outcome_selected,
+ context="strict grammar upstream iterator",
+ )
+
+
+def _terminal_outputs(
+ chunk: GenerationChunk,
+ texts: Mapping[int, Sequence[str]],
+ choice_finish_reasons: Mapping[int, str],
+ tool_call_choices: set[int],
+) -> list[str]:
+ """Return the text of every choice that stopped naturally without a tool call.
+
+ Non-streamed candidates carry their own finish reasons on the terminal.
+ Streamed choices of an ``n > 1`` request finish on earlier per-choice
+ chunks, before the shared terminal.
+ """
+ if chunk.candidates:
+ return [
+ text if isinstance(text := candidate.get("text"), str) else ""
+ for candidate in chunk.candidates
+ if candidate.get("finish_reason") in (None, "stop") and not candidate.get("tool_calls")
+ ]
+ choices = sorted(set(texts) | set(choice_finish_reasons) | tool_call_choices) or [chunk.choice_index]
+ return [
+ "".join(texts.get(index, ()))
+ for index in choices
+ if index not in tool_call_choices and choice_finish_reasons.get(index, "stop") == "stop"
+ ]
+
+
+def _reject_json_constant(value: str) -> Any:
+ raise ValueError(f"{value} is not valid JSON")
+
+
+def unverifiable_schema_keyword(schema: Any) -> str | None:
+ """Return a keyword the verifier cannot evaluate within its pattern budget.
+
+ ``unevaluatedProperties`` resolves ``patternProperties`` through the
+ standard-library ``re`` engine inside ``jsonschema``, outside the bounded
+ ``regex`` engine used for every other pattern keyword.
+ """
+ return _find_schema_keyword(schema, "schema")
+
+
+def _find_schema_keyword(value: Any, context: str) -> str | None:
+ if isinstance(value, dict):
+ if context == "schema":
+ for keyword in _UNVERIFIABLE_SCHEMA_KEYWORDS:
+ if keyword in value:
+ return keyword
+ for key, child in value.items():
+ if found := _find_schema_keyword(child, _schema_child_context(context, key)):
+ return found
+ elif isinstance(value, list):
+ child_context = "schema" if context == "schema" else "other"
+ for item in value:
+ if found := _find_schema_keyword(item, child_context):
+ return found
+ return None
+
+
+def _schema_child_context(parent: str, key: str) -> str:
+ """Classify a child position; unknown keywords are scanned as subschemas."""
+ if parent == "schema_map":
+ return "schema"
+ if parent != "schema":
+ return "other"
+ if key in _SCHEMA_MAP_KEYWORDS:
+ return "schema_map"
+ if key in _DATA_KEYWORDS:
+ return "other"
+ return "schema"
+
+
+def _json_schema_violation(schema: dict[str, Any], text: str) -> str | None:
+ try:
+ instance = json.loads(text, parse_constant=_reject_json_constant)
+ except (ValueError, RecursionError):
+ return "generated output is not valid JSON"
+ if unverifiable_schema_keyword(schema) is not None:
+ return _UNVERIFIABLE_MESSAGE
+ validator_class = _bounded_validator_class(validators.validator_for(schema, default=Draft202012Validator))
+ error = next(validator_class(schema, registry=_LOCAL_REFERENCES).iter_errors(instance), None)
+ if error is None:
+ return None
+ path = error.json_path
+ if len(path) > _MAX_PATH_CHARS:
+ path = path[: _MAX_PATH_CHARS - 3] + "..."
+ return f"generated output does not match the requested JSON schema at {path} ('{error.validator}' keyword)"
+
+
+def _regex_violation(pattern: str, text: str) -> str | None:
+ if regex.fullmatch(pattern, text, timeout=_remaining_pattern_budget()) is None:
+ return "generated output does not match the requested regex"
+ return None
+
+
+def _remaining_pattern_budget() -> float:
+ remaining = _pattern_deadline.get() - time.monotonic()
+ if remaining <= 0:
+ raise TimeoutError("strict grammar pattern budget exhausted")
+ return remaining
+
+
+def _pattern_search(pattern: str, text: str) -> bool:
+ return regex.search(pattern, text, timeout=_remaining_pattern_budget()) is not None
+
+
+def _pattern(validator: Any, pattern: str, instance: Any, schema: Mapping[str, Any]) -> Iterator[ValidationError]:
+ if validator.is_type(instance, "string") and not _pattern_search(pattern, instance):
+ yield ValidationError("string does not match pattern")
+
+
+def _pattern_properties(
+ validator: Any,
+ pattern_properties: Mapping[str, Any],
+ instance: Any,
+ schema: Mapping[str, Any],
+) -> Iterator[ValidationError]:
+ if not validator.is_type(instance, "object"):
+ return
+ for pattern, subschema in pattern_properties.items():
+ for key, value in instance.items():
+ if _pattern_search(pattern, key):
+ yield from validator.descend(value, subschema, path=key, schema_path=pattern)
+
+
+def _additional_properties(
+ validator: Any,
+ additional: Any,
+ instance: Any,
+ schema: Mapping[str, Any],
+) -> Iterator[ValidationError]:
+ if not validator.is_type(instance, "object"):
+ return
+ properties = schema.get("properties", {})
+ patterns = tuple(schema.get("patternProperties", {}))
+ extras = [
+ key
+ for key in instance
+ if key not in properties and not any(_pattern_search(pattern, key) for pattern in patterns)
+ ]
+ if validator.is_type(additional, "object"):
+ for extra in extras:
+ yield from validator.descend(instance[extra], additional, path=extra)
+ elif not additional and extras:
+ yield ValidationError("additional properties are not allowed")
+
+
+@lru_cache(maxsize=8)
+def _bounded_validator_class(base: type) -> Any:
+ return validators.extend(
+ base,
+ {
+ "pattern": _pattern,
+ "patternProperties": _pattern_properties,
+ "additionalProperties": _additional_properties,
+ },
+ )
diff --git a/packages/sie_server/src/sie_server/types/grammar.py b/packages/sie_server/src/sie_server/types/grammar.py
index 21acdae0b..3865c1581 100644
--- a/packages/sie_server/src/sie_server/types/grammar.py
+++ b/packages/sie_server/src/sie_server/types/grammar.py
@@ -65,9 +65,12 @@ class GrammarSpec:
label: Optional human-readable name surfaced from the OpenAI
``response_format.json_schema.name`` field. Used for log
lines and metric labels; never affects the compile result.
- strict: Optional pass-through from ``response_format.json_schema.strict``.
- Forwarded to the backend if it accepts a strict flag;
- otherwise advisory.
+ strict: Native ``grammar.strict`` or OpenAI
+ ``response_format.json_schema.strict``. ``True`` makes the worker
+ verify the finished output of a ``json_schema`` or ``regex``
+ grammar (see :mod:`sie_server.processors.strict_grammar`) and
+ fail the request with ``MODEL_OUTPUT_PARSE_ERROR`` when it does
+ not conform. Ingress rejects ``True`` on ``ebnf`` grammars.
"""
kind: GrammarKind
diff --git a/packages/sie_server/src/sie_server/types/openapi.py b/packages/sie_server/src/sie_server/types/openapi.py
index 02b6c7a7e..46e2b0b6c 100644
--- a/packages/sie_server/src/sie_server/types/openapi.py
+++ b/packages/sie_server/src/sie_server/types/openapi.py
@@ -369,7 +369,13 @@ class NativeJsonSchemaGrammarModel(BaseModel):
json_schema: dict[str, Any]
label: str | None = None
- strict: bool | None = None
+ strict: bool | None = Field(
+ default=None,
+ description=(
+ "When true, the finished output must parse as JSON and validate against json_schema; "
+ "otherwise the request fails with MODEL_OUTPUT_PARSE_ERROR"
+ ),
+ )
model_config = {"extra": "forbid"}
@@ -378,7 +384,13 @@ class NativeRegexGrammarModel(BaseModel):
regex: str = Field(..., max_length=4 * 1024)
label: str | None = None
- strict: bool | None = None
+ strict: bool | None = Field(
+ default=None,
+ description=(
+ "When true, the finished output must match regex in full; "
+ "otherwise the request fails with MODEL_OUTPUT_PARSE_ERROR"
+ ),
+ )
model_config = {"extra": "forbid"}
@@ -387,7 +399,10 @@ class NativeEbnfGrammarModel(BaseModel):
ebnf: str = Field(..., max_length=8 * 1024)
label: str | None = None
- strict: bool | None = None
+ strict: bool | None = Field(
+ default=None,
+ description="EBNF output cannot be verified, so true is rejected with 400 unsupported_field",
+ )
model_config = {"extra": "forbid"}
diff --git a/packages/sie_server/tests/adapters/test_mlx_generation.py b/packages/sie_server/tests/adapters/test_mlx_generation.py
index 168aa735a..062bb732b 100644
--- a/packages/sie_server/tests/adapters/test_mlx_generation.py
+++ b/packages/sie_server/tests/adapters/test_mlx_generation.py
@@ -21,6 +21,7 @@ from sie_server.adapters.sglang.generation import (
SGLangGenerationAdapter,
_translate_to_mlx_kwargs,
)
+from sie_server.types.grammar import GrammarSpec
@pytest.fixture
@@ -235,6 +236,25 @@ async def test_generate_rejects_videos_as_unsupported_field(adapter: MLXGenerati
assert error.value.code == "unsupported_field"
[email protected]("stream", [False, True])
+def test_preflight_rejects_grammar_as_unsupported_field(adapter: MLXGenerationAdapter, stream: bool) -> None:
+ grammar = GrammarSpec(kind="json_schema", value={"type": "object"}, strict=True)
+
+ with pytest.raises(GenerationUnsupportedFieldError) as error:
+ adapter.preflight_generate({"prompt": "hi", "max_new_tokens": 8, "grammar": grammar}, stream=stream)
+
+ assert error.value.param == "grammar"
+ assert error.value.code == "unsupported_field"
+ assert adapter.preflight_generate({"prompt": "hi", "max_new_tokens": 8}, stream=stream) is None
+
+
+async def test_generate_rejects_grammar_instead_of_ignoring_it(adapter: MLXGenerationAdapter) -> None:
+ with pytest.raises(GenerationUnsupportedFieldError) as error:
+ gen = adapter.generate(prompt="hi", max_new_tokens=8, grammar=GrammarSpec(kind="regex", value="[a-z]+"))
+ await gen.__anext__()
+ assert error.value.param == "grammar"
+
+
async def test_generate_rejects_unsupported_min_new_tokens(adapter: MLXGenerationAdapter) -> None:
with pytest.raises(ValueError, match="min_new_tokens is not supported"):
gen = adapter.generate(prompt="hi", max_new_tokens=8, min_new_tokens=2)
diff --git a/packages/sie_server/tests/api/test_generate.py b/packages/sie_server/tests/api/test_generate.py
index 947d3c314..b1dd19dec 100644
--- a/packages/sie_server/tests/api/test_generate.py
+++ b/packages/sie_server/tests/api/test_generate.py
@@ -29,6 +29,7 @@ from sie_server.adapters._generation_base import (
)
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters.base import ModelCapabilities, ModelDims
+from sie_server.adapters.mlx.generation import MLXGenerationAdapter
from sie_server.api import generate as generate_api
from sie_server.api.generate import router as generate_router
from sie_server.config.engine import EngineConfig
@@ -41,6 +42,7 @@ from sie_server.config.model import (
ProfileConfig,
Tasks,
)
+from sie_server.core.loader import expand_profile_variants
from sie_server.core.registry import ModelRegistry
from sie_server.types.grammar import OUTLINES_JSON_SCHEMA_TYPE_MESSAGE, GrammarSpec
from sie_server.types.inputs import ImageInput
@@ -123,6 +125,8 @@ class _FakeGenAdapter(GenerationAdapter):
error_code: str | None = None
error_message: str | None = None
cached_tokens: int | None = None
+ # Generated text; ``None`` echoes the prompt.
+ output_text: str | None = None
async def generate(
self,
@@ -165,7 +169,10 @@ class _FakeGenAdapter(GenerationAdapter):
self.last_call["images"] = images
# Yield one delta + a terminal chunk so the local-dev route can
# drain the iterator into the walking-skeleton-shaped aggregate response.
- yield GenerationChunk(text_delta=f"echo:{prompt}", is_first=True)
+ yield GenerationChunk(
+ text_delta=self.output_text if self.output_text is not None else f"echo:{prompt}",
+ is_first=True,
+ )
yield GenerationChunk(
text_delta="",
done=True,
@@ -1010,6 +1017,7 @@ class TestGenerateEndpoint:
stream: bool,
) -> None:
registry.get_config.return_value = _make_config(grammar=[expected.kind])
+ fake_adapter.output_text = '{"title": "Quarterly report"}'
response = client.post(
"/v1/generate/Qwen__Qwen3-4B-Instruct",
@@ -1729,3 +1737,282 @@ class TestGenerateEndpoint:
assert response.status_code == 503
assert response.json()["detail"]["code"] == "RESOURCE_EXHAUSTED"
assert response.headers["retry-after"] == "12"
+
+
+_STRICT_SCHEMA = {
+ "type": "object",
+ "properties": {"title": {"type": "string"}},
+ "required": ["title"],
+ "additionalProperties": False,
+}
+
+
+def _grammar_routed_configs() -> dict[str, ModelConfig]:
+ config = _make_config(model_id="Qwen/Qwen3.5-4B", grammar=["json_schema"])
+ assert config.tasks.generate is not None
+ config.tasks.generate.grammar_profile = "no-spec"
+ config.profiles["default"].adapter_options.loadtime["speculative"] = {"algorithm": "NEXTN", "num_steps": 3}
+ config.profiles["no-spec"] = ProfileConfig(
+ extends="default",
+ adapter_options=AdapterOptions(
+ loadtime={"reasoning_parser": "qwen3", "speculative": {"enabled": False}},
+ ),
+ )
+ return expand_profile_variants([config])
+
+
+def _serve_configs(registry: MagicMock, configs: Mapping[str, ModelConfig]) -> None:
+ registry.has_model.side_effect = configs.__contains__
+ registry.get_config.side_effect = configs.__getitem__
+
+
+def _sse_events(text: str) -> list[dict[str, object]]:
+ return [json.loads(line.removeprefix("data: ")) for line in text.splitlines() if line.startswith("data: {")]
+
+
+class TestStrictStructuredOutput:
+ """``strict`` grammars are verified on the terminal path of the direct route."""
+
+ def test_blocking_strict_schema_violation_is_a_typed_error(
+ self,
+ client: TestClient,
+ registry: MagicMock,
+ fake_adapter: _FakeGenAdapter,
+ ) -> None:
+ registry.get_config.return_value = _make_config(grammar=["json_schema"])
+ fake_adapter.output_text = "[]"
+
+ response = client.post(
+ "/v1/generate/Qwen__Qwen3-4B-Instruct",
+ json={
+ "prompt": "Summarise",
+ "grammar": {"json_schema": _STRICT_SCHEMA, "strict": True},
+ "max_new_tokens": 8,
+ },
+ )
+
+ assert response.status_code == 500
+ assert response.json()["detail"] == {
+ "code": "MODEL_OUTPUT_PARSE_ERROR",
+ "message": "generated output does not match the requested JSON schema at $ ('type' keyword)",
+ }
+
+ def test_streaming_strict_schema_violation_errors_on_the_terminal_event(
+ self,
+ client: TestClient,
+ registry: MagicMock,
+ fake_adapter: _FakeGenAdapter,
+ ) -> None:
+ registry.get_config.return_value = _make_config(grammar=["json_schema"])
+ fake_adapter.output_text = '{"title": 7}'
+
+ response = client.post(
+ "/v1/generate/Qwen__Qwen3-4B-Instruct",
+ json={
+ "prompt": "Summarise",
+ "grammar": {"json_schema": _STRICT_SCHEMA, "strict": True},
+ "max_new_tokens": 8,
+ "stream": True,
+ },
+ )
+
+ assert response.status_code == 200
+ events = _sse_events(response.text)
+ assert events[0]["text_delta"] == '{"title": 7}'
+ terminal = events[-1]
+ assert terminal["done"] is True
+ assert terminal["finish_reason"] == "error"
+ assert terminal["error"] == {
+ "code": "MODEL_OUTPUT_PARSE_ERROR",
+ "message": "generated output does not match the requested JSON schema at $.title ('type' keyword)",
+ }
+ assert response.text.endswith("data: [DONE]\n\n")
+
+ @pytest.mark.parametrize("stream", [False, True])
+ def test_strict_regex_requires_a_full_match(
+ self,
+ client: TestClient,
+ registry: MagicMock,
+ fake_adapter: _FakeGenAdapter,
+ stream: bool,
+ ) -> None:
+ registry.get_config.return_value = _make_config(grammar=["regex"])
+ fake_adapter.output_text = "ABC-1234 trailing"
+
+ response = client.post(
+ "/v1/generate/Qwen__Qwen3-4B-Instruct",
+ json={
+ "prompt": "Code?",
+ "grammar": {"regex": r"[A-Z]{3}-\d{4}", "strict": True},
+ "max_new_tokens": 8,
+ "stream": stream,
+ },
+ )
+
+ expected = {
+ "code": "MODEL_OUTPUT_PARSE_ERROR",
+ "message": "generated output does not match the requested regex",
+ }
+ if stream:
+ assert _sse_events(response.text)[-1]["error"] == expected
+ else:
+ assert response.status_code == 500
+ assert response.json()["detail"] == expected
+
+ @pytest.mark.parametrize("strict", [None, False])
+ @pytest.mark.parametrize("stream", [False, True])
+ def test_non_strict_grammar_output_is_returned_unchanged(
+ self,
+ client: TestClient,
+ registry: MagicMock,
+ fake_adapter: _FakeGenAdapter,
+ strict: bool | None,
+ stream: bool,
+ ) -> None:
+ registry.get_config.return_value = _make_config(grammar=["json_schema"])
+ fake_adapter.output_text = "[]"
+ grammar: dict[str, object] = {"json_schema": _STRICT_SCHEMA}
+ if strict is not None:
+ grammar["strict"] = strict
+
+ response = client.post(
+ "/v1/generate/Qwen__Qwen3-4B-Instruct",
+ json={"prompt": "Summarise", "grammar": grammar, "max_new_tokens": 8, "stream": stream},
+ )
+
+ assert response.status_code == 200
+ if stream:
+ terminal = _sse_events(response.text)[-1]
+ assert terminal["finish_reason"] == "stop"
+ assert "error" not in terminal
+ else:
+ assert response.json()["text"] == "[]"
+ assert response.json()["finish_reason"] == "stop"
+
+ def test_strict_output_that_conforms_is_returned(
+ self,
+ client: TestClient,
+ registry: MagicMock,
+ fake_adapter: _FakeGenAdapter,
+ ) -> None:
+ registry.get_config.return_value = _make_config(grammar=["json_schema"])
+ fake_adapter.output_text = '{"title": "Quarterly report"}'
+
+ response = client.post(
+ "/v1/generate/Qwen__Qwen3-4B-Instruct",
+ json={
+ "prompt": "Summarise",
+ "grammar": {"json_schema": _STRICT_SCHEMA, "strict": True},
+ "max_new_tokens": 8,
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json()["text"] == '{"title": "Quarterly report"}'
+
+ def test_strict_ebnf_is_rejected_before_dispatch(
+ self,
+ client: TestClient,
+ registry: MagicMock,
+ fake_adapter: _FakeGenAdapter,
+ ) -> None:
+ registry.get_config.return_value = _make_config(grammar=["ebnf"])
+
+ response = client.post(
+ "/v1/generate/Qwen__Qwen3-4B-Instruct",
+ json={"prompt": "Yes?", "grammar": {"ebnf": 'root ::= "yes"', "strict": True}, "max_new_tokens": 8},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["detail"]["code"] == "unsupported_field"
+ assert response.json()["detail"]["param"] == "grammar.strict"
+ assert fake_adapter.last_call is None
+
+
+class TestGrammarProfileAdmission:
+ """Grammar requests on the direct route run on the declared grammar profile."""
+
+ @pytest.mark.parametrize("stream", [False, True])
+ def test_grammar_request_runs_on_the_grammar_profile(
+ self,
+ client: TestClient,
+ registry: MagicMock,
+ fake_adapter: _FakeGenAdapter,
+ stream: bool,
+ ) -> None:
+ _serve_configs(registry, _grammar_routed_configs())
+
+ response = client.post(
+ "/v1/generate/Qwen__Qwen3.5-4B",
+ json={
+ "prompt": "Hi",
+ "grammar": {"json_schema": {"type": "object"}},
+ "max_new_tokens": 8,
+ "stream": stream,
+ },
+ )
+
+ assert response.status_code == 200, response.text
+ registry.get.assert_called_with("Qwen/Qwen3.5-4B:no-spec")
+ registry.touch_lru.assert_called_with("Qwen/Qwen3.5-4B:no-spec")
+ assert fake_adapter.last_call is not None
+ assert fake_adapter.last_call["grammar"] == GrammarSpec(kind="json_schema", value={"type": "object"})
+ if not stream:
+ assert response.json()["model"] == "Qwen/Qwen3.5-4B"
+
+ def test_unconstrained_request_keeps_the_requested_profile(
+ self,
+ client: TestClient,
+ registry: MagicMock,
+ ) -> None:
+ _serve_configs(registry, _grammar_routed_configs())
+
+ response = client.post("/v1/generate/Qwen__Qwen3.5-4B", json={"prompt": "Hi", "max_new_tokens": 8})
+
+ assert response.status_code == 200, response.text
+ registry.get.assert_called_with("Qwen/Qwen3.5-4B")
+ assert response.json()["model"] == "Qwen/Qwen3.5-4B"
+
+ def test_missing_grammar_profile_rejects_instead_of_running_speculatively(
+ self,
+ client: TestClient,
+ registry: MagicMock,
+ fake_adapter: _FakeGenAdapter,
+ ) -> None:
+ configs = _grammar_routed_configs()
+ del configs["Qwen/Qwen3.5-4B:no-spec"]
+ _serve_configs(registry, configs)
+
+ response = client.post(
+ "/v1/generate/Qwen__Qwen3.5-4B",
+ json={"prompt": "Hi", "grammar": {"json_schema": {"type": "object"}}, "max_new_tokens": 8},
+ )
+
+ assert response.status_code == 400
+ detail = response.json()["detail"]
+ assert detail["code"] == "unsupported_field"
+ assert detail["param"] == "grammar"
+ assert "'no-spec'" in detail["message"]
+ registry.get.assert_not_called()
+ assert fake_adapter.last_call is None
+
+ def test_mlx_backend_rejects_grammar_in_preflight(
+ self,
+ client: TestClient,
+ registry: MagicMock,
+ ) -> None:
+ registry.get_config.return_value = _make_config(model_id="Qwen/Qwen3.5-4B", grammar=["json_schema"])
+ adapter = MLXGenerationAdapter(model_name_or_path="Qwen/Qwen3.5-4B", mlx_repo="mlx-community/Qwen3.5-4B-4bit")
+ registry.get.return_value = adapter
+
+ response = client.post(
+ "/v1/generate/Qwen__Qwen3.5-4B",
+ json={"prompt": "Hi", "grammar": {"json_schema": {"type": "object"}}, "max_new_tokens": 8},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["detail"] == {
+ "code": "unsupported_field",
+ "message": "structured-output grammars are not supported by the MLX generation backend",
+ "param": "grammar",
+ }
diff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.py
index 72c778731..6285c5792 100644
--- a/packages/sie_server/tests/api/test_openai_local.py
+++ b/packages/sie_server/tests/api/test_openai_local.py
@@ -26,8 +26,10 @@ from sie_server.adapters.mlx.generation import MLXGenerationAdapter
from sie_server.adapters.sglang.generation import SGLangGenerationAdapter
from sie_server.api import openai_local
from sie_server.api.openai_local import _validate_mlx_seed, router
+from sie_server.config.model import ModelConfig
from sie_server.core import video_frames
from sie_server.core.inference_output import ScoreOutput
+from sie_server.core.loader import expand_profile_variants
from sie_server.core.timing import RequestTiming
from sie_server.core.worker import WorkerResult
from sie_server.types.inputs import MAX_ITEM_TEXT_BYTES
@@ -1400,3 +1402,274 @@ def test_rerank_non_finite_scores_return_top_level_openai_500(bad: float) -> Non
assert error["type"] == "server_error"
assert "m" in error["message"]
assert "non-finite" in error["message"]
+
+
+_STRICT_RESPONSE_FORMAT = {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "answer",
+ "strict": True,
+ "schema": {
+ "type": "object",
+ "properties": {"answer": {"type": "string"}},
+ "required": ["answer"],
+ "additionalProperties": False,
+ },
+ },
+}
+
+
+def _chat_completion(
+ content: str | None, *, finish_reason: str = "stop", tool_calls: list[Any] | None = None
+) -> dict[str, Any]:
+ message: dict[str, Any] = {"role": "assistant", "content": content}
+ if tool_calls is not None:
+ message["tool_calls"] = tool_calls
+ return {
+ "id": "chatcmpl-strict",
+ "object": "chat.completion",
+ "created": 1,
+ "model": "upstream-served-model",
+ "choices": [{"index": 0, "message": message, "logprobs": None, "finish_reason": finish_reason}],
+ "usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7},
+ }
+
+
+def _chat_stream(*contents: str) -> bytes:
+ events: list[dict[str, Any]] = [
+ {
+ "id": "chatcmpl-strict",
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "model": "upstream-served-model",
+ "choices": [{"index": 0, "delta": {"content": content}, "finish_reason": None}],
+ }
+ for content in contents
+ ]
+ events.append(
+ {
+ "id": "chatcmpl-strict",
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "model": "upstream-served-model",
+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
+ }
+ )
+ return b"".join(f"data: {json.dumps(event)}\n\n".encode() for event in events) + b"data: [DONE]\n\n"
+
+
+def _chat_request(response_format: dict[str, Any], *, stream: bool = False) -> dict[str, Any]:
+ return {
+ "model": "Qwen/Qwen3-0.6B",
+ "messages": [{"role": "user", "content": "Answer in JSON"}],
+ "max_tokens": 8,
+ "stream": stream,
+ "response_format": response_format,
+ }
+
+
+def test_cuda_chat_strict_schema_violation_returns_a_typed_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ client, _ = _cuda_chat_client(
+ monkeypatch, lambda _request: httpx.Response(200, json=_chat_completion('{"answer": 3}'))
+ )
+
+ response = client.post("/v1/chat/completions", json=_chat_request(_STRICT_RESPONSE_FORMAT))
+
+ assert response.status_code == 500
+ assert response.json() == {
+ "error": {
+ "message": "generated output does not match the requested JSON schema at $.answer ('type' keyword)",
+ "type": "server_error",
+ "param": None,
+ "code": "MODEL_OUTPUT_PARSE_ERROR",
+ }
+ }
+
+
+def test_cuda_chat_strict_schema_violation_errors_the_stream(monkeypatch: pytest.MonkeyPatch) -> None:
+ upstream_stream = _ChunkedAsyncStream([_chat_stream('{"answer"', ": 3}")])
+
+ def _handler(_request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, stream=upstream_stream, headers={"content-type": "text/event-stream"})
+
+ client, _ = _cuda_chat_client(monkeypatch, _handler)
+
+ response = client.post("/v1/chat/completions", json=_chat_request(_STRICT_RESPONSE_FORMAT, stream=True))
+
+ assert response.status_code == 200
+ data_lines = [line.removeprefix("data: ") for line in response.text.splitlines() if line.startswith("data: ")]
+ assert data_lines[-1] == "[DONE]"
+ events = [json.loads(line) for line in data_lines[:-1]]
+ assert "".join(event["choices"][0]["delta"].get("content", "") for event in events[:-1]) == '{"answer": 3}'
+ assert events[-1] == {
+ "error": {
+ "message": "generated output does not match the requested JSON schema at $.answer ('type' keyword)",
+ "type": "server_error",
+ "param": None,
+ "code": "MODEL_OUTPUT_PARSE_ERROR",
+ }
+ }
+ assert '"finish_reason": "stop"' not in response.text
+ assert upstream_stream.closed is True
+
+
[email protected]("stream", [False, True])
+def test_cuda_chat_conforming_strict_output_is_returned(monkeypatch: pytest.MonkeyPatch, stream: bool) -> None:
+ def _handler(_request: httpx.Request) -> httpx.Response:
+ if stream:
+ return httpx.Response(
+ 200,
+ stream=_ChunkedAsyncStream([_chat_stream('{"answer": ', '"yes"}')]),
+ headers={"content-type": "text/event-stream"},
+ )
+ return httpx.Response(200, json=_chat_completion('{"answer": "yes"}'))
+
+ client, _ = _cuda_chat_client(monkeypatch, _handler)
+
+ response = client.post("/v1/chat/completions", json=_chat_request(_STRICT_RESPONSE_FORMAT, stream=stream))
+
+ assert response.status_code == 200
+ assert "MODEL_OUTPUT_PARSE_ERROR" not in response.text
+ if not stream:
+ assert response.json()["choices"][0]["message"]["content"] == '{"answer": "yes"}'
+
+
+ "response_format",
+ [
+ {**_STRICT_RESPONSE_FORMAT, "json_schema": {**_STRICT_RESPONSE_FORMAT["json_schema"], "strict": False}},
+ {"type": "json_schema", "json_schema": {"name": "answer", "schema": {"type": "object"}}},
+ {"type": "json_object"},
+ ],
+)
+def test_cuda_chat_non_strict_response_format_is_not_verified(
+ monkeypatch: pytest.MonkeyPatch,
+ response_format: dict[str, Any],
+) -> None:
+ client, _ = _cuda_chat_client(monkeypatch, lambda _request: httpx.Response(200, json=_chat_completion("[]")))
+
+ response = client.post("/v1/chat/completions", json=_chat_request(response_format))
+
+ assert response.status_code == 200
+ assert response.json()["choices"][0]["message"]["content"] == "[]"
+
+
[email protected]("finish_reason", ["length", "tool_calls"])
+def test_cuda_chat_strict_output_skips_truncated_and_tool_call_turns(
+ monkeypatch: pytest.MonkeyPatch,
+ finish_reason: str,
+) -> None:
+ tool_calls = (
+ [{"id": "call_1", "type": "function", "function": {"name": "lookup", "arguments": "{}"}}]
+ if finish_reason == "tool_calls"
+ else None
+ )
+ body = _chat_completion(
+ '{"answer"' if finish_reason == "length" else None, finish_reason=finish_reason, tool_calls=tool_calls
+ )
+ client, _ = _cuda_chat_client(monkeypatch, lambda _request: httpx.Response(200, json=body))
+
+ response = client.post("/v1/chat/completions", json=_chat_request(_STRICT_RESPONSE_FORMAT))
+
+ assert response.status_code == 200
+ assert response.json()["choices"][0]["finish_reason"] == finish_reason
+
+
+def _serve_grammar_routed_configs(registry: MagicMock, *, without: tuple[str, ...] = ()) -> None:
+ config = ModelConfig.model_validate(
+ {
+ "sie_id": "Qwen/Qwen3.5-4B",
+ "hf_id": "Qwen/Qwen3.5-4B",
+ "inputs": {"text": True},
+ "tasks": {
+ "generate": {
+ "context_length": 4096,
+ "max_output_tokens": 64,
+ "grammar_profile": "no-spec",
+ "capabilities": {"grammar": ["json_schema"]},
+ }
+ },
+ "profiles": {
+ "default": {
+ "max_batch_tokens": 4096,
+ "kv_budget_tokens": 2048,
+ "adapter_path": "sie_server.adapters.sglang.generation:SGLangGenerationAdapter",
+ "adapter_options": {"loadtime": {"speculative": {"algorithm": "NEXTN", "num_steps": 3}}},
+ },
+ "no-spec": {
+ "extends": "default",
+ "adapter_options": {"loadtime": {"speculative": {"enabled": False}}},
+ },
+ },
+ }
+ )
+ configs = {name: value for name, value in expand_profile_variants([config]).items() if name not in without}
+ registry.has_model.side_effect = configs.__contains__
+ registry.get_config.side_effect = configs.__getitem__
+
+
+def test_cuda_chat_strict_schema_with_unevaluated_properties_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:
+ def _handler(_request: httpx.Request) -> httpx.Response:
+ raise AssertionError("an unverifiable strict schema must not reach the child")
+
+ client, registry = _cuda_chat_client(monkeypatch, _handler)
+ response_format = {
+ "type": "json_schema",
+ "json_schema": {
+ "name": "answer",
+ "strict": True,
+ "schema": {"type": "object", "unevaluatedProperties": False},
+ },
+ }
+
+ response = client.post("/v1/chat/completions", json=_chat_request(response_format))
+
+ assert response.status_code == 400
+ error = response.json()["error"]
+ assert error["code"] == "unsupported_field"
+ assert error["param"] == "response_format"
+ registry.get.assert_not_called()
+
+
+def test_cuda_chat_response_format_runs_on_the_grammar_profile(monkeypatch: pytest.MonkeyPatch) -> None:
+ seen: dict[str, Any] = {}
+
+ def _handler(request: httpx.Request) -> httpx.Response:
+ seen["body"] = json.loads(request.content)
+ return httpx.Response(200, json=_chat_completion('{"answer": "yes"}'))
+
+ client, registry = _cuda_chat_client(monkeypatch, _handler)
+ _serve_grammar_routed_configs(registry)
+ request = {**_chat_request(_STRICT_RESPONSE_FORMAT), "model": "Qwen/Qwen3.5-4B"}
+
+ response = client.post("/v1/chat/completions", json=request)
+
+ assert response.status_code == 200, response.text
+ registry.get.assert_called_once_with("Qwen/Qwen3.5-4B:no-spec")
+ assert response.json()["model"] == "Qwen/Qwen3.5-4B"
+ assert seen["body"]["response_format"] == _STRICT_RESPONSE_FORMAT
+
+ registry.get.reset_mock()
+ plain = {key: value for key, value in request.items() if key != "response_format"}
+ assert client.post("/v1/chat/completions", json=plain).status_code == 200
+ registry.get.assert_called_once_with("Qwen/Qwen3.5-4B")
+
+
+def test_cuda_chat_response_format_without_its_grammar_profile_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:
+ def _handler(_request: httpx.Request) -> httpx.Response:
+ raise AssertionError("a request without a grammar-safe profile must not reach the child")
+
+ client, registry = _cuda_chat_client(monkeypatch, _handler)
+ _serve_grammar_routed_configs(registry, without=("Qwen/Qwen3.5-4B:no-spec",))
+
+ response = client.post(
+ "/v1/chat/completions",
+ json={**_chat_request(_STRICT_RESPONSE_FORMAT), "model": "Qwen/Qwen3.5-4B"},
+ )
+
+ assert response.status_code == 400
+ error = response.json()["error"]
+ assert error["code"] == "unsupported_field"
+ assert error["param"] == "response_format"
+ assert "'no-spec'" in error["message"]
+ registry.get.assert_not_called()
diff --git a/packages/sie_server/tests/core/test_grammar_routing.py b/packages/sie_server/tests/core/test_grammar_routing.py
new file mode 100644
index 000000000..672819a7a
--- /dev/null
+++ b/packages/sie_server/tests/core/test_grammar_routing.py
@@ -0,0 +1,70 @@
+"""Tests for the worker-side grammar-profile admission helper."""
+
+from __future__ import annotations
+
+import shutil
+from pathlib import Path
+
+import pytest
+from sie_server.adapters._generation_base import GenerationUnsupportedFieldError
+from sie_server.core.grammar_routing import resolve_grammar_serving_model
+from sie_server.core.registry import ModelRegistry
+
+_MODELS_DIR = Path(__file__).resolve().parents[2] / "models"
+_CATALOG = ("Qwen__Qwen3.5-4B.yaml", "Qwen__Qwen3.6-27B.yaml", "sie-fake.yaml")
+
+
+def _registry(tmp_path: Path, model_filter: list[str] | None = None) -> ModelRegistry:
+ for name in _CATALOG:
+ shutil.copy(_MODELS_DIR / name, tmp_path / name)
+ return ModelRegistry(models_dir=tmp_path, model_filter=model_filter, enable_hot_reload=False)
+
+
+ ("requested", "serving"),
+ [
+ ("Qwen/Qwen3.5-4B", "Qwen/Qwen3.5-4B:no-spec"),
+ ("Qwen/Qwen3.5-4B:a100-40gb", "Qwen/Qwen3.5-4B:no-spec"),
+ ("Qwen/Qwen3.5-4B:long-context", "Qwen/Qwen3.5-4B:no-spec"),
+ ("Qwen/Qwen3.5-4B:no-spec", "Qwen/Qwen3.5-4B:no-spec"),
+ ("Qwen/Qwen3.6-27B", "Qwen/Qwen3.6-27B"),
+ ("Qwen/Qwen3.6-27B:long-context", "Qwen/Qwen3.6-27B:long-context-no-spec"),
+ ("Qwen/Qwen3.6-27B:long-context-thinking", "Qwen/Qwen3.6-27B:long-context-thinking-no-spec"),
+ ("Qwen/Qwen3.6-27B:long-context-no-spec", "Qwen/Qwen3.6-27B:long-context-no-spec"),
+ ("sie-fake", "sie-fake"),
+ ("org/unknown", "org/unknown"),
+ ],
+)
+def test_grammar_requests_resolve_to_the_grammar_safe_profile(tmp_path: Path, requested: str, serving: str) -> None:
+ assert resolve_grammar_serving_model(_registry(tmp_path), requested) == serving
+
+
+def test_missing_grammar_profile_is_rejected_instead_of_served_speculatively(tmp_path: Path) -> None:
+ registry = _registry(tmp_path, model_filter=["Qwen/Qwen3.5-4B"])
+
+ with pytest.raises(GenerationUnsupportedFieldError) as exc_info:
+ resolve_grammar_serving_model(registry, "Qwen/Qwen3.5-4B")
+
+ assert exc_info.value.param == "grammar"
+ assert "'no-spec'" in str(exc_info.value)
+
+
+def test_variant_served_without_its_base_keeps_a_grammar_safe_launch(tmp_path: Path) -> None:
+ registry = _registry(tmp_path, model_filter=["Qwen/Qwen3.6-27B:long-context-no-spec"])
+
+ assert (
+ resolve_grammar_serving_model(registry, "Qwen/Qwen3.6-27B:long-context-no-spec")
+ == "Qwen/Qwen3.6-27B:long-context-no-spec"
+ )
+
+
+def test_speculative_variant_served_without_its_base_needs_its_grammar_profile(tmp_path: Path) -> None:
+ registry = _registry(tmp_path, model_filter=["Qwen/Qwen3.6-27B:long-context"])
+
+ with pytest.raises(GenerationUnsupportedFieldError, match="'long-context-no-spec'"):
+ resolve_grammar_serving_model(registry, "Qwen/Qwen3.6-27B:long-context")
+
+ both = _registry(tmp_path, model_filter=["Qwen/Qwen3.6-27B:long-context", "Qwen/Qwen3.6-27B:long-context-no-spec"])
+ assert (
+ resolve_grammar_serving_model(both, "Qwen/Qwen3.6-27B:long-context") == "Qwen/Qwen3.6-27B:long-context-no-spec"
+ )
diff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.py
index b9850533a..9c5f7d3f0 100644
--- a/packages/sie_server/tests/processors/test_streaming.py
+++ b/packages/sie_server/tests/processors/test_streaming.py
@@ -37,6 +37,7 @@ from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters.base import ModelCapabilities, ModelDims
from sie_server.config.engine import EngineConfig
from sie_server.config.model import ModelConfig
+from sie_server.core.loader import expand_profile_variants
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
@@ -4464,3 +4465,190 @@ def test_validate_rejects_malformed_video_messages(messages: list[dict[str, Any]
result = proc._validate_generate_params({"generate": {"messages": messages, "max_new_tokens": 8}}, None)
assert isinstance(result, _ValidationError)
assert fragment in result.message
+
+
+_STRICT_SCHEMA_PAYLOAD = {
+ "kind": "json_schema",
+ "value": {"type": "object", "properties": {"x": {"type": "integer"}}, "required": ["x"]},
+ "strict": True,
+}
+
+
+def _completion_script(text: str) -> list[GenerationChunk]:
+ return [
+ GenerationChunk(text_delta=text, is_first=True),
+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=2, completion_tokens=3),
+ ]
+
+
[email protected]("stream", [False, True])
+async def test_strict_grammar_violation_publishes_a_typed_terminal_error(stream: bool) -> None:
+ nc = AsyncMock()
+ proc = StreamingProcessor(
+ nc=nc, registry=_make_registry(_FakeGenAdapter(_completion_script('{"x": "one"}'))), worker_id="w1"
+ )
+ wi = _make_work_item(
+ generate={"prompt": "Hi", "max_new_tokens": 8, "grammar": _STRICT_SCHEMA_PAYLOAD, "stream": stream}
+ )
+ msg = _make_msg(wi)
+
+ await proc.process(msg, "test/model")
+
+ terminal = _terminal_chunk(nc)
+ assert terminal["done"] is True
+ assert terminal["finish_reason"] == "error"
+ assert terminal["error"]["code"] == "MODEL_OUTPUT_PARSE_ERROR"
+ assert terminal["error"]["message"] == (
+ "generated output does not match the requested JSON schema at $.x ('type' keyword)"
+ )
+ msg.ack.assert_awaited()
+
+
+async def test_strict_grammar_verifies_output_when_the_adapter_omits_the_terminal() -> None:
+ nc = AsyncMock()
+ adapter = _FakeGenAdapter([GenerationChunk(text_delta='{"x": "one"}', is_first=True)])
+ proc = StreamingProcessor(nc=nc, registry=_make_registry(adapter), worker_id="w1")
+ wi = _make_work_item(generate={"prompt": "Hi", "max_new_tokens": 8, "grammar": _STRICT_SCHEMA_PAYLOAD})
+
+ await proc.process(_make_msg(wi), "test/model")
+
+ terminal = _terminal_chunk(nc)
+ assert terminal["done"] is True
+ assert terminal["finish_reason"] == "error"
+ assert terminal["error"]["code"] == "MODEL_OUTPUT_PARSE_ERROR"
+
+
[email protected]("strict", [None, False])
+async def test_non_strict_grammar_output_settles_normally(strict: bool | None) -> None:
+ nc = AsyncMock()
+ proc = StreamingProcessor(
+ nc=nc, registry=_make_registry(_FakeGenAdapter(_completion_script("not json"))), worker_id="w1"
+ )
+ grammar = {key: value for key, value in _STRICT_SCHEMA_PAYLOAD.items() if key != "strict"}
+ if strict is not None:
+ grammar["strict"] = strict
+
+ await proc.process(
+ _make_msg(_make_work_item(generate={"prompt": "Hi", "max_new_tokens": 8, "grammar": grammar})), "test/model"
+ )
+
+ terminal = _terminal_chunk(nc)
+ assert terminal["finish_reason"] == "stop"
+ assert terminal.get("error") is None
+
+
+async def test_strict_grammar_conforming_output_settles_normally() -> None:
+ nc = AsyncMock()
+ proc = StreamingProcessor(
+ nc=nc, registry=_make_registry(_FakeGenAdapter(_completion_script('{"x": 1}'))), worker_id="w1"
+ )
+ wi = _make_work_item(generate={"prompt": "Hi", "max_new_tokens": 8, "grammar": _STRICT_SCHEMA_PAYLOAD})
+
+ await proc.process(_make_msg(wi), "test/model")
+
+ terminal = _terminal_chunk(nc)
+ assert terminal["finish_reason"] == "stop"
+ assert terminal.get("error") is None
+
+
+async def test_strict_ebnf_work_item_is_rejected_before_dispatch() -> None:
+ nc = AsyncMock()
+ adapter = _FakeGenAdapter(_completion_script("yes"))
+ proc = StreamingProcessor(nc=nc, registry=_make_registry(adapter), worker_id="w1")
+ grammar = {"kind": "ebnf", "value": 'root ::= "yes"', "strict": True}
+
+ await proc.process(
+ _make_msg(_make_work_item(generate={"prompt": "Hi", "max_new_tokens": 8, "grammar": grammar})), "test/model"
+ )
+
+ terminal = _terminal_chunk(nc)
+ assert terminal["error"]["code"] == "unsupported_field"
+ assert adapter.close_calls == 0
+
+
+def _grammar_routed_registry(adapter: GenerationAdapter, *, served: tuple[str, ...] | None = None) -> MagicMock:
+ config = ModelConfig.model_validate(
+ {
+ "sie_id": "test/model",
+ "hf_id": "test/model",
+ "inputs": {"text": True},
+ "tasks": {
+ "generate": {
+ "context_length": 4096,
+ "max_output_tokens": 512,
+ "grammar_profile": "no-spec",
+ "capabilities": {"grammar": ["json_schema"]},
+ }
+ },
+ "max_sequence_length": 4096,
+ "profiles": {
+ "default": {
+ "max_batch_tokens": 4096,
+ "kv_budget_tokens": 2048,
+ "adapter_path": "sie_server.adapters.fake.adapter:FakeAdapter",
+ "adapter_options": {"loadtime": {"speculative": {"algorithm": "NEXTN", "num_steps": 3}}},
+ },
+ "no-spec": {
+ "extends": "default",
+ "adapter_options": {"loadtime": {"speculative": {"enabled": False}}},
+ },
+ },
+ }
+ )
+ configs = expand_profile_variants([config])
+ if served is not None:
+ configs = {name: value for name, value in configs.items() if name in served}
+ registry = _make_registry(adapter)
+ registry.has_model.side_effect = configs.__contains__
+ registry.get_config.side_effect = configs.__getitem__
+ return registry
+
+
+async def test_grammar_work_item_runs_on_the_grammar_profile(monkeypatch: pytest.MonkeyPatch) -> None:
+ nc = AsyncMock()
+ registry = _grammar_routed_registry(_FakeGenAdapter(_completion_script('{"x": 1}')))
+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")
+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))
+ wi = _make_work_item(generate={"prompt": "Hi", "max_new_tokens": 8, "grammar": _STRICT_SCHEMA_PAYLOAD})
+
+ await proc.process(_make_msg(wi), "test/model")
+
+ registry.get.assert_called_with("test/model:no-spec")
+ assert _terminal_chunk(nc)["finish_reason"] == "stop"
+
+
+async def test_unconstrained_work_item_keeps_the_requested_profile(monkeypatch: pytest.MonkeyPatch) -> None:
+ nc = AsyncMock()
+ registry = _grammar_routed_registry(_FakeGenAdapter(_completion_script("free text")))
+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")
+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))
+
+ await proc.process(_make_msg(_make_work_item()), "test/model")
+
+ registry.get.assert_called_with("test/model")
+
+
+async def test_grammar_work_item_without_its_grammar_profile_is_rejected() -> None:
+ nc = AsyncMock()
+ adapter = _FakeGenAdapter(_completion_script('{"x": 1}'))
+ registry = _grammar_routed_registry(adapter, served=("test/model",))
+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")
+ wi = _make_work_item(generate={"prompt": "Hi", "max_new_tokens": 8, "grammar": _STRICT_SCHEMA_PAYLOAD})
+ msg = _make_msg(wi)
+
+ await proc.process(msg, "test/model")
+
+ terminal = _terminal_chunk(nc)
+ assert terminal["error"]["code"] == "unsupported_field"
+ assert terminal["error"]["param"] == "grammar"
+ registry.get.assert_not_called()
+ assert adapter.close_calls == 0
+ msg.ack.assert_awaited()
diff --git a/packages/sie_server/tests/processors/test_strict_grammar.py b/packages/sie_server/tests/processors/test_strict_grammar.py
new file mode 100644
index 000000000..0bfddf57c
--- /dev/null
+++ b/packages/sie_server/tests/processors/test_strict_grammar.py
@@ -0,0 +1,451 @@
+"""Tests for strict structured-output verification."""
+
+from __future__ import annotations
+
+import time
+import urllib.request
+from collections.abc import AsyncIterator
+
+import pytest
+from sie_server.adapters._generation_base import GenerationChunk, ToolCallDelta
+from sie_server.processors import strict_grammar
+from sie_server.processors.strict_grammar import (
+ MODEL_OUTPUT_PARSE_ERROR,
+ enforce_strict_grammar,
+ output_violation,
+ requires_output_validation,
+)
+from sie_server.types.grammar import GrammarSpec
+
+_SCHEMA = {
+ "type": "object",
+ "properties": {
+ "name": {"type": "string", "pattern": "^[A-Z]"},
+ "count": {"type": "integer"},
+ },
+ "required": ["name", "count"],
+ "additionalProperties": False,
+}
+_STRICT_SCHEMA = GrammarSpec(kind="json_schema", value=_SCHEMA, strict=True)
+_STRICT_REGEX = GrammarSpec(kind="regex", value=r"[A-Z]{3}-\d{4}", strict=True)
+
+
+async def _stream(chunks: list[GenerationChunk]) -> AsyncIterator[GenerationChunk]:
+ for chunk in chunks:
+ yield chunk
+
+
+async def _drain(chunks: AsyncIterator[GenerationChunk]) -> list[GenerationChunk]:
+ return [chunk async for chunk in chunks]
+
+
+def _completion(*deltas: str, finish_reason: str = "stop") -> list[GenerationChunk]:
+ chunks = [GenerationChunk(text_delta=delta) for delta in deltas]
+ chunks.append(
+ GenerationChunk(
+ text_delta="",
+ done=True,
+ finish_reason=finish_reason, # type: ignore[arg-type]
+ prompt_tokens=3,
+ completion_tokens=len(deltas),
+ )
+ )
+ return chunks
+
+
+ ("grammar", "expected"),
+ [
+ (None, False),
+ (GrammarSpec(kind="json_schema", value=_SCHEMA), False),
+ (GrammarSpec(kind="json_schema", value=_SCHEMA, strict=False), False),
+ (_STRICT_SCHEMA, True),
+ (_STRICT_REGEX, True),
+ (GrammarSpec(kind="ebnf", value='root ::= "a"', strict=True), False),
+ ],
+)
+def test_requires_output_validation(grammar: GrammarSpec | None, expected: bool) -> None:
+ assert requires_output_validation(grammar) is expected
+
+
+ ("text", "expected"),
+ [
+ ('{"name": "Ada", "count": 2}', None),
+ (' {"name": "Ada", "count": 2}\n', None),
+ ("[]", "generated output does not match the requested JSON schema at $ ('type' keyword)"),
+ ('{"name": "Ada"}', "generated output does not match the requested JSON schema at $ ('required' keyword)"),
+ (
+ '{"name": "ada", "count": 2}',
+ "generated output does not match the requested JSON schema at $.name ('pattern' keyword)",
+ ),
+ (
+ '{"name": "Ada", "count": 2, "extra": true}',
+ "generated output does not match the requested JSON schema at $ ('additionalProperties' keyword)",
+ ),
+ ('{"name": "Ada", "count": ', "generated output is not valid JSON"),
+ ('{"name": "Ada", "count": NaN}', "generated output is not valid JSON"),
+ ("", "generated output is not valid JSON"),
+ ],
+)
+def test_json_schema_output_violation(text: str, expected: str | None) -> None:
+ assert output_violation(_STRICT_SCHEMA, text) == expected
+
+
+def test_json_schema_pattern_properties_use_the_bounded_engine() -> None:
+ grammar = GrammarSpec(
+ kind="json_schema",
+ value={
+ "type": "object",
+ "patternProperties": {"^x-": {"type": "string"}},
+ "additionalProperties": False,
+ },
+ strict=True,
+ )
+
+ assert output_violation(grammar, '{"x-trace": "abc"}') is None
+ assert output_violation(grammar, '{"x-trace": 1}') == (
+ "generated output does not match the requested JSON schema at $.x-trace ('type' keyword)"
+ )
+ assert output_violation(grammar, '{"other": "abc"}') == (
+ "generated output does not match the requested JSON schema at $ ('additionalProperties' keyword)"
+ )
+
+
+def test_json_schema_internal_refs_resolve_and_remote_refs_are_never_fetched(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ def refuse_network(*_args: object, **_kwargs: object) -> None:
+ raise AssertionError("strict grammar verification must not fetch remote schemas")
+
+ monkeypatch.setattr(urllib.request, "urlopen", refuse_network)
+ local = GrammarSpec(
+ kind="json_schema",
+ value={"$defs": {"item": {"type": "integer"}}, "type": "array", "items": {"$ref": "#/$defs/item"}},
+ strict=True,
+ )
+ remote = GrammarSpec(kind="json_schema", value={"$ref": "https://schemas.example.com/item.json"}, strict=True)
+
+ assert output_violation(local, "[1, 2]") is None
+ assert output_violation(local, '[1, "2"]') == (
+ "generated output does not match the requested JSON schema at $[1] ('type' keyword)"
+ )
+ assert output_violation(remote, "{}") == "generated output could not be verified against the requested grammar"
+
+
+def test_unevaluated_properties_is_never_evaluated_with_unbounded_patterns(monkeypatch: pytest.MonkeyPatch) -> None:
+ def refuse_validation(*_args: object, **_kwargs: object) -> None:
+ raise AssertionError("jsonschema must not evaluate unevaluatedProperties")
+
+ monkeypatch.setattr(strict_grammar, "_bounded_validator_class", refuse_validation)
+ schema = {
+ "type": "object",
+ "properties": {"child": {"patternProperties": {"(a|aa)+$": {}}, "unevaluatedProperties": False}},
+ }
+ grammar = GrammarSpec(kind="json_schema", value=schema, strict=True)
+
+ assert strict_grammar.unverifiable_schema_keyword(schema) == "unevaluatedProperties"
+ assert output_violation(grammar, '{"child": {}}') == (
+ "generated output could not be verified against the requested grammar"
+ )
+
+
+ "schema",
+ [
+ {
+ "$schema": "https://json-schema.org/draft/2019-09/schema",
+ "type": "array",
+ "items": [],
+ "additionalItems": {"unevaluatedProperties": False, "patternProperties": {"(a|aa)+$": {}}},
+ },
+ {"type": "object", "dependencies": {"a": {"unevaluatedProperties": False}}},
+ {"type": "string", "contentSchema": {"unevaluatedProperties": False}},
+ {"anyOf": [{"items": [{"unevaluatedProperties": False}]}]},
+ ],
+)
+def test_unevaluated_properties_is_found_in_every_subschema_position(schema: dict[str, object]) -> None:
+ assert strict_grammar.unverifiable_schema_keyword(schema) == "unevaluatedProperties"
+ assert output_violation(GrammarSpec(kind="json_schema", value=schema, strict=True), "[{}]") == (
+ "generated output could not be verified against the requested grammar"
+ )
+
+
+ "schema",
+ [
+ {"type": "object", "properties": {"unevaluatedProperties": {"type": "string"}}},
+ {"enum": [{"unevaluatedProperties": False}]},
+ {"const": {"unevaluatedProperties": False}},
+ {"dependentRequired": {"unevaluatedProperties": ["a"]}},
+ ],
+)
+def test_unevaluated_properties_as_data_or_a_name_is_verifiable(schema: dict[str, object]) -> None:
+ assert strict_grammar.unverifiable_schema_keyword(schema) is None
+
+
+def test_unevaluated_properties_as_a_property_name_is_verifiable() -> None:
+ schema = {"type": "object", "properties": {"unevaluatedProperties": {"type": "string"}}}
+
+ assert strict_grammar.unverifiable_schema_keyword(schema) is None
+ assert (
+ output_violation(GrammarSpec(kind="json_schema", value=schema, strict=True), '{"unevaluatedProperties": "x"}')
+ is None
+ )
+
+
+ ("text", "expected"),
+ [
+ ("ABC-1234", None),
+ ("ABC-1234 ", "generated output does not match the requested regex"),
+ ("xABC-1234", "generated output does not match the requested regex"),
+ ],
+)
+def test_regex_output_violation_requires_a_full_match(text: str, expected: str | None) -> None:
+ assert output_violation(_STRICT_REGEX, text) == expected
+
+
+def test_pathological_pattern_is_bounded_and_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(strict_grammar, "_PATTERN_BUDGET_S", 0.2)
+ grammar = GrammarSpec(kind="regex", value=r"(a|aa)+$", strict=True)
+
+ started = time.monotonic()
+ violation = output_violation(grammar, "a" * 64 + "!")
+
+ assert violation == "generated output could not be verified against the requested grammar"
+ assert time.monotonic() - started < 5
+
+
+async def test_strict_violation_replaces_the_stop_terminal() -> None:
+ chunks = await _drain(enforce_strict_grammar(_stream(_completion('{"name": ', '"Ada"}')), _STRICT_SCHEMA))
+
+ assert [chunk.text_delta for chunk in chunks[:-1]] == ['{"name": ', '"Ada"}']
+ terminal = chunks[-1]
+ assert terminal.done is True
+ assert terminal.finish_reason == "error"
+ assert terminal.error_code == MODEL_OUTPUT_PARSE_ERROR
+ assert terminal.error_message == (
+ "generated output does not match the requested JSON schema at $ ('required' keyword)"
+ )
+ assert terminal.prompt_tokens == 3
+ assert terminal.completion_tokens == 2
+
+
+async def test_conforming_strict_output_keeps_the_stop_terminal() -> None:
+ chunks = await _drain(
+ enforce_strict_grammar(_stream(_completion('{"name": "Ada", ', '"count": 1}')), _STRICT_SCHEMA)
+ )
+
+ assert chunks[-1].finish_reason == "stop"
+ assert chunks[-1].error_code is None
+
+
+ "grammar",
+ [
+ None,
+ GrammarSpec(kind="json_schema", value=_SCHEMA),
+ GrammarSpec(kind="json_schema", value=_SCHEMA, strict=False),
+ ],
+)
+def test_non_strict_grammars_return_the_stream_unchanged(grammar: GrammarSpec | None) -> None:
+ upstream = _stream(_completion("not json"))
+
+ assert enforce_strict_grammar(upstream, grammar) is upstream
+
+
[email protected]("finish_reason", ["length", "cancelled", "error"])
+async def test_non_stop_terminals_are_not_verified(finish_reason: str) -> None:
+ chunks = await _drain(
+ enforce_strict_grammar(_stream(_completion('{"name": ', finish_reason=finish_reason)), _STRICT_SCHEMA)
+ )
+
+ assert chunks[-1].finish_reason == finish_reason
+ assert chunks[-1].error_code is None
+
+
+async def test_existing_terminal_errors_are_preserved() -> None:
+ upstream = [
+ GenerationChunk(
+ text_delta="",
+ done=True,
+ finish_reason="error",
+ error_code="empty_model_output",
+ error_message="model produced no visible output text",
+ )
+ ]
+
+ chunks = await _drain(enforce_strict_grammar(_stream(upstream), _STRICT_SCHEMA))
+
+ assert chunks[-1].error_code == "empty_model_output"
+
+
+async def test_tool_call_turns_are_not_verified() -> None:
+ upstream = [
+ GenerationChunk(text_delta="", tool_call_delta=ToolCallDelta(index=0, id="call_1", function_name="lookup")),
+ GenerationChunk(text_delta="", tool_call_delta=ToolCallDelta(index=0, arguments_delta='{"q": "x"}')),
+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),
+ ]
+
+ chunks = await _drain(enforce_strict_grammar(_stream(upstream), _STRICT_SCHEMA))
+
+ assert chunks[-1].finish_reason == "stop"
+ assert chunks[-1].error_code is None
+
+
+async def test_every_candidate_is_verified() -> None:
+ terminal = GenerationChunk(
+ text_delta="",
+ done=True,
+ finish_reason="stop",
+ candidates=(
+ {"text": '{"name": "Ada", "count": 1}', "finish_reason": "stop", "logprobs": None},
+ {"text": '{"name": "Ada"}', "finish_reason": "stop", "logprobs": None},
+ {"text": '{"name": ', "finish_reason": "length", "logprobs": None},
+ ),
+ )
+
+ chunks = await _drain(enforce_strict_grammar(_stream([terminal]), _STRICT_SCHEMA))
+
+ assert chunks[-1].error_code == MODEL_OUTPUT_PARSE_ERROR
+ assert "'required' keyword" in (chunks[-1].error_message or "")
+
+
+async def test_shared_tool_call_terminal_still_verifies_choices_that_stopped() -> None:
+ terminal = GenerationChunk(
+ text_delta="",
+ done=True,
+ finish_reason="tool_calls",
+ candidates=(
+ {
+ "text": "",
+ "finish_reason": "tool_calls",
+ "logprobs": None,
+ "tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "f", "arguments": "{}"}}],
+ },
+ {"text": '{"name": "Ada"}', "finish_reason": "stop", "logprobs": None},
+ ),
+ )
+
+ chunks = await _drain(enforce_strict_grammar(_stream([terminal]), _STRICT_SCHEMA))
+
+ assert chunks[-1].error_code == MODEL_OUTPUT_PARSE_ERROR
+ assert "'required' keyword" in (chunks[-1].error_message or "")
+
+
+async def test_streamed_tool_call_terminal_still_verifies_other_choices() -> None:
+ upstream = [
+ GenerationChunk(
+ text_delta="", choice_index=0, tool_call_delta=ToolCallDelta(index=0, id="c", function_name="f")
+ ),
+ GenerationChunk(text_delta="", choice_index=0, finish_reason="tool_calls"),
+ GenerationChunk(text_delta="not a code", choice_index=1),
+ GenerationChunk(text_delta="", choice_index=1, finish_reason="stop"),
+ GenerationChunk(text_delta="", done=True, finish_reason="tool_calls"),
+ ]
+
+ chunks = await _drain(enforce_strict_grammar(_stream(upstream), _STRICT_REGEX))
+
+ assert chunks[-1].error_code == MODEL_OUTPUT_PARSE_ERROR
+
+
+async def test_streamed_choices_are_verified_independently() -> None:
+ upstream = [
+ GenerationChunk(text_delta="ABC-", choice_index=0),
+ GenerationChunk(text_delta="XYZ-", choice_index=1),
+ GenerationChunk(text_delta="1234", choice_index=0),
+ GenerationChunk(text_delta="12", choice_index=1),
+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),
+ ]
+
+ chunks = await _drain(enforce_strict_grammar(_stream(upstream), _STRICT_REGEX))
+
+ assert chunks[-1].error_code == MODEL_OUTPUT_PARSE_ERROR
+ assert chunks[-1].error_message == "generated output does not match the requested regex"
+
+
+async def test_streamed_choice_finish_reasons_exclude_truncated_and_tool_call_choices() -> None:
+ upstream = [
+ GenerationChunk(text_delta="ABC-1234", choice_index=0),
+ GenerationChunk(text_delta="XYZ-", choice_index=1),
+ GenerationChunk(text_delta="", choice_index=0, finish_reason="stop"),
+ GenerationChunk(text_delta="12", choice_index=1, finish_reason="length"),
+ GenerationChunk(
+ text_delta="",
+ choice_index=2,
+ tool_call_delta=ToolCallDelta(index=0, id="call_1", function_name="lookup"),
+ ),
+ GenerationChunk(text_delta="", choice_index=2, finish_reason="stop"),
+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),
+ ]
+
+ chunks = await _drain(enforce_strict_grammar(_stream(upstream), _STRICT_REGEX))
+
+ assert chunks[-1].finish_reason == "stop"
+ assert chunks[-1].error_code is None
+
+
+async def test_streamed_choice_that_stops_is_still_verified() -> None:
+ upstream = [
+ GenerationChunk(text_delta="ABC-1234", choice_index=0, finish_reason="length"),
+ GenerationChunk(text_delta="not a code", choice_index=1),
+ GenerationChunk(text_delta="", choice_index=1, finish_reason="stop"),
+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),
+ ]
+
+ chunks = await _drain(enforce_strict_grammar(_stream(upstream), _STRICT_REGEX))
+
+ assert chunks[-1].error_code == MODEL_OUTPUT_PARSE_ERROR
+
+
+async def test_missing_terminal_is_verified_as_an_implicit_stop() -> None:
+ upstream = [GenerationChunk(text_delta='{"name": '), GenerationChunk(text_delta='"Ada"}')]
+
+ chunks = await _drain(enforce_strict_grammar(_stream(upstream), _STRICT_SCHEMA))
+
+ assert [chunk.text_delta for chunk in chunks[:-1]] == ['{"name": ', '"Ada"}']
+ terminal = chunks[-1]
+ assert terminal.done is True
+ assert terminal.finish_reason == "error"
+ assert terminal.error_code == MODEL_OUTPUT_PARSE_ERROR
+
+
+async def test_conforming_output_without_a_terminal_is_passed_through() -> None:
+ upstream = [GenerationChunk(text_delta='{"name": "Ada", "count": 1}')]
+
+ chunks = await _drain(enforce_strict_grammar(_stream(upstream), _STRICT_SCHEMA))
+
+ assert chunks == upstream
+
+
+async def test_closing_the_wrapper_closes_the_upstream_iterator() -> None:
+ closed = False
+
+ async def upstream() -> AsyncIterator[GenerationChunk]:
+ nonlocal closed
+ try:
+ yield GenerationChunk(text_delta="{")
+ yield GenerationChunk(text_delta="}")
+ finally:
+ closed = True
+
+ wrapped = enforce_strict_grammar(upstream(), _STRICT_SCHEMA)
+ assert (await anext(wrapped)).text_delta == "{"
+ await wrapped.aclose() # type: ignore[attr-defined]
+
+ assert closed is True
diff --git a/packages/sie_ts_sdk/README.md b/packages/sie_ts_sdk/README.md
index 8ff9639f9..35ef9cca4 100644
--- a/packages/sie_ts_sdk/README.md
+++ b/packages/sie_ts_sdk/README.md
@@ -174,8 +174,9 @@ Streaming calls throw `SIEStreamError` for mid-stream error chunks —
the HTTP connection was healthy but the worker or gateway emitted an
error envelope partway through. Branch on `error.code` (for example
`empty_model_output`, a terminal generation that produced no visible
-text) and, when `error.requestId` is present, use it to correlate with
-gateway logs. For a validated `RESOURCE_EXHAUSTED` terminal,
+text, or `MODEL_OUTPUT_PARSE_ERROR`, a strict grammar whose finished
+output did not conform) and, when `error.requestId` is present, use it
+to correlate with gateway logs. For a validated `RESOURCE_EXHAUSTED` terminal,
`error.retryAfter` carries the operator hint in milliseconds; its presence
does not make retrying generation safe after output has already arrived.
diff --git a/uv.lock b/uv.lock
index 1682d75b7..7db0228a4 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4853,6 +4853,7 @@ dependencies = [
{ name = "glirel" },
{ name = "httpx" },
{ name = "huggingface-hub" },
+ { name = "jsonschema" },
{ name = "loguru" },
{ name = "msgpack" },
{ name = "msgpack-numpy" },
@@ -4872,6 +4873,8 @@ dependencies = [
{ name = "pydantic-settings" },
{ name = "python-multipart" },
{ name = "pyyaml" },
+ { name = "referencing" },
+ { name = "regex" },
{ name = "requests" },
{ name = "rich" },
{ name = "safetensors" },
@@ -4923,6 +4926,7 @@ requires-dist = [
{ name = "glirel", specifier = ">=1.0,<2" },
{ name = "httpx", specifier = ">=0.28.1" },
{ name = "huggingface-hub", specifier = ">=0.26,<2" },
+ { name = "jsonschema", specifier = ">=4.23,<5" },
{ name = "loguru", specifier = ">=0.7,<1" },
{ name = "msgpack", specifier = ">=1.2.1,<2" },
{ name = "msgpack-numpy", specifier = ">=0.4,<1" },
@@ -4943,6 +4947,8 @@ requires-dist = [
{ name = "pydantic-settings", specifier = ">=2.6,<3" },
{ name = "python-multipart", specifier = ">=0.0.20,<1" },
{ name = "pyyaml", specifier = ">=6,<7" },
+ { name = "referencing", specifier = ">=0.36,<1" },
+ { name = "regex", specifier = ">=2024.11.6" },
{ name = "requests", specifier = ">=2.32,<3" },
{ name = "rich", specifier = ">=13,<14" },
{ name = "safetensors", specifier = ">=0.4,<1" },