Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
"""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,
enforce_strict_tool_arguments,
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
@pytest.mark.parametrize(
("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
@pytest.mark.parametrize(
("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"
)
@pytest.mark.parametrize(
"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"
)
@pytest.mark.parametrize(
"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
)
@pytest.mark.parametrize(
("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
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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
@pytest.mark.parametrize(
"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
@pytest.mark.asyncio
@pytest.mark.parametrize("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
@pytest.mark.asyncio
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"
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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 "")
@pytest.mark.asyncio
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 "")
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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"
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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
@pytest.mark.asyncio
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
# -- strict function-tool arguments ---------------------------------------------
# ``minimum`` and ``pattern`` are among the keywords the grammar backend can drop,
# so the terminal check is what guarantees them.
_TOOL_SCHEMAS = {
"lookup": {**_SCHEMA, "properties": {**_SCHEMA["properties"], "count": {"type": "integer", "minimum": 1}}}
}
def _tool_call(name: str, arguments: str) -> list[GenerationChunk]:
return [
GenerationChunk(text_delta="", tool_call_delta=ToolCallDelta(index=0, id="call_1", function_name=name)),
GenerationChunk(text_delta="", tool_call_delta=ToolCallDelta(index=0, arguments_delta=arguments)),
GenerationChunk(text_delta="", done=True, finish_reason="tool_calls"),
]
@pytest.mark.asyncio
async def test_strict_tool_arguments_that_violate_the_schema_error_the_terminal() -> None:
upstream = _tool_call("lookup", '{"name": "Ada", "count": 0}')
chunks = await _drain(enforce_strict_tool_arguments(_stream(upstream), _TOOL_SCHEMAS))
assert chunks[-1].finish_reason == "error"
assert chunks[-1].error_code == MODEL_OUTPUT_PARSE_ERROR
assert "'lookup'" in (chunks[-1].error_message or "")
assert "minimum" in (chunks[-1].error_message or "")
@pytest.mark.asyncio
async def test_invalid_strict_tool_arguments_are_never_streamed() -> None:
"""The deltas of a strict call are held until the terminal check, so a violation reaches no client."""
upstream = _tool_call("lookup", '{"name": "Ada", "count": 0}')
chunks = await _drain(enforce_strict_tool_arguments(_stream(upstream), _TOOL_SCHEMAS))
assert [chunk.tool_call_delta for chunk in chunks] == [None]
assert chunks[0].error_code == MODEL_OUTPUT_PARSE_ERROR
@pytest.mark.asyncio
async def test_strict_tool_deltas_are_released_in_order_once_valid() -> None:
text = GenerationChunk(text_delta="Looking it up.")
trailing = GenerationChunk(text_delta=" Done.")
calls = _tool_call("lookup", '{"name": "Ada", "count": 2}')
upstream = [text, *calls[:2], trailing, calls[2]]
released: list[GenerationChunk] = []
async for chunk in enforce_strict_tool_arguments(_stream(upstream), _TOOL_SCHEMAS):
released.append(chunk)
if chunk is text:
# Text before any strict call is not delayed.
assert len(released) == 1
assert released == upstream
@pytest.mark.asyncio
async def test_a_choice_finish_after_a_strict_call_is_held_until_validation() -> None:
"""With ``n > 1`` a choice closes before the terminal; it must not close on an invalid call."""
calls = _tool_call("lookup", '{"name": "Ada", "count": 0}')
choice_finish = GenerationChunk(text_delta="", finish_reason="tool_calls")
chunks = await _drain(enforce_strict_tool_arguments(_stream([*calls[:2], choice_finish, calls[2]]), _TOOL_SCHEMAS))
assert [chunk.finish_reason for chunk in chunks] == ["error"]
@pytest.mark.asyncio
@pytest.mark.parametrize(("day", "valid"), [("2026-01-01", True), ("tomorrow", False)])
async def test_strict_tool_argument_formats_are_checked(day: str, valid: bool) -> None:
schemas = {"book": {"type": "object", "properties": {"day": {"type": "string", "format": "date"}}}}
upstream = _tool_call("book", f'{{"day": "{day}"}}')
chunks = await _drain(enforce_strict_tool_arguments(_stream(upstream), schemas))
assert (chunks[-1].error_code is None) is valid
@pytest.mark.asyncio
async def test_an_upstream_error_drops_the_unvalidated_strict_call() -> None:
calls = _tool_call("lookup", '{"name": "Ada", "count": 2}')
failed = GenerationChunk(text_delta="", done=True, finish_reason="error", error_code="upstream_error")
chunks = await _drain(enforce_strict_tool_arguments(_stream([*calls[:2], failed]), _TOOL_SCHEMAS))
assert chunks == [failed]
@pytest.mark.asyncio
async def test_conforming_strict_tool_arguments_keep_the_terminal() -> None:
upstream = _tool_call("lookup", '{"name": "Ada", "count": 2}')
chunks = await _drain(enforce_strict_tool_arguments(_stream(upstream), _TOOL_SCHEMAS))
assert chunks == upstream
@pytest.mark.asyncio
async def test_non_strict_tool_calls_are_not_validated() -> None:
upstream = _tool_call("other", '{"anything": true}')
chunks = await _drain(enforce_strict_tool_arguments(_stream(upstream), _TOOL_SCHEMAS))
assert chunks[-1].error_code is None
@pytest.mark.asyncio
async def test_strict_tool_calls_on_candidates_are_validated() -> None:
function = {"name": "lookup", "arguments": '{"name": "ada", "count": 1}'}
call = {"id": "call_1", "type": "function", "function": function}
terminal = GenerationChunk(
text_delta="", done=True, finish_reason="tool_calls", candidates=({"tool_calls": [call]},)
)
chunks = await _drain(enforce_strict_tool_arguments(_stream([terminal]), _TOOL_SCHEMAS))
assert chunks[-1].error_code == MODEL_OUTPUT_PARSE_ERROR
assert "pattern" in (chunks[-1].error_message or "")
def test_no_strict_tools_return_the_stream_unchanged() -> None:
upstream = _stream([])
assert enforce_strict_tool_arguments(upstream, {}) is upstream