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
fix: isolate grammar followers and type malformed backend errors
Attila Laszlo Nagy4c5e05fe1ce5
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.pyindex 49078df0a..04ca11165 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py@@ -170,7 +170,7 @@ def _unique_json_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:result: dict[str, Any] = {}for key, value in pairs:if key in result:- raise ValueError("SGLang /generate returned duplicate JSON keys")+ raise GenerationError("SGLang /generate returned duplicate JSON keys")result[key] = valuereturn result@@ -197,7 +197,7 @@ async def _raise_for_sglang_http_error(try:body = await asyncio.wait_for(read_error(), timeout=1.0)payload = json.loads(body, object_pairs_hook=_unique_json_object)- except (ValueError, RecursionError, httpx.HTTPError, TimeoutError):+ except (ValueError, RecursionError, GenerationError, httpx.HTTPError, TimeoutError):passelse:if payload == {"error": {"message": _JSON_SCHEMA_TYPE_DIAGNOSTIC}}:diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.pyindex df073ef72..8547f3a6b 100644--- a/packages/sie_server/src/sie_server/processors/streaming.py+++ b/packages/sie_server/src/sie_server/processors/streaming.py@@ -3636,7 +3636,7 @@ class StreamingProcessor:# load, so a generous ceiling here still guarantees the# follower settles its own work item rather than hanging# until ack_wait and triggering redelivery.- await _wait_for(future_to_await, timeout=_GRAMMAR_FOLLOWER_TIMEOUT_S)+ await _wait_for(asyncio.shield(future_to_await), timeout=_GRAMMAR_FOLLOWER_TIMEOUT_S)except Exception as exc: # noqa: BLE001# Leader's compile failed, was cancelled, or did not# resolve in time; surface the same terminal-error path.diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.pyindex b6c13829e..8e4475400 100644--- a/packages/sie_server/tests/adapters/test_sglang_generation.py+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py@@ -2849,3 +2849,27 @@ async def test_encoded_http_error_is_not_read_or_decompressed(adapter, encoding,):raise AssertionError("error response must not yield a generation chunk")assert closed.is_set()+++ ("n", "stream", "best_of"), [(1, False, None), (2, True, None), (2, False, None), (1, False, 2)]+)+async def test_duplicate_event_keys_raise_typed_error_before_output(adapter, n, stream, best_of) -> None:+ payload = '{"text":"secret","text":"[]","meta_info":{"finish_reason":{"type":"stop"},"prompt_tokens":1,"completion_tokens":1}}'++ def respond(request):+ body = json.loads(request.content)+ content = "data: " + payload + "\n\n" if body["stream"] else "[" + payload + "]"+ return httpx.Response(200, text=content)++ async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as client:+ adapter._http_client = client+ adapter._server_url = "http://localhost:30005"+ with pytest.raises(GenerationError, match="duplicate JSON keys") as error:+ async for _ in adapter.generate(+ prompt="Optional value", max_new_tokens=8, grammar=_TYPE_GRAMMAR, n=n, stream=stream, best_of=best_of+ ):+ raise AssertionError("duplicate keys must not yield text or usage")+ assert error.value.code == "inference_error"+ assert "secret" not in str(error.value)diff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.pyindex f249100c2..f4dc8743c 100644--- a/packages/sie_server/tests/processors/test_streaming.py+++ b/packages/sie_server/tests/processors/test_streaming.py@@ -4110,7 +4110,7 @@ async def test_known_type_refusal_is_identical_for_preflight_leader_and_followermessages = [_make_msg(_make_work_item()) for _ in range(2)]def wait_for(awaitable, *, timeout):- if any(awaitable is future for future in proc._grammar_inflight.values()):+ if timeout == streaming_mod._GRAMMAR_FOLLOWER_TIMEOUT_S:following.set()return real_wait_for(awaitable, timeout=timeout)@@ -4174,3 +4174,88 @@ async def test_backend_type_refusal_survives_worker_terminal_and_settlement(monkassert terminal.get("usage") is Nonemessage.ack.assert_awaited_once()assert adapter.close_calls == 1++[email protected]("interruption", ["cancel", "timeout"])[email protected]("refusal", [False, True])+async def test_grammar_follower_interruption_preserves_shared_compile(monkeypatch, interruption, refusal) -> None:+ started = asyncio.Event()+ release = asyncio.Event()+ following = asyncio.Event()+ real_wait_for = streaming_mod._wait_for+ nc = AsyncMock()+ registry = _make_registry(_FakeGenAdapter([]))+ registry.get_config.side_effect = KeyError("no config")+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ grammar = GrammarSpec(kind="json_schema", value={"type": ["string", "null"]})+ messages = [_make_msg(_make_work_item()) for _ in range(3)]++ async def tokenizer(_):+ started.set()+ await release.wait()+ return object()++ def compile_result(*_):+ if refusal:+ raise GrammarValidationError(OUTLINES_JSON_SCHEMA_TYPE_MESSAGE, code="invalid_request", param="grammar")+ return True++ calls = _patch_compile(monkeypatch, compile_result)+ monkeypatch.setattr(proc, "_get_tokenizer", tokenizer)++ def wait_for(awaitable, *, timeout):+ if timeout == streaming_mod._GRAMMAR_FOLLOWER_TIMEOUT_S:+ following.set()+ if interruption == "timeout" and asyncio.current_task() is interrupted:+ timeout = 0+ return real_wait_for(awaitable, timeout=timeout)++ monkeypatch.setattr(streaming_mod, "_wait_for", wait_for)++ async def run(index):+ return await proc._ensure_grammar_ready(+ grammar,+ model_id="test/model",+ reply_subject="_INBOX.test",+ request_id=f"req-{index}",+ attempt_id=f"att-{index}",+ msg=messages[index],+ )++ leader = asyncio.create_task(run(0))+ try:+ await asyncio.wait_for(started.wait(), timeout=3)+ interrupted = asyncio.create_task(run(1))+ await asyncio.wait_for(following.wait(), timeout=3)+ following.clear()+ remaining = asyncio.create_task(run(2))+ await asyncio.wait_for(following.wait(), timeout=3)+ if interruption == "cancel":+ interrupted.cancel()+ with pytest.raises(asyncio.CancelledError):+ await interrupted+ messages[1].ack.assert_not_awaited()+ messages[1].nak.assert_not_awaited()+ assert all(chunk["request_id"] != "req-1" for chunk in _decode_chunks(nc))+ else:+ assert await asyncio.wait_for(interrupted, timeout=3) is False+ messages[1].ack.assert_awaited_once()+ timed_out = [chunk for chunk in _decode_chunks(nc) if chunk["request_id"] == "req-1"]+ assert len(timed_out) == 1+ assert timed_out[0]["error"]["code"] == "grammar_compile_failed"+ assert timed_out[0].get("usage") is None+ shared = next(iter(proc._grammar_inflight.values()))+ assert not shared.done()+ finally:+ release.set()+ assert await asyncio.gather(leader, remaining) == [not refusal, not refusal]+ assert len(calls) == 1+ assert proc._grammar_inflight == {}+ if refusal:+ for message in (messages[0], messages[2]):+ message.ack.assert_awaited_once()+ terminals = _decode_chunks(nc)+ kept = [chunk for chunk in terminals if chunk["request_id"] in {"req-0", "req-2"}]+ assert len(kept) == 2+ assert all(chunk["error"]["code"] == "invalid_request" and chunk.get("usage") is None for chunk in kept)