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
release: v0.6.27
github-actions[bot]5d12cd581ddd
diff --git a/.coderabbit.yaml b/.coderabbit.yamldeleted file mode 100644index 8d5b19761..000000000--- a/.coderabbit.yaml+++ /dev/null@@ -1,24 +0,0 @@-# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json--reviews:- request_changes_workflow: true- auto_review:- enabled: false- drafts: false- labels:- - "coderabbit-direct"- path_filters:- - "examples/**"- - "README.md"- - "!examples/**/data/**"- - "!examples/**/fixtures/**"- - "examples/**/fixtures/SOURCES.md"- - "!examples/**/verified-run/**"- - "examples/**/verified-run/README.md"- - "!examples/**/uv.lock"- path_instructions:- - path: "examples/**"- instructions: |- Review runnable source, tests, configuration, and documentation.- Check that commands match the implementation and that tests cover failure paths.- Flag client-side model-name translation and undocumented synthetic results.diff --git a/.gitignore b/.gitignoreindex 775c78612..6b61fdcd7 100644--- a/.gitignore+++ b/.gitignore@@ -264,6 +264,7 @@ override.tf.json!deploy/cloud/terraform/aws-edge/.terraform.lock.hcl!deploy/cloud/terraform/s3-state/.terraform.lock.hcl!deploy/cloud/terraform/vercel/.terraform.lock.hcl+!deploy/cloud/terraform/console-preview/.terraform.lock.hcl!deploy/cloud/terraform/examples/dev/.terraform.lock.hcl!deploy/cloud/terraform/examples/dev-eu/.terraform.lock.hcl!deploy/cloud/terraform/examples/staging/.terraform.lock.hcldiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4f7e34045..b17394e26 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,60 @@# Changelog+## v0.6.27++- chore(release): refresh locks and generated sources+- chore(main): release 0.6.27+- fix(server): constrain SGLang compatibility paths+- fix(server): preserve LightOn SGLang compatibility+- fix(server): keep Qwen3-VL reranker batches working on transformers 5.3+- fix(generation): pair long-context qwen image bounds+- fix(generation): preserve qwen vision bounds+- fix(generation): validate high-context thinking profiles+- test(generation): align grammar backend expectations+- fix(generation): align direct backend output limits+- fix(generation): use compatible Qwen 27B grammar backend+- fix(generation): use compatible Qwen 35B grammar backend+- feat(generation): add hardware-specific context profiles+- fix(generation): preserve Gemma reasoning boundaries+- fix(generation): fit Gemma 256k KV cache on H100+- fix(sdk): retry pre-execution SSE capacity errors+- fix(generation): reserve Gemma long-context workspace+- feat(generation): add 256k profile candidates+- feat(generation): add strict Responses API parity+- fix(generation): hide split Gemma thinking boundary+- fix(generation): reject overflowing runtime numerics+- fix(generation): handle family-specific reasoning boundaries+- fix(generation): unblock cold model startup+- fix(server): align Gemma xgrammar dependency+- feat(server): complete generative model serving+- fix(server): enforce Qwen fast image bounds+- test(server): align vision profile contracts+- fix(server): bound Qwen visual context+- fix(server): replace stale root playground with redirect to Swagger docs+- fix(server): pin docling to its artifact revision and stop OCR gating load+- fix(colbert): honor transformers-5 rope_parameters when serving on the 4.x bundle+- fix(cloud): close connector review gaps+- fix(cloud): close connector review findings+- fix(clients): send connector repair idempotency header+- fix(cloud): address connector runtime review findings+- test(cloud): prove public postgres connector lifecycle+- feat(clients): expose recovery-bound connector repair+- feat(cloud): add direct connector inference+- feat(gateway): expose immutable execution evidence+- feat(clients): add connector plan controls+- feat(cloud): add connector plan schema policy+- feat(cloud): add connector plan guardrails+- fix(models): complete mLateOn serving recipe+- fix(server): preprocess native extract images+- feat(models): onboard lightonai/mLateOn (scaffolded)+- fix(sidecar): harden local generation cancellation+- test(server): shorten local ingest socket paths+- fix(sidecar): reserve cancel request bytes+- feat(server): add bounded local-ingest generation client+- fix(sidecar): harden local generation streaming+- feat(sidecar): stream generation over local ingest+- feat(models): onboard ibm-granite/granite-embedding-97m-multilingual-r2 (scaffolded)+## v0.6.26- chore(release): refresh locks and generated sourcesdiff --git a/Cargo.lock b/Cargo.lockindex dc2168233..54c1a858f 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3583,7 +3583,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-audio-prep"-version = "0.6.26"+version = "0.6.27"dependencies = ["audioadapter-buffers","opusic-sys",@@ -3597,7 +3597,7 @@ dependencies = [[[package]]name = "sie-gateway"-version = "0.6.26"+version = "0.6.27"dependencies = ["arc-swap","async-nats",@@ -3655,11 +3655,12 @@ dependencies = [[[package]]name = "sie-server-sidecar"-version = "0.6.26"+version = "0.6.27"dependencies = ["anyhow","async-nats","async-trait",+ "base64 0.22.1","blake3","bytes","clap",diff --git a/conformance/openai_generation/responses_request_vectors.json b/conformance/openai_generation/responses_request_vectors.jsonnew file mode 100644index 000000000..d95c18edb--- /dev/null+++ b/conformance/openai_generation/responses_request_vectors.json@@ -0,0 +1,158 @@+{+ "accepted": [+ {+ "name": "string defaults",+ "body": {"model": "m", "input": "Tell me a joke"},+ "expected": {+ "model": "m",+ "prompt": "Tell me a joke",+ "messages": null,+ "max_output_tokens": 16,+ "temperature": null,+ "top_p": null,+ "seed": null+ }+ },+ {+ "name": "developer and text parts",+ "body": {+ "model": "m",+ "input": [+ {"role": "developer", "content": "Be concise"},+ {+ "role": "user",+ "content": [+ {"type": "input_text", "text": "Hi "},+ {"type": "text", "text": "there"}+ ]+ }+ ],+ "stream": false+ },+ "expected": {+ "model": "m",+ "prompt": null,+ "messages": [+ {"role": "system", "content": "Be concise"},+ {"role": "user", "content": "Hi there"}+ ],+ "max_output_tokens": 16,+ "temperature": null,+ "top_p": null,+ "seed": null+ }+ },+ {+ "name": "sampling overrides",+ "body": {+ "model": "m",+ "input": "x",+ "max_output_tokens": 32,+ "temperature": 0.25,+ "top_p": 0.8,+ "seed": -1+ },+ "expected": {+ "model": "m",+ "prompt": "x",+ "messages": null,+ "max_output_tokens": 32,+ "temperature": 0.25,+ "top_p": 0.8,+ "seed": -1+ }+ }+ ],+ "rejected": [+ {+ "name": "known unsupported tools",+ "body": {"model": "m", "input": "x", "tools": []},+ "param": "tools",+ "code": "unsupported_field"+ },+ {+ "name": "unknown top-level field",+ "body": {"model": "m", "input": "x", "foo": true},+ "param": "foo",+ "code": "unsupported_field"+ },+ {+ "name": "empty message array",+ "body": {"model": "m", "input": []},+ "param": "input",+ "code": "invalid_request"+ },+ {+ "name": "unknown message field",+ "body": {"model": "m", "input": [{"role": "user", "content": "x", "name": "caller"}]},+ "param": "input[0].name",+ "code": "unsupported_field"+ },+ {+ "name": "unknown content-part field",+ "body": {+ "model": "m",+ "input": [{"role": "user", "content": [{"type": "input_text", "text": "x", "foo": true}]}]+ },+ "param": "input[0].content[0].foo",+ "code": "unsupported_field"+ },+ {+ "name": "non-text content part",+ "body": {+ "model": "m",+ "input": [{"role": "user", "content": [{"type": "input_image", "text": "x"}]}]+ },+ "param": "input[0].content[0].type",+ "code": "unsupported_field"+ },+ {+ "name": "missing role",+ "body": {"model": "m", "input": [{"content": "x"}]},+ "param": "input[0].role",+ "code": "invalid_request"+ },+ {+ "name": "tool role without tool-output support",+ "body": {"model": "m", "input": [{"role": "tool", "content": "x"}]},+ "param": "input[0].role",+ "code": "invalid_request"+ },+ {+ "name": "streaming unsupported",+ "body": {"model": "m", "input": "x", "stream": true},+ "param": "stream",+ "code": "unsupported_field"+ },+ {+ "name": "stream type",+ "body": {"model": "m", "input": "x", "stream": "false"},+ "param": "stream",+ "code": "invalid_request"+ },+ {+ "name": "zero top p",+ "body": {"model": "m", "input": "x", "top_p": 0},+ "param": "top_p",+ "code": "invalid_request"+ },+ {+ "name": "temperature exceeds runtime precision",+ "body": {"model": "m", "input": "x", "temperature": 1e100},+ "param": "temperature",+ "code": "invalid_request"+ },+ {+ "name": "seed outside signed i64",+ "body": {"model": "m", "input": "x", "seed": 9223372036854775808},+ "param": "seed",+ "code": "invalid_request"+ },+ {+ "name": "invalid output cap",+ "body": {"model": "m", "input": "x", "max_output_tokens": 0},+ "param": "max_output_tokens",+ "code": "invalid_request"+ }+ ]+}diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex fadecb7df..e8a44e466 100644--- a/deploy/helm/sie-cluster/Chart.yaml+++ b/deploy/helm/sie-cluster/Chart.yaml@@ -4,8 +4,8 @@ description: >-SIE (Search Inference Engine) Kubernetes deployment with gateway, GPU workers,and observabilitytype: application-version: 0.6.26 # x-release-please-version-appVersion: v0.6.26 # x-release-please-version+version: 0.6.27 # x-release-please-version+appVersion: v0.6.27 # x-release-please-versionkeywords:- inference- embeddingdiff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex 87bf106c4..acbd0575f 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.6.26"+version = "0.6.27"description = "SIE integration for ChromaDB"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_crewai/pyproject.toml b/integrations/sie_crewai/pyproject.tomlindex 8132a5361..05ff0f9d3 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.6.26"+version = "0.6.27"description = "SIE integration for CrewAI"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_dspy/pyproject.toml b/integrations/sie_dspy/pyproject.tomlindex c25908146..539a45fa2 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.6.26"+version = "0.6.27"description = "SIE integration for DSPy"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_haystack/pyproject.toml b/integrations/sie_haystack/pyproject.tomlindex 08c506a02..95a5bc6d3 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.6.26"+version = "0.6.27"description = "SIE integration for Haystack"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_lancedb/pyproject.toml b/integrations/sie_lancedb/pyproject.tomlindex 842c30a06..109c9965c 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.6.26"+version = "0.6.27"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex 968b1e00f..dbe0b193f 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.6.26"+version = "0.6.27"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex dd141c0af..884c66ab0 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.6.26"+version = "0.6.27"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex 59fcdf23f..967f9af2f 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.6.26"+version = "0.6.27"description = "SIE integration for Qdrant"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_ts_chroma/package.json b/integrations/sie_ts_chroma/package.jsonindex 9a014afba..327a19ba0 100644--- a/integrations/sie_ts_chroma/package.json+++ b/integrations/sie_ts_chroma/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-chroma",- "version": "0.6.26",+ "version": "0.6.27","description": "SIE embedding function for ChromaDB","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_lancedb/package.json b/integrations/sie_ts_lancedb/package.jsonindex 90b9a708b..e030bc4de 100644--- a/integrations/sie_ts_lancedb/package.json+++ b/integrations/sie_ts_lancedb/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-lancedb",- "version": "0.6.26",+ "version": "0.6.27","description": "SIE embedding function and reranker for LanceDB","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_langchain/package.json b/integrations/sie_ts_langchain/package.jsonindex eba7ece40..2abbd0958 100644--- a/integrations/sie_ts_langchain/package.json+++ b/integrations/sie_ts_langchain/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-langchain",- "version": "0.6.26",+ "version": "0.6.27","description": "SIE embeddings integration for LangChain.js","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_llamaindex/package.json b/integrations/sie_ts_llamaindex/package.jsonindex 9387cca26..9483587d9 100644--- a/integrations/sie_ts_llamaindex/package.json+++ b/integrations/sie_ts_llamaindex/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-llamaindex",- "version": "0.6.26",+ "version": "0.6.27","description": "SIE embeddings integration for LlamaIndex.TS","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_weaviate/pyproject.toml b/integrations/sie_weaviate/pyproject.tomlindex 8175d3594..c540ba005 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.6.26"+version = "0.6.27"description = "SIE integration for Weaviate"readme = "README.md"requires-python = ">=3.10"diff --git a/packages/sie_audio_prep/Cargo.toml b/packages/sie_audio_prep/Cargo.tomlindex 46a41095b..cbd2e54d5 100644--- a/packages/sie_audio_prep/Cargo.toml+++ b/packages/sie_audio_prep/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-audio-prep"-version = "0.6.26"+version = "0.6.27"edition = "2021"license = "Apache-2.0"description = "Bounded, shared audio decoding and resampling for SIE workers."diff --git a/packages/sie_audio_prep/build_wheel.py b/packages/sie_audio_prep/build_wheel.pyindex 0c1f23444..bda5a7d5e 100644--- a/packages/sie_audio_prep/build_wheel.py+++ b/packages/sie_audio_prep/build_wheel.py@@ -16,7 +16,7 @@ import zipfilefrom pathlib import PathMATURIN_VERSION = "1.13.3"-AUDIO_PREP_VERSION = "0.6.26" # x-release-please-version+AUDIO_PREP_VERSION = "0.6.27" # x-release-please-versionAUDIO_WHEEL_COMPATIBILITY = "manylinux_2_28"AUDIO_WHEEL_FILENAME = f"sie_audio_prep-{AUDIO_PREP_VERSION}-cp312-abi3-{AUDIO_WHEEL_COMPATIBILITY}_x86_64.whl"AUDIO_WHEEL_REMOTE = f"/opt/sie/wheels/{AUDIO_WHEEL_FILENAME}"diff --git a/packages/sie_audio_prep/pyproject.toml b/packages/sie_audio_prep/pyproject.tomlindex 6530f07d5..864a7710f 100644--- a/packages/sie_audio_prep/pyproject.toml+++ b/packages/sie_audio_prep/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "maturin"[project]name = "sie-audio-prep"-version = "0.6.26"+version = "0.6.27"description = "Bounded, shared audio decoding and resampling for SIE workers."requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex 8bd2e5ac5..a093669d1 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.6.26"+version = "0.6.27"edition = "2021"publish = falsediff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex 2baa62992..217c3dc8d 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -319,7 +319,15 @@]},"chat_template_kwargs": {- "description": "Per-request overrides for kwargs passed to the tokenizer's\n``apply_chat_template`` call. Object whose entries are merged on\ntop of the model YAML's ``chat_template_kwargs`` (the YAML wins\nfor keys present in both — adjust the YAML when a request needs\nto defeat a baked-in default). Typical use: pass\n``{\"enable_thinking\": false}`` to the Qwen3 family to suppress\n``<think>`` reasoning on a per-request basis. Absent → only the\nmodel YAML's defaults apply."+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/ChatTemplateKwargs",+ "description": "Per-request overrides from the bounded tokenizer-template contract.\nOnly ``enable_thinking`` and ``guardian_config.risk_name`` are\naccepted; unknown keys reject with 400 instead of reaching\n``apply_chat_template``. Values are merged under the model YAML's\noperator-owned defaults, which win on conflict."+ }+ ]},"frequency_penalty": {"description": "OpenAI ``frequency_penalty`` in ``[-2.0, 2.0]``; out-of-range or\nnon-numeric values yield 400 ``invalid_request``.",@@ -708,6 +716,31 @@],"type": "object"},+ "ChatTemplateKwargs": {+ "additionalProperties": false,+ "description": "Bounded tokenizer-template options accepted from a chat request.\n\nUnknown keys are rejected at the gateway instead of being forwarded to a\ntokenizer implementation as arbitrary keyword arguments.",+ "properties": {+ "enable_thinking": {+ "description": "Qwen-family switch controlling whether the template opens a thinking block.",+ "type": [+ "boolean",+ "null"+ ]+ },+ "guardian_config": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/GuardianChatTemplateConfig",+ "description": "Granite Guardian risk selection."+ }+ ]+ }+ },+ "type": "object"+ },"ClusterSummary": {"properties": {"gpu_count": {@@ -747,9 +780,9 @@]},"max_tokens": {- "description": "Positive integer; defaults to 16 (OpenAI's documented default for\ncompletions) when absent.",- "format": "int32",- "minimum": 0,+ "description": "Maximum number of generated tokens. Defaults to 16 when absent or null.",+ "maximum": 4294967295,+ "minimum": 1,"type": ["integer","null"@@ -812,8 +845,10 @@]},"temperature": {- "description": "Sampling temperature. Finite number ``>= 0``.",+ "description": "Sampling temperature representable by the worker runtime.","format": "float",+ "maximum": 3.4028234663852886e+38,+ "minimum": 0,"type": ["number","null"@@ -1765,6 +1800,22 @@],"type": "object"},+ "GuardianChatTemplateConfig": {+ "additionalProperties": false,+ "description": "Bounded Granite Guardian options accepted by ``chat_template_kwargs``.",+ "properties": {+ "risk_name": {+ "description": "Non-empty Granite Guardian risk identifier, at most 128 characters.",+ "maxLength": 128,+ "minLength": 1,+ "type": "string"+ }+ },+ "required": [+ "risk_name"+ ],+ "type": "object"+ },"HealthResponse": {"properties": {"cluster": {@@ -3297,16 +3348,18 @@"type": "object"},"ResponsesRequest": {+ "additionalProperties": false,"description": "OpenAI-compatible ``POST /v1/responses`` request (Responses MVP).\n\n**Strict allow-list**: unknown fields reject with 400\n``unsupported_field``. Type-invalid values reject with 400 ``invalid_request``.\n\n**Known-rejected fields**:\n- ``tools`` / ``tool_choice`` — rejected with 400 ``unsupported_field``.\n- ``previous_response_id`` — rejected with 400 ``unsupported_field``\n (Responses MVP is stateless single-turn).\n- ``reasoning`` — rejected with 400 ``unsupported_field``.\n- ``background`` — rejected with 400 ``unsupported_field``.\n- ``metadata`` — rejected with 400 ``unsupported_field``.\n- ``instructions`` — rejected with 400 ``unsupported_field``.\n- ``stream: true`` — rejected with 400 ``unsupported_field`` (SSE on\n Responses is deferred; use ``stream: false`` or omit).\n- Multimodal ``image_url`` / ``input_image`` content parts on the array\n form — rejected with 400 ``unsupported_field``: the Responses surface is\n text-only. (Vision input is supported on ``/v1/chat/completions``.)","properties": {"input": {- "description": "Either a string prompt OR an array of `{role, content}` messages (array-input support). Array form: `role` is one of `\"system\" | \"user\" | \"assistant\" | \"developer\"` (\"developer\" normalizes to \"system\"). `content` is a string or an array of text-only content parts; image parts (`image_url` / `input_image`) reject with 400 unsupported_field. The array must not be empty.",+ "description": "Either a string prompt OR an array of `{role, content}` messages (array-input support). Array form: `role` is one of `\"system\" | \"user\" | \"assistant\" | \"developer\"` (\"developer\" normalizes to \"system\"). `content` is a string or an array of `text`, `input_text`, or `output_text` parts; image parts (`image_url` / `input_image`) reject with 400 unsupported_field. The array must not be empty.","oneOf": [{"type": "string"},{"items": {+ "additionalProperties": false,"properties": {"content": {"oneOf": [@@ -3315,6 +3368,7 @@},{"items": {+ "additionalProperties": false,"properties": {"text": {"type": "string"@@ -3322,13 +3376,15 @@"type": {"enum": ["text",- "input_text"+ "input_text",+ "output_text"],"type": "string"}},"required": [- "type"+ "type",+ "text"],"type": "object"},@@ -3358,15 +3414,16 @@]},"max_output_tokens": {- "description": "Defaults to 16 (mirroring completions) when absent. Positive integer.",- "format": "int32",- "minimum": 0,+ "description": "Maximum number of generated tokens. Defaults to 16 when absent or null.",+ "maximum": 4294967295,+ "minimum": 1,"type": ["integer","null"]},"model": {+ "minLength": 1,"type": "string"},"seed": {@@ -3391,8 +3448,10 @@]},"temperature": {- "description": "Sampling temperature. Finite number ``>= 0``.",+ "description": "Sampling temperature representable by the worker runtime.","format": "float",+ "maximum": 3.4028234663852886e+38,+ "minimum": 0,"type": ["number","null"@@ -3686,7 +3745,7 @@"url": "https://www.apache.org/licenses/LICENSE-2.0.html"},"title": "SIE Gateway",- "version": "0.6.26"+ "version": "0.6.27"},"openapi": "3.1.0","paths": {@@ -4313,6 +4372,16 @@},"description": "Model not found"},+ "413": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"+ }+ }+ },+ "description": "Request body is too large"+ },"500": {"content": {"application/json": {@@ -6831,6 +6900,123 @@},"responses": {"200": {+ "content": {+ "application/json": {+ "schema": {+ "additionalProperties": false,+ "properties": {+ "created_at": {+ "type": "integer"+ },+ "id": {+ "type": "string"+ },+ "model": {+ "type": "string"+ },+ "object": {+ "const": "response",+ "type": "string"+ },+ "output": {+ "items": {+ "additionalProperties": false,+ "properties": {+ "content": {+ "items": {+ "additionalProperties": false,+ "properties": {+ "annotations": {+ "items": {+ "type": "object"+ },+ "type": "array"+ },+ "text": {+ "type": "string"+ },+ "type": {+ "const": "output_text",+ "type": "string"+ }+ },+ "required": [+ "type",+ "text",+ "annotations"+ ],+ "type": "object"+ },+ "type": "array"+ },+ "id": {+ "type": "string"+ },+ "role": {+ "const": "assistant",+ "type": "string"+ },+ "status": {+ "const": "completed",+ "type": "string"+ },+ "type": {+ "const": "message",+ "type": "string"+ }+ },+ "required": [+ "type",+ "id",+ "role",+ "status",+ "content"+ ],+ "type": "object"+ },+ "type": "array"+ },+ "status": {+ "const": "completed",+ "type": "string"+ },+ "usage": {+ "additionalProperties": false,+ "properties": {+ "input_tokens": {+ "minimum": 0,+ "type": "integer"+ },+ "output_tokens": {+ "minimum": 0,+ "type": "integer"+ },+ "total_tokens": {+ "minimum": 0,+ "type": "integer"+ }+ },+ "required": [+ "input_tokens",+ "output_tokens",+ "total_tokens"+ ],+ "type": "object"+ }+ },+ "required": [+ "id",+ "object",+ "created_at",+ "model",+ "status",+ "output",+ "usage"+ ],+ "type": "object"+ }+ }+ },"description": "Response object","headers": {"X-Inference-Time": {@@ -6944,6 +7130,16 @@},"description": "Model not found"},+ "413": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIErrorEnvelope"+ }+ }+ },+ "description": "Request body is too large"+ },"500": {"content": {"application/json": {diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rsindex 82ac376f0..17124b2c1 100644--- a/packages/sie_gateway/src/handlers/config_api.rs+++ b/packages/sie_gateway/src/handlers/config_api.rs@@ -733,6 +733,7 @@ mod tests {profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -926,6 +927,7 @@ mod tests {profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("nonexistent.module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -969,6 +971,8 @@ mod tests {// compute_model_status directly.let entry = crate::types::model::ModelEntry {name: "empty/model".to_string(),+ canonical_base_model: "empty/model".to_string(),+ canonical_profile: "default".to_string(),pool: None,bundles: Vec::new(),adapter_modules: Default::default(),diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex 3ad094189..b52609ac6 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -223,6 +223,8 @@ fn canonical_worker_models(fn worker_only_model_info(name: &str, loaded: bool) -> Value {ModelEntry {name: name.to_string(),+ canonical_base_model: name.to_string(),+ canonical_profile: "default".to_string(),pool: None,bundles: Vec::new(),adapter_modules: HashSet::new(),@@ -235,6 +237,7 @@ fn worker_only_model_info(name: &str, loaded: bool) -> Value {max_sequence_length: None,revision: None,max_output_tokens: None,+ profile_max_output_tokens: HashMap::new(),grammar_capabilities: None,grammar_profile: None,profile_parents: HashMap::new(),@@ -355,6 +358,7 @@ mod route_tests {profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -383,6 +387,7 @@ mod route_tests {profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -393,6 +398,7 @@ mod route_tests {profiles.insert("candle".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server_rust.adapters.candle:CandleEmbeddingAdapter".to_string(),),@@ -423,6 +429,7 @@ mod route_tests {profiles.insert("candle".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server_rust.adapters.candle:CandleEmbeddingAdapter".to_string(),),@@ -526,6 +533,7 @@ mod route_tests {profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -543,6 +551,7 @@ mod route_tests {profiles.insert("a100".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(8192),compute_precision: None,diff --git a/packages/sie_gateway/src/handlers/pools.rs b/packages/sie_gateway/src/handlers/pools.rsindex 935207dfd..cd76a1791 100644--- a/packages/sie_gateway/src/handlers/pools.rs+++ b/packages/sie_gateway/src/handlers/pools.rs@@ -306,6 +306,7 @@ mod tests {profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:SentenceTransformerAdapter".to_string(),@@ -322,6 +323,7 @@ mod tests {profiles.insert("fp8".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:SentenceTransformerAdapter".to_string(),diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 60605c8ba..1ee1df37a 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -4366,10 +4366,8 @@ struct ChatRequestParams {/// in :mod:`openapi.rs` for the canonical use case (anti-stop-first/// fix on Qwen3.6 greedy decoding).min_tokens: Option<u32>,- /// Per-request chat-template kwargs (e.g. ``{"enable_thinking":- /// false}``); forwarded verbatim to the worker which merges them on- /// top of the model YAML's defaults at template-render time. Absent- /// → only the model YAML's defaults apply.+ /// Per-request chat-template kwargs from the bounded public contract;+ /// validated before publication and revalidated by the worker.chat_template_kwargs: Option<serde_json::Value>,/// Routing hints plumbed through to the work envelope.routing_key: Option<String>,@@ -5082,7 +5080,7 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {let temperature = match obj.get("temperature") {None | Some(serde_json::Value::Null) => None,Some(v) => match v.as_f64() {- Some(f) if f.is_finite() && f >= 0.0 => Some(f as f32),+ Some(f) if f.is_finite() && f >= 0.0 && f <= f32::MAX as f64 => Some(f as f32),_ => {return bad("'temperature' must be a finite number >= 0",@@ -5244,21 +5242,69 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {}}}- // -- chat_template_kwargs: opaque map of kwargs for the tokenizer's- // ``apply_chat_template``. Validated only as an object (or null);- // the worker merges it onto the model YAML defaults at render- // time. Reject non-object values so a bad client doesn't smuggle- // a string/array past the schema and then crash render in the- // worker.+ // -- chat_template_kwargs: bounded kwargs for the tokenizer's+ // ``apply_chat_template``. The worker merges them under the model+ // YAML defaults at render time. Unknown keys reject here rather than+ // crossing the queue as arbitrary tokenizer arguments.let mut chat_template_kwargs: Option<serde_json::Value> = None;if let Some(val) = obj.get("chat_template_kwargs") {if !val.is_null() {- if !val.is_object() {+ let Some(kwargs) = val.as_object() else {return bad("'chat_template_kwargs' must be an object",Some("chat_template_kwargs"),oai_code::INVALID_REQUEST,);+ };+ for key in kwargs.keys() {+ if !matches!(key.as_str(), "enable_thinking" | "guardian_config") {+ return bad(+ &format!("unsupported chat_template_kwargs key: {key}"),+ Some(&format!("chat_template_kwargs.{key}")),+ oai_code::UNSUPPORTED_FIELD,+ );+ }+ }+ if let Some(enable_thinking) = kwargs.get("enable_thinking") {+ if !enable_thinking.is_boolean() {+ return bad(+ "'chat_template_kwargs.enable_thinking' must be a boolean",+ Some("chat_template_kwargs.enable_thinking"),+ oai_code::INVALID_REQUEST,+ );+ }+ }+ if let Some(guardian_config) = kwargs.get("guardian_config") {+ let Some(guardian) = guardian_config.as_object() else {+ return bad(+ "'chat_template_kwargs.guardian_config' must be an object",+ Some("chat_template_kwargs.guardian_config"),+ oai_code::INVALID_REQUEST,+ );+ };+ for key in guardian.keys() {+ if key != "risk_name" {+ return bad(+ &format!("unsupported chat_template_kwargs.guardian_config key: {key}"),+ Some(&format!("chat_template_kwargs.guardian_config.{key}")),+ oai_code::UNSUPPORTED_FIELD,+ );+ }+ }+ match guardian+ .get("risk_name")+ .and_then(|risk_name| risk_name.as_str())+ {+ Some(risk_name)+ if !risk_name.is_empty() && risk_name.chars().count() <= 128 => {}+ _ => {+ return bad(+ "'chat_template_kwargs.guardian_config.risk_name' must be a non-empty string of at most 128 characters",+ Some("chat_template_kwargs.guardian_config.risk_name"),+ oai_code::INVALID_REQUEST,+ );+ }+ }}chat_template_kwargs = Some(val.clone());}@@ -6708,6 +6754,7 @@ pub fn route_grammar_to_profile((status = 200, description = "Chat completion response", body = crate::openapi::ChatCompletionResponse),(status = 400, description = "Invalid or unsupported request", body = crate::openapi::OpenAIErrorEnvelope),(status = 404, description = "Model not found", body = crate::openapi::OpenAIErrorEnvelope),+ (status = 413, description = "Request body is too large", body = crate::openapi::OpenAIErrorEnvelope),(status = 500, description = "Worker emitted malformed response", body = crate::openapi::OpenAIErrorEnvelope),(status = 503, description = "Provisioning in progress, queue unavailable, or model loading", body = crate::openapi::OpenAIErrorEnvelope),)@@ -6861,7 +6908,7 @@ async fn proxy_chat_inner(}}}- if let Some(cap) = info.info_extras.max_output_tokens {+ if let Some(cap) = info.effective_max_output_tokens() {if cap > 0 && params.max_new_tokens > cap {return (StatusCode::BAD_REQUEST,@@ -7386,7 +7433,7 @@ fn completions_params_from_json(body: &serde_json::Value) -> CompletionsParamsRelet temperature = match obj.get("temperature") {None | Some(serde_json::Value::Null) => None,Some(v) => match v.as_f64() {- Some(f) if f.is_finite() && f >= 0.0 => Some(f as f32),+ Some(f) if f.is_finite() && f >= 0.0 && f <= f32::MAX as f64 => Some(f as f32),_ => {return bad("'temperature' must be a finite number >= 0",@@ -7882,10 +7929,10 @@ fn responses_params_from_json(body: &serde_json::Value) -> ResponsesParamsResult}};- // Allowed roles mirror the chat parser. ``developer`` is normalized- // to ``system`` so the wire stays on the 4-role set the worker's- // chat template understands.- const ALLOWED_ROLES: &[&str] = &["system", "user", "assistant", "tool", "developer"];+ // The stateless Responses MVP accepts ordinary text messages only.+ // Tool outputs require the wider Responses item/tool contract, which is+ // explicitly out of scope here. ``developer`` normalizes to ``system``.+ const ALLOWED_ROLES: &[&str] = &["system", "user", "assistant", "developer"];let input = match obj.get("input") {Some(serde_json::Value::String(s)) => {@@ -7910,6 +7957,16 @@ fn responses_params_from_json(body: &serde_json::Value) -> ResponsesParamsResultoai_code::INVALID_REQUEST,);};+ for key in o.keys() {+ if !matches!(key.as_str(), "role" | "content") {+ let param = format!("input[{i}].{key}");+ return bad(+ &format!("'{param}' is not supported by this endpoint"),+ Some(¶m),+ oai_code::UNSUPPORTED_FIELD,+ );+ }+ }let role = match o.get("role").and_then(|v| v.as_str()) {Some("developer") => "system".to_string(),Some(r) if ALLOWED_ROLES.contains(&r) => r.to_string(),@@ -7946,6 +8003,16 @@ fn responses_params_from_json(body: &serde_json::Value) -> ResponsesParamsResultoai_code::INVALID_REQUEST,);};+ for key in part_obj.keys() {+ if !matches!(key.as_str(), "type" | "text") {+ let param = format!("input[{i}].content[{j}].{key}");+ return bad(+ &format!("'{param}' is not supported by this endpoint"),+ Some(¶m),+ oai_code::UNSUPPORTED_FIELD,+ );+ }+ }let ptype = match part_obj.get("type").and_then(|v| v.as_str()) {Some(t) => t,None => {@@ -8060,7 +8127,7 @@ fn responses_params_from_json(body: &serde_json::Value) -> ResponsesParamsResultlet temperature = match obj.get("temperature") {None | Some(serde_json::Value::Null) => None,Some(v) => match v.as_f64() {- Some(f) if f.is_finite() && f >= 0.0 => Some(f as f32),+ Some(f) if f.is_finite() && f >= 0.0 && f <= f32::MAX as f64 => Some(f as f32),_ => {return bad("'temperature' must be a finite number >= 0",@@ -8176,6 +8243,7 @@ fn build_responses_body((status = 200, description = "Response object"),(status = 400, description = "Invalid or unsupported request", body = crate::openapi::OpenAIErrorEnvelope),(status = 404, description = "Model not found", body = crate::openapi::OpenAIErrorEnvelope),+ (status = 413, description = "Request body is too large", body = crate::openapi::OpenAIErrorEnvelope),(status = 500, description = "Worker emitted malformed response", body = crate::openapi::OpenAIErrorEnvelope),(status = 503, description = "Provisioning in progress, queue unavailable, or model loading", body = crate::openapi::OpenAIErrorEnvelope),)@@ -10878,7 +10946,7 @@ fn generate_params_from_json(let temperature = match parsed.get("temperature") {None | Some(serde_json::Value::Null) => None,Some(v) => match v.as_f64() {- Some(f) if f.is_finite() && f >= 0.0 => Some(f as f32),+ Some(f) if f.is_finite() && f >= 0.0 && f <= f32::MAX as f64 => Some(f as f32),_ => {return Err((StatusCode::BAD_REQUEST,@@ -11281,7 +11349,7 @@ fn generate_params_from_rmpv(};let temperature = match parse_number("temperature")? {None => None,- Some(f) if f.is_finite() && f >= 0.0 => Some(f as f32),+ Some(f) if f.is_finite() && f >= 0.0 && f <= f32::MAX as f64 => Some(f as f32),Some(_) => {return Err((StatusCode::BAD_REQUEST,@@ -14219,6 +14287,7 @@ mod tests {profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -19726,6 +19795,7 @@ mod tests {let registry = empty_registry();let mk = || ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -19814,6 +19884,7 @@ mod tests {profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -19854,6 +19925,7 @@ mod tests {let registry = empty_registry();let default_profile = ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -19863,6 +19935,7 @@ mod tests {extends: None,};let nospec_profile = ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -19926,6 +19999,7 @@ mod tests {profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -20401,7 +20475,10 @@ mod tests {#[test]fn test_chat_params_from_json_accepts_chat_template_kwargs_object() {let mut body = _chat_body_min("m");- body["chat_template_kwargs"] = serde_json::json!({"enable_thinking": false});+ body["chat_template_kwargs"] = serde_json::json!({+ "enable_thinking": false,+ "guardian_config": {"risk_name": "harm"}+ });let p = _expect_chat_ok(body);assert_eq!(p.chat_template_kwargs@@ -20421,6 +20498,44 @@ mod tests {assert_eq!(v["error"]["param"], "chat_template_kwargs");}+ /// Arbitrary tokenizer kwargs reject instead of crossing the queue.+ #[tokio::test]+ async fn test_chat_params_from_json_rejects_unknown_chat_template_kwarg() {+ let mut body = _chat_body_min("m");+ body["chat_template_kwargs"] = serde_json::json!({"arbitrary_tokenizer_kwarg": true});+ let v = _expect_chat_err(body).await;+ assert_eq!(v["error"]["code"], "unsupported_field");+ assert_eq!(+ v["error"]["param"],+ "chat_template_kwargs.arbitrary_tokenizer_kwarg"+ );+ }++ /// Accepted template kwargs keep their declared scalar types.+ #[tokio::test]+ async fn test_chat_params_from_json_rejects_non_boolean_enable_thinking() {+ let mut body = _chat_body_min("m");+ body["chat_template_kwargs"] = serde_json::json!({"enable_thinking": "false"});+ let v = _expect_chat_err(body).await;+ assert_eq!(v["error"]["code"], "invalid_request");+ assert_eq!(v["error"]["param"], "chat_template_kwargs.enable_thinking");+ }++ /// Granite Guardian config is closed to its one declared risk selector.+ #[tokio::test]+ async fn test_chat_params_from_json_rejects_unknown_guardian_config_kwarg() {+ let mut body = _chat_body_min("m");+ body["chat_template_kwargs"] = serde_json::json!({+ "guardian_config": {"risk_name": "harm", "extra": true}+ });+ let v = _expect_chat_err(body).await;+ assert_eq!(v["error"]["code"], "unsupported_field");+ assert_eq!(+ v["error"]["param"],+ "chat_template_kwargs.guardian_config.extra"+ );+ }+/// ``repetition_penalty`` outside ``(0.0, 2.0]`` rejects (both ends).#[tokio::test]async fn test_chat_params_from_json_rejects_repetition_penalty_out_of_range() {@@ -21863,6 +21978,83 @@ mod tests {serde_json::from_slice(&bytes).unwrap()}+ #[tokio::test]+ async fn test_responses_shared_request_conformance_vectors() {+ let raw = include_str!(+ "../../../../conformance/openai_generation/responses_request_vectors.json"+ );+ let vectors: serde_json::Value = serde_json::from_str(raw).expect("valid conformance JSON");++ for case in vectors["accepted"].as_array().expect("accepted vectors") {+ let name = case["name"].as_str().expect("case name");+ let params = match responses_params_from_json(&case["body"]) {+ ResponsesParamsResult::Ok(params) => params,+ ResponsesParamsResult::Err(_) => panic!("accepted case {name:?} was rejected"),+ };+ let (prompt, messages) = match params.input {+ publisher::GenerateInput::Prompt { prompt } => {+ (Some(prompt), serde_json::Value::Null)+ }+ publisher::GenerateInput::Messages { messages } => (+ None,+ serde_json::Value::Array(+ messages+ .into_iter()+ .map(|message| {+ serde_json::json!({+ "role": message.role,+ "content": message.content,+ })+ })+ .collect(),+ ),+ ),+ };+ let mut observed = serde_json::json!({+ "model": params.model,+ "prompt": prompt,+ "messages": messages,+ "max_output_tokens": params.max_new_tokens,+ "temperature": params.temperature,+ "top_p": params.top_p,+ "seed": params.seed,+ });+ let mut expected = case["expected"].clone();+ for field in ["temperature", "top_p"] {+ match (observed[field].as_f64(), expected[field].as_f64()) {+ (Some(left), Some(right)) => assert!(+ (left - right).abs() <= f32::EPSILON as f64,+ "accepted case {name:?} field {field:?}: {left} != {right}"+ ),+ (None, None) if observed[field].is_null() && expected[field].is_null() => {}+ _ => panic!("accepted case {name:?} field {field:?} differs"),+ }+ observed+ .as_object_mut()+ .expect("observed object")+ .remove(field);+ expected+ .as_object_mut()+ .expect("expected object")+ .remove(field);+ }+ assert_eq!(observed, expected, "accepted case {name:?}");+ }++ for case in vectors["rejected"].as_array().expect("rejected vectors") {+ let name = case["name"].as_str().expect("case name");+ let error = _responses_err(case["body"].clone()).await;+ assert_eq!(+ error["error"]["param"], case["param"],+ "rejected case {name:?}"+ );+ assert_eq!(+ error["error"]["code"], case["code"],+ "rejected case {name:?}"+ );+ }+ }+#[test]fn test_responses_params_ok_string_input() {match responses_params_from_json(&_responses_body_min("m")) {@@ -22728,6 +22920,7 @@ mod tests {max_sequence_length: None,revision: None,max_output_tokens: None,+ profile_max_output_tokens: std::collections::HashMap::new(),grammar_capabilities: None,grammar_profile: None,profile_parents: std::collections::HashMap::new(),@@ -22741,6 +22934,8 @@ mod tests {};ModelEntry {name: "acme/multi".to_string(),+ canonical_base_model: "acme/multi".to_string(),+ canonical_profile: "default".to_string(),pool: None,bundles: Vec::new(),adapter_modules: std::collections::HashSet::new(),@@ -23145,6 +23340,8 @@ mod tests {use crate::types::model::{ModelEntry, ModelInfoExtras};let entry = ModelEntry {name: "acme/bare".to_string(),+ canonical_base_model: "acme/bare".to_string(),+ canonical_profile: "default".to_string(),pool: None,bundles: Vec::new(),adapter_modules: std::collections::HashSet::new(),diff --git a/packages/sie_gateway/src/nats/manager.rs b/packages/sie_gateway/src/nats/manager.rsindex 1d51e3b3f..42aaa29d0 100644--- a/packages/sie_gateway/src/nats/manager.rs+++ b/packages/sie_gateway/src/nats/manager.rs@@ -698,6 +698,7 @@ adapters:profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string(),),diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex fe14909cf..65f8fe4fc 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -130,6 +130,8 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {GenerateUsage,ChatCompletionRequest,ChatCompletionMessage,+ ChatTemplateKwargs,+ GuardianChatTemplateConfig,ChatCompletionResponse,ChatCompletionChoice,ChatCompletionChoiceMessage,@@ -908,6 +910,25 @@ fn patch_completions_request_schema(value: &mut Value) {else {return;};+ properties.insert(+ "max_tokens".to_string(),+ json!({+ "description": "Maximum number of generated tokens. Defaults to 16 when absent or null.",+ "type": ["integer", "null"],+ "minimum": 1,+ "maximum": u32::MAX,+ }),+ );+ properties.insert(+ "temperature".to_string(),+ json!({+ "description": "Sampling temperature representable by the worker runtime.",+ "type": ["number", "null"],+ "format": "float",+ "minimum": 0,+ "maximum": f32::MAX,+ }),+ );properties.insert("stop".to_string(),json!({@@ -962,22 +983,27 @@ fn patch_responses_request_schema(value: &mut Value) {else {return;};+ schema["additionalProperties"] = json!(false);let Some(properties) = schema.get_mut("properties").and_then(|properties| properties.as_object_mut())else {return;};+ if let Some(model) = properties.get_mut("model") {+ model["minLength"] = json!(1);+ }// input: either a string OR an array of {role, content} messages.properties.insert("input".to_string(),json!({"description": "Either a string prompt OR an array of `{role, content}` messages \(array-input support). Array form: `role` is one of \- `\"system\" | \"user\" | \"assistant\" | \"developer\"` (\"developer\" \- normalizes to \"system\"). `content` is a string or an array of \- text-only content parts; image parts (`image_url` / `input_image`) \- reject with 400 unsupported_field. The array must not be empty.",+ `\"system\" | \"user\" | \"assistant\" | \"developer\"` \+ (\"developer\" normalizes to \"system\"). `content` is a string or \+ an array of `text`, `input_text`, or `output_text` parts; image parts \+ (`image_url` / `input_image`) reject with 400 unsupported_field. The \+ array must not be empty.","oneOf": [{"type": "string"},{@@ -985,6 +1011,7 @@ fn patch_responses_request_schema(value: &mut Value) {"minItems": 1,"items": {"type": "object",+ "additionalProperties": false,"required": ["role", "content"],"properties": {"role": {@@ -998,11 +1025,12 @@ fn patch_responses_request_schema(value: &mut Value) {"type": "array","items": {"type": "object",- "required": ["type"],+ "additionalProperties": false,+ "required": ["type", "text"],"properties": {"type": {"type": "string",- "enum": ["text", "input_text"],+ "enum": ["text", "input_text", "output_text"],},"text": {"type": "string"},},@@ -1016,6 +1044,25 @@ fn patch_responses_request_schema(value: &mut Value) {],}),);+ properties.insert(+ "max_output_tokens".to_string(),+ json!({+ "description": "Maximum number of generated tokens. Defaults to 16 when absent or null.",+ "type": ["integer", "null"],+ "minimum": 1,+ "maximum": u32::MAX,+ }),+ );+ properties.insert(+ "temperature".to_string(),+ json!({+ "description": "Sampling temperature representable by the worker runtime.",+ "type": ["number", "null"],+ "format": "float",+ "minimum": 0,+ "maximum": f32::MAX,+ }),+ );properties.insert("stream".to_string(),json!({@@ -1154,6 +1201,71 @@ fn patch_responses_path(value: &mut Value) {}),);}+ if let Some(success) = op_obj+ .get_mut("responses")+ .and_then(|responses| responses.get_mut("200"))+ .and_then(|response| response.as_object_mut())+ {+ success.insert(+ "content".to_string(),+ json!({+ "application/json": {+ "schema": {+ "type": "object",+ "additionalProperties": false,+ "required": ["id", "object", "created_at", "model", "status", "output", "usage"],+ "properties": {+ "id": {"type": "string"},+ "object": {"type": "string", "const": "response"},+ "created_at": {"type": "integer"},+ "model": {"type": "string"},+ "status": {"type": "string", "const": "completed"},+ "output": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": ["type", "id", "role", "status", "content"],+ "properties": {+ "type": {"type": "string", "const": "message"},+ "id": {"type": "string"},+ "role": {"type": "string", "const": "assistant"},+ "status": {"type": "string", "const": "completed"},+ "content": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": ["type", "text", "annotations"],+ "properties": {+ "type": {"type": "string", "const": "output_text"},+ "text": {"type": "string"},+ "annotations": {+ "type": "array",+ "items": {"type": "object"},+ },+ },+ },+ },+ },+ },+ },+ "usage": {+ "type": "object",+ "additionalProperties": false,+ "required": ["input_tokens", "output_tokens", "total_tokens"],+ "properties": {+ "input_tokens": {"type": "integer", "minimum": 0},+ "output_tokens": {"type": "integer", "minimum": 0},+ "total_tokens": {"type": "integer", "minimum": 0},+ },+ },+ },+ }+ }+ }),+ );+ }}}@@ -1931,6 +2043,30 @@ pub struct ChatCompletionMessage {pub tool_call_id: Option<String>,}+/// Bounded Granite Guardian options accepted by ``chat_template_kwargs``.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(deny_unknown_fields)]+pub struct GuardianChatTemplateConfig {+ /// Non-empty Granite Guardian risk identifier, at most 128 characters.+ #[schema(min_length = 1, max_length = 128)]+ pub risk_name: String,+}++/// Bounded tokenizer-template options accepted from a chat request.+///+/// Unknown keys are rejected at the gateway instead of being forwarded to a+/// tokenizer implementation as arbitrary keyword arguments.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+#[serde(deny_unknown_fields)]+pub struct ChatTemplateKwargs {+ /// Qwen-family switch controlling whether the template opens a thinking block.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub enable_thinking: Option<bool>,+ /// Granite Guardian risk selection.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub guardian_config: Option<GuardianChatTemplateConfig>,+}+/// OpenAI-compatible ``POST /v1/chat/completions`` request.////// **Strict allow-list:** unknown top-level fields reject with 400@@ -1993,16 +2129,13 @@ pub struct ChatCompletionRequest {/// under greedy decode). Absent → sampler default (no minimum).#[serde(default, skip_serializing_if = "Option::is_none")]pub min_tokens: Option<u32>,- /// Per-request overrides for kwargs passed to the tokenizer's- /// ``apply_chat_template`` call. Object whose entries are merged on- /// top of the model YAML's ``chat_template_kwargs`` (the YAML wins- /// for keys present in both — adjust the YAML when a request needs- /// to defeat a baked-in default). Typical use: pass- /// ``{"enable_thinking": false}`` to the Qwen3 family to suppress- /// ``<think>`` reasoning on a per-request basis. Absent → only the- /// model YAML's defaults apply.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub chat_template_kwargs: Option<Value>,+ /// Per-request overrides from the bounded tokenizer-template contract.+ /// Only ``enable_thinking`` and ``guardian_config.risk_name`` are+ /// accepted; unknown keys reject with 400 instead of reaching+ /// ``apply_chat_template``. Values are merged under the model YAML's+ /// operator-owned defaults, which win on conflict.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub chat_template_kwargs: Option<ChatTemplateKwargs>,/// Number of candidate completions, ``[1, 128]``. ``n>1`` returns a/// multi-entry ``choices`` array. Streaming with ``n>1`` is supported:/// per-``choice_index`` delta chunks plus per-choice closure chunks@@ -2225,10 +2358,9 @@ pub struct ResponsesRequest {pub model: String,/// Either a string prompt OR an array of ``{role, content}`` messages/// (array-input support). Array form: ``role`` is one of- /// ``"system" | "user" | "assistant" | "developer"`` (``"tool"`` is- /// nominally accepted but Responses tools are rejected so it is- /// effectively unreachable). ``content`` is a string or an array of- /// text-only content parts; image parts reject.+ /// ``"system" | "user" | "assistant" | "developer"``.+ /// ``content`` is a string or an array of text-only content parts; image+ /// parts reject.pub input: Value,/// Defaults to 16 (mirroring completions) when absent. Positive integer.#[serde(default, skip_serializing_if = "Option::is_none")]@@ -3243,6 +3375,53 @@ mod tests {assert!(!user_description.contains("Logged at debug level"));}+ #[test]+ fn openapi_json_documents_strict_responses_contract() {+ let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();+ let request = &spec["components"]["schemas"]["ResponsesRequest"];++ assert_eq!(request["additionalProperties"], false);+ assert_eq!(request["properties"]["model"]["minLength"], 1);+ assert_eq!(request["properties"]["max_output_tokens"]["minimum"], 1);+ assert_eq!(+ request["properties"]["max_output_tokens"]["maximum"],+ u32::MAX+ );+ let message = &request["properties"]["input"]["oneOf"][1]["items"];+ assert_eq!(message["additionalProperties"], false);+ assert!(!message["properties"]["role"]["enum"]+ .as_array()+ .unwrap()+ .iter()+ .any(|role| role == "tool"));+ let part = &message["properties"]["content"]["oneOf"][1]["items"];+ assert_eq!(part["additionalProperties"], false);+ assert_eq!(part["required"], json!(["type", "text"]));+ assert!(part["properties"]["type"]["enum"]+ .as_array()+ .unwrap()+ .iter()+ .any(|part_type| part_type == "output_text"));++ let response = &spec["paths"]["/v1/responses"]["post"]["responses"]["200"]["content"]+ ["application/json"]["schema"];+ assert_eq!(response["additionalProperties"], false);+ assert_eq!(response["properties"]["object"]["const"], "response");+ assert_eq!(+ response["properties"]["output"]["items"]["properties"]["content"]["items"]+ ["properties"]["type"]["const"],+ "output_text"+ );+ assert_eq!(+ response["properties"]["usage"]["required"],+ json!(["input_tokens", "output_tokens", "total_tokens"])+ );+ assert!(spec["paths"]["/v1/responses"]["post"]["responses"]+ .as_object()+ .unwrap()+ .contains_key("413"));+ }+#[test]fn openapi_document_includes_gateway_paths() {let doc = ApiDoc::openapi();diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rsindex affe951a0..4206a57fc 100644--- a/packages/sie_gateway/src/queue/publisher.rs+++ b/packages/sie_gateway/src/queue/publisher.rs@@ -204,13 +204,11 @@ impl Default for GenerateInput {/// One image attached to a chat message, extracted from an OpenAI/// ``image_url`` data URI at the gateway.///-/// ``data`` is the **base64 payload string**, NOT raw bytes. This is-/// deliberate: the generate work item travels through the sidecar's-/// ``WorkItem.generate: serde_json::Value``, and ``serde_json::Value``-/// cannot hold a msgpack ``bin`` (rmp_serde rejects it with "invalid type:-/// byte array"). A base64 string round-trips cleanly through-/// ``serde_json::Value`` with no sidecar changes. The worker base64-decodes-/// it back to bytes (see ``_parse_message_images_field``).+/// ``data`` remains a base64 payload string at gateway ingress so the public+/// JSON shape and existing queue publishers stay compatible. The Rust+/// sidecar validates and normalizes it to bounded msgpack binary before+/// Python model execution; mixed-version Python workers accept both binary+/// and the legacy base64 representation.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct ChatImage {/// Base64-encoded image bytes (standard alphabet, no ``data:`` prefix).@@ -365,9 +363,10 @@ pub struct GenerateParams {#[serde(default, skip_serializing_if = "Option::is_none")]pub min_tokens: Option<u32>,/// Per-request kwargs forwarded to the tokenizer's- /// ``apply_chat_template``. Worker merges them on top of the model- /// YAML defaults (YAML wins on conflict). Validated as a JSON- /// object by the gateway. Absent → only YAML defaults apply.+ /// ``apply_chat_template``. Worker merges them under the model YAML+ /// defaults (YAML wins on conflict). The gateway accepts only the+ /// bounded public schema and the worker revalidates it after dequeue.+ /// Absent → only YAML defaults apply.#[serde(default, skip_serializing_if = "Option::is_none")]pub chat_template_kwargs: Option<serde_json::Value>,/// Structured-output spec. Absent when the request omitted thediff --git a/packages/sie_gateway/src/state/config_bootstrap.rs b/packages/sie_gateway/src/state/config_bootstrap.rsindex 7b5edae79..2d38849c4 100644--- a/packages/sie_gateway/src/state/config_bootstrap.rs+++ b/packages/sie_gateway/src/state/config_bootstrap.rs@@ -841,6 +841,7 @@ mod tests {profiles: HashMap::from([("default".to_string(),crate::types::model::ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string(),),diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex f998f4bf7..a2fc1ee77 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -50,6 +50,60 @@ pub enum ResolveError {BundleConflict(BundleConflictError),}+/// Immutable encode-routing evidence captured from one registry snapshot.+///+/// Connector planning persists this as output identity, so every field must+/// come from the same `ArcSwap` generation. In particular, a config reload+/// must never pair revision A with bundle hash B or dense dimension C.+#[derive(Debug, Clone, PartialEq, Eq)]+#[allow(dead_code)] // consumed by the managed gateway wrapper, not the standalone binary+pub struct ModelExecutionEvidence {+ /// Canonical base model used by rate-book identity.+ pub model: String,+ /// Canonical routed model id (the base or one explicit profile variant).+ pub served_model: String,+ pub profile: String,+ pub revision: String,+ pub served_bundle: String,+ pub engine: String,+ pub adapter_path: String,+ pub pool: String,+ pub config_sha256: String,+ pub output_dimensions: u32,+ /// Hard post-tokenization sequence bound for one encode item. Connector+ /// reservations use this instead of treating UTF-8 bytes as tokens.+ pub max_sequence_length: u32,+}++#[derive(Debug, Clone, PartialEq, Eq)]+#[allow(dead_code)] // consumed by the managed gateway wrapper, not the standalone binary+pub enum ModelExecutionEvidenceError {+ ModelUnavailable,+ BundleUnavailable,+ AdapterUnavailable,+ MutableRevision,+ ConfigUnavailable,+ DenseOutputUnavailable,+ TokenCeilingUnavailable,+}++impl std::fmt::Display for ModelExecutionEvidenceError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let message = match self {+ Self::ModelUnavailable => "model is unavailable",+ Self::BundleUnavailable => "model is unavailable in the selected bundle",+ Self::AdapterUnavailable => "model profile has no concrete adapter",+ Self::MutableRevision => "model revision is not immutable",+ Self::ConfigUnavailable => "bundle configuration identity is unavailable",+ Self::DenseOutputUnavailable => "model has no fixed dense output shape",+ Self::TokenCeilingUnavailable => "model has no bounded encode sequence length",+ };+ f.write_str(message)+ }+}++impl std::error::Error for ModelExecutionEvidenceError {}+impl std::fmt::Display for ResolveError {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {match self {@@ -69,6 +123,8 @@ pub type AddModelConfigOutcome = (Vec<String>, Vec<String>, Vec<String>);const DEFAULT_MODEL_POOL: &str = "default";const MAX_POOL_NAME_LEN: usize = 128;+/// Largest release-governed sequence length accepted as execution evidence.+pub const MAX_MODEL_SEQUENCE_LENGTH: u64 = 1_000_000;/// Outcome of resolving where a grammar-constrained request must dispatch.///@@ -466,6 +522,8 @@ impl ModelRegistry {}entries.push(ModelEntry {name: format!("{}:{}", base_entry.name, profile_name),+ canonical_base_model: base_entry.canonical_base_model.clone(),+ canonical_profile: profile_name,pool: base_entry.pool.clone(),bundles: Vec::new(),adapter_modules: variant_adapters,@@ -599,7 +657,9 @@ impl ModelRegistry {let adapter_modules = Self::base_route_adapter_modules_from_profiles(&config.profiles);Ok(ModelEntry {- name: model_name,+ name: model_name.clone(),+ canonical_base_model: model_name,+ canonical_profile: "default".to_string(),pool,bundles: Vec::new(),adapter_modules,@@ -680,6 +740,8 @@ impl ModelRegistry {}entries.push(ModelEntry {name: format!("{}:{}", base_entry.name, profile_name),+ canonical_base_model: base_entry.canonical_base_model.clone(),+ canonical_profile: profile_name,pool: base_entry.pool.clone(),bundles: Vec::new(),adapter_modules: variant_adapters,@@ -708,6 +770,7 @@ impl ModelRegistry {fn empty_profile_config() -> crate::types::model::ProfileConfig {crate::types::model::ProfileConfig {+ max_output_tokens: None,adapter_path: None,max_batch_tokens: None,compute_precision: None,@@ -744,6 +807,9 @@ impl ModelRegistry {if profile.compute_precision.is_some() {resolved.compute_precision = profile.compute_precision.clone();}+ if profile.max_output_tokens.is_some() {+ resolved.max_output_tokens = profile.max_output_tokens;+ }resolved.adapter_options = ModelRegistry::merge_adapter_options(resolved.adapter_options,profile.adapter_options.clone(),@@ -770,6 +836,7 @@ impl ModelRegistry {/// re-evaluate them — the stored CanonicalProfile would be stale.fn merge_profiles_for_resolution(existing: &HashMap<String, CanonicalProfile>,+ existing_output_caps: &HashMap<String, u32>,incoming: &HashMap<String, crate::types::model::ProfileConfig>,) -> HashMap<String, crate::types::model::ProfileConfig> {let mut merged: HashMap<String, crate::types::model::ProfileConfig> = existing@@ -778,6 +845,7 @@ impl ModelRegistry {(name.clone(),crate::types::model::ProfileConfig {+ max_output_tokens: existing_output_caps.get(name).copied(),adapter_path: canon.adapter_path.clone(),max_batch_tokens: canon.max_batch_tokens,compute_precision: canon.compute_precision.clone(),@@ -1369,6 +1437,99 @@ impl ModelRegistry {(bundle_config_hash, revision)}+ /// Resolve one connector encode identity from a single registry snapshot.+ ///+ /// Unlike the compatibility tuple above, this fails closed when any+ /// output-affecting value is absent. A durable connector checkpoint may+ /// only name a model whose weights, route config, and dense shape are all+ /// immutable and known before source admission.+ #[allow(dead_code)] // consumed by the managed gateway wrapper, not the standalone binary+ pub fn resolve_execution_evidence(+ &self,+ model: &str,+ bundle_id: &str,+ ) -> Result<ModelExecutionEvidence, ModelExecutionEvidenceError> {+ let snap = self.snapshot.load();+ let served_model = Self::canonical_model_name(&snap, model)+ .ok_or(ModelExecutionEvidenceError::ModelUnavailable)?;+ let entry = snap+ .models+ .get(&served_model)+ .ok_or(ModelExecutionEvidenceError::ModelUnavailable)?;+ if !entry.bundles.iter().any(|bundle| bundle == bundle_id) {+ return Err(ModelExecutionEvidenceError::BundleUnavailable);+ }+ let engine = snap+ .bundles+ .get(bundle_id)+ .map(|bundle| bundle.engine.clone())+ .filter(|engine| !engine.is_empty())+ .ok_or(ModelExecutionEvidenceError::BundleUnavailable)?;+ let adapter_path = Self::effective_adapter_path_from_entry(entry, "default")+ .map(str::to_string)+ .ok_or(ModelExecutionEvidenceError::AdapterUnavailable)?;++ let base_model = entry.canonical_base_model.clone();+ let profile = entry.canonical_profile.clone();+ let revision = Self::immutable_model_revision(entry)+ .ok_or(ModelExecutionEvidenceError::MutableRevision)?;+ // A batch lane is a scheduling class over the model's catalog pool;+ // use the registry-owned pool from this same snapshot rather than the+ // lane's `batch` admission label or a caller-supplied second lookup.+ let pool = Self::entry_pool_name(entry).to_string();+ let config_sha256 = snap+ .bundle_pool_config_hashes+ .get(&(bundle_id.to_string(), pool.clone()))+ .filter(|value| !value.is_empty())+ .cloned()+ .ok_or(ModelExecutionEvidenceError::ConfigUnavailable)?;+ if config_sha256.len() != 64+ || !config_sha256+ .bytes()+ .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))+ {+ return Err(ModelExecutionEvidenceError::ConfigUnavailable);+ }+ let output_dimensions = entry+ .info_extras+ .dims+ .get("dense")+ .copied()+ .and_then(|value| u32::try_from(value).ok())+ .filter(|value| *value > 0)+ .ok_or(ModelExecutionEvidenceError::DenseOutputUnavailable)?;+ if !entry+ .info_extras+ .outputs+ .iter()+ .any(|output| output == "dense")+ {+ return Err(ModelExecutionEvidenceError::DenseOutputUnavailable);+ }+ let max_sequence_length = entry+ .profile_configs+ .get("default")+ .and_then(Self::profile_max_sequence_length)+ .or(entry.info_extras.max_sequence_length)+ .filter(|value| (1..=MAX_MODEL_SEQUENCE_LENGTH).contains(value))+ .and_then(|value| u32::try_from(value).ok())+ .ok_or(ModelExecutionEvidenceError::TokenCeilingUnavailable)?;++ Ok(ModelExecutionEvidence {+ model: base_model,+ served_model,+ profile,+ revision,+ served_bundle: bundle_id.to_string(),+ engine,+ adapter_path,+ pool,+ config_sha256,+ output_dimensions,+ max_sequence_length,+ })+ }+fn normalize_pool_name(pool_name: &str) -> String {let pool_name = pool_name.trim().to_lowercase();if pool_name.is_empty() {@@ -1528,6 +1689,15 @@ impl ModelRegistry {let bundle_adapter_set: HashSet<&str> =bundle.adapters.iter().map(|s| s.as_str()).collect();+ let has_profile_for_bundle = |entry: &ModelEntry| {+ entry.profile_configs.values().any(|profile| {+ profile+ .adapter_path+ .as_deref()+ .map(|path| path.split(':').next().unwrap_or(path))+ .is_some_and(|module| bundle_adapter_set.contains(module))+ })+ };let mut items: Vec<serde_json::Value> = Vec::new();@@ -1537,10 +1707,7 @@ impl ModelRegistry {for model_name in model_names {let synthetic_variant = Self::synthetic_profile_variant_parts(model_name, models);if let Some((base_name, _)) = synthetic_variant {- if models- .get(base_name)- .is_some_and(|base_entry| base_entry.bundles.iter().any(|b| b == bundle_id))- {+ if models.get(base_name).is_some_and(&has_profile_for_bundle) {// The base entry already carries all profiles compatible with this// bundle. Only hash synthetic variants when they are the sole// routing identity for this bundle, e.g. `model:candle`.@@ -1562,14 +1729,10 @@ impl ModelRegistry {} else {(model_name.as_str(), None)};- if !model_entry.bundles.contains(&bundle_id.to_string()) {- continue;- }- let has_overlap = model_entry- .adapter_modules- .iter()- .any(|a| bundle_adapter_set.contains(a.as_str()));- if !has_overlap {+ // `entry.bundles` describes the base/default route. Hashing must+ // additionally include bundles selected only by named profiles so+ // workers and gateways canonicalize those profiles identically.+ if !has_profile_for_bundle(model_entry) {continue;}@@ -1877,8 +2040,11 @@ impl ModelRegistry {// ``default``). Build a temporary ``ProfileConfig`` map combining// already-stored canonical profiles with the incoming ones —// incoming wins on collisions — and resolve against that.- let merged_profiles =- Self::merge_profiles_for_resolution(&existing.profile_configs, &config.profiles);+ let merged_profiles = Self::merge_profiles_for_resolution(+ &existing.profile_configs,+ &existing.info_extras.profile_max_output_tokens,+ &config.profiles,+ );for profile_name in config.profiles.keys() {if existing.profile_names.contains(profile_name) {@@ -1949,6 +2115,8 @@ impl ModelRegistry {sie_id.clone(),ModelEntry {name: sie_id.clone(),+ canonical_base_model: sie_id.clone(),+ canonical_profile: "default".to_string(),pool: incoming_pool,bundles: Vec::new(),adapter_modules: Self::base_route_adapter_modules_from_profiles(@@ -2093,6 +2261,7 @@ impl ModelRegistry {let lora_refreshed = ModelInfoExtras::from_model_config(&merged_config);existing.lora_adapters = lora_refreshed.lora_adapters;existing.profile_lora_adapters = lora_refreshed.profile_lora_adapters;+ existing.profile_max_output_tokens = lora_refreshed.profile_max_output_tokens;}}}@@ -2118,6 +2287,7 @@ mod tests {extends: Option<&str>,) -> crate::types::model::ProfileConfig {crate::types::model::ProfileConfig {+ max_output_tokens: None,adapter_path: adapter_path.map(str::to_string),max_batch_tokens,compute_precision: None,@@ -2219,6 +2389,7 @@ mod tests {profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -2256,6 +2427,7 @@ mod tests {let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);let mk = || ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -2396,6 +2568,7 @@ mod tests {profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -2481,6 +2654,7 @@ profiles:profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -2532,6 +2706,7 @@ profiles:profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -2544,6 +2719,7 @@ profiles:profiles.insert("bad/name".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -2651,6 +2827,12 @@ profiles:models_dir.join("org__profile-only.yaml"),r#"sie_id: org/profile-only+hf_revision: 0123456789abcdef0123456789abcdef01234567+max_sequence_length: 512+tasks:+ encode:+ dense:+ dim: 384profiles:experimental:adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter@@ -2674,6 +2856,12 @@ profiles:.unwrap(),"candle");+ let evidence = registry+ .resolve_execution_evidence("ORG/PROFILE-ONLY:EXPERIMENTAL", "candle")+ .expect("profile-only variant retains canonical execution identity");+ assert_eq!(evidence.model, "org/profile-only");+ assert_eq!(evidence.served_model, "org/profile-only:experimental");+ assert_eq!(evidence.profile, "experimental");}#[test]@@ -2693,6 +2881,7 @@ profiles:profiles.insert("experimental".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server_rust.adapters.candle:CandleEmbeddingAdapter".to_string(),),@@ -2705,14 +2894,17 @@ profiles:registry.add_model_config(ModelConfig {name: "org/profile-only".to_string(),- hf_revision: None,+ hf_revision: Some("0123456789abcdef0123456789abcdef01234567".to_string()),adapter_module: None,default_bundle: None,pool: None,profiles,inputs: None,- tasks: None,- max_sequence_length: None,+ tasks: Some(+ serde_yaml::from_str("encode:\n dense:\n dim: 384\n")+ .expect("valid task fixture"),+ ),+ max_sequence_length: Some(512),}).unwrap();@@ -2729,6 +2921,12 @@ profiles:.unwrap(),"candle");+ let evidence = registry+ .resolve_execution_evidence("ORG/PROFILE-ONLY:EXPERIMENTAL", "candle")+ .expect("delta profile-only variant retains canonical execution identity");+ assert_eq!(evidence.model, "org/profile-only");+ assert_eq!(evidence.served_model, "org/profile-only:experimental");+ assert_eq!(evidence.profile, "experimental");}#[test]@@ -3159,6 +3357,7 @@ profiles:profiles.insert("default".to_string(),ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string(),),@@ -3431,6 +3630,7 @@ adapters:m.insert("default".to_string(),crate::types::model::ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:SentenceTransformerAdapter".to_string(),@@ -3478,6 +3678,7 @@ adapters:profiles.insert("default".to_string(),crate::types::model::ProfileConfig {+ max_output_tokens: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -3517,6 +3718,7 @@ encode:profiles.insert("default".to_string(),crate::types::model::ProfileConfig {+ max_output_tokens: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -3527,6 +3729,7 @@ encode:profiles.insert("alt".to_string(),crate::types::model::ProfileConfig {+ max_output_tokens: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(2048),compute_precision: None,@@ -3585,6 +3788,7 @@ adapters:profiles.insert("default".to_string(),crate::types::model::ProfileConfig {+ max_output_tokens: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -3619,6 +3823,7 @@ encode:profiles.insert("default".to_string(),crate::types::model::ProfileConfig {+ max_output_tokens: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(4096),compute_precision: None,@@ -3629,6 +3834,7 @@ encode:profiles.insert("alt".to_string(),crate::types::model::ProfileConfig {+ max_output_tokens: None,adapter_path: Some("module:Adapter".to_string()),max_batch_tokens: Some(2048),compute_precision: None,@@ -3673,6 +3879,7 @@ encode:m.insert("default".to_string(),crate::types::model::ProfileConfig {+ max_output_tokens: None,adapter_path: Some(adapter_path.to_string()),max_batch_tokens: Some(max_batch_tokens),compute_precision: None,@@ -3812,12 +4019,13 @@ adapters:let seed: ModelConfig = serde_yaml::from_str(r#"sie_id: test/model-tasks: {generate: {grammar_profile: no-spec}}+tasks: {generate: {grammar_profile: no-spec, max_output_tokens: 4096}}profiles:default: {adapter_path: "sie_server.adapters.sentence_transformer:SentenceTransformerAdapter", max_batch_tokens: 4096}no-spec:adapter_path: "sie_server.adapters.sentence_transformer:SentenceTransformerAdapter"max_batch_tokens: 4096+ max_output_tokens: 32768adapter_options: {loadtime: {grammar_backend: outlines, speculative: {enabled: false}}}"#,)@@ -3849,6 +4057,20 @@ profiles:registry.grammar_route_variant("test/model:h100-fp8"),GrammarRoute::Keep,);+ assert_eq!(+ registry+ .get_model_info("test/model:h100-fp8")+ .and_then(|entry| entry.effective_max_output_tokens()),+ Some(32768),+ "delta child must inherit the stored parent's profile output cap",+ );+ assert_eq!(+ registry+ .get_model_info("test/model")+ .and_then(|entry| entry.effective_max_output_tokens()),+ Some(4096),+ "profile cap must not widen the bare route",+ );// Same delta under the test-only authoritative path must also succeed// because the override path uses the same merged resolution map.@@ -3902,6 +4124,7 @@ adapters:m.insert("default".to_string(),crate::types::model::ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:SentenceTransformerAdapter".to_string(),@@ -3960,6 +4183,7 @@ adapters:m.insert("a100-40gb".to_string(),crate::types::model::ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:SentenceTransformerAdapter".to_string(),@@ -4131,6 +4355,160 @@ profiles:assert_ne!(first, second);}+ #[test]+ fn test_resolve_execution_evidence_is_one_snapshot_and_profile_exact() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();+ fs::write(+ bundles_dir.join("default.yaml"),+ "name: default\nadapters:\n - sie_server.adapters.sentence_transformer\n",+ )+ .unwrap();+ fs::write(+ models_dir.join("revisioned.yaml"),+ r#"+sie_id: org/revisioned+hf_revision: 0123456789abcdef0123456789abcdef01234567+max_sequence_length: 4096+tasks:+ encode:+ dense:+ dim: 384+profiles:+ default:+ adapter_path: sie_server.adapters.sentence_transformer:Adapter+ quality:+ adapter_path: sie_server.adapters.sentence_transformer:Adapter+ adapter_options:+ loadtime:+ max_seq_length: 32768+"#,+ )+ .unwrap();+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);++ let evidence = registry+ .resolve_execution_evidence("ORG/REVISIONED:QUALITY", "default")+ .expect("pinned dense profile has executable evidence");+ assert_eq!(evidence.model, "org/revisioned");+ assert_eq!(evidence.served_model, "org/revisioned:quality");+ assert_eq!(evidence.profile, "quality");+ assert_eq!(+ evidence.revision,+ "0123456789abcdef0123456789abcdef01234567"+ );+ assert_eq!(evidence.served_bundle, "default");+ assert_eq!(evidence.engine, "pytorch");+ assert_eq!(+ evidence.adapter_path,+ "sie_server.adapters.sentence_transformer:Adapter"+ );+ assert_eq!(evidence.pool, "default");+ assert_eq!(evidence.config_sha256.len(), 64);+ assert!(evidence+ .config_sha256+ .bytes()+ .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f')));+ assert_eq!(evidence.output_dimensions, 384);+ assert_eq!(evidence.max_sequence_length, 32768);+ }++ #[test]+ fn test_resolve_execution_evidence_fails_closed() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();+ fs::write(+ bundles_dir.join("default.yaml"),+ "name: default\nadapters:\n - sie_server.adapters.sentence_transformer\n",+ )+ .unwrap();+ fs::write(+ models_dir.join("mutable.yaml"),+ r#"+sie_id: org/mutable+hf_revision: main+max_sequence_length: 512+tasks:+ encode:+ dense:+ dim: 384+profiles:+ default:+ adapter_path: sie_server.adapters.sentence_transformer:Adapter+"#,+ )+ .unwrap();+ fs::write(+ models_dir.join("unpinned-shape.yaml"),+ r#"+sie_id: org/no-dense-shape+hf_revision: 0123456789abcdef0123456789abcdef01234567+max_sequence_length: 512+tasks:+ score: {}+profiles:+ default:+ adapter_path: sie_server.adapters.sentence_transformer:Adapter+"#,+ )+ .unwrap();+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);++ assert_eq!(+ registry.resolve_execution_evidence("org/mutable", "default"),+ Err(ModelExecutionEvidenceError::MutableRevision)+ );+ assert_eq!(+ registry.resolve_execution_evidence("org/no-dense-shape", "default"),+ Err(ModelExecutionEvidenceError::DenseOutputUnavailable)+ );+ assert_eq!(+ registry.resolve_execution_evidence("org/mutable", "missing"),+ Err(ModelExecutionEvidenceError::BundleUnavailable)+ );++ fs::write(+ models_dir.join("unbounded.yaml"),+ r#"+sie_id: org/unbounded+hf_revision: 0123456789abcdef0123456789abcdef01234567+tasks:+ encode:+ dense:+ dim: 384+profiles:+ default:+ adapter_path: sie_server.adapters.sentence_transformer:Adapter+"#,+ )+ .unwrap();+ registry.reload();+ assert_eq!(+ registry.resolve_execution_evidence("org/unbounded", "default"),+ Err(ModelExecutionEvidenceError::TokenCeilingUnavailable)+ );++ fs::write(+ models_dir.join("oversized-bound.yaml"),+ r#"+sie_id: org/oversized-bound+hf_revision: 0123456789abcdef0123456789abcdef01234567+max_sequence_length: 1000001+tasks:+ encode:+ dense:+ dim: 384+profiles:+ default:+ adapter_path: sie_server.adapters.sentence_transformer:Adapter+"#,+ )+ .unwrap();+ registry.reload();+ assert_eq!(+ registry.resolve_execution_evidence("org/oversized-bound", "default"),+ Err(ModelExecutionEvidenceError::TokenCeilingUnavailable)+ );+ }+#[test]fn test_revision_only_delta_updates_identity_and_bundle_hash() {let (_dir, bundles_dir, models_dir) = create_test_dirs();@@ -4312,7 +4690,7 @@ profiles:}#[test]- fn test_compute_bundle_config_hash_includes_candle_profile_variant() {+ fn test_compute_bundle_config_hash_collates_profile_specific_bundle_variants() {let (_dir, bundles_dir, models_dir) = create_test_dirs();fs::write(@@ -4352,6 +4730,13 @@ profiles:runtime:pooling: clsnormalize: true+ candle-fast:+ adapter_path: "sie_server_rust.adapters.candle:CandleEmbeddingAdapter"+ max_batch_tokens: 1024+ adapter_options:+ runtime:+ pooling: mean+ normalize: false"#,).unwrap();@@ -4361,8 +4746,11 @@ profiles:let candle_pool_hash = registry.compute_bundle_config_hash_for_pool("candle", "default");assert!(registry.model_exists("BAAI/bge-m3:candle"));- assert!(!candle_hash.is_empty());- assert_eq!(candle_hash.len(), 64);+ assert!(registry.model_exists("BAAI/bge-m3:candle-fast"));+ assert_eq!(+ candle_hash,+ "8ba96ca592759bd243500067acf12ec261b442ac0059aea51dffdaf271f45f8a"+ );assert_eq!(candle_pool_hash, candle_hash);assert_ne!(candle_hash, registry.compute_bundle_config_hash("default"));}@@ -4454,6 +4842,7 @@ adapters:m.insert("default".to_string(),crate::types::model::ProfileConfig {+ max_output_tokens: None,adapter_path: Some("sie_server.adapters.sentence_transformer:A".to_string(),),diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rsindex cd83c897e..b832641dc 100644--- a/packages/sie_gateway/src/types/model.rs+++ b/packages/sie_gateway/src/types/model.rs@@ -19,6 +19,11 @@ pub struct ModelInfoExtras {/// when the model has no ``generate`` task or the field was not/// set.pub max_output_tokens: Option<u32>,+ /// Per-profile overrides of ``tasks.generate.max_output_tokens``.+ /// Values are inheritance-resolved from ``profiles.<name>`` so request+ /// admission can use the concrete route's cap without widening the bare+ /// model or sibling variants.+ pub profile_max_output_tokens: HashMap<String, u32>,/// ``tasks.generate.capabilities.grammar`` from the/// model YAML — the list of grammar ``kind`` strings the model/// supports (e.g. ``["json_schema", "regex"]``). Gateway rejects@@ -240,6 +245,37 @@ impl ModelInfoExtras {.profile_parents.insert(profile_name.to_string(), parent_name.to_string());}++ fn resolve_profile_output_cap(+ profiles: &serde_yaml::Mapping,+ profile_name: &str,+ seen: &mut HashSet<String>,+ ) -> Option<u32> {+ if !seen.insert(profile_name.to_string()) {+ return None;+ }+ let profile = profiles.get(profile_name)?.as_mapping()?;+ if let Some(cap) = profile+ .get("max_output_tokens")+ .and_then(serde_yaml::Value::as_u64)+ .filter(|value| *value > 0)+ .and_then(|value| u32::try_from(value).ok())+ {+ return Some(cap);+ }+ let parent = profile.get("extends").and_then(serde_yaml::Value::as_str)?;+ resolve_profile_output_cap(profiles, parent, seen)+ }++ for profile_name in profiles.keys().filter_map(serde_yaml::Value::as_str) {+ if let Some(cap) =+ resolve_profile_output_cap(profiles, profile_name, &mut HashSet::new())+ {+ extras+ .profile_max_output_tokens+ .insert(profile_name.to_string(), cap);+ }+ }}// Multi-LoRA: collect the served-names declared per profile and@@ -306,6 +342,7 @@ impl ModelInfoExtras {max_sequence_length: config.max_sequence_length,revision: None,max_output_tokens: None,+ profile_max_output_tokens: HashMap::new(),grammar_capabilities: None,grammar_profile: None,profile_parents: HashMap::new(),@@ -363,6 +400,8 @@ pub struct ProfileConfig {#[serde(default)]pub compute_precision: Option<String>,#[serde(default)]+ pub max_output_tokens: Option<u32>,+ #[serde(default)]pub adapter_options: Option<serde_json::Value>,#[serde(default)]pub extends: Option<String>,@@ -371,6 +410,13 @@ pub struct ProfileConfig {#[derive(Debug, Clone)]pub struct ModelEntry {pub name: String,+ /// Canonical catalog model id shared by the bare route and every explicit+ /// profile variant. This remains available for profile-only catalogs where+ /// the bare route is intentionally absent from the registry snapshot.+ pub canonical_base_model: String,+ /// Canonical catalog profile represented by this route (`default` for the+ /// bare model, otherwise the explicit `base-model:profile` suffix).+ pub canonical_profile: String,pub pool: Option<String>,pub bundles: Vec<String>,pub adapter_modules: HashSet<String>,@@ -380,6 +426,17 @@ pub struct ModelEntry {}impl ModelEntry {+ /// Effective output-token cap for this concrete route. A profile override+ /// takes precedence only for that route; otherwise the model-level cap is+ /// retained as the worker-authoritative fallback.+ pub fn effective_max_output_tokens(&self) -> Option<u32> {+ self.info_extras+ .profile_max_output_tokens+ .get(&self.canonical_profile)+ .copied()+ .or(self.info_extras.max_output_tokens)+ }+/// JSON shaped like ``sie_server.api.models.ModelInfo`` for HTTP clients.pub fn to_model_info_value(&self, loaded: bool) -> Value {let state = if loaded { "loaded" } else { "available" };@@ -519,6 +576,7 @@ mod tests {#[test]fn test_canonical_profile_basic() {let profile = ProfileConfig {+ max_output_tokens: None,adapter_path: Some("module:Adapter".into()),max_batch_tokens: Some(4096),compute_precision: Some("float16".into()),@@ -535,6 +593,7 @@ mod tests {#[test]fn test_canonical_profile_strips_null_only_options() {let profile = ProfileConfig {+ max_output_tokens: None,adapter_path: Some("mod:A".into()),max_batch_tokens: None,compute_precision: None,@@ -548,6 +607,7 @@ mod tests {#[test]fn test_canonical_profile_strips_false_only_options() {let profile = ProfileConfig {+ max_output_tokens: None,adapter_path: Some("mod:A".into()),max_batch_tokens: None,compute_precision: None,@@ -562,6 +622,7 @@ mod tests {fn test_canonical_profile_keeps_meaningful_options() {let opts = serde_json::json!({"batch_size": 32, "key": null});let profile = ProfileConfig {+ max_output_tokens: None,adapter_path: Some("mod:A".into()),max_batch_tokens: None,compute_precision: None,@@ -575,6 +636,7 @@ mod tests {#[test]fn test_canonical_profile_drops_empty_nested_option_maps() {let profile = ProfileConfig {+ max_output_tokens: None,adapter_path: Some("mod:A".into()),max_batch_tokens: None,compute_precision: None,@@ -610,6 +672,7 @@ mod tests {let canonicalize = |opts: &serde_json::Value| {CanonicalProfile::from_profile(&ProfileConfig {+ max_output_tokens: None,adapter_path: Some("mod:A".into()),max_batch_tokens: None,compute_precision: None,@@ -668,6 +731,7 @@ mod tests {#[test]fn test_canonical_profile_keeps_nonzero_numbers() {let profile = ProfileConfig {+ max_output_tokens: None,adapter_path: Some("mod:A".into()),max_batch_tokens: None,compute_precision: None,@@ -681,6 +745,7 @@ mod tests {#[test]fn test_canonical_profile_equality() {let p1 = ProfileConfig {+ max_output_tokens: None,adapter_path: Some("mod:A".into()),max_batch_tokens: Some(4096),compute_precision: None,@@ -714,6 +779,65 @@ pool: customer-a);}+ #[test]+ fn test_profile_output_caps_are_inheritance_resolved_and_route_scoped() {+ let raw: serde_yaml::Value = serde_yaml::from_str(+ r#"+sie_id: acme/generator+tasks:+ generate:+ context_length: 262144+ max_output_tokens: 4096+profiles:+ default:+ adapter_path: module:Adapter+ long:+ extends: default+ max_output_tokens: 32768+ thinking:+ extends: long+ sibling:+ extends: default+"#,+ )+ .unwrap();++ let extras = ModelInfoExtras::from_yaml_raw(&raw);+ assert_eq!(extras.max_output_tokens, Some(4096));+ assert_eq!(extras.profile_max_output_tokens.get("long"), Some(&32768));+ assert_eq!(+ extras.profile_max_output_tokens.get("thinking"),+ Some(&32768)+ );+ assert!(!extras.profile_max_output_tokens.contains_key("default"));+ assert!(!extras.profile_max_output_tokens.contains_key("sibling"));+ }++ #[test]+ fn test_model_entry_effective_output_cap_does_not_widen_siblings() {+ let mut profile_caps = HashMap::new();+ profile_caps.insert("thinking".to_string(), 81920);+ let entry = |profile: &str| ModelEntry {+ name: format!("acme/generator:{profile}"),+ canonical_base_model: "acme/generator".to_string(),+ canonical_profile: profile.to_string(),+ pool: None,+ bundles: Vec::new(),+ adapter_modules: HashSet::new(),+ profile_names: HashSet::new(),+ profile_configs: HashMap::new(),+ info_extras: ModelInfoExtras {+ max_output_tokens: Some(4096),+ profile_max_output_tokens: profile_caps.clone(),+ ..ModelInfoExtras::default()+ },+ };++ assert_eq!(entry("thinking").effective_max_output_tokens(), Some(81920));+ assert_eq!(entry("sibling").effective_max_output_tokens(), Some(4096));+ assert_eq!(entry("default").effective_max_output_tokens(), Some(4096));+ }+#[test]fn test_model_config_sie_id_alias() {let yaml = r#"@@ -1039,6 +1163,8 @@ tasks:let info_extras = ModelInfoExtras::from_yaml_raw(&raw);let entry = ModelEntry {name: "Qwen/Qwen3-4B-Instruct-2507".to_string(),+ canonical_base_model: "Qwen/Qwen3-4B-Instruct-2507".to_string(),+ canonical_profile: "default".to_string(),pool: None,bundles: Vec::new(),adapter_modules: HashSet::new(),@@ -1156,6 +1282,8 @@ profiles:let info_extras = ModelInfoExtras::from_yaml_raw(&raw);let entry = ModelEntry {name: "acme/multi-profile-lora".to_string(),+ canonical_base_model: "acme/multi-profile-lora".to_string(),+ canonical_profile: "default".to_string(),pool: None,bundles: Vec::new(),adapter_modules: HashSet::new(),@@ -1210,6 +1338,8 @@ profiles:let info_extras = ModelInfoExtras::from_yaml_raw(&raw);let entry = ModelEntry {name: "acme/multi-profile-lora".to_string(),+ canonical_base_model: "acme/multi-profile-lora".to_string(),+ canonical_profile: "default".to_string(),pool: None,bundles: Vec::new(),adapter_modules: HashSet::new(),diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex a7499c155..07eb334e2 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.6.26"+version = "0.6.27"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12"license = { text = "Apache-2.0" }diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.pyindex c02b4e848..5339838cf 100644--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py@@ -34,6 +34,7 @@ _RESERVED_BASE_URL_HEADERS = frozenset("content-type","cookie","host",+ "idempotency-key","keep-alive","proxy-authenticate","proxy-authorization",diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.pyindex 4eb223e4d..e219fa33c 100644--- a/packages/sie_sdk/src/sie_sdk/client/async_.py+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py@@ -37,7 +37,7 @@ import warningsfrom collections.abc import AsyncIterator, Mapping, Sequencefrom pathlib import Pathfrom typing import IO, Any, Literal, Self, cast, overload-from urllib.parse import urlencode+from urllib.parse import quote, urlencodeimport aiohttpimport msgpack@@ -47,7 +47,15 @@ from sie_sdk.audio import convert_item_audiofrom sie_sdk.documents import convert_item_documentfrom sie_sdk.files import resolve_uploadfrom sie_sdk.images import ImageLike, convert_images_for_json, convert_item_images-from sie_sdk.jobs import TERMINAL_JOB_STATES, build_job_body, decode_chunk_bytes, job_chunks+from sie_sdk.jobs import (+ TERMINAL_JOB_STATES,+ build_job_body,+ decode_chunk_bytes,+ job_chunks,+ require_connection_name,+ require_connection_schema_policy,+ require_connector_idempotency_key,+)from sie_sdk.types import (Batch,BatchList,@@ -91,6 +99,7 @@ from ._shared import (ESTIMATE_PATH,HTTP_CLIENT_ERROR,HTTP_GATEWAY_TIMEOUT,+ HTTP_SERVICE_UNAVAILABLE,JSON_CONTENT_TYPE,LORA_LOADING_DEFAULT_DELAY_S,LORA_LOADING_ERROR_CODE,@@ -2515,8 +2524,9 @@ class SIEAsyncClient:"""Open an aiohttp SSE stream (with pre-stream provisioning retry) and yield chunks.Shared by :meth:`stream_chat_completions` and :meth:`stream_generate`.- Only the *pre-stream* response is retried (503 PROVISIONING / MODEL_LOADING); once bytes flow- a failure is terminal (non-idempotent). The ``async with`` keeps the+ Pre-execution capacity errors are retried when they arrive either as+ an HTTP 503 or as the first SSE event. Once a chunk has been yielded a+ failure is terminal (non-idempotent). The ``async with`` keeps theconnection open while the caller consumes the generator."""timeout = provision_timeout_s if provision_timeout_s is not None else DEFAULT_PROVISION_TIMEOUT_S@@ -2554,6 +2564,7 @@ class SIEAsyncClient:)else:self._check_server_version(_AioResponse(raw.status, b"", raw.headers))+ yielded_chunk = Falseasync for payload in aiter_sse_payloads(_aiter_text_lines(raw.content)):try:chunk = json.loads(payload)@@ -2564,9 +2575,28 @@ class SIEAsyncClient:err = sse_chunk_error(chunk)if err is not None:code, message = err+ if not yielded_chunk:+ capacity_response = _AioResponse(+ HTTP_SERVICE_UNAVAILABLE,+ json.dumps({"error": {"code": code, "message": message}}).encode(),+ {},+ )+ retry_delay, oom_retries = next_stream_retry_delay(+ capacity_response,+ model=model,+ gpu=resolved_gpu,+ wait_for_capacity=wait_for_capacity,+ start_time=start_time,+ timeout=timeout,+ oom_retries=oom_retries,+ max_oom_retries=max_oom_retries,+ )+ breakraise ServerError(message, code=code)yield chunk- return+ yielded_chunk = True+ else:+ returnexcept aiohttp.ClientConnectorError as e:if wait_for_capacity and is_transient_connect_error(e):delay_s = compute_retry_delay(@@ -2847,6 +2877,7 @@ class _AsyncNamespace:url: str,*,json_body: Any = None,+ request_headers: Mapping[str, str] | None = None,timeout_s: float | None = None,include_base_url_headers: bool = True,) -> Any:@@ -2856,25 +2887,27 @@ class _AsyncNamespace:POSTs (jobs.submit / batches.create) floor it to 120s so a large preflightdoes not abort while the server keeps working."""+ headers = {"Accept": JSON_CONTENT_TYPE, **dict(request_headers or {})}try:if method == "GET":response = await self._c._get(url,- headers={"Accept": JSON_CONTENT_TYPE},+ headers=headers,include_base_url_headers=include_base_url_headers,)elif method == "DELETE":response = await self._c._delete(url,- headers={"Accept": JSON_CONTENT_TYPE},+ headers=headers,include_base_url_headers=include_base_url_headers,)else:# Pre-serialize so the Content-Type is unambiguously application/json.+ headers["Content-Type"] = JSON_CONTENT_TYPEresponse = await self._c._post(url,data=json.dumps(json_body).encode("utf-8"),- headers={"Accept": JSON_CONTENT_TYPE, "Content-Type": JSON_CONTENT_TYPE},+ headers=headers,timeout_s=timeout_s,include_base_url_headers=include_base_url_headers,)@@ -2906,10 +2939,12 @@ class _AsyncJobs(_AsyncNamespace):sink_connection: str | None = None,field_map: Mapping[str, Any] | None = None,output_field: str | None = None,+ execution: Literal["plan", "run"] | None = None,when: Any = None,output_types: Sequence[str] | None = None,options: Mapping[str, Any] | None = None,- ) -> JobSubmitResult:+ idempotency_key: str | None = None,+ ) -> JobSubmitResult | JobStatus:"""Async ``jobs.submit``. See :class:`SIEClient` ``.jobs.submit`` for details."""body = build_job_body(source=source,@@ -2920,15 +2955,28 @@ class _AsyncJobs(_AsyncNamespace):sink_connection=sink_connection,field_map=field_map,output_field=output_field,+ execution=execution,when=when,output_types=output_types,options=options,)- return await self._request_json("POST", "/v1/jobs", json_body=body, timeout_s=max(self._c._timeout, 120.0))+ request_headers = None+ if "src" in body:+ request_headers = {"Idempotency-Key": require_connector_idempotency_key(idempotency_key)}+ elif idempotency_key is not None:+ msg = "idempotency_key applies only to connector-src jobs; inline items must omit it"+ raise ValueError(msg)+ return await self._request_json(+ "POST",+ "/v1/jobs",+ json_body=body,+ request_headers=request_headers,+ timeout_s=max(self._c._timeout, 120.0),+ )async def get(self, job_id: str) -> JobStatus:"""Async ``jobs.get``."""- return await self._request_json("GET", f"/v1/jobs/{job_id}")+ return await self._request_json("GET", f"/v1/jobs/{quote(job_id, safe='')}")async def list(self) -> Sequence[JobStatus]:"""Async ``jobs.list``."""@@ -2939,7 +2987,34 @@ class _AsyncJobs(_AsyncNamespace):async def cancel(self, job_id: str) -> JobStatus:"""Async ``jobs.cancel``."""- return await self._request_json("POST", f"/v1/jobs/{job_id}/cancel")+ return await self._request_json("POST", f"/v1/jobs/{quote(job_id, safe='')}/cancel")++ async def execute(self, job_id: str, plan_revision: int, idempotency_key: str) -> JobStatus:+ """Async ``jobs.execute`` — confirm one exact connector plan revision."""+ return await self._request_json(+ "POST",+ f"/v1/jobs/{quote(job_id, safe='')}/execute",+ json_body={"plan_revision": plan_revision},+ request_headers={"Idempotency-Key": require_connector_idempotency_key(idempotency_key)},+ )++ async def repair(+ self,+ job_id: str,+ plan_revision: int,+ recovery_attempt_ordinal: int,+ idempotency_key: str,+ ) -> JobStatus:+ """Async ``jobs.repair`` — repair one exact recovery-required attempt."""+ return await self._request_json(+ "POST",+ f"/v1/jobs/{quote(job_id, safe='')}/repair",+ json_body={+ "plan_revision": plan_revision,+ "recovery_attempt_ordinal": recovery_attempt_ordinal,+ },+ request_headers={"Idempotency-Key": require_connector_idempotency_key(idempotency_key)},+ )async def results(self, job_id: str) -> JobResults:"""Async ``jobs.results`` — read + decode the finished job's chunk refs."""@@ -2964,11 +3039,11 @@ class _AsyncJobs(_AsyncNamespace):}async def wait(self, job_id: str, *, timeout_s: float = 600.0, poll_s: float = 2.0) -> JobStatus:- """Poll ``get`` until the job reaches a terminal state or ``timeout_s`` elapses."""+ """Poll until terminal, or return a connector plan at its stable planned phase."""deadline = time.monotonic() + timeout_swhile True:job = await self.get(job_id)- if job.get("state") in TERMINAL_JOB_STATES:+ if job.get("state") in TERMINAL_JOB_STATES or job.get("phase") == "planned":return jobif time.monotonic() >= deadline:msg = f"job {job_id} still {job.get('state')!r} after {timeout_s:.0f}s"@@ -3016,9 +3091,21 @@ class _AsyncConnections(_AsyncNamespace):raise ValueError(msg)return f"{self._c._control_plane_url}/internal/orgs/{self._c._org}/connections"- async def add(self, name: str, type: str, secret: str) -> ConnectionCreated:- """Async ``connections.add``."""- body = {"type": type, "name": name, "secret": secret}+ async def add(+ self,+ name: str,+ type: str,+ secret: str,+ *,+ source_schema: str | None = None,+ sink_schema: str | None = None,+ ) -> ConnectionCreated:+ """Async ``connections.add`` with optional PostgreSQL schema policy."""+ require_connection_name(name)+ body: dict[str, Any] = {"type": type, "name": name, "secret": secret}+ schema_policy = require_connection_schema_policy(type, source_schema, sink_schema)+ if schema_policy is not None:+ body["source_schema"], body["sink_schema"] = schema_policyreturn await self._request_json("POST", self._base(), json_body=body, include_base_url_headers=False)async def list(self) -> Sequence[Connection]:@@ -3030,7 +3117,8 @@ class _AsyncConnections(_AsyncNamespace):async def revoke(self, name: str) -> ConnectionRevoked:"""Async ``connections.revoke``."""- return await self._request_json("DELETE", f"{self._base()}/{name}", include_base_url_headers=False)+ canonical_name = require_connection_name(name)+ return await self._request_json("DELETE", f"{self._base()}/{canonical_name}", include_base_url_headers=False)# ---------------------------------------------------------------------------diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex 4f04d9e21..4570d43c4 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -45,7 +45,7 @@ from collections.abc import Iterator, Mapping, Sequencefrom functools import partialfrom pathlib import Pathfrom typing import IO, Any, Literal, Self, cast, overload-from urllib.parse import urlencode+from urllib.parse import quote, urlencodeimport httpximport msgpack@@ -55,7 +55,15 @@ from sie_sdk.audio import convert_item_audiofrom sie_sdk.documents import convert_item_documentfrom sie_sdk.files import resolve_uploadfrom sie_sdk.images import ImageLike, convert_images_for_json, convert_item_images-from sie_sdk.jobs import TERMINAL_JOB_STATES, build_job_body, decode_chunk_bytes, job_chunks+from sie_sdk.jobs import (+ TERMINAL_JOB_STATES,+ build_job_body,+ decode_chunk_bytes,+ job_chunks,+ require_connection_name,+ require_connection_schema_policy,+ require_connector_idempotency_key,+)from sie_sdk.types import (Batch,BatchList,@@ -99,6 +107,7 @@ from ._shared import (ESTIMATE_PATH,HTTP_CLIENT_ERROR,HTTP_GATEWAY_TIMEOUT,+ HTTP_SERVICE_UNAVAILABLE,JSON_CONTENT_TYPE,LORA_LOADING_DEFAULT_DELAY_S,LORA_LOADING_ERROR_CODE,@@ -2829,10 +2838,11 @@ class SIEClient:"""Open an SSE stream (with pre-stream provisioning retry) and yield chunks.Shared by :meth:`stream_chat_completions` and :meth:`stream_generate`.- Only the *pre-stream* response is retried (503 PROVISIONING / MODEL_LOADING); once bytes start- flowing a failure is terminal (non-idempotent). Yielding inside the- ``with`` keeps the stream open while the caller consumes it; an early- ``break`` tears the context down and the worker sees the disconnect.+ Pre-execution capacity errors are retried when they arrive either as+ an HTTP 503 or as the first SSE event. Once a chunk has been yielded a+ failure is terminal (non-idempotent). Yielding inside the ``with``+ keeps the stream open while the caller consumes it; an early ``break``+ tears the context down and the worker sees the disconnect."""self._reset_retry_count()timeout = provision_timeout_s if provision_timeout_s is not None else DEFAULT_PROVISION_TIMEOUT_S@@ -2865,6 +2875,7 @@ class SIEClient:self._record_retry()else:self._check_server_version(response)+ yielded_chunk = Falsefor payload in iter_sse_payloads(response.iter_lines()):try:chunk = json.loads(payload)@@ -2875,9 +2886,28 @@ class SIEClient:err = sse_chunk_error(chunk)if err is not None:code, message = err+ if not yielded_chunk:+ capacity_response = httpx.Response(+ HTTP_SERVICE_UNAVAILABLE,+ json={"error": {"code": code, "message": message}},+ )+ retry_delay, oom_retries = next_stream_retry_delay(+ capacity_response,+ model=model,+ gpu=resolved_gpu,+ wait_for_capacity=wait_for_capacity,+ start_time=start_time,+ timeout=timeout,+ oom_retries=oom_retries,+ max_oom_retries=max_oom_retries,+ )+ self._record_retry()+ breakraise ServerError(message, code=code)yield chunk- return+ yielded_chunk = True+ else:+ returnexcept httpx.ConnectError as e:if wait_for_capacity and is_transient_connect_error(e):delay_s = compute_retry_delay(@@ -3256,11 +3286,14 @@ class _SyncNamespace:url: str,*,json_body: Any = None,+ request_headers: Mapping[str, str] | None = None,timeout_s: float | None = None,include_base_url_headers: bool = True,) -> Any:"""One JSON request over the client's httpx transport (bearer auth reused)."""headers = {"Accept": JSON_CONTENT_TYPE, "Content-Type": JSON_CONTENT_TYPE}+ if request_headers:+ headers.update(request_headers)try:response = self._c._client.request(method,@@ -3305,25 +3338,34 @@ class _SyncJobs(_SyncNamespace):sink_connection: str | None = None,field_map: Mapping[str, Any] | None = None,output_field: str | None = None,+ execution: Literal["plan", "run"] | None = None,when: Any = None,output_types: Sequence[str] | None = None,options: Mapping[str, Any] | None = None,- ) -> JobSubmitResult:- """Submit a batch job (``POST /v1/jobs``); returns the created-job envelope.+ idempotency_key: str | None = None,+ ) -> JobSubmitResult | JobStatus:+ """Submit a batch job (``POST /v1/jobs``).++ Returns the created-job envelope, or the current :class:`JobStatus`+ when an exact connector idempotency replay has already progressed.``source`` is either inline items (a list, or a bare string = one textitem) or a connector ``scheme://<connection>/…`` URI (incl.the internal ``upload://<file-id>`` push-to-us source); ``sink``- is ``"return"`` (default), ``"inplace"``, or a connector URI; ``when`` is- ``"now"`` (default), ``"schedule:<cron>"``, or ``"watch:<source>"``.+ is ``"return"`` (default), ``"inplace"``, or a connector URI. Jobs are+ immediate: omit ``when`` or pass ``"now"``; schedule/watch are not yet+ part of the public jobs schema.``field_map`` names the uniform source slots(``{"id_field", "input_field", "carry", "input_type"}``) and``output_field`` the sink target — connector jobs only; the- per-connector URI params keep working as aliases. ``options`` carries- the per-item options plus the op inputs (operation matrix:+ per-connector URI params keep working as aliases. ``options`` is one+ job-level operation map applied uniformly to every item (operation matrix:score → ``options["query"]``, extract → ``options["labels"]`` /``options["output_schema"]``, generate → sampling such as``max_new_tokens``), forwarded as-is.+ Connector submissions require a caller-owned, retry-stable+ ``idempotency_key``; inline submissions remain header-free and must+ omit it."""body = build_job_body(source=source,@@ -3334,15 +3376,28 @@ class _SyncJobs(_SyncNamespace):sink_connection=sink_connection,field_map=field_map,output_field=output_field,+ execution=execution,when=when,output_types=output_types,options=options,)- return self._request_json("POST", "/v1/jobs", json_body=body, timeout_s=max(self._c._timeout, 120.0))+ request_headers = None+ if "src" in body:+ request_headers = {"Idempotency-Key": require_connector_idempotency_key(idempotency_key)}+ elif idempotency_key is not None:+ msg = "idempotency_key applies only to connector-src jobs; inline items must omit it"+ raise ValueError(msg)+ return self._request_json(+ "POST",+ "/v1/jobs",+ json_body=body,+ request_headers=request_headers,+ timeout_s=max(self._c._timeout, 120.0),+ )def get(self, job_id: str) -> JobStatus:"""Fetch a job's public status doc (``GET /v1/jobs/{id}``)."""- return self._request_json("GET", f"/v1/jobs/{job_id}")+ return self._request_json("GET", f"/v1/jobs/{quote(job_id, safe='')}")def list(self) -> Sequence[JobStatus]:"""List the org's jobs (``GET /v1/jobs``; scoped to the key's org)."""@@ -3353,7 +3408,34 @@ class _SyncJobs(_SyncNamespace):def cancel(self, job_id: str) -> JobStatus:"""Cancel a job (``POST /v1/jobs/{id}/cancel``); the hold's remainder releases."""- return self._request_json("POST", f"/v1/jobs/{job_id}/cancel")+ return self._request_json("POST", f"/v1/jobs/{quote(job_id, safe='')}/cancel")++ def execute(self, job_id: str, plan_revision: int, idempotency_key: str) -> JobStatus:+ """Confirm one exact connector plan revision for execution."""+ return self._request_json(+ "POST",+ f"/v1/jobs/{quote(job_id, safe='')}/execute",+ json_body={"plan_revision": plan_revision},+ request_headers={"Idempotency-Key": require_connector_idempotency_key(idempotency_key)},+ )++ def repair(+ self,+ job_id: str,+ plan_revision: int,+ recovery_attempt_ordinal: int,+ idempotency_key: str,+ ) -> JobStatus:+ """Repair one exact recovery-required connector attempt and cutoff."""+ return self._request_json(+ "POST",+ f"/v1/jobs/{quote(job_id, safe='')}/repair",+ json_body={+ "plan_revision": plan_revision,+ "recovery_attempt_ordinal": recovery_attempt_ordinal,+ },+ request_headers={"Idempotency-Key": require_connector_idempotency_key(idempotency_key)},+ )def results(self, job_id: str) -> JobResults:"""Retrieve a finished job's chunk refs and decode the per-item results.@@ -3383,11 +3465,11 @@ class _SyncJobs(_SyncNamespace):}def wait(self, job_id: str, *, timeout_s: float = 600.0, poll_s: float = 2.0) -> JobStatus:- """Poll ``get`` until the job reaches a terminal state or ``timeout_s`` elapses."""+ """Poll until terminal, or return a connector plan at its stable planned phase."""deadline = time.monotonic() + timeout_swhile True:job = self.get(job_id)- if job.get("state") in TERMINAL_JOB_STATES:+ if job.get("state") in TERMINAL_JOB_STATES or job.get("phase") == "planned":return jobif time.monotonic() >= deadline:msg = f"job {job_id} still {job.get('state')!r} after {timeout_s:.0f}s"@@ -3440,9 +3522,27 @@ class _SyncConnections(_SyncNamespace):raise ValueError(msg)return f"{self._c._control_plane_url}/internal/orgs/{self._c._org}/connections"- def add(self, name: str, type: str, secret: str) -> ConnectionCreated:- """Create an org-scoped connection (connector auth). ``type`` is the connector family."""- body = {"type": type, "name": name, "secret": secret}+ def add(+ self,+ name: str,+ type: str,+ secret: str,+ *,+ source_schema: str | None = None,+ sink_schema: str | None = None,+ ) -> ConnectionCreated:+ """Create an org-scoped connection (connector auth).++ PostgreSQL connections may bind an immutable ``source_schema`` /+ ``sink_schema`` policy. Both schema names must be supplied together;+ legacy connections without the policy remain ineligible for the strong+ incremental planner profile.+ """+ require_connection_name(name)+ body: dict[str, Any] = {"type": type, "name": name, "secret": secret}+ schema_policy = require_connection_schema_policy(type, source_schema, sink_schema)+ if schema_policy is not None:+ body["source_schema"], body["sink_schema"] = schema_policyreturn self._request_json("POST", self._base(), json_body=body, include_base_url_headers=False)def list(self) -> Sequence[Connection]:@@ -3454,7 +3554,8 @@ class _SyncConnections(_SyncNamespace):def revoke(self, name: str) -> ConnectionRevoked:"""Revoke (soft-delete) a connection; frees the name for reuse."""- return self._request_json("DELETE", f"{self._base()}/{name}", include_base_url_headers=False)+ canonical_name = require_connection_name(name)+ return self._request_json("DELETE", f"{self._base()}/{canonical_name}", include_base_url_headers=False)# ---------------------------------------------------------------------------diff --git a/packages/sie_sdk/src/sie_sdk/jobs.py b/packages/sie_sdk/src/sie_sdk/jobs.pyindex 82fa60b96..9f4bdbfa3 100644--- a/packages/sie_sdk/src/sie_sdk/jobs.py+++ b/packages/sie_sdk/src/sie_sdk/jobs.py@@ -14,8 +14,9 @@ unit-testable without a gateway:from __future__ import annotations+import refrom collections.abc import Mapping, Sequence-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, Literalfrom urllib.parse import urlsplitimport msgpack@@ -42,6 +43,18 @@ _INTERNAL_SCHEMES = frozenset({"upload"})_FIELD_MAP_KEYS = frozenset({"id_field", "input_field", "carry", "input_type"})_INPUT_TYPES = frozenset({"text", "document"})+# One canonical path segment across the SDK, gateway, dispatcher, and control+# plane. This is deliberately ASCII-only: connection names cross credential+# resolution and HTTP routing boundaries and must not have decoded aliases.+_CONNECTION_NAME_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}\Z", re.ASCII)+_POSTGRES_SCHEMA_PATTERN = re.compile(r"[A-Za-z_][A-Za-z0-9_$]{0,62}\Z", re.ASCII)++# Public connector actions share the gateway's bounded printable-ASCII header+# contract. Callers own this value so a logical retry can reuse the same key;+# generating it inside ``submit``/``execute`` would turn a retry into a new+# mutation.+_CONNECTOR_IDEMPOTENCY_KEY_MAX_BYTES = 256+# msgpack + the numpy codec are hard deps of the SDK, so always importable here._RESULT_OBJECT_HOOK = msgpack_numpy.decode@@ -61,6 +74,54 @@ def _is_connector_uri(value: Any) -> bool:return isinstance(value, str) and "://" in value+def require_connection_name(name: str) -> str:+ """Return a canonical named-connection path segment or fail before I/O."""+ if _CONNECTION_NAME_PATTERN.fullmatch(name) is None:+ msg = "connection name must be 1-128 ASCII letters, digits, '.', '_', or '-', and start with a letter or digit"+ raise ValueError(msg)+ return name+++def require_connection_schema_policy(+ connection_type: str,+ source_schema: str | None,+ sink_schema: str | None,+) -> tuple[str, str] | None:+ """Validate the optional Postgres source/sink namespace pair before I/O."""+ if (source_schema is None) != (sink_schema is None):+ msg = "source_schema and sink_schema must be supplied together"+ raise ValueError(msg)+ if source_schema is None or sink_schema is None:+ return None+ if connection_type != "postgres":+ msg = "source_schema and sink_schema apply only to postgres connections"+ raise ValueError(msg)+ if (+ _POSTGRES_SCHEMA_PATTERN.fullmatch(source_schema) is None+ or _POSTGRES_SCHEMA_PATTERN.fullmatch(sink_schema) is None+ ):+ msg = "source_schema and sink_schema must be canonical Postgres identifiers of at most 63 ASCII bytes"+ raise ValueError(msg)+ return source_schema, sink_schema+++def require_connector_idempotency_key(key: str | None) -> str:+ """Return a valid retry-stable connector action idempotency key.++ The gateway requires exactly one ``Idempotency-Key`` header containing+ 1-256 printable ASCII bytes. Keeping the same validation in the SDK fails+ before I/O without weakening the gateway's authoritative check.+ """+ if (+ not isinstance(key, str)+ or not 1 <= len(key) <= _CONNECTOR_IDEMPOTENCY_KEY_MAX_BYTES+ or not all(0x20 <= ord(char) <= 0x7E for char in key)+ ):+ msg = f"connector idempotency_key must contain 1-{_CONNECTOR_IDEMPOTENCY_KEY_MAX_BYTES} printable ASCII bytes"+ raise ValueError(msg)+ return key++def connection_name(uri: str) -> str:"""The connection an org registered, referenced by the URI authority.@@ -68,12 +129,15 @@ def connection_name(uri: str) -> str:→ ``customer-bucket``. Credentials never appear in the call — the job onlynames the connection; the runner resolves it org-scoped."""- parts = urlsplit(uri)- name = parts.netloc or parts.path.lstrip("/").split("/", 1)[0]+ # Read the raw authority rather than a URL parser's normalized netloc:+ # control characters must fail, not disappear into an alias before the+ # canonical path-segment check.+ after_scheme = uri.split("://", 1)[1] if "://" in uri else ""+ name = re.split(r"[/?#]", after_scheme, maxsplit=1)[0]if not name:msg = f"connector URI {uri!r} names no connection (expected 'scheme://<connection>/…')"raise ValueError(msg)- return name+ return require_connection_name(name)def _is_internal_uri(uri: str) -> bool:@@ -95,8 +159,14 @@ def _resolve_source(source: Any, connection: str | None) -> dict[str, Any]:return {"items": [_norm_item(item, i) for i, item in enumerate(source)]}if _is_connector_uri(source):if _is_internal_uri(source):- return {"src": source, **({"connection": connection} if connection else {})}- return {"src": source, "connection": connection or connection_name(source)}+ return {+ "src": source,+ **({"connection": require_connection_name(connection)} if connection else {}),+ }+ return {+ "src": source,+ "connection": require_connection_name(connection) if connection else connection_name(source),+ }if isinstance(source, str) and source.strip():# A bare string is one inline text item (the "embed this text" case).return {"items": [{"text": source}]}@@ -115,9 +185,9 @@ def _resolve_sink(sink: Any, *, source_connection: str | None, sink_connection:if _is_internal_uri(sink):# Internal scheme: OUR Files store, no connection to name.if sink_connection is not None:- body["sink_connection"] = sink_connection+ body["sink_connection"] = require_connection_name(sink_connection)return body- resolved = sink_connection if sink_connection is not None else connection_name(sink)+ resolved = require_connection_name(sink_connection) if sink_connection is not None else connection_name(sink)# Thread the sink connection when explicitly overridden or distinct from# the source's (the common "index my own store" case reuses the source).if sink_connection is not None or resolved != source_connection:@@ -170,21 +240,10 @@ def _resolve_field_map(field_map: Mapping[str, Any] | None, output_field: str |def _resolve_when(when: Any) -> dict[str, Any]:- """Map the ``when`` trigger: now (default) | schedule(cron) | watch(source)."""- if when is None or not isinstance(when, str) or when.strip().lower() in {"", "now"}:+ """Accept the only trigger implemented by the strict public jobs schema."""+ if when is None or (isinstance(when, str) and when.strip().lower() in {"", "now"}):return {}- text = when.strip()- if text.lower().startswith("schedule:"):- return {"when": "schedule", "schedule": text.split(":", 1)[1].strip()}- if text.lower().startswith("watch:"):- return {"when": "watch", "watch": text.split(":", 1)[1].strip()}- if text.lower() == "schedule":- msg = "schedule trigger needs a cron expr: when='schedule:<cron>'"- raise ValueError(msg)- # A bare cron expression (5 whitespace-separated fields) is a schedule.- if len(text.split()) == 5:- return {"when": "schedule", "schedule": text}- msg = f"unrecognized when {when!r}: use 'now', 'schedule:<cron>', or 'watch:<source>'"+ msg = f"scheduled and watched jobs are not available; omit when or use 'now', got {when!r}"raise ValueError(msg)@@ -198,6 +257,7 @@ def build_job_body(sink_connection: str | None = None,field_map: Mapping[str, Any] | None = None,output_field: str | None = None,+ execution: Literal["plan", "run"] | None = None,when: Any = None,output_types: Sequence[str] | None = None,options: Mapping[str, Any] | None = None,@@ -209,13 +269,15 @@ def build_job_body(``sink_connection`` override the names derived from the URIs; ``field_map``+ ``output_field`` are the uniform mapping slots (connector jobsonly — per-connector ``id_column``/``text_column``/``column`` params keep- working as aliases). ``options`` is the opaque per-item options map plus- the op inputs (operation matrix: score → ``options.query``,+ working as aliases). ``options`` is one opaque job-level operation map,+ applied uniformly to every item (operation matrix: score → ``options.query``,extract → ``options.labels`` / ``options.output_schema``, generate →sampling such as ``max_new_tokens``); it is forwarded as-is. Only thefields that are set ride the wire, so an inline submit is byte-for-bytethe realtime POC body and the connector body is additive (``/v1``- additive-only rule).+ additive-only rule). The public contract requires every connector-src+ request to set ``execution``; inline requests must omit it, including for+ callers outside this repository.Raises:ValueError: If the source/sink/when/field_map/options slots cannot be@@ -224,7 +286,26 @@ def build_job_body(body: dict[str, Any] = {"operation": operation, "model": model}source_fields = _resolve_source(source, connection)body.update(source_fields)- body.update(_resolve_sink(sink, source_connection=source_fields.get("connection"), sink_connection=sink_connection))+ sink_fields = _resolve_sink(+ sink,+ source_connection=source_fields.get("connection"),+ sink_connection=sink_connection,+ )+ if "items" in source_fields and (connection is not None or sink_fields or sink_connection is not None):+ msg = "connection/sink/sink_connection apply only to connector-src jobs; inline items return results"+ raise ValueError(msg)+ body.update(sink_fields)+ if "src" in body:+ if execution not in {"plan", "run"}:+ msg = "connector jobs require execution='plan' or execution='run'"+ raise ValueError(msg)+ if execution != "run" and (_is_internal_uri(str(source)) or (isinstance(sink, str) and _is_internal_uri(sink))):+ msg = "upload:// connector jobs are run-only; set execution='run'"+ raise ValueError(msg)+ body["execution"] = execution+ elif execution is not None:+ msg = "execution applies only to connector-src jobs; inline items must omit it"+ raise ValueError(msg)mapping_fields = _resolve_field_map(field_map, output_field)if mapping_fields and "src" not in body:msg = "field_map/output_field apply to connector-src jobs; an inline items job maps nothing"@@ -235,7 +316,7 @@ def build_job_body(body["output_types"] = list(output_types)if options is not None:if not isinstance(options, Mapping):- msg = f"options must be a mapping (per-item options + op inputs), got {type(options).__name__}"+ msg = f"options must be a mapping (one job-level operation map), got {type(options).__name__}"raise ValueError(msg)if options:body["options"] = dict(options)diff --git a/packages/sie_sdk/src/sie_sdk/queue_types.py b/packages/sie_sdk/src/sie_sdk/queue_types.pyindex e854133aa..e374262b6 100644--- a/packages/sie_sdk/src/sie_sdk/queue_types.py+++ b/packages/sie_sdk/src/sie_sdk/queue_types.py@@ -147,6 +147,9 @@ class WorkResult(_WorkResultRequired, total=False):execution_identity_sha256: Opaque worker-origin SHA-256 binding thesuccessful result to one immutable managed deployment/resourceidentity. Optional for rolling and self-host compatibility.+ executed_bundle_config_hash: Worker-origin hash of the registry bundle+ held stable for this successful execution. Optional for rolling+ and self-host compatibility."""result_msgpack: bytes | None@@ -168,6 +171,7 @@ class WorkResult(_WorkResultRequired, total=False):units: dict[str, int] | Noneexecution_identity_sha256: str | None+ executed_bundle_config_hash: str | None# -- NATS subject helpers ---------------------------------------------------diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.pyindex 9a5fac592..86c679474 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -1254,6 +1254,148 @@ class RateIdentity(TypedDict):region: str+class ConnectorJobValidation(TypedDict, total=False):+ """Planner proofs safe to expose to a connector caller."""++ source: str+ identity: str+ sink: str+++class ConnectorJobCapabilities(TypedDict, total=False):+ """The bounded behavior proven for one connector plan revision."""++ incremental_inference: bool+ incremental_source_scan: bool+ source_scan: str+ source_proof: str+ checkpoint_profile: str+ incremental_selection: bool+ inference: str+ sink_targets: Any+ snapshot: str+ ordering: str+ deletion_handling: str+ publication: str+++class ConnectorPlanOutputShape(TypedDict):+ """Redacted, canonical output shape for one connector plan."""++ result_kind: Literal["vector"]+ output_field: Literal["embedding"]+ output_types: list[Literal["dense"]]+ dimensions: int | None+++class ConnectorJobPlan(TypedDict, total=False):+ """A durable inspect-first plan. It contains metadata, never source rows."""++ revision: int+ expires_at: float+ executable: bool+ executor_available: bool | None+ executor_availability: str+ blocking_code: str | None+ rows: int+ mapped_bytes: int+ input_bytes: int+ eligible_count: int+ eligible_count_quality: str+ eligible_input_byte_count: int+ matched_checkpoint_count: int+ skipped_unchanged_count: int+ deleted_preserved_count: int+ output_dimensions: int | None+ output: Required[ConnectorPlanOutputShape]+ cost_basis: str+ max_reservation_credits: int+ validation: ConnectorJobValidation+ capabilities: ConnectorJobCapabilities+++class ConnectorJobCheckpoint(TypedDict, total=False):+ """Public checkpoint/fence position for the connector profile."""++ profile: str+ profile_version: int+ region: str+ expected_generation: int+ generation: int+ published_revision: int+++class ConnectorJobItemOutcomes(TypedDict, total=False):+ """Bounded item counters for one connector attempt."""++ claimed: int+ dispatched: int+ inferred: int+ staged: int+ published: int+ failed: int+ reexecution_required: int+ skipped_unchanged: int+++class ConnectorJobPublication(TypedDict, total=False):+ """Public evidence for one atomic sink publication."""++ attempt_ordinal: int+ revision: int+ published: int+ skipped_unchanged: int+ deleted: int+ failed: int+ reexecuted: int+ committed_at: float+++class ConnectorJobOverlapOwner(TypedDict, total=False):+ """The exact earlier attempt that already owns an overlapping cutoff."""++ job_id: str+ attempt_ordinal: int+++class ConnectorJobAttempt(TypedDict, total=False):+ """One public execute/repair attempt; private dispatch authority is omitted."""++ ordinal: Required[int]+ action: Required[Literal["execute", "repair"]]+ state: Required[str]+ recovery_attempt_ordinal: int+ outcome: str | None+ error_code: str | None+ replayed: bool+ billed_credits: int | None+ overlap_owner: ConnectorJobOverlapOwner | None+ item_outcomes: ConnectorJobItemOutcomes+ publication: ConnectorJobPublication | None+ created_at: float+ finished_at: float | None+++class ConnectorJobRepairWindow(TypedDict, total=False):+ """Bounded repair budget for the current recovery-required cutoff."""++ expires_at: float | None+ attempts_used: int | None+ attempts_remaining: int | None+ attempts_max: int | None+++class ConnectorJobRecovery(TypedDict, total=False):+ """Public crash-recovery posture; tokens and receipt MACs never appear."""++ required: bool+ state: str | None+ outcome: str | None+ error_code: str | None+ reexecution_required: bool+ repair: ConnectorJobRepairWindow++class JobChunk(TypedDict, total=False):"""One spawned chunk's settle metadata (``output.chunks[]``; results-as-refs).@@ -1287,20 +1429,41 @@ class JobSubmitResult(TypedDict, total=False):total_items: intchunks: intpreflight: JobPreflight- # Connector jobs echo the resolved ends instead of total_items.- input_source: str- source: str- sink: str+ # Connector source/sink URIs and SQL are deliberately absent from public+ # responses; the governed plan exposes only bounded aggregate evidence.+ execution: Literal["plan", "run"]+ phase: str+ plan_revision: int+ plan_expires_at: float+ idempotency_expires_at: float+ plan: ConnectorJobPlan+ checkpoint: ConnectorJobCheckpoint+ attempt: ConnectorJobAttempt+ publication: ConnectorJobPublication | None+ recovery: ConnectorJobRecoveryclass JobStatus(TypedDict, total=False):"""A job's public status doc from ``GET /v1/jobs/{id}`` (refs, never payloads)."""- id: str- object: str- operation: str- model: str- state: JobState+ id: Required[str]+ object: Required[str]+ operation: Required[str]+ model: Required[str]+ state: Required[JobState]+ execution: Literal["plan", "run"]+ phase: str+ outcome: str | None+ error_code: str | None+ plan_revision: int | None+ plan_expires_at: float | None+ idempotency_expires_at: float | None+ plan: ConnectorJobPlan | None+ checkpoint: ConnectorJobCheckpoint+ attempt: ConnectorJobAttempt+ attempts: list[ConnectorJobAttempt]+ publication: ConnectorJobPublication | None+ recovery: ConnectorJobRecoverytotal_items: intcompleted_items: intpreflight: JobPreflight@@ -1351,6 +1514,9 @@ class Connection(TypedDict, total=False):id: inttype: strname: str+ authorization_generation: int+ source_schema: str | None+ sink_schema: str | Nonecreated_at: float@@ -1362,6 +1528,9 @@ class ConnectionCreated(TypedDict, total=False):id: inttype: strname: str+ authorization_generation: int+ source_schema: str | None+ sink_schema: str | Nonecreated_at: floatdiff --git a/packages/sie_sdk/tests/client/test_base_url_headers.py b/packages/sie_sdk/tests/client/test_base_url_headers.pyindex 406d00298..db80bf528 100644--- a/packages/sie_sdk/tests/client/test_base_url_headers.py+++ b/packages/sie_sdk/tests/client/test_base_url_headers.py@@ -129,6 +129,7 @@ def test_sync_adversarial_ref_origins_stay_bare(ref: str) -> None:({"Bad\nName": "value"}, ValueError),({"X-Edge": "value\r\ninjected: yes"}, ValueError),({"Authorization": "other"}, ValueError),+ ({"Idempotency-Key": "edge-owned"}, ValueError),({"Keep-Alive": "timeout=5"}, ValueError),({"TE": "trailers"}, ValueError),({"Trailer": "X-Checksum"}, ValueError),@@ -142,6 +143,11 @@ def test_sync_rejects_unsafe_base_url_headers(headers: Any, error: type[ExceptioSIEClient(BASE_URL, base_url_headers=headers)+def test_async_rejects_edge_header_that_would_override_connector_idempotency() -> None:+ with pytest.raises(ValueError, match="SDK-owned header"):+ SIEAsyncClient(BASE_URL, base_url_headers={"idempotency-key": "edge-owned"})++@pytest.mark.parametrize("base_url",[diff --git a/packages/sie_sdk/tests/client/test_chat.py b/packages/sie_sdk/tests/client/test_chat.pyindex a2576a795..4e69965ef 100644--- a/packages/sie_sdk/tests/client/test_chat.py+++ b/packages/sie_sdk/tests/client/test_chat.py@@ -259,6 +259,39 @@ def test_stream_chat_retries_503_provisioning_then_streams() -> None:client.close()+def test_stream_chat_retries_first_sse_model_loading_then_streams() -> None:+ loading = {+ "error": {"code": "MODEL_LOADING", "message": "loading"},+ }+ s200_loading = _FakeStream(lines=_sse(loading))+ s200_ok = _FakeStream(lines=_sse(_chat_chunk("ok", finish="stop")))+ with patch("sie_sdk.client.sync.httpx.Client") as mc, patch("sie_sdk.client.sync.time.sleep"):+ mc.return_value.stream.side_effect = [s200_loading, s200_ok]+ client = SIEClient("http://localhost:8080")++ out = list(client.stream_chat_completions("m", [{"role": "user", "content": "hi"}], provision_timeout_s=5.0))++ assert [c["choices"][0]["delta"].get("content") for c in out] == ["ok"]+ assert mc.return_value.stream.call_count == 2+ assert client.last_retry_count == 1+ client.close()+++def test_stream_chat_does_not_retry_sse_model_loading_after_output() -> None:+ loading = {"error": {"code": "MODEL_LOADING", "message": "loading"}}+ partial_then_loading = _FakeStream(lines=_sse(_chat_chunk("partial"), loading))+ with patch("sie_sdk.client.sync.httpx.Client") as mc:+ mc.return_value.stream.return_value = partial_then_loading+ client = SIEClient("http://localhost:8080")++ with pytest.raises(ServerError, match="loading"):+ list(client.stream_chat_completions("m", [{"role": "user", "content": "hi"}]))++ assert mc.return_value.stream.call_count == 1+ assert client.last_retry_count == 0+ client.close()++def test_chat_completions_reports_pre_execution_retry() -> None:retry = MagicMock()retry.status_code = 503diff --git a/packages/sie_sdk/tests/client/test_chat_async.py b/packages/sie_sdk/tests/client/test_chat_async.pyindex c6c70fff1..a1bbc0d86 100644--- a/packages/sie_sdk/tests/client/test_chat_async.py+++ b/packages/sie_sdk/tests/client/test_chat_async.py@@ -9,7 +9,7 @@ from __future__ import annotationsimport jsonfrom typing import Any, Self-from unittest.mock import AsyncMock, MagicMock+from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom sie_sdk import SIEAsyncClient@@ -256,6 +256,46 @@ async def test_async_stream_chat_retries_503_provisioning_then_streams() -> Noneawait client.close()+async def test_async_stream_chat_retries_first_sse_model_loading_then_streams() -> None:+ loading = {+ "error": {"code": "MODEL_LOADING", "message": "loading"},+ }+ s200_loading = _FakeRaw(status=200, line_bytes=_sse_bytes(loading))+ s200_ok = _FakeRaw(status=200, line_bytes=_sse_bytes(_chat_chunk("ok", finish="stop")))+ client = SIEAsyncClient("http://localhost:8080")+ session = _patch_session(client, post_side_effect=[s200_loading, s200_ok])++ with patch("sie_sdk.client.async_.asyncio.sleep"):+ out = [+ c+ async for c in client.stream_chat_completions(+ "m", [{"role": "user", "content": "hi"}], provision_timeout_s=5.0+ )+ ]++ assert [c["choices"][0]["delta"].get("content") for c in out] == ["ok"]+ assert session.post.call_count == 2+ await client.close()+++async def test_async_stream_chat_does_not_retry_sse_model_loading_after_output() -> None:+ loading = {"error": {"code": "MODEL_LOADING", "message": "loading"}}+ partial_then_loading = _FakeRaw(+ status=200,+ line_bytes=_sse_bytes(_chat_chunk("partial"), loading),+ )+ client = SIEAsyncClient("http://localhost:8080")+ session = _patch_session(client, post_returns=partial_then_loading)++ with pytest.raises(ServerError, match="loading"):+ _ = [c async for c in client.stream_chat_completions("m", [{"role": "user", "content": "hi"}])]++ assert session.post.call_count == 1+ await client.close()++@pytest.mark.asyncioasync def test_async_chat_completions_504_retains_terminal_request_metadata_without_retry() -> None:timeout = _FakeRaw(diff --git a/packages/sie_sdk/tests/client/test_connections.py b/packages/sie_sdk/tests/client/test_connections.pyindex 2c81b55b3..30e0d17c9 100644--- a/packages/sie_sdk/tests/client/test_connections.py+++ b/packages/sie_sdk/tests/client/test_connections.py@@ -49,6 +49,37 @@ def test_add_posts_to_control_plane_with_secret() -> None:client.close()+ ("connection_type", "source_schema", "sink_schema"),+ [+ ("postgres", "source", None),+ ("postgres", None, "sink"),+ ("s3", "source", "sink"),+ ("postgres", "source.bad", "sink"),+ ("postgres", "source", "sink-bad"),+ ("postgres", "source", "sink\n"),+ ("postgres", "source", "s" * 64),+ ],+)+def test_invalid_schema_policy_fails_before_sync_io(+ connection_type: str,+ source_schema: str | None,+ sink_schema: str | None,+) -> None:+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ client = SIEClient(GW, api_key=KEY, control_plane_url=CP, org="acme")+ with pytest.raises(ValueError, match="schema"):+ client.connections.add(+ name="wh",+ type=connection_type,+ secret="dsn", # noqa: S106+ source_schema=source_schema,+ sink_schema=sink_schema,+ )+ mock_client.return_value.request.assert_not_called()+ client.close()++def test_list_returns_connections_array() -> None:payload = {"org": "acme", "account_id": 7, "connections": [{"id": 1, "type": "postgres", "name": "wh"}]}with patch("sie_sdk.client.sync.httpx.Client") as mock_client:@@ -72,6 +103,30 @@ def test_revoke_deletes_named_connection() -> None:client.close()+ "invalid_name",+ [+ "../other",+ "warehouse/name",+ "warehouse%2fname",+ "warehouse\n",+ "warehouse\r",+ "warehouse\u2028",+ "café",+ "a" * 129,+ ],+)+def test_invalid_connection_name_fails_before_sync_io(invalid_name: str) -> None:+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ client = SIEClient(GW, api_key=KEY, control_plane_url=CP, org="acme")+ with pytest.raises(ValueError, match="connection name"):+ client.connections.add(name=invalid_name, type="postgres", secret="dsn") # noqa: S106+ with pytest.raises(ValueError, match="connection name"):+ client.connections.revoke(invalid_name)+ mock_client.return_value.request.assert_not_called()+ client.close()++def test_connections_without_control_plane_raises() -> None:with patch("sie_sdk.client.sync.httpx.Client"):client = SIEClient(GW, api_key=KEY)@@ -102,3 +157,32 @@ async def test_async_add_and_revoke() -> None:assert revoked["state"] == "revoked"assert client._delete.call_args.args[0] == f"{CP}/internal/orgs/acme/connections/wh"await client.close()+++async def test_invalid_schema_policy_fails_before_async_io() -> None:+ client = SIEAsyncClient(GW, api_key=KEY, control_plane_url=CP, org="acme")+ client._post = AsyncMock()+ with pytest.raises(ValueError, match="supplied together"):+ await client.connections.add(+ name="wh",+ type="postgres",+ secret="dsn", # noqa: S106+ source_schema="source_data",+ )+ client._post.assert_not_awaited()+ await client.close()+++async def test_invalid_connection_name_fails_before_async_io() -> None:+ client = SIEAsyncClient(GW, api_key=KEY, control_plane_url=CP, org="acme")+ client._post = AsyncMock()+ client._delete = AsyncMock()+ with pytest.raises(ValueError, match="connection name"):+ await client.connections.add(name="../other", type="postgres", secret="dsn") # noqa: S106+ with pytest.raises(ValueError, match="connection name"):+ await client.connections.revoke("../other")+ client._post.assert_not_awaited()+ client._delete.assert_not_awaited()+ await client.close()diff --git a/packages/sie_sdk/tests/client/test_jobs.py b/packages/sie_sdk/tests/client/test_jobs.pyindex 5edbcf78e..4ba441c0b 100644--- a/packages/sie_sdk/tests/client/test_jobs.py+++ b/packages/sie_sdk/tests/client/test_jobs.py@@ -63,6 +63,7 @@ def test_submit_inline_maps_items_and_posts_v1_jobs() -> None:body = mock_client.return_value.request.call_args.kwargs["json"]assert (method, url) == ("POST", "/v1/jobs")assert body == {"operation": "encode", "model": "BAAI/bge-m3", "items": [{"text": "a"}, {"text": "b"}]}+ assert "Idempotency-Key" not in mock_client.return_value.request.call_args.kwargs["headers"]client.close()@@ -74,12 +75,32 @@ def test_submit_connector_job_body() -> None:source="postgres://warehouse?query=x",model="BAAI/bge-m3",sink="s3://out/vecs",+ execution="plan",+ idempotency_key="plan-postgres-1",)- body = mock_client.return_value.request.call_args.kwargs["json"]+ call = mock_client.return_value.request.call_args+ body = call.kwargs["json"]assert body["src"] == "postgres://warehouse?query=x"assert body["connection"] == "warehouse"assert body["sink"] == "s3://out/vecs"assert body["sink_connection"] == "out"+ assert body["execution"] == "plan"+ assert [(key, value) for key, value in call.kwargs["headers"].items() if key.lower() == "idempotency-key"] == [+ ("Idempotency-Key", "plan-postgres-1")+ ]+ client.close()+++def test_submit_connector_requires_retry_stable_idempotency_key_before_io() -> None:+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ client = SIEClient(GW, api_key=KEY)+ with pytest.raises(ValueError, match="idempotency_key"):+ client.jobs.submit(+ source="postgres://warehouse?query=x",+ model="BAAI/bge-m3",+ execution="plan",+ )+ mock_client.return_value.request.assert_not_called()client.close()@@ -94,6 +115,8 @@ def test_submit_field_map_job_body() -> None:sink="upload://file-out",field_map={"id_field": "doc_id", "input_field": "text", "carry": ["source_url"], "input_type": "text"},output_field="embedding",+ execution="run",+ idempotency_key="run-upload-1",)body = mock_client.return_value.request.call_args.kwargs["json"]assert body["src"] == "upload://file-abc?format=csv"@@ -120,6 +143,8 @@ def test_submit_score_options_query_rides_the_wire() -> None:operation="score",sink="postgres://warehouse?table=scores",options={"query": "rank these documents"},+ execution="run",+ idempotency_key="run-score-1",)body = mock_client.return_value.request.call_args.kwargs["json"]assert body["operation"] == "score"@@ -139,6 +164,73 @@ def test_get_and_cancel_hit_expected_urls() -> None:client.close()+ ("job_id", "encoded_job_id"),+ [+ ("job-victim/cancel", "job-victim%2Fcancel"),+ ("job-victim?next=/cancel", "job-victim%3Fnext%3D%2Fcancel"),+ ("job-victim#cancel", "job-victim%23cancel"),+ ],+)+def test_sync_job_id_is_one_percent_encoded_path_segment(job_id: str, encoded_job_id: str) -> None:+ response = {"id": "job-victim", "state": "succeeded", "output": {"kind": "refs", "chunks": []}}+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.request = MagicMock(return_value=_resp(200, response))+ client = SIEClient(GW, api_key=KEY)++ client.jobs.get(job_id)+ assert mock_client.return_value.request.call_args.args == ("GET", f"/v1/jobs/{encoded_job_id}")+ client.jobs.cancel(job_id)+ assert mock_client.return_value.request.call_args.args == ("POST", f"/v1/jobs/{encoded_job_id}/cancel")+ client.jobs.execute(job_id, 3, "execute-plan-3")+ assert mock_client.return_value.request.call_args.args == ("POST", f"/v1/jobs/{encoded_job_id}/execute")+ client.jobs.repair(job_id, 3, 2, "repair-plan-3-attempt-2")+ assert mock_client.return_value.request.call_args.args == ("POST", f"/v1/jobs/{encoded_job_id}/repair")+ client.jobs.results(job_id)+ assert mock_client.return_value.request.call_args.args == ("GET", f"/v1/jobs/{encoded_job_id}")+ client.close()+++def test_execute_posts_exact_revision_and_one_idempotency_key() -> None:+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.request = MagicMock(return_value=_resp(200, {"id": "job-1", "state": "queued"}))+ client = SIEClient(GW, api_key=KEY)+ result = client.jobs.execute("job-1", 3, "execute-plan-3")+ call = mock_client.return_value.request.call_args+ assert call.args == ("POST", "/v1/jobs/job-1/execute")+ assert call.kwargs["json"] == {"plan_revision": 3}+ assert [(key, value) for key, value in call.kwargs["headers"].items() if key.lower() == "idempotency-key"] == [+ ("Idempotency-Key", "execute-plan-3")+ ]+ assert result["id"] == "job-1"+ client.close()+++def test_repair_posts_exact_revision_predecessor_and_one_idempotency_key() -> None:+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.request = MagicMock(return_value=_resp(202, {"id": "job-1", "state": "running"}))+ client = SIEClient(GW, api_key=KEY)+ result = client.jobs.repair("job-1", 3, 2, "repair-plan-3-attempt-2")+ call = mock_client.return_value.request.call_args+ assert call.args == ("POST", "/v1/jobs/job-1/repair")+ assert call.kwargs["json"] == {"plan_revision": 3, "recovery_attempt_ordinal": 2}+ assert [(key, value) for key, value in call.kwargs["headers"].items() if key.lower() == "idempotency-key"] == [+ ("Idempotency-Key", "repair-plan-3-attempt-2")+ ]+ assert result["id"] == "job-1"+ client.close()+++def test_wait_returns_stable_planned_phase_without_polling() -> None:+ planned = {"id": "job-plan-1", "state": "queued", "execution": "plan", "phase": "planned"}+ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.request = MagicMock(return_value=_resp(200, planned))+ client = SIEClient(GW, api_key=KEY)+ assert client.jobs.wait("job-plan-1", poll_s=0)["phase"] == "planned"+ mock_client.return_value.request.assert_called_once()+ client.close()++def test_list_returns_data_array() -> None:with patch("sie_sdk.client.sync.httpx.Client") as mock_client:mock_client.return_value.request = MagicMock(@@ -200,6 +292,18 @@ async def test_async_submit_serializes_json_body() -> None:call = client._post.call_argsassert call.args[0] == "/v1/jobs"assert json.loads(call.kwargs["data"]) == {"operation": "encode", "model": "m", "items": [{"text": "a"}]}+ assert "Idempotency-Key" not in call.kwargs["headers"]+ await client.close()+++async def test_async_wait_returns_stable_planned_phase_without_polling() -> None:+ client = SIEAsyncClient(GW, api_key=KEY)+ client._get = AsyncMock(+ return_value=_FakeAio(200, {"id": "job-plan-1", "state": "queued", "execution": "plan", "phase": "planned"})+ )+ assert (await client.jobs.wait("job-plan-1", poll_s=0))["phase"] == "planned"+ client._get.assert_awaited_once()await client.close()@@ -223,11 +327,29 @@ async def test_async_submit_field_map_body() -> None:sink="postgres://wh?table=doc_vectors",field_map={"id_field": "id", "input_field": "body", "carry": ["source_url"]},output_field="embedding",+ execution="plan",+ idempotency_key="async-plan-postgres-1",)body = json.loads(client._post.call_args.kwargs["data"])assert body["field_map"] == {"id_field": "id", "input_field": "body", "carry": ["source_url"]}assert body["output_field"] == "embedding"assert body["connection"] == "wh"+ assert body["execution"] == "plan"+ assert client._post.call_args.kwargs["headers"]["Idempotency-Key"] == "async-plan-postgres-1"+ await client.close()+++async def test_async_submit_connector_requires_retry_stable_idempotency_key_before_io() -> None:+ client = SIEAsyncClient(GW, api_key=KEY)+ client._post = AsyncMock()+ with pytest.raises(ValueError, match="idempotency_key"):+ await client.jobs.submit(+ source="postgres://wh?query=select id, body from docs",+ model="BAAI/bge-m3",+ execution="plan",+ )+ client._post.assert_not_awaited()await client.close()@@ -258,3 +380,61 @@ async def test_async_list_and_cancel() -> None:assert out["state"] == "cancelled"assert client._post.call_args.args[0] == "/v1/jobs/job-9/cancel"await client.close()+++ ("job_id", "encoded_job_id"),+ [+ ("job-victim/cancel", "job-victim%2Fcancel"),+ ("job-victim?next=/cancel", "job-victim%3Fnext%3D%2Fcancel"),+ ("job-victim#cancel", "job-victim%23cancel"),+ ],+)+async def test_async_job_id_is_one_percent_encoded_path_segment(job_id: str, encoded_job_id: str) -> None:+ response = {"id": "job-victim", "state": "succeeded", "output": {"kind": "refs", "chunks": []}}+ client = SIEAsyncClient(GW, api_key=KEY)+ client._get = AsyncMock(return_value=_FakeAio(200, response))+ client._post = AsyncMock(return_value=_FakeAio(200, response))++ await client.jobs.get(job_id)+ assert client._get.call_args.args[0] == f"/v1/jobs/{encoded_job_id}"+ await client.jobs.cancel(job_id)+ assert client._post.call_args.args[0] == f"/v1/jobs/{encoded_job_id}/cancel"+ await client.jobs.execute(job_id, 3, "execute-plan-3")+ assert client._post.call_args.args[0] == f"/v1/jobs/{encoded_job_id}/execute"+ await client.jobs.repair(job_id, 3, 2, "repair-plan-3-attempt-2")+ assert client._post.call_args.args[0] == f"/v1/jobs/{encoded_job_id}/repair"+ await client.jobs.results(job_id)+ assert client._get.call_args.args[0] == f"/v1/jobs/{encoded_job_id}"+ await client.close()+++async def test_async_execute_posts_exact_revision_and_one_idempotency_key() -> None:+ client = SIEAsyncClient(GW, api_key=KEY)+ client._post = AsyncMock(return_value=_FakeAio(200, {"id": "job-9", "state": "queued"}))+ result = await client.jobs.execute("job-9", 2, "async-execute-plan-2")+ call = client._post.call_args+ assert call.args[0] == "/v1/jobs/job-9/execute"+ assert json.loads(call.kwargs["data"]) == {"plan_revision": 2}+ assert [(key, value) for key, value in call.kwargs["headers"].items() if key.lower() == "idempotency-key"] == [+ ("Idempotency-Key", "async-execute-plan-2")+ ]+ assert result["id"] == "job-9"+ await client.close()+++async def test_async_repair_posts_exact_revision_predecessor_and_one_idempotency_key() -> None:+ client = SIEAsyncClient(GW, api_key=KEY)+ client._post = AsyncMock(return_value=_FakeAio(202, {"id": "job-9", "state": "running"}))+ result = await client.jobs.repair("job-9", 2, 1, "async-repair-plan-2-attempt-1")+ call = client._post.call_args+ assert call.args[0] == "/v1/jobs/job-9/repair"+ assert json.loads(call.kwargs["data"]) == {"plan_revision": 2, "recovery_attempt_ordinal": 1}+ assert [(key, value) for key, value in call.kwargs["headers"].items() if key.lower() == "idempotency-key"] == [+ ("Idempotency-Key", "async-repair-plan-2-attempt-1")+ ]+ assert result["id"] == "job-9"+ await client.close()diff --git a/packages/sie_sdk/tests/test_jobs_body.py b/packages/sie_sdk/tests/test_jobs_body.pyindex 46b21869e..4f06d2bbd 100644--- a/packages/sie_sdk/tests/test_jobs_body.py+++ b/packages/sie_sdk/tests/test_jobs_body.py@@ -6,7 +6,7 @@ import msgpackimport numpy as npimport pytestfrom sie_sdk import build_job_body, connection_name-from sie_sdk.jobs import decode_chunk_bytes, decode_result_item, job_chunks+from sie_sdk.jobs import decode_chunk_bytes, decode_result_item, job_chunks, require_connector_idempotency_keydef test_inline_list_source_becomes_items() -> None:@@ -26,20 +26,42 @@ def test_connector_uri_source_derives_connection() -> None:operation="encode",model="m",sink="postgres://warehouse?table=vecs",+ execution="plan",)assert body["src"] == "postgres://warehouse?query=SELECT+1"assert body["connection"] == "warehouse"assert body["sink"] == "postgres://warehouse?table=vecs"+ assert body["execution"] == "plan"# Same-store sink reuses the source connection — no redundant sink_connection.assert "sink_connection" not in body+def test_connector_requires_explicit_execution_and_inline_rejects_it() -> None:+ with pytest.raises(ValueError, match="require execution"):+ build_job_body(+ source="postgres://warehouse?query=SELECT+1",+ operation="encode",+ model="m",+ sink="postgres://warehouse?table=vecs",+ )+ with pytest.raises(ValueError, match="only to connector"):+ build_job_body(source=["a"], operation="encode", model="m", execution="plan")++[email protected]("key", [None, "", "line\nbreak", "café", "x" * 257])+def test_connector_idempotency_key_matches_gateway_header_contract(key: str | None) -> None:+ with pytest.raises(ValueError, match="printable ASCII"):+ require_connector_idempotency_key(key)+ assert require_connector_idempotency_key("logical-retry-1") == "logical-retry-1"++def test_distinct_sink_threads_sink_connection() -> None:body = build_job_body(source="postgres://wh?query=x",operation="encode",model="m",sink="s3://out-bucket/vecs",+ execution="run",)assert body["sink_connection"] == "out-bucket"@@ -52,13 +74,16 @@ def test_explicit_connection_overrides_derived() -> None:sink="postgres://wh?table=t",connection="prod-wh",sink_connection="prod-wh",+ execution="run",)assert body["connection"] == "prod-wh"assert body["sink_connection"] == "prod-wh"def test_inplace_sink_sentinel() -> None:- body = build_job_body(source="postgres://wh?query=x", operation="encode", model="m", sink="inplace")+ body = build_job_body(+ source="postgres://wh?query=x", operation="encode", model="m", sink="inplace", execution="run"+ )assert body["sink"] == "inplace"@@ -72,9 +97,6 @@ def test_return_sink_is_omitted() -> None:[("now", {}),(None, {}),- ("schedule:*/5 * * * *", {"when": "schedule", "schedule": "*/5 * * * *"}),- ("*/5 * * * *", {"when": "schedule", "schedule": "*/5 * * * *"}),- ("watch:s3://in", {"when": "watch", "watch": "s3://in"}),],)def test_when_trigger_mapping(when: str | None, expected: dict[str, str]) -> None:@@ -85,6 +107,12 @@ def test_when_trigger_mapping(when: str | None, expected: dict[str, str]) -> Nonassert "when" not in body[email protected]("when", ["schedule:*/5 * * * *", "*/5 * * * *", "watch:s3://in"])+def test_unavailable_when_trigger_is_rejected(when: str) -> None:+ with pytest.raises(ValueError, match="not available"):+ build_job_body(source=["a"], operation="encode", model="m", when=when)++def test_output_types_ride_only_when_set() -> None:assert build_job_body(source=["a"], operation="encode", model="m", output_types=["dense"])["output_types"] == ["dense"@@ -100,6 +128,7 @@ def test_options_forward_op_inputs_as_is() -> None:operation="score",model="BAAI/bge-m3",sink="postgres://wh?table=scores",+ execution="run",options={"query": "rank these documents"},)assert score["options"] == {"query": "rank these documents"}@@ -119,6 +148,7 @@ def test_options_forward_op_inputs_as_is() -> None:operation="generate",model="Qwen/Qwen3-4B-Instruct-2507",sink="postgres://wh?table=docs&mode=inplace&column=summary",+ execution="run",options={"max_new_tokens": 64, "temperature": 0.0},)assert generate["options"] == {"max_new_tokens": 64, "temperature": 0.0}@@ -152,6 +182,7 @@ def test_field_map_and_output_field_ride_connector_jobs() -> None:field_map={"id_field": "id", "input_field": "body", "carry": ["source_url"], "input_type": "text"},sink="postgres://wh?table=doc_vectors",output_field="embedding",+ execution="plan",)assert body["field_map"] == {"id_field": "id",@@ -169,12 +200,18 @@ def test_field_map_omitted_keys_do_not_ride() -> None:model="m",sink="postgres://wh?table=t",field_map={"id_field": "id"},+ execution="plan",)assert body["field_map"] == {"id_field": "id"}assert "output_field" not in body# An all-empty field_map rides nothing (additive-only wire).body = build_job_body(- source="postgres://wh?query=x", operation="encode", model="m", sink="postgres://wh?table=t", field_map={}+ source="postgres://wh?query=x",+ operation="encode",+ model="m",+ sink="postgres://wh?table=t",+ field_map={},+ execution="plan",)assert "field_map" not in body@@ -195,6 +232,7 @@ def test_bad_field_map_raises(field_map: dict, match: str) -> None:model="m",sink="postgres://wh?table=t",field_map=field_map,+ execution="plan",)@@ -205,6 +243,20 @@ def test_field_map_on_inline_items_raises() -> None:build_job_body(source=["a"], operation="encode", model="m", output_field="embedding")+ "connector_fields",+ [+ {"sink": "inplace"},+ {"sink": "postgres://wh?table=vecs"},+ {"sink_connection": "wh"},+ {"connection": "wh"},+ ],+)+def test_connector_fields_on_inline_items_raise(connector_fields: dict[str, str]) -> None:+ with pytest.raises(ValueError, match="connector-src"):+ build_job_body(source=["a"], operation="encode", model="m", **connector_fields)++# ---- §4.5.4 upload:// (internal scheme — no connection derived) ----------------@@ -215,6 +267,7 @@ def test_upload_source_derives_no_connection() -> None:model="m",sink="upload://file-out",field_map={"id_field": "doc_id", "input_field": "text", "input_type": "text"},+ execution="run",)assert body["src"] == "upload://file-abc?format=csv"assert body["sink"] == "upload://file-out"@@ -222,6 +275,17 @@ def test_upload_source_derives_no_connection() -> None:assert "sink_connection" not in body+def test_upload_connector_is_run_only() -> None:+ with pytest.raises(ValueError, match="run-only"):+ build_job_body(+ source="upload://file-abc",+ operation="encode",+ model="m",+ sink="upload://file-out",+ execution="plan",+ )++def test_upload_source_to_external_sink_threads_sink_connection() -> None:body = build_job_body(source="upload://file-abc",@@ -229,6 +293,7 @@ def test_upload_source_to_external_sink_threads_sink_connection() -> None:model="m",sink="postgres://wh?table=doc_vectors",sink_connection="wh",+ execution="run",)assert "connection" not in bodyassert body["sink_connection"] == "wh"@@ -251,6 +316,43 @@ def test_connection_name(uri: str, expected: str) -> None:assert connection_name(uri) == expected+ "invalid_name",+ [+ "../other",+ "warehouse/name",+ r"warehouse\name",+ "warehouse%2fname",+ "warehouse\n",+ "warehouse\r",+ "warehouse\u2028",+ "_warehouse",+ "café",+ "a" * 129,+ ],+)+def test_connector_connection_names_are_canonical(invalid_name: str) -> None:+ if invalid_name != "warehouse/name":+ with pytest.raises(ValueError, match="connection name"):+ connection_name(f"postgres://{invalid_name}?query=x")+ with pytest.raises(ValueError, match="connection name"):+ build_job_body(+ source="postgres://warehouse?query=x",+ operation="encode",+ model="m",+ sink="postgres://warehouse?table=out",+ connection=invalid_name,+ )+ with pytest.raises(ValueError, match="connection name"):+ build_job_body(+ source="postgres://warehouse?query=x",+ operation="encode",+ model="m",+ sink="postgres://warehouse?table=out",+ sink_connection=invalid_name,+ )++def _chunk_bytes(n: int, dims: int) -> bytes:items = [{diff --git a/packages/sie_server/Dockerfile.cpu b/packages/sie_server/Dockerfile.cpuindex 0bddc0725..7325f478b 100644--- a/packages/sie_server/Dockerfile.cpu+++ b/packages/sie_server/Dockerfile.cpu@@ -108,7 +108,7 @@ RUN echo "import sys; sys.path.insert(0, '/app/bundle-libs')" \# .venv cleanup + stdlib trim — runs here so /app/.venv reaches its final# form BEFORE bundle divergence. Largest wins: torch/include, *.a static# libs, stripping shared objects. Keep bytecode (cold-start matters more-# than size).+# than size) and wheel RECORD metadata used by native-library loaders.RUN set -eux; \cd /app/.venv/lib/python3.12/site-packages; \find . -type d -name '__pycache__' -prune -exec rm -rf {} +; \@@ -116,7 +116,6 @@ RUN set -eux; \find . -type d -name 'tests' -prune -exec rm -rf {} +; \rm -rf torch/test torch/utils/tensorboard torch/utils/bottleneck 2>/dev/null || true; \find torch -type f -name '*.a' -delete 2>/dev/null || true; \- find . -type f -name 'RECORD' -path '*dist-info*' -delete; \rm -rf /app/.venv/share/jupyter 2>/dev/null || true; \rm -rf /usr/local/lib/python3.12/test /usr/local/lib/python3.12/idlelib 2>/dev/null || true; \find /app/.venv -exec touch -h -d @0 {} + 2>/dev/null || true@@ -151,7 +150,8 @@ RUN --mount=type=cache,target=/root/.cache/pip \-r /tmp/bundle-requirements.txt; \fi-# bundle-libs cleanup (symmetric to the .venv cleanup in base).+# bundle-libs cleanup (symmetric to the .venv cleanup in base). Preserve+# dist-info RECORD files for runtime native-library discovery.RUN set -eux; \if [ -d /app/bundle-libs ]; then \cd /app/bundle-libs; \@@ -160,7 +160,6 @@ RUN set -eux; \find . -type d -name 'tests' -prune -exec rm -rf {} +; \rm -rf torch/test torch/utils/tensorboard torch/utils/bottleneck 2>/dev/null || true; \find torch -type f -name '*.a' -delete 2>/dev/null || true; \- find . -type f -name 'RECORD' -path '*dist-info*' -delete; \fi; \find /app/bundle-libs -exec touch -h -d @0 {} + 2>/dev/null || truediff --git a/packages/sie_server/Dockerfile.cuda12 b/packages/sie_server/Dockerfile.cuda12index 0769cbf36..01f17b490 100644--- a/packages/sie_server/Dockerfile.cuda12+++ b/packages/sie_server/Dockerfile.cuda12@@ -121,7 +121,9 @@ RUN echo "import sys; sys.path.insert(0, '/app/bundle-libs')" \# Conservative venv cleanup — only things known to be runtime-safe. Keep# torch/include (triton JIT compiles against torch C++ headers for# sglang/flash-attn custom ops) and keep gcc/libc6-dev at runtime.-# Main wins: byte-compiled caches, *.a static libs, tests/, RECORD metadata.+# Main wins: byte-compiled caches, *.a static libs, and tests/. Keep wheel+# RECORD metadata: native loaders such as tvm_ffi use it to locate packaged+# shared libraries (including xgrammar's libxgrammar_bindings.so).# Runs here (not in builder) so /app/.venv reaches its final form BEFORE# bundle divergence, making the runtime COPY cache-hit across bundles.RUN set -eux; \@@ -131,7 +133,6 @@ RUN set -eux; \find . -type d -name 'tests' -prune -exec rm -rf {} +; \rm -rf torch/test torch/utils/tensorboard torch/utils/bottleneck 2>/dev/null || true; \find torch -type f -name '*.a' -delete 2>/dev/null || true; \- find . -type f -name 'RECORD' -path '*dist-info*' -delete; \# All nvidia-*-cu12 packages are kept — torch._C DT_NEEDED links libcufile,# libnccl, and similar; removing any breaks `import torch`.find nvidia -type f -name '*.a' -delete 2>/dev/null || true; \@@ -187,7 +188,8 @@ RUN --mount=type=cache,target=/root/.cache/pip \# bundle-libs cleanup (symmetric to the .venv cleanup in base). The .venv# tree is already final in the base stage; only the per-bundle tree needs-# cleanup here.+# cleanup here. Preserve dist-info RECORD files for runtime native-library+# discovery.RUN set -eux; \if [ -d /app/bundle-libs ]; then \cd /app/bundle-libs; \@@ -196,7 +198,6 @@ RUN set -eux; \find . -type d -name 'tests' -prune -exec rm -rf {} +; \rm -rf torch/test torch/utils/tensorboard torch/utils/bottleneck 2>/dev/null || true; \find torch -type f -name '*.a' -delete 2>/dev/null || true; \- find . -type f -name 'RECORD' -path '*dist-info*' -delete; \find nvidia -type f -name '*.a' -delete 2>/dev/null || true; \fi; \# Normalize mtimes so rebuilds of the same bundle produce identical layer bytes.diff --git a/packages/sie_server/Dockerfile.cuda13 b/packages/sie_server/Dockerfile.cuda13index 3b1844985..b359aff25 100644--- a/packages/sie_server/Dockerfile.cuda13+++ b/packages/sie_server/Dockerfile.cuda13@@ -127,7 +127,8 @@ RUN echo "import sys; sys.path.insert(0, '/app/bundle-libs')" \# Conservative venv cleanup — only runtime-safe removals. Keep torch/include# (triton JIT compiles against torch C++ headers for sglang/flashinfer custom-# ops) and gcc/libc6-dev at runtime.+# ops), gcc/libc6-dev, and wheel RECORD metadata. Native loaders such as+# tvm_ffi use RECORD to locate packaged shared libraries.RUN set -eux; \cd /app/.venv/lib/python3.12/site-packages; \find . -type d -name '__pycache__' -prune -exec rm -rf {} +; \@@ -135,7 +136,6 @@ RUN set -eux; \find . -type d -name 'tests' -prune -exec rm -rf {} +; \rm -rf torch/test torch/utils/tensorboard torch/utils/bottleneck 2>/dev/null || true; \find torch -type f -name '*.a' -delete 2>/dev/null || true; \- find . -type f -name 'RECORD' -path '*dist-info*' -delete; \find nvidia -type f -name '*.a' -delete 2>/dev/null || true; \rm -rf /app/.venv/share/jupyter 2>/dev/null || true; \find /app/.venv -exec touch -h -d @0 {} + 2>/dev/null || true@@ -193,7 +193,8 @@ RUN --mount=type=cache,target=/root/.cache/pip \-r /tmp/bundle-requirements.txt ; \fi-# bundle-libs cleanup (symmetric to the .venv cleanup in base).+# bundle-libs cleanup (symmetric to the .venv cleanup in base). Preserve+# dist-info RECORD files so tvm_ffi can find xgrammar's native binding.RUN set -eux; \if [ -d /app/bundle-libs ]; then \cd /app/bundle-libs; \@@ -202,7 +203,6 @@ RUN set -eux; \find . -type d -name 'tests' -prune -exec rm -rf {} +; \rm -rf torch/test torch/utils/tensorboard torch/utils/bottleneck 2>/dev/null || true; \find torch -type f -name '*.a' -delete 2>/dev/null || true; \- find . -type f -name 'RECORD' -path '*dist-info*' -delete; \find nvidia -type f -name '*.a' -delete 2>/dev/null || true; \fi; \find /app/bundle-libs -exec touch -h -d @0 {} + 2>/dev/null || truediff --git a/packages/sie_server/bundles/default.yaml b/packages/sie_server/bundles/default.yamlindex cdfc5c5da..02701943f 100644--- a/packages/sie_server/bundles/default.yaml+++ b/packages/sie_server/bundles/default.yaml@@ -77,8 +77,10 @@ deps:timm: '>=0.9.0,<1.0'# siglip (Marqo/marqo-ecommerce-embeddings-B uses open_clip native loader)open-clip-torch: '>=2.24'- # docling — composite-document parser (PDF/DOCX/HTML)- docling: '>=2,<3'+ # docling — composite-document parser (PDF/DOCX/HTML).+ # Pinned to the compatibility pair of the immutable artifact revision in+ # models/docling.yaml; see packages/sie_server/pyproject.toml (#2872).+ docling: '>=2.99,<2.100'# Flash Attention 2 — CUDA only, prebuilt wheelflash-attn:url: https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.7.11/flash_attn-2.7.4+cu129torch2.9-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whldiff --git a/packages/sie_server/bundles/gemma.yaml b/packages/sie_server/bundles/gemma.yamlindex a2be23bc5..80952b0c7 100644--- a/packages/sie_server/bundles/gemma.yaml+++ b/packages/sie_server/bundles/gemma.yaml@@ -8,7 +8,8 @@ default: false# matrix (.github/release-matrix.json). Bundles without this field default to# ``cuda12``.platform: cuda13-# Dedicated worker image for Google Gemma 4 (see issue #1415).+# CUDA 13 SGLang worker image, introduced for Google Gemma 4 (see issue #1415)+# and reused by profiles that require newer generic engine features.## VALIDATED on a Modal L4 (driver 580.95.05 / CUDA 13.0) on 2026-06-18:# google/gemma-4-E2B-it serves end-to-end on sglang 0.5.13 — the gemma4@@ -16,8 +17,10 @@ platform: cuda13# and /v1/chat/completions returns 200 (with --disable-cuda-graph, which the# model configs set via adapter_options.loadtime.disable_cuda_graph).#-# Kept SEPARATE from the `sglang` bundle so the Qwen3.x stack there stays on-# its sglang 0.5.10.post1 / torch 2.9.1 toolchain, untouched.+# Kept SEPARATE from the `sglang` bundle so its Qwen3.x default/non-thinking+# profiles stay on sglang 0.5.10.post1 / torch 2.9.1. Qwen3.6-27B reasoning+# variants opt into this image through the generic strict-thinking adapter;+# the rest of the Qwen catalog remains untouched.## VERSION NOTE: Gemma 4 first shipped in sglang 0.5.11, but 0.5.11's bundled# JIT kernel (jit_kernel/csrc/elementwise/activation.cuh) fails to compile@@ -31,12 +34,13 @@ platform: cuda13# ships torch 2.9.1, so the gemma image carries two torches (~+3 GB); slimming# torch out of sie-server core would remove that (tracked follow-up in #1415).#-# The distinct adapter module (a thin SGLangGenerationAdapter subclass) scopes-# routing here: bundle compatibility keys on the adapter module path, so Gemma-# models reference `...sglang.gemma` and only this bundle declares it — Qwen3.x-# keep routing to `sglang`.+# Distinct thin adapter modules scope routing here because bundle compatibility+# keys on module paths. Gemma models use `...sglang.gemma`; reasoning profiles+# that need the newer token filter use `...sglang.cuda13`. Qwen routes without+# that explicit adapter remain on the shared `sglang` bundle.adapters:- sie_server.adapters.sglang.gemma+- sie_server.adapters.sglang.cuda13deps:# sglang 0.5.13 = the validated Gemma 4 engine (0.5.11 has the activation.cuh# JIT bug above). Verified transitive resolution on the Modal L4 cu130 image:@@ -57,3 +61,8 @@ deps:# bundle's rationale). NOTE: 0.5.13 uses xgrammar 0.2.x, not the 0.1.32 the# sglang bundle pins for the older engine.xgrammar: '==0.2.1'+ # XGrammar 0.2.1 imports ``tvm_ffi`` while its package metadata leaves the+ # dependency open at >=0.1.9. SGLang 0.5.13 pins apache-tvm-ffi==0.1.9+ # exactly, so declare the same version explicitly: this keeps the import in+ # the image and lets the bundle resolve as one compatible dependency set.+ apache-tvm-ffi: '==0.1.9'diff --git a/packages/sie_server/models/Qwen__Qwen3-0.6B.yaml b/packages/sie_server/models/Qwen__Qwen3-0.6B.yamlindex 5e6d08341..93fc0b994 100644--- a/packages/sie_server/models/Qwen__Qwen3-0.6B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3-0.6B.yaml@@ -31,6 +31,10 @@ tasks:grammar: []streaming: truetools: false+ # Qwen3 enables reasoning by default. Keep the bare model deterministic+ # and direct; the explicit ``:thinking`` profile below opts back in.+ chat_template_kwargs:+ enable_thinking: falsemax_sequence_length: 4096# KV-cache memory math (Qwen3-0.6B, bf16):# layers=28, kv_heads=8, head_dim=128, bytes_per_elem=2@@ -117,3 +121,31 @@ profiles:default_sampling:temperature: 0.0top_p: 1.0+ # Explicit reasoning mode. Qwen3-0.6B supports the chat-template thinking+ # switch; use the model-card sampling recipe instead of inheriting the+ # non-thinking profile's greedy decode.+ thinking:+ extends: default+ chat_template_kwargs:+ enable_thinking: true+ adapter_options:+ runtime:+ first_chunk_timeout_s: 30+ inter_chunk_timeout_s: 10+ overall_timeout_s: 300+ default_sampling:+ temperature: 0.6+ top_p: 0.95+ top_k: 20+ # The checkpoint's native window is 32,768 tokens. Keep the 4K bare/L4+ # shape for fast smoke traffic and expose the full window on the dedicated+ # A100 launch shape, whose checked-in KV budget covers one 32K admission.+ long-context:+ extends: a100-40gb+ adapter_options:+ loadtime:+ max_seq_length: 32768+ mem_fraction_static: 0.85+ served_model_name: Qwen/Qwen3-0.6B+ disable_cuda_graph: true+ attention_backend: tritondiff --git a/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml b/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yamlindex be1738e47..5f11e3fe8 100644--- a/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml+++ b/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml@@ -48,8 +48,8 @@ tasks:# to ``grammar`` above (behind an xgrammar profile + via-SIE EBNF smoke)# to enable grammar-constrained SQL. Informational (not request-gated).sql: true- # Forwarded verbatim to ``tokenizer.apply_chat_template(**kwargs)`` when- # the worker renders an OpenAI-shaped ``messages`` request.+ # Forwarded through the bounded template-kwargs contract to+ # ``tokenizer.apply_chat_template(**kwargs)`` for OpenAI-shaped messages.# Qwen3's chat template emits a ``<think>``/``</think>`` reasoning block# unless this flag suppresses it.chat_template_kwargs:diff --git a/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml b/packages/sie_server/models/Qwen__Qwen3.5-4B.yamlindex 76be4eb30..b9d4890c1 100644--- a/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml@@ -14,9 +14,9 @@ inputs:tasks:generate:# Native context length is 262,144 tokens (YaRN extends to ~1M).- # Keep the public request context at 8192 for every profile. The larger- # A100/H100 capacity measurements below size batching and admission; they- # are not a claim that a longer request context has been release-gated.+ # Keep the bare request context at 8192. The explicit ``:long-context``+ # profile below exposes the already-measured 32K A100 launch shape without+ # widening latency/capacity expectations for every caller.context_length: 8192max_output_tokens: 4096# Route grammar-constrained requests (response_format / grammar) to the@@ -151,6 +151,8 @@ profiles:# also sets the SGLANG_ENABLE_SPEC_V2=1 env var when# speculative.enabled — both are required as a pair.extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'- "--mamba-scheduler-strategy"- "extra_buffer"runtime:@@ -171,6 +173,53 @@ profiles:# those results remain reproducible while production uses the bare model id.a100-40gb:extends: default+ # Explicit reasoning mode. The tokenizer switch changes output semantics,+ # so it is a named profile rather than the bare model default. Thinking uses+ # Qwen's recommended sampling recipe; the launch shape remains the measured+ # A100 default.+ thinking:+ extends: default+ chat_template_kwargs:+ enable_thinking: true+ adapter_options:+ runtime:+ first_chunk_timeout_s: 60+ inter_chunk_timeout_s: 15+ overall_timeout_s: 300+ default_sampling:+ temperature: 1.0+ top_p: 0.95+ top_k: 20+ presence_penalty: 1.5+ stop_tokens:+ - "<|im_end|>"+ # The checkpoint is native to 262K and the checked-in A100 calibration+ # already boots SGLang at 32K. Expose that conservative measured window as+ # an opt-in variant while the bare model remains 8K.+ long-context:+ extends: default+ adapter_options:+ loadtime:+ max_seq_length: 32768+ mlx_repo: mlx-community/Qwen3.5-4B-4bit+ mem_fraction_static: 0.85+ served_model_name: Qwen/Qwen3.5-4B+ disable_cuda_graph: true+ attention_backend: triton+ grammar_backend: outlines+ reasoning_parser: qwen3+ tool_call_parser: qwen3_coder+ speculative:+ enabled: true+ algorithm: nextn+ num_steps: 3+ eagle_topk: 1+ num_draft_tokens: 4+ extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'+ - "--mamba-scheduler-strategy"+ - "extra_buffer"# L4 is severely constrained for Qwen3.5-4B + NEXTN — fits only ~3# concurrent requests, context cap ≈ 8192. Use this explicit profile for# smoke / c=1 only; it is not the production default.@@ -198,6 +247,8 @@ profiles:eagle_topk: 1num_draft_tokens: 4extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'- "--mamba-scheduler-strategy"- "extra_buffer"- "--disable-overlap-schedule"@@ -235,6 +286,8 @@ profiles:eagle_topk: 1num_draft_tokens: 4extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'- "--mamba-scheduler-strategy"- "extra_buffer"runtime:@@ -276,6 +329,8 @@ profiles:# identical so a config diff between them shows only the# speculative block (the intent of the ablation).extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'- "--mamba-scheduler-strategy"- "extra_buffer"runtime:diff --git a/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml b/packages/sie_server/models/Qwen__Qwen3.6-27B.yamlindex 3d1d306f2..b057feeee 100644--- a/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml@@ -16,20 +16,18 @@ tasks:generate:# Native context length is 262,144 tokens (YaRN extends to ~1M).# Keep the base model contract at the 8K launch window. The managed- # tester rollout exposes the 32K surface only through the- # ``:rtx-pro-6000`` variant below, whose profile-level ``max_seq_length``- # is promoted into the generated variant config by the loader.+ # tester rollout exposes the 32K surface through the+ # ``:rtx-pro-6000`` shape and its semantic ``:long-context`` alias below;+ # profile-level ``max_seq_length`` is promoted into each generated variant+ # config by the loader.context_length: 8192max_output_tokens: 4096- # NEXTN cannot safely run Outlines grammar decoding. The gateway rewrites+ # NEXTN cannot safely run constrained decoding. The gateway rewrites# grammar-constrained requests to this non-speculative sibling, which is# deployed on the same H100 machine class as the default lane.grammar_profile: no-speccapabilities:- # Same constraint as Qwen3.5-4B: SGLang's outlines_backend does- # not implement ebnf. xgrammar smoke would pass all three; flip- # ``grammar_backend: xgrammar`` and re-add ``"ebnf"`` here if a- # consumer needs it.+ # EBNF remains unadvertised until it has model-specific runtime evidence.grammar: ["json_schema", "regex"]streaming: truetools: true@@ -53,9 +51,8 @@ tasks:chat_template_kwargs:enable_thinking: falseprewarm_grammars:- # Bare pattern, NOT anchored — Outlines regexes are implicitly- # anchored and its FSM engine rejects ``^``/``$``. See the- # Qwen3.5-4B model card for the full back-story.+ # Keep the prewarm pattern bare so it has the same portable semantics+ # across the worker preflight and SGLang's xgrammar runtime.- name: yes_nokind: regexvalue: "(yes|no)"@@ -102,7 +99,7 @@ profiles:served_model_name: Qwen/Qwen3.6-27Bdisable_cuda_graph: trueattention_backend: triton- grammar_backend: outlines+ grammar_backend: xgrammarreasoning_parser: qwen3tool_call_parser: qwen3_coder# Preserve the smaller 2/2 H100 draft shape for a future validated@@ -118,6 +115,8 @@ profiles:# Keep it paired with ``--disable-overlap-schedule`` for all NEXTN# launch profiles.extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'- "--mamba-scheduler-strategy"- "extra_buffer"- "--disable-overlap-schedule"@@ -147,7 +146,7 @@ profiles:served_model_name: Qwen/Qwen3.6-27Bdisable_cuda_graph: trueattention_backend: triton- grammar_backend: outlines+ grammar_backend: xgrammarreasoning_parser: qwen3tool_call_parser: qwen3_coderspeculative:@@ -160,6 +159,8 @@ profiles:# NEXTN + mamba-scheduler ``extra_buffer`` on the hybrid Gated-# DeltaNet architecture (same constraint as Qwen3.5-4B).extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'- "--mamba-scheduler-strategy"- "extra_buffer"- "--disable-overlap-schedule"@@ -194,12 +195,14 @@ profiles:served_model_name: Qwen/Qwen3.6-27Bdisable_cuda_graph: trueattention_backend: triton- grammar_backend: outlines+ grammar_backend: xgrammarreasoning_parser: qwen3tool_call_parser: qwen3_coderspeculative:enabled: falseextra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'- "--quantization"- "fp8"# RTX PRO 6000 (96 GB GDDR7, Blackwell Server Edition, sm_120) profile.@@ -252,7 +255,7 @@ profiles:# the boot smoke verifies; switch to flashinfer here if triton lacks# sm_120 coverage in the pinned SGLang build.attention_backend: triton- grammar_backend: outlines+ grammar_backend: xgrammarreasoning_parser: qwen3tool_call_parser: qwen3_coder# Model-card NEXTN 3/4 — restored here (vs ``default``'s conservative@@ -269,6 +272,8 @@ profiles:# companions on the hybrid Gated-DeltaNet architecture. List is the# FULL set (production full-replaces ``extra_launch_args``, not merge).extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'- "--quantization"- "fp8"- "--mamba-scheduler-strategy"@@ -297,6 +302,122 @@ profiles:min_new_tokens: 10stop_tokens:- "<|im_end|>"+ # Explicit native-window candidate for one H100-80GB admission. Keep this+ # standalone (rather than extending ``h100-fp8``) so the matching+ # ``long-context-thinking`` child can inherit it without forbidden profile+ # chaining. Online FP8 limits weight memory; KV remains BF16 until measured+ # H100 evidence proves a lower-precision cache is necessary and faithful.+ long-context:+ # Qwen's official non-thinking serving recipe uses max_tokens=32768.+ # Keep the bare 8K profile at 4096 while exposing that decode ceiling only+ # on variants whose total context can accommodate it.+ max_output_tokens: 32768+ max_batch_tokens: 262144+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter+ kv_budget_tokens: 262144+ adapter_options:+ loadtime:+ max_seq_length: 262144+ mem_fraction_static: 0.95+ served_model_name: Qwen/Qwen3.6-27B+ disable_cuda_graph: true+ attention_backend: triton+ grammar_backend: xgrammar+ reasoning_parser: qwen3+ tool_call_parser: qwen3_coder+ speculative:+ enabled: false+ extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'+ - "--quantization"+ - "fp8"+ - "--mamba-scheduler-strategy"+ - "extra_buffer"+ - "--disable-overlap-schedule"+ runtime:+ first_chunk_timeout_s: 900+ inter_chunk_timeout_s: 30+ overall_timeout_s: 1800+ default_sampling:+ temperature: 0.7+ top_p: 0.8+ top_k: 20+ presence_penalty: 1.5+ min_new_tokens: 10+ stop_tokens:+ - "<|im_end|>"+ # Same measured 256K launch/admission envelope with Qwen thinking enabled.+ long-context-thinking:+ extends: long-context+ # Official Qwen3.6 thinking examples use max_tokens=81920.+ max_output_tokens: 81920+ # SGLang 0.5.13's strict-thinking token filter prevents a premature EOS+ # from leaving the whole answer inside the private reasoning channel.+ adapter_path: sie_server.adapters.sglang.cuda13:SGLangStrictThinkingAdapter+ chat_template_kwargs:+ enable_thinking: true+ adapter_options:+ runtime:+ first_chunk_timeout_s: 900+ inter_chunk_timeout_s: 30+ overall_timeout_s: 1800+ default_sampling:+ temperature: 1.0+ top_p: 0.95+ top_k: 20+ presence_penalty: 0.0+ min_new_tokens: 10+ stop_tokens:+ - "<|im_end|>"+ # Hardware-explicit aliases for the exact H100-80GB native-window shape.+ # Machine placement remains a separate gateway decision; these names make+ # the validated context/GPU pairing discoverable to callers.+ h100-256k:+ extends: long-context+ h100-256k-thinking:+ extends: long-context+ max_output_tokens: 81920+ adapter_path: sie_server.adapters.sglang.cuda13:SGLangStrictThinkingAdapter+ chat_template_kwargs:+ enable_thinking: true+ adapter_options:+ runtime:+ first_chunk_timeout_s: 900+ inter_chunk_timeout_s: 30+ overall_timeout_s: 1800+ default_sampling:+ temperature: 1.0+ top_p: 0.95+ top_k: 20+ presence_penalty: 0.0+ min_new_tokens: 10+ stop_tokens:+ - "<|im_end|>"+ # Explicit reasoning mode uses the validated native-window H100 lane. Qwen's+ # model card recommends at least 128K context for thinking; keeping this alias+ # on the 8K base lane would expose a mode that routinely truncates before its+ # private thought closes. The bare model remains non-thinking and answer-only.+ thinking:+ extends: long-context+ max_output_tokens: 81920+ adapter_path: sie_server.adapters.sglang.cuda13:SGLangStrictThinkingAdapter+ chat_template_kwargs:+ enable_thinking: true+ adapter_options:+ runtime:+ first_chunk_timeout_s: 900+ inter_chunk_timeout_s: 30+ overall_timeout_s: 1800+ default_sampling:+ temperature: 1.0+ top_p: 0.95+ top_k: 20+ presence_penalty: 0.0+ min_new_tokens: 10+ stop_tokens:+ - "<|im_end|>"# Throughput profile (H100-80GB) — the flagship's batch story. The# ``default`` NEXTN-spec shape is latency-optimized single-stream and# throughput-FLAT (~44 tok/s aggregate c=1→32, effective batch ≈1 —@@ -318,7 +439,7 @@ profiles:# 0.90 leaves headroom on top of the ~54 GB BF16 weights.# * ``--cuda-graph-max-bs 32``: pin graph coverage through the measured# c=32 operating point so deep decode batches stay on graphs.- # * triton attention + outlines grammar kept for Qwen3.x family parity.+ # * triton attention + xgrammar structured decoding.## UX story: ``Qwen/Qwen3.6-27B`` (default, latency / single-stream) ·# ``:batch`` (this profile, throughput) · ``:thinking`` (reasoning).@@ -333,12 +454,14 @@ profiles:mem_fraction_static: 0.90served_model_name: Qwen/Qwen3.6-27Battention_backend: triton- grammar_backend: outlines+ grammar_backend: xgrammarreasoning_parser: qwen3tool_call_parser: qwen3_coderspeculative:enabled: falseextra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'- "--cuda-graph-max-bs"- "32"runtime:@@ -369,12 +492,14 @@ profiles:served_model_name: Qwen/Qwen3.6-27Bdisable_cuda_graph: trueattention_backend: triton- grammar_backend: outlines+ grammar_backend: xgrammarreasoning_parser: qwen3tool_call_parser: qwen3_coderspeculative:enabled: falseextra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'- "--mamba-scheduler-strategy"- "extra_buffer"- "--disable-overlap-schedule"@@ -382,11 +507,12 @@ profiles:first_chunk_timeout_s: 90inter_chunk_timeout_s: 15overall_timeout_s: 600+ # A strict grammar may complete valid JSON in fewer than ten tokens.+ # Do not force post-schema tokens on grammar-routed profiles.default_sampling:temperature: 0.7top_p: 0.8top_k: 20presence_penalty: 1.5- min_new_tokens: 10stop_tokens:- "<|im_end|>"diff --git a/packages/sie_server/models/Qwen__Qwen3.6-35B-A3B.yaml b/packages/sie_server/models/Qwen__Qwen3.6-35B-A3B.yamlindex 8d4a9f533..320d39165 100644--- a/packages/sie_server/models/Qwen__Qwen3.6-35B-A3B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3.6-35B-A3B.yaml@@ -12,8 +12,8 @@ inputs:video: falsetasks:generate:- # Native context is 262,144 tokens. Start with the established 8K Qwen3.6- # serving contract until the single-H100 FP8 KV boundary is measured.+ # Native context is 262,144 tokens. Keep the bare model on the established+ # 8K Qwen3.6 contract and expose a conservative 32K opt-in profile below.context_length: 8192max_output_tokens: 4096capabilities:@@ -37,12 +37,16 @@ profiles:served_model_name: Qwen/Qwen3.6-35B-A3Bdisable_cuda_graph: trueattention_backend: triton- grammar_backend: outlines+ # Outlines fails at request time on this hybrid architecture because+ # its backend lacks the vocabulary-mask API used by the scheduler.+ grammar_backend: xgrammarreasoning_parser: qwen3tool_call_parser: qwen3_coderspeculative:enabled: falseextra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'- "--quantization"- "fp8"runtime:@@ -60,3 +64,105 @@ profiles:# Caller-visible FP8 alias; select the H100-80GB machine profile separately.h100-fp8:extends: default+ # Explicit reasoning mode uses the native-window H100 shape because Qwen's+ # model card recommends at least 128K context for thinking. The shorter bare+ # route remains an explicitly non-thinking compatibility surface.+ thinking:+ extends: long-context+ max_output_tokens: 81920+ chat_template_kwargs:+ enable_thinking: true+ adapter_options:+ runtime:+ first_chunk_timeout_s: 900+ inter_chunk_timeout_s: 30+ overall_timeout_s: 1800+ default_sampling:+ temperature: 1.0+ top_p: 0.95+ top_k: 20+ presence_penalty: 1.5+ stop_tokens:+ - "<|im_end|>"+ # Explicit native-window candidate for one H100-80GB admission. This is a+ # standalone parent so the thinking twin can inherit the exact launch shape+ # without profile chaining. Online FP8 limits weight memory; KV stays BF16+ # unless measured H100 evidence requires a separately validated cache dtype.+ long-context:+ # Qwen's official non-thinking serving recipe uses max_tokens=32768.+ # Keep the bare 8K profile at 4096 while exposing that decode ceiling only+ # on variants whose total context can accommodate it.+ max_output_tokens: 32768+ max_batch_tokens: 262144+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter+ kv_budget_tokens: 262144+ adapter_options:+ loadtime:+ max_seq_length: 262144+ mem_fraction_static: 0.95+ served_model_name: Qwen/Qwen3.6-35B-A3B+ disable_cuda_graph: true+ attention_backend: triton+ grammar_backend: xgrammar+ reasoning_parser: qwen3+ tool_call_parser: qwen3_coder+ speculative:+ enabled: false+ extra_launch_args:+ - "--mm-process-config"+ - '{"image":{"min_pixels":65536,"max_pixels":1003520}}'+ - "--quantization"+ - "fp8"+ runtime:+ first_chunk_timeout_s: 900+ inter_chunk_timeout_s: 30+ overall_timeout_s: 1800+ default_sampling:+ temperature: 0.7+ top_p: 0.8+ top_k: 20+ presence_penalty: 1.5+ stop_tokens:+ - "<|im_end|>"+ # Same measured 256K launch/admission envelope with Qwen thinking enabled.+ long-context-thinking:+ extends: long-context+ # Official Qwen3.6 thinking examples use max_tokens=81920.+ max_output_tokens: 81920+ chat_template_kwargs:+ enable_thinking: true+ adapter_options:+ runtime:+ first_chunk_timeout_s: 900+ inter_chunk_timeout_s: 30+ overall_timeout_s: 1800+ default_sampling:+ temperature: 1.0+ top_p: 0.95+ top_k: 20+ presence_penalty: 1.5+ stop_tokens:+ - "<|im_end|>"+ # Hardware-explicit aliases for the exact H100-80GB native-window shape.+ # Machine placement remains a separate gateway decision; these names make+ # the validated context/GPU pairing discoverable to callers.+ h100-256k:+ extends: long-context+ h100-256k-thinking:+ extends: long-context+ max_output_tokens: 81920+ chat_template_kwargs:+ enable_thinking: true+ adapter_options:+ runtime:+ first_chunk_timeout_s: 900+ inter_chunk_timeout_s: 30+ overall_timeout_s: 1800+ default_sampling:+ temperature: 1.0+ top_p: 0.95+ top_k: 20+ presence_penalty: 1.5+ stop_tokens:+ - "<|im_end|>"diff --git a/packages/sie_server/models/defog__sqlcoder-7b-2.yaml b/packages/sie_server/models/defog__sqlcoder-7b-2.yamlindex adb7f0c41..40e856487 100644--- a/packages/sie_server/models/defog__sqlcoder-7b-2.yaml+++ b/packages/sie_server/models/defog__sqlcoder-7b-2.yaml@@ -68,3 +68,12 @@ profiles:default_sampling:temperature: 0.0top_p: 1.0+ # The checkpoint supports 16,384 tokens. Keep the bare 8K contract for the+ # measured Spider recipe and expose the full native window explicitly.+ long-context:+ extends: default+ adapter_options:+ loadtime:+ max_seq_length: 16384+ mem_fraction_static: 0.85+ served_model_name: defog/sqlcoder-7b-2diff --git a/packages/sie_server/models/google__gemma-4-26B-A4B-it.yaml b/packages/sie_server/models/google__gemma-4-26B-A4B-it.yamlindex 51f306825..b2f377f04 100644--- a/packages/sie_server/models/google__gemma-4-26B-A4B-it.yaml+++ b/packages/sie_server/models/google__gemma-4-26B-A4B-it.yaml@@ -26,7 +26,8 @@ inputs:video: falsetasks:generate:- # Conservative contract pending calibration on a Gemma-4-capable engine.+ # Conservative bare contract; ``:long-context`` exposes a 32K opt-in+ # window, well below this large model's native 256K limit.context_length: 8192max_output_tokens: 4096# Grammar (response_format / json_schema / regex) is served by the@@ -91,6 +92,29 @@ profiles:# ``default``).no-spec:extends: default+ # Gemma 4 supports an explicit tokenizer thinking switch. Keep it opt-in so+ # the bare/OpenAI-compatible response remains answer-only.+ thinking:+ extends: default+ chat_template_kwargs:+ enable_thinking: true+ # Full 256K requires a dedicated KV calibration. Start with a conservative+ # 32K profile and a matching one-request admission budget on the BF16 H100+ # launch shape.+ long-context:+ extends: default+ max_batch_tokens: 32768+ kv_budget_tokens: 32768+ adapter_options:+ loadtime:+ max_seq_length: 32768+ mem_fraction_static: 0.90+ served_model_name: google/gemma-4-26B-A4B-it+ disable_cuda_graph: true+ attention_backend: triton+ grammar_backend: xgrammar+ reasoning_parser: gemma4+ tool_call_parser: gemma4# ``mtp`` variant — Gemma 4 MTP for the 26B MoE: NEXTN with the paired draft# ``google/gemma-4-26B-A4B-it-assistant``, BF16 (FP8 dropped — see header).# BF16 weights + the draft + the MTP cuda graph need more headroom than thediff --git a/packages/sie_server/models/google__gemma-4-31B-it.yaml b/packages/sie_server/models/google__gemma-4-31B-it.yamlindex 2e2eb2815..4f91f5100 100644--- a/packages/sie_server/models/google__gemma-4-31B-it.yaml+++ b/packages/sie_server/models/google__gemma-4-31B-it.yaml@@ -13,8 +13,8 @@ inputs:video: falsetasks:generate:- # Native context is 262,144 tokens. Keep the initial served contract at 8K- # until the H100 FP8 smoke calibrates KV capacity and long-context quality.+ # Native context is 262,144 tokens. Keep the bare served contract at 8K+ # and expose the native-window candidates through explicit profiles below.context_length: 8192max_output_tokens: 4096capabilities:@@ -62,3 +62,110 @@ profiles:# Caller-visible FP8 alias; select the H100-80GB machine profile separately.h100-fp8:extends: default+ # Gemma 4 supports an explicit tokenizer thinking switch. Use the measured+ # H100 96K shape so the generic reasoning alias has the same decode budget as+ # its hardware-explicit twin; the bare route remains answer-only.+ thinking:+ extends: h100-96k+ max_output_tokens: 32768+ chat_template_kwargs:+ enable_thinking: true+ # Explicit native-window candidate for one H200 admission. Keep the profile+ # standalone so the thinking and hardware-explicit aliases can inherit the+ # exact CUDA 13 launch shape without profile chaining. Online FP8 limits+ # weight memory, and FP8 E4M3 limits KV memory; the release gate separately+ # validates near-boundary decode and quality instead of weakening the+ # conservative bare-model contract.+ long-context:+ max_batch_tokens: 262144+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.gemma:SGLangGemmaAdapter+ kv_budget_tokens: 262144+ adapter_options:+ loadtime:+ max_seq_length: 262144+ # Leave transient FP8 GEMM workspace outside SGLang's static pool.+ mem_fraction_static: 0.90+ served_model_name: google/gemma-4-31B-it+ disable_cuda_graph: true+ attention_backend: triton+ grammar_backend: xgrammar+ reasoning_parser: gemma4+ tool_call_parser: gemma4+ speculative:+ enabled: false+ extra_launch_args:+ - "--quantization"+ - "fp8"+ - "--kv-cache-dtype"+ - "fp8_e4m3"+ runtime:+ first_chunk_timeout_s: 900+ inter_chunk_timeout_s: 30+ overall_timeout_s: 1800+ default_sampling:+ temperature: 1.0+ top_p: 0.95+ top_k: 64+ min_new_tokens: 1+ stop_tokens:+ - "<end_of_turn>"+ # Same measured 256K launch/admission envelope with Gemma thinking enabled.+ long-context-thinking:+ extends: long-context+ # The 4K control truncated otherwise-correct reasoning on 2/10 MMLU-Pro+ # rows. A 32K cap leaves ample room for the final answer without changing+ # the profile's sampling defaults or forcing callers to request it.+ max_output_tokens: 32768+ chat_template_kwargs:+ enable_thinking: true+ # H200 has enough memory for the native window. These aliases expose the+ # tested hardware/context pairing while machine placement remains separate.+ h200-256k:+ extends: long-context+ h200-256k-thinking:+ extends: long-context+ max_output_tokens: 32768+ chat_template_kwargs:+ enable_thinking: true+ # On H100-80GB this launch shape measured a 107,538-token KV capacity. Cap+ # the public profile at 96K to leave room for the chat template and decode;+ # never use SGLang auto-truncation to simulate a larger accepted context.+ h100-96k:+ max_batch_tokens: 98304+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.sglang.gemma:SGLangGemmaAdapter+ kv_budget_tokens: 98304+ adapter_options:+ loadtime:+ max_seq_length: 98304+ mem_fraction_static: 0.90+ served_model_name: google/gemma-4-31B-it+ disable_cuda_graph: true+ attention_backend: triton+ grammar_backend: xgrammar+ reasoning_parser: gemma4+ tool_call_parser: gemma4+ speculative:+ enabled: false+ extra_launch_args:+ - "--quantization"+ - "fp8"+ - "--kv-cache-dtype"+ - "fp8_e4m3"+ runtime:+ first_chunk_timeout_s: 900+ inter_chunk_timeout_s: 30+ overall_timeout_s: 1800+ default_sampling:+ temperature: 1.0+ top_p: 0.95+ top_k: 64+ min_new_tokens: 1+ stop_tokens:+ - "<end_of_turn>"+ h100-96k-thinking:+ extends: h100-96k+ max_output_tokens: 32768+ chat_template_kwargs:+ enable_thinking: truediff --git a/packages/sie_server/models/google__gemma-4-E2B-it.yaml b/packages/sie_server/models/google__gemma-4-E2B-it.yamlindex 1f9d4c829..f90538f17 100644--- a/packages/sie_server/models/google__gemma-4-E2B-it.yaml+++ b/packages/sie_server/models/google__gemma-4-E2B-it.yaml@@ -20,7 +20,8 @@ inputs:video: falsetasks:generate:- # Conservative contract pending calibration on a Gemma-4-capable engine.+ # Conservative bare contract; ``:long-context`` exposes a 32K opt-in+ # window, well below this edge model's native 128K limit.context_length: 8192max_output_tokens: 4096# Grammar (response_format / json_schema / regex) is served by the@@ -85,6 +86,27 @@ profiles:# ``grammar_profile`` can point here (the validator forbids naming ``default``).no-spec:extends: default+ # Gemma 4 supports an explicit tokenizer thinking switch. Keep it opt-in so+ # the bare/OpenAI-compatible response remains answer-only.+ thinking:+ extends: default+ chat_template_kwargs:+ enable_thinking: true+ # Full 128K requires a dedicated KV calibration. Start with a conservative+ # 32K profile and a matching one-request admission budget.+ long-context:+ extends: default+ kv_budget_tokens: 32768+ adapter_options:+ loadtime:+ max_seq_length: 32768+ mem_fraction_static: 0.85+ served_model_name: google/gemma-4-E2B-it+ disable_cuda_graph: true+ attention_backend: triton+ grammar_backend: xgrammar+ reasoning_parser: gemma4+ tool_call_parser: gemma4# ``mtp`` variant — Gemma 4 multi-token prediction (speculative decoding):# NEXTN with the paired external draft ``google/gemma-4-E2B-it-assistant``# (sglang 0.5.12+ Gemma 4 MTP; cookbook recipe num_steps=5 / num_draft_tokens=6diff --git a/packages/sie_server/models/google__gemma-4-E4B-it.yaml b/packages/sie_server/models/google__gemma-4-E4B-it.yamlindex b3bf0b555..d7ec3d104 100644--- a/packages/sie_server/models/google__gemma-4-E4B-it.yaml+++ b/packages/sie_server/models/google__gemma-4-E4B-it.yaml@@ -20,7 +20,8 @@ inputs:video: falsetasks:generate:- # Conservative contract pending calibration on a Gemma-4-capable engine.+ # Conservative bare contract; ``:long-context`` exposes a 32K opt-in+ # window, well below this edge model's native 128K limit.context_length: 8192max_output_tokens: 4096# Grammar (response_format / json_schema / regex) is served by the@@ -85,6 +86,27 @@ profiles:# ``grammar_profile`` can point here (the validator forbids naming ``default``).no-spec:extends: default+ # Gemma 4 supports an explicit tokenizer thinking switch. Keep it opt-in so+ # the bare/OpenAI-compatible response remains answer-only.+ thinking:+ extends: default+ chat_template_kwargs:+ enable_thinking: true+ # Full 128K requires a dedicated KV calibration. Start with a conservative+ # 32K profile and a matching one-request admission budget.+ long-context:+ extends: default+ kv_budget_tokens: 32768+ adapter_options:+ loadtime:+ max_seq_length: 32768+ mem_fraction_static: 0.85+ served_model_name: google/gemma-4-E4B-it+ disable_cuda_graph: true+ attention_backend: triton+ grammar_backend: xgrammar+ reasoning_parser: gemma4+ tool_call_parser: gemma4# ``mtp`` variant — Gemma 4 multi-token prediction (speculative decoding):# NEXTN with the paired external draft ``google/gemma-4-E4B-it-assistant``# (sglang 0.5.12+ Gemma 4 MTP; cookbook recipe num_steps=5 / num_draft_tokens=6diff --git a/packages/sie_server/models/ibm-granite__granite-embedding-97m-multilingual-r2.yaml b/packages/sie_server/models/ibm-granite__granite-embedding-97m-multilingual-r2.yamlnew file mode 100644index 000000000..28f130f12--- /dev/null+++ b/packages/sie_server/models/ibm-granite__granite-embedding-97m-multilingual-r2.yaml@@ -0,0 +1,35 @@+sie_id: ibm-granite/granite-embedding-97m-multilingual-r2+hf_id: ibm-granite/granite-embedding-97m-multilingual-r2+hf_revision: 835ad14087e140460703cf0fae09f97d469d65c2+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 384+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 32768+profiles:+ default:+ max_batch_tokens: 16384+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.modernbert_flash:ModernBERTFlashAdapter+ adapter_options:+ # Standard HF ModernBERT safetensors checkpoint, not an open_clip-format+ # one: config.json claims architectures ["ModernBertModel"] / model_type+ # "modernbert", so no open_clip backend loadtime options apply.+ loadtime: {}+ runtime:+ # 1_Pooling/config.json claim: {"pooling_mode_cls_token": true}+ pooling: cls+ # modules.json claim: "type": "sentence_transformers.models.Normalize"+ normalize: true+ # No query/doc templates: config_sentence_transformers.json claim is+ # {"prompts": {"query": "", "document": ""}} (both empty) and the+ # evidence records default_prompt_name: null.diff --git a/packages/sie_server/models/lightonai__mLateOn.yaml b/packages/sie_server/models/lightonai__mLateOn.yamlnew file mode 100644index 000000000..92d3fccc0--- /dev/null+++ b/packages/sie_server/models/lightonai__mLateOn.yaml@@ -0,0 +1,49 @@+sie_id: lightonai/mLateOn+hf_id: lightonai/mLateOn+hf_revision: 35391e36392085d72a93d232f6122607a234ad7a+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense: null+ sparse: null+ multivector:+ dim: 128+ score: {}+ extract: null+max_sequence_length: 8192+profiles:+ default:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server.adapters.colbert_modernbert_flash.adapter:ColBERTModernBERTFlashAdapter+ adapter_options:+ loadtime:+ # 3_Dense/config.json claim: {"out_features": 128} — the final module of+ # the evidence's Dense stack (768 -> 1536 -> 768 -> 128); the verdict's+ # machine-stamped token_dim (#2789).+ token_dim: 128+ # The pinned PyLate recipe declares 8192 total query/document tokens.+ # sentence_bert_config.json stores 8191 because upstream inserts the+ # configured marker as a separate token after backbone tokenization;+ # this adapter tokenizes the marker and text together.+ max_seq_length: 8192+ # config_sentence_transformers.json is the checkpoint's canonical+ # PyLate recipe for prefixes, lengths, query expansion, and skiplist.+ query_prefix: '[Q] '+ doc_prefix: '[D] '+ # PyLate ColBERT.encode normalizes token embeddings by default before+ # MaxSim; the checkpoint does not override that call-time default.+ normalize: true+ query_max_length: 8192+ # PyLate retains special tokens and masks only padding when query+ # expansion is disabled, as declared by this checkpoint.+ skip_special_tokens: false+ # The pinned recipe declares skiplist_words: [].+ doc_punctuation_skiplist: false+ # No serving-time truncation override: preserve the pinned 8192-token+ # query/document recipe.+ runtime: {}diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex 39c488878..7f066a19f 100644--- a/packages/sie_server/openapi.json+++ b/packages/sie_server/openapi.json@@ -3,28 +3,9 @@"info": {"title": "SIE Server","description": "Search Inference Engine - GPU inference server for search workloads",- "version": "0.6.26"+ "version": "0.6.27"},"paths": {- "/": {- "get": {- "summary": "Root",- "description": "Basic HTML status page for the root endpoint.",- "operationId": "root__get",- "responses": {- "200": {- "description": "Successful Response",- "content": {- "text/html": {- "schema": {- "type": "string"- }- }- }- }- }- }- },"/healthz": {"get": {"tags": [@@ -752,6 +733,162 @@}}}+ },+ "/v1/completions": {+ "post": {+ "tags": [+ "openai-compat"+ ],+ "summary": "Completions",+ "description": "Generate one raw-prompt OpenAI legacy completion.",+ "operationId": "completions_v1_completions_post",+ "parameters": [+ {+ "name": "X-SIE-MACHINE-PROFILE",+ "in": "header",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "X-Sie-Machine-Profile"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OpenAI text completion, or text_completion Server-Sent Events when stream is true",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAICompletionResponseModel"+ }+ },+ "text/event-stream": {+ "schema": {+ "type": "string",+ "description": "OpenAI text_completion events ending in [DONE]"+ }+ }+ }+ },+ "400": {+ "description": "Invalid or unsupported request"+ },+ "404": {+ "description": "Model not found"+ },+ "413": {+ "description": "Request body or prompt is too large"+ },+ "500": {+ "description": "Generation failed"+ },+ "503": {+ "description": "Model loading or temporarily unavailable"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ },+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAICompletionRequestModel"+ }+ }+ }+ }+ }+ },+ "/v1/responses": {+ "post": {+ "tags": [+ "openai-compat"+ ],+ "summary": "Responses",+ "description": "Create one stateless, text-only OpenAI Responses result.",+ "operationId": "responses_v1_responses_post",+ "parameters": [+ {+ "name": "X-SIE-MACHINE-PROFILE",+ "in": "header",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "X-Sie-Machine-Profile"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIResponsesResponseModel"+ }+ }+ }+ },+ "400": {+ "description": "Invalid or unsupported request"+ },+ "404": {+ "description": "Model not found"+ },+ "413": {+ "description": "Request body or rendered input is too large"+ },+ "500": {+ "description": "Generation failed"+ },+ "503": {+ "description": "Model loading or temporarily unavailable"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ }+ }+ },+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIResponsesRequestModel"+ }+ }+ }+ }+ }}},"components": {@@ -1476,6 +1613,83 @@"title": "MultiVectorModel","description": "Multi-vector (token-level) embedding."},+ "OpenAICompletionChoiceModel": {+ "properties": {+ "text": {+ "type": "string",+ "title": "Text"+ },+ "index": {+ "type": "integer",+ "title": "Index"+ },+ "finish_reason": {+ "type": "string",+ "title": "Finish Reason"+ }+ },+ "type": "object",+ "required": [+ "text",+ "index",+ "finish_reason"+ ],+ "title": "OpenAICompletionChoiceModel",+ "description": "One choice in a blocking OpenAI legacy completion."+ },+ "OpenAICompletionResponseModel": {+ "properties": {+ "id": {+ "type": "string",+ "title": "Id"+ },+ "object": {+ "type": "string",+ "const": "text_completion",+ "title": "Object"+ },+ "created": {+ "type": "integer",+ "title": "Created"+ },+ "model": {+ "type": "string",+ "title": "Model"+ },+ "choices": {+ "items": {+ "$ref": "#/components/schemas/OpenAICompletionChoiceModel"+ },+ "type": "array",+ "title": "Choices"+ },+ "system_fingerprint": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "System Fingerprint"+ },+ "usage": {+ "$ref": "#/components/schemas/GenerateUsageModel"+ }+ },+ "type": "object",+ "required": [+ "id",+ "object",+ "created",+ "model",+ "choices",+ "usage"+ ],+ "title": "OpenAICompletionResponseModel",+ "description": "Blocking OpenAI legacy-completions response."+ },"OpenAIEmbeddingData": {"properties": {"object": {@@ -1637,48 +1851,189 @@"title": "OpenAIEmbeddingResponse","description": "OpenAI-compatible embedding response."},- "OpenAIUsage": {+ "OpenAIResponseOutputMessageModel": {"properties": {- "prompt_tokens": {- "type": "integer",- "title": "Prompt Tokens",- "description": "Number of tokens in the input"+ "type": {+ "type": "string",+ "const": "message",+ "title": "Type"},- "total_tokens": {- "type": "integer",- "title": "Total Tokens",- "description": "Total tokens (same as prompt_tokens for embeddings)"+ "id": {+ "type": "string",+ "title": "Id"+ },+ "role": {+ "type": "string",+ "const": "assistant",+ "title": "Role"+ },+ "status": {+ "type": "string",+ "const": "completed",+ "title": "Status"+ },+ "content": {+ "items": {+ "$ref": "#/components/schemas/OpenAIResponseOutputTextModel"+ },+ "type": "array",+ "title": "Content"}},- "additionalProperties": false,"type": "object","required": [- "prompt_tokens",- "total_tokens"+ "type",+ "id",+ "role",+ "status",+ "content"],- "title": "OpenAIUsage",- "description": "Token usage information."+ "title": "OpenAIResponseOutputMessageModel"},- "ProfileInfo": {+ "OpenAIResponseOutputTextModel": {"properties": {- "is_default": {- "type": "boolean",- "title": "Is Default",- "default": false+ "type": {+ "type": "string",+ "const": "output_text",+ "title": "Type"+ },+ "text": {+ "type": "string",+ "title": "Text"+ },+ "annotations": {+ "items": {+ "additionalProperties": true,+ "type": "object"+ },+ "type": "array",+ "title": "Annotations"}},"type": "object",- "title": "ProfileInfo",- "description": "Information about a profile."+ "required": [+ "type",+ "text",+ "annotations"+ ],+ "title": "OpenAIResponseOutputTextModel"},- "RelationModel": {+ "OpenAIResponseUsageModel": {"properties": {- "head": {- "type": "string",- "title": "Head",- "description": "Head entity text"+ "input_tokens": {+ "type": "integer",+ "minimum": 0.0,+ "title": "Input Tokens"},- "tail": {+ "output_tokens": {+ "type": "integer",+ "minimum": 0.0,+ "title": "Output Tokens"+ },+ "total_tokens": {+ "type": "integer",+ "minimum": 0.0,+ "title": "Total Tokens"+ }+ },+ "type": "object",+ "required": [+ "input_tokens",+ "output_tokens",+ "total_tokens"+ ],+ "title": "OpenAIResponseUsageModel"+ },+ "OpenAIResponsesResponseModel": {+ "properties": {+ "id": {+ "type": "string",+ "title": "Id"+ },+ "object": {+ "type": "string",+ "const": "response",+ "title": "Object"+ },+ "created_at": {+ "type": "integer",+ "title": "Created At"+ },+ "model": {+ "type": "string",+ "title": "Model"+ },+ "status": {+ "type": "string",+ "const": "completed",+ "title": "Status"+ },+ "output": {+ "items": {+ "$ref": "#/components/schemas/OpenAIResponseOutputMessageModel"+ },+ "type": "array",+ "title": "Output"+ },+ "usage": {+ "$ref": "#/components/schemas/OpenAIResponseUsageModel"+ }+ },+ "type": "object",+ "required": [+ "id",+ "object",+ "created_at",+ "model",+ "status",+ "output",+ "usage"+ ],+ "title": "OpenAIResponsesResponseModel",+ "description": "One completed direct OpenAI Responses result."+ },+ "OpenAIUsage": {+ "properties": {+ "prompt_tokens": {+ "type": "integer",+ "title": "Prompt Tokens",+ "description": "Number of tokens in the input"+ },+ "total_tokens": {+ "type": "integer",+ "title": "Total Tokens",+ "description": "Total tokens (same as prompt_tokens for embeddings)"+ }+ },+ "additionalProperties": false,+ "type": "object",+ "required": [+ "prompt_tokens",+ "total_tokens"+ ],+ "title": "OpenAIUsage",+ "description": "Token usage information."+ },+ "ProfileInfo": {+ "properties": {+ "is_default": {+ "type": "boolean",+ "title": "Is Default",+ "default": false+ }+ },+ "type": "object",+ "title": "ProfileInfo",+ "description": "Information about a profile."+ },+ "RelationModel": {+ "properties": {+ "head": {+ "type": "string",+ "title": "Head",+ "description": "Head entity text"+ },+ "tail": {"type": "string","title": "Tail","description": "Tail entity text"@@ -2871,6 +3226,377 @@"title": "GenerateRequestModel","type": "object"},+ "OpenAICompletionStreamOptionsModel": {+ "additionalProperties": false,+ "description": "Supported OpenAI legacy-completions stream controls.",+ "properties": {+ "include_usage": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Emit one usage-only chunk immediately before the [DONE] terminator",+ "title": "Include Usage"+ }+ },+ "title": "OpenAICompletionStreamOptionsModel",+ "type": "object"+ },+ "OpenAICompletionRequestModel": {+ "additionalProperties": false,+ "description": "Strict single-candidate subset of the OpenAI legacy Completions API.",+ "properties": {+ "model": {+ "description": "Generation model id",+ "minLength": 1,+ "title": "Model",+ "type": "string"+ },+ "prompt": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "items": {+ "type": "string"+ },+ "type": "array"+ }+ ],+ "description": "One raw prompt string, or a one-element string array; no chat template is applied",+ "title": "Prompt"+ },+ "max_tokens": {+ "anyOf": [+ {+ "maximum": 4294967295,+ "minimum": 1,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": 16,+ "description": "Maximum generated tokens",+ "title": "Max Tokens"+ },+ "temperature": {+ "anyOf": [+ {+ "maximum": 3.4028234663852886e+38,+ "minimum": 0,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Sampling temperature override",+ "title": "Temperature"+ },+ "top_p": {+ "anyOf": [+ {+ "exclusiveMinimum": 0,+ "maximum": 1,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Nucleus-sampling probability override",+ "title": "Top P"+ },+ "stop": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "One stop sequence or an array of stop sequences",+ "title": "Stop"+ },+ "frequency_penalty": {+ "anyOf": [+ {+ "maximum": 2,+ "minimum": -2,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Frequency penalty",+ "title": "Frequency Penalty"+ },+ "presence_penalty": {+ "anyOf": [+ {+ "maximum": 2,+ "minimum": -2,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Presence penalty",+ "title": "Presence Penalty"+ },+ "seed": {+ "anyOf": [+ {+ "maximum": 9223372036854775807,+ "minimum": -9223372036854775808,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Optional signed 64-bit sampling seed",+ "format": "int64",+ "title": "Seed"+ },+ "stream": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Return OpenAI text_completion Server-Sent Events",+ "title": "Stream"+ },+ "stream_options": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/OpenAICompletionStreamOptionsModel"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "n": {+ "anyOf": [+ {+ "const": 1,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Only one completion candidate is supported",+ "title": "N"+ }+ },+ "required": [+ "model",+ "prompt"+ ],+ "title": "OpenAICompletionRequestModel",+ "type": "object"+ },+ "OpenAIResponseInputContentPartModel": {+ "additionalProperties": false,+ "description": "One text-only content part accepted by the Responses MVP.",+ "properties": {+ "type": {+ "enum": [+ "text",+ "input_text",+ "output_text"+ ],+ "title": "Type",+ "type": "string"+ },+ "text": {+ "title": "Text",+ "type": "string"+ }+ },+ "required": [+ "type",+ "text"+ ],+ "title": "OpenAIResponseInputContentPartModel",+ "type": "object"+ },+ "OpenAIResponseInputMessageModel": {+ "additionalProperties": false,+ "description": "One stateless text message accepted by the Responses MVP.",+ "properties": {+ "role": {+ "enum": [+ "system",+ "user",+ "assistant",+ "developer"+ ],+ "title": "Role",+ "type": "string"+ },+ "content": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "items": {+ "$ref": "#/components/schemas/OpenAIResponseInputContentPartModel"+ },+ "type": "array"+ }+ ],+ "title": "Content"+ }+ },+ "required": [+ "role",+ "content"+ ],+ "title": "OpenAIResponseInputMessageModel",+ "type": "object"+ },+ "OpenAIResponsesRequestModel": {+ "additionalProperties": false,+ "description": "Strict stateless, text-only subset of the OpenAI Responses API.",+ "properties": {+ "model": {+ "description": "Generation model id",+ "minLength": 1,+ "title": "Model",+ "type": "string"+ },+ "input": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "items": {+ "$ref": "#/components/schemas/OpenAIResponseInputMessageModel"+ },+ "minItems": 1,+ "type": "array"+ }+ ],+ "title": "Input"+ },+ "max_output_tokens": {+ "anyOf": [+ {+ "maximum": 4294967295,+ "minimum": 1,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": 16,+ "description": "Maximum generated tokens",+ "title": "Max Output Tokens"+ },+ "temperature": {+ "anyOf": [+ {+ "maximum": 3.4028234663852886e+38,+ "minimum": 0,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Sampling temperature override",+ "title": "Temperature"+ },+ "top_p": {+ "anyOf": [+ {+ "exclusiveMinimum": 0,+ "maximum": 1,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Nucleus-sampling probability override",+ "title": "Top P"+ },+ "seed": {+ "anyOf": [+ {+ "maximum": 9223372036854775807,+ "minimum": -9223372036854775808,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Optional signed 64-bit sampling seed",+ "format": "int64",+ "title": "Seed"+ },+ "stream": {+ "anyOf": [+ {+ "const": false,+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Responses streaming is not supported",+ "title": "Stream"+ }+ },+ "required": [+ "model",+ "input"+ ],+ "title": "OpenAIResponsesRequestModel",+ "type": "object"+ },"ScoreRequestModel": {"description": "Request body for score endpoint.","examples": [diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex a3d8eb08b..5c13e240c 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.6.26"+version = "0.6.27"description = "Search Inference Engine - GPU inference server for search workloads"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }@@ -34,8 +34,17 @@ dependencies = ["gliner>=0.2,<1","glirel>=1.0,<2","gliclass>=0.1,<1",- # Docling, composite-document parser (PDF/DOCX/HTML) for extract()- "docling>=2,<3",+ # Docling, composite-document parser (PDF/DOCX/HTML) for extract().+ # PINNED TO THE ARTIFACT REVISION, NOT FLOATED (#2872). Docling resolves+ # its RapidOCR det/cls/rec files by a version-specific path table, so the+ # library version and the immutable artifact revision pinned in+ # models/docling.yaml (superlinked/docling-artifacts @ 6281da32, the+ # "Docling 2.99 inference artifacts" commit) are ONE compatibility pair.+ # A floating '>=2,<3' let the Linux resolution drift to 2.116, whose table+ # asks for PP-OCRv6 while the committed artifacts ship PP-OCRv4 only —+ # docling then failed to load on BOTH profiles. Moving this range requires+ # re-curating and re-pinning the artifact revision in the same change.+ "docling>=2.99,<2.100",# Pin opencv-python-headless in place of opencv-python (pulled in via# docling -> rapidocr). The GUI build dlopens libxcb.so.1 / libGL.so.1# which aren't present in the worker images; the headless wheel ships thediff --git a/packages/sie_server/src/sie_server/_ipc_test_harness.py b/packages/sie_server/src/sie_server/_ipc_test_harness.pyindex e18c0b5ca..4cb46533b 100644--- a/packages/sie_server/src/sie_server/_ipc_test_harness.py+++ b/packages/sie_server/src/sie_server/_ipc_test_harness.py@@ -167,23 +167,80 @@ class _StubExecutor:class _FakeGenerateProcessor:- def signal_cancel(self, request_id: str) -> bool: # noqa: ARG002- return False+ def __init__(self) -> None:+ self._cancel_events: dict[str, asyncio.Event] = {}++ def signal_cancel(self, request_id: str) -> bool:+ event = self._cancel_events.get(request_id)+ if event is None:+ return False+ event.set()+ return True++ async def prewarm_grammars_for_model(self, model_id: str) -> None: # noqa: ARG002+ return Noneasync def process(self, msg: Any, model_id: str) -> None:work_item = msgpack.unpackb(msg.data, raw=False)await msg.in_progress()- payload = msgpack.packb(- {+ generate = work_item.get("generate") or {}+ request_id = work_item.get("request_id")+ messages = generate.get("messages") or []+ images = messages[0].get("images") if messages else []+ image_data = images[0].get("data") if images else None+ test_nak_reason = generate.get("test_nak_reason")+ wait_for_cancel = bool(generate.get("wait_for_cancel"))+ cancel_event = asyncio.Event()+ if wait_for_cancel:+ self._cancel_events[request_id] = cancel_event++ def payload(*, seq: int, done: bool, text_delta: str, finish_reason: str | None) -> bytes:+ body = {+ "kind": "chunk",+ "request_id": request_id,+ "attempt_id": "ipc-test-harness",+ "seq": seq,+ "text_delta": text_delta,+ "done": done,+ "image_data_is_bytes": isinstance(image_data, bytes),+ "image_data": image_data,+ "model_id": model_id,"smoke": "generate","source": "ipc_test_harness",- "model_id": model_id,- "request_id": work_item.get("request_id"),"work_item_id": work_item.get("work_item_id"),- },- use_bin_type=True,- )- await msg._sink.publish(work_item["reply_subject"], payload)+ }+ if finish_reason is not None:+ body["finish_reason"] = finish_reason+ return msgpack.packb(body, use_bin_type=True)++ try:+ if isinstance(test_nak_reason, str) and test_nak_reason:+ await msg._sink.publish(+ work_item["reply_subject"],+ msgpack.packb(+ {+ "kind": "nak",+ "request_id": request_id,+ "attempt_id": "ipc-test-harness",+ "reason": test_nak_reason,+ },+ use_bin_type=True,+ ),+ )+ await msg.ack()+ return+ if wait_for_cancel:+ await msg._sink.publish(+ work_item["reply_subject"],+ payload(seq=0, done=False, text_delta="started", finish_reason=None),+ )+ await cancel_event.wait()+ terminal = payload(seq=1, done=True, text_delta="", finish_reason="cancelled")+ else:+ terminal = payload(seq=0, done=True, text_delta="generated", finish_reason="stop")+ await msg._sink.publish(work_item["reply_subject"], terminal)+ finally:+ self._cancel_events.pop(request_id, None)await msg.ack()diff --git a/packages/sie_server/src/sie_server/adapters/_generation_base.py b/packages/sie_server/src/sie_server/adapters/_generation_base.pyindex 7c420fc60..6ceace549 100644--- a/packages/sie_server/src/sie_server/adapters/_generation_base.py+++ b/packages/sie_server/src/sie_server/adapters/_generation_base.py@@ -17,8 +17,8 @@ from __future__ import annotationsimport gcimport loggingfrom abc import abstractmethod-from collections.abc import AsyncIterator-from dataclasses import dataclass+from collections.abc import AsyncIterator, Mapping+from dataclasses import dataclass, replacefrom typing import Any, ClassVar, Literal, castfrom sie_server.adapters._spec import AdapterSpec@@ -28,6 +28,17 @@ from sie_server.types.inputs import ImageInputlogger = logging.getLogger(__name__)+_THINK_OPEN = "<think>"+_THINK_CLOSE = "</think>"+_GEMMA_CHANNEL_OPEN = "<" + "|channel" + ">"+_GEMMA_CHANNEL_CLOSE = "<" + "channel|" + ">"++ReasoningFormat = Literal["qwen3", "gemma4"]+_REASONING_BOUNDARIES: dict[ReasoningFormat, tuple[str, str]] = {+ "qwen3": (_THINK_OPEN, _THINK_CLOSE),+ "gemma4": (_GEMMA_CHANNEL_OPEN + "thought\n", _GEMMA_CHANNEL_CLOSE),+}+# Finish reason values surfaced to gateway / client. ``cancelled`` lands when# the worker observed a cancel signal mid-stream (§4.4.2). ``error`` lands@@ -147,6 +158,242 @@ class GenerationResult:completion_tokens: int+class ThinkingBlockStripper:+ """Incrementally remove family-specific model reasoning blocks from text.++ SGLang's native ``/generate`` endpoint returns raw decoded text, so its+ launch-time ``--reasoning-parser`` does not protect SIE's generation+ stream. Delimiters may be split across arbitrary engine chunks; retain+ only the longest possible delimiter prefix between calls so neither a+ partial tag nor its body can escape before the closing tag arrives.+ """++ __slots__ = ("_buffer", "_close", "_inside", "_open")++ def __init__(self, inside: bool = False, *, reasoning_format: ReasoningFormat = "qwen3") -> None:+ self._buffer = ""+ self._inside = inside+ self._open, self._close = _REASONING_BOUNDARIES[reasoning_format]++ @staticmethod+ def _delimiter_prefix_length(text: str, delimiters: tuple[str, ...]) -> int:+ max_len = min(max(map(len, delimiters)) - 1, len(text))+ for length in range(max_len, 0, -1):+ suffix = text[-length:]+ if any(delimiter.startswith(suffix) for delimiter in delimiters):+ return length+ return 0++ def feed(self, text: str) -> str:+ self._buffer += text+ visible: list[str] = []++ while self._buffer:+ if self._inside:+ close_at = self._buffer.find(self._close)+ if close_at >= 0:+ self._buffer = self._buffer[close_at + len(self._close) :]+ self._inside = False+ continue++ keep = self._delimiter_prefix_length(self._buffer, (self._close,))+ self._buffer = self._buffer[-keep:] if keep else ""+ break++ open_at = self._buffer.find(self._open)+ close_at = self._buffer.find(self._close)+ matches = [+ (index, delimiter)+ for index, delimiter in ((open_at, self._open), (close_at, self._close))+ if index >= 0+ ]+ if matches:+ marker_at, marker = min(matches, key=lambda match: match[0])+ visible.append(self._buffer[:marker_at])+ self._buffer = self._buffer[marker_at + len(marker) :]+ if marker == self._open:+ self._inside = True+ # A stray closing marker is still hidden, but does not cause+ # surrounding ordinary answer text to be discarded.+ continue++ keep = self._delimiter_prefix_length(self._buffer, (self._open, self._close))+ emit_upto = len(self._buffer) - keep+ visible.append(self._buffer[:emit_upto])+ self._buffer = self._buffer[emit_upto:]+ break++ return "".join(visible)++ @property+ def inside(self) -> bool:+ return self._inside++ def finish(self) -> str:+ """Flush ordinary buffered text, but never truncated private reasoning."""+ visible = "" if self._inside else self._buffer+ self._buffer = ""+ self._inside = False+ return visible+++def _strip_complete_thinking_blocks(+ text: str,+ *,+ start_inside: bool = False,+ reasoning_format: ReasoningFormat = "qwen3",+) -> str:+ stripper = ThinkingBlockStripper(inside=start_inside, reasoning_format=reasoning_format)+ return stripper.feed(text) + stripper.finish()+++async def suppress_thinking_blocks(+ chunks: AsyncIterator[GenerationChunk],+ *,+ start_inside: bool = False,+ reasoning_format: ReasoningFormat = "qwen3",+) -> AsyncIterator[GenerationChunk]:+ """Hide model reasoning blocks while preserving generation metadata.++ Callers decide whether the resolved model declares the hidden-thinking+ contract. Both non-thinking and explicit thinking profiles use this wrapper:+ the profile controls tokenizer/model behavior, never public visibility of+ the private reasoning channel. Per-choice state keeps interleaved ``n > 1``+ streams independent, and terminal ``candidates`` are normalized through the+ same rule. When text is rewritten its token logprobs are omitted because the+ engine's token list can no longer be faithfully aligned with the visible+ delta. ``start_inside`` covers chat templates that place the opening+ reasoning marker in the prompt, so generated text begins with private+ reasoning and only emits the closing marker. ``reasoning_format`` selects+ the boundary pair declared by the model's generation backend.++ Closing the wrapper eagerly closes the upstream adapter iterator so client+ cancellation still reaches SGLang's ``/abort_request`` cleanup.+ """+ states: dict[int, ThinkingBlockStripper] = {}+ emitted_visible_text = False+ try:+ async for chunk in chunks:+ rewritten_candidates = chunk.candidates+ if chunk.candidates is not None:+ candidate_items: list[dict[str, Any]] = []+ for candidate in chunk.candidates:+ item = dict(candidate)+ text = item.get("text")+ if isinstance(text, str):+ visible = _strip_complete_thinking_blocks(+ text,+ start_inside=start_inside,+ reasoning_format=reasoning_format,+ )+ if visible != text:+ item["text"] = visible+ item["logprobs"] = None+ candidate_items.append(item)+ rewritten_candidates = tuple(candidate_items)++ state = states.setdefault(+ chunk.choice_index,+ ThinkingBlockStripper(inside=start_inside, reasoning_format=reasoning_format),+ )+ was_inside = state.inside+ visible_delta = state.feed(chunk.text_delta)+ text_changed = visible_delta != chunk.text_delta+ if chunk.done or chunk.finish_reason is not None:+ visible_delta += state.finish()++ is_first = bool(visible_delta) and not emitted_visible_text+ emitted_visible_text = emitted_visible_text or bool(visible_delta)+ rewritten = replace(+ chunk,+ text_delta=visible_delta,+ is_first=is_first,+ logprobs=None if text_changed or was_inside else chunk.logprobs,+ candidates=rewritten_candidates,+ )++ # Reasoning-only engine deltas have no wire-visible information.+ # Keep terminals, per-choice finish markers, tool/error chunks, and+ # non-streaming candidate aggregates intact.+ if (+ not rewritten.text_delta+ and not rewritten.done+ and rewritten.finish_reason is None+ and rewritten.tool_call_delta is None+ and rewritten.error_code is None+ and rewritten.error_message is None+ and rewritten.logprobs is None+ and rewritten.candidates is None+ ):+ continue++ yield rewritten+ finally:+ aclose = getattr(chunks, "aclose", None)+ if aclose is not None:+ await aclose()+++def thinking_blocks_must_be_hidden(config: Any) -> bool:+ """Return whether the resolved config declares hidden thinking semantics.++ An explicit boolean is materialized for every reasoning-capable Qwen and+ Gemma 4 variant. ``False`` keeps model reasoning disabled; ``True`` enables+ it internally. In both cases raw ``<think>`` blocks are never public output.+ """+ tasks = getattr(config, "tasks", None)+ generate = getattr(tasks, "generate", None)+ kwargs = getattr(generate, "chat_template_kwargs", None)+ return isinstance(kwargs, dict) and isinstance(kwargs.get("enable_thinking"), bool)+++def _reasoning_format(value: object) -> ReasoningFormat | None:+ if value == "gemma4":+ return "gemma4"+ if value == "qwen3":+ return "qwen3"+ return None+++def resolve_reasoning_format(config: Any, adapter: Any | None = None) -> ReasoningFormat:+ """Resolve the model's reasoning boundaries, preferring the loaded adapter."""+ adapter_format = _reasoning_format(getattr(adapter, "reasoning_parser", None))+ if adapter_format is not None:+ return adapter_format++ resolver = getattr(config, "resolve_profile", None)+ if callable(resolver):+ try:+ loadtime = getattr(resolver("default"), "loadtime", None)+ except (KeyError, ValueError):+ loadtime = None+ if isinstance(loadtime, Mapping):+ configured_format = _reasoning_format(loadtime.get("reasoning_parser"))+ if configured_format is not None:+ return configured_format+ return "qwen3"+++def reasoning_starts_in_prompt(prompt: str, reasoning_format: ReasoningFormat) -> bool:+ """Return whether the rendered prompt ends inside a reasoning boundary."""+ opening, closing = _REASONING_BOUNDARIES[reasoning_format]+ opening_at = prompt.rfind(opening)+ if reasoning_format == "gemma4" and prompt.endswith(_GEMMA_CHANNEL_OPEN):+ # Gemma's template can seed only the channel control token in the+ # prompt; the model then generates the ``thought\n`` self-label. Treat+ # that split boundary as open so the reasoning body stays private.+ opening_at = len(prompt) - len(_GEMMA_CHANNEL_OPEN)+ return opening_at > prompt.rfind(closing)+++def thinking_mode_is_enabled(config: Any) -> bool:+ """Return whether the resolved tokenizer profile enables private reasoning."""+ tasks = getattr(config, "tasks", None)+ generate = getattr(tasks, "generate", None)+ kwargs = getattr(generate, "chat_template_kwargs", None)+ return isinstance(kwargs, dict) and kwargs.get("enable_thinking") is True++async def collect_generation(chunks: AsyncIterator[GenerationChunk],) -> GenerationResult:diff --git a/packages/sie_server/src/sie_server/adapters/_pylate_dense.py b/packages/sie_server/src/sie_server/adapters/_pylate_dense.pyindex 8967cd12d..015232d62 100644--- a/packages/sie_server/src/sie_server/adapters/_pylate_dense.py+++ b/packages/sie_server/src/sie_server/adapters/_pylate_dense.py@@ -3,19 +3,21 @@pylate ColBERT checkpoints describe their projection head in ``modules.json``:module 0 is the sentence-transformers ``Transformer`` backbone, and every latermodule is a ``pylate.models.Dense.Dense`` whose weights live in-``<path>/model.safetensors`` under the single key ``linear.weight`` (shape-``[out_features, in_features]``). pylate's ``Dense.forward`` is literally-``self.linear(x)`` — it never applies the checkpoint's ``activation_function``-— so with ``bias: false`` / ``use_residual: false`` the whole head is the-sequential matmul ``hidden @ W0.T @ W1.T ...`` on the backbone's final-normed-``last_hidden_state``. This composition is proven bit-exact against official-pylate output in ``_poc/pylate-dense-chain/FINDINGS.md``. See #1680.+``<path>/model.safetensors`` under ``linear.weight`` and, for dimension-changing+residual layers, ``residual.weight``. With Identity activation and no bias, a+residual layer is still one matmul: ``linear(x) + residual(x)`` is equivalent to+``x @ (W_linear + W_residual).T`` (or ``W_linear + I`` when the dimensions are+equal). The whole head can therefore remain the sequential matmul+``hidden @ W0.T @ W1.T ...`` on the backbone's final-normed+``last_hidden_state``. The non-residual composition is proven bit-exact against+official pylate output in ``_poc/pylate-dense-chain/FINDINGS.md``. See #1680.Any checkpoint whose modules.json is absent, has no Dense modules (e.g.mxbai-colbert-large-v1 ships a Transformer-only modules.json), or declares math-this loader does not reproduce (bias, residual, non-Identity activation, dim-discontinuities) yields ``None`` so callers keep their existing behavior-(legacy projection probes / backbone truncation) — degrade, don't fail.+this loader does not reproduce (bias, non-Identity activation, malformed+residual weights, dim discontinuities) yields ``None`` so callers keep their+existing behavior (legacy projection probes / backbone truncation) — degrade,+don't fail."""from __future__ import annotations@@ -147,17 +149,8 @@ def load_pylate_dense_chain("Dense module %s has bias=true for %s; using backbone truncation", rel_dir, model_name_or_path)return None- # Missing key == false (GTE-ModernColBERT's config has no use_residual key).- if config.get("use_residual"):- logger.warning(- "Dense module %s has use_residual=true for %s; using backbone truncation",- rel_dir,- model_name_or_path,- )- return None- # pylate's Dense.forward never applies activation_function, but- # sentence-transformers' Dense.forward does — a non-Identity value means- # the checkpoint was trained with math we would not reproduce: degrade.+ # PyLate applies activation_function before any residual. Only Identity+ # keeps the layer reducible to the linear composition used below.activation = config.get("activation_function")if activation is not None and str(activation).rsplit(".", 1)[-1] != "Identity":logger.warning(@@ -213,6 +206,36 @@ def load_pylate_dense_chain(model_name_or_path,)return None+ use_residual = bool(config.get("use_residual", False))+ residual = state.get("residual.weight")+ if use_residual:+ if expected_shape[0] == expected_shape[1]:+ if residual is not None:+ logger.warning(+ "Dense module %s for %s unexpectedly ships residual.weight for an identity residual; "+ "using backbone truncation",+ rel_dir,+ model_name_or_path,+ )+ return None+ residual = torch.eye(expected_shape[0], dtype=weight.dtype, device=weight.device)+ elif residual is None or tuple(residual.shape) != expected_shape:+ logger.warning(+ "Dense module %s residual shape %s != config (out, in)=%s for %s; using backbone truncation",+ rel_dir,+ None if residual is None else tuple(residual.shape),+ expected_shape,+ model_name_or_path,+ )+ return None+ weight = weight + residual+ elif residual is not None:+ logger.warning(+ "Dense module %s for %s ships residual.weight with use_residual=false; using backbone truncation",+ rel_dir,+ model_name_or_path,+ )+ return Noneweights.append(weight)# Shape-guard the chain ends plus adjacency: the first hop must consume thediff --git a/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/adapter.py b/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/adapter.pyindex abf0a9646..9f9362815 100644--- a/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/adapter.py@@ -1,6 +1,7 @@from __future__ import annotationsimport logging+from collections.abc import Mappingfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, ClassVar@@ -32,6 +33,39 @@ logger = logging.getLogger(__name__)_ERR_CPU_NOT_SUPPORTED = "ColBERTModernBERTFlashAdapter requires CUDA for Flash Attention."+def _nested_rope_theta(config: Any, layer_kind: str) -> float | None:+ """Return ``rope_theta`` for ``layer_kind`` from a transformers>=5 nested+ ``rope_parameters`` mapping, or None when it is absent or malformed.++ transformers 5.x re-serializes ModernBERT rope as+ ``rope_parameters[{"full_attention", "sliding_attention"}]["rope_theta"]``+ and drops the flat ``global_rope_theta``/``local_rope_theta`` keys. This+ bundle's 4.x config class does not ingest the nested mapping —+ ``PretrainedConfig`` retains it as an opaque attribute while the flat attrs+ fill in from class defaults — so without this read a 5.x-serialized+ checkpoint is silently served with sliding-window layers at the+ class-default theta 10000 instead of its trained value (mLateOn trains+ both layer kinds at 160000; the #2807 parity probe measured per-token+ cosine vs pylate down to 0.588 from this alone).++ Precedence: nested-when-present wins — a 5.x-serialized config is+ authoritative about itself, and 4.x-written configs carry no+ ``rope_parameters`` key, so their flat-attr path stays byte-identical. A+ malformed nested declaration (non-mapping, missing layer kind, non-numeric+ theta) falls back to the flat attrs rather than failing the load.+ """+ rope_parameters = getattr(config, "rope_parameters", None)+ if not isinstance(rope_parameters, Mapping):+ return None+ entry = rope_parameters.get(layer_kind)+ if not isinstance(entry, Mapping):+ return None+ theta = entry.get("rope_theta")+ if isinstance(theta, bool) or not isinstance(theta, (int, float)):+ return None+ return float(theta)++class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):"""ColBERT adapter for ModernBERT with RoPE and Flash Attention 2 varlen.@@ -506,6 +540,9 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):ModernBERT uses different rope_theta values for global vs local attentionlayers: ``global_rope_theta`` (default 160000) for global layers and``local_rope_theta`` (default 10000) for local (sliding-window) layers.+ A transformers>=5 nested ``rope_parameters`` declaration takes+ precedence over the flat attrs when present (see ``_nested_rope_theta``+ for the rationale and fallback contract).Args:position_ids: Packed position IDs [total_tokens].@@ -518,9 +555,13 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):cfg = self._model.configif use_global:- base = getattr(cfg, "global_rope_theta", getattr(cfg, "rope_theta", 160000.0))+ base = _nested_rope_theta(cfg, "full_attention")+ if base is None:+ base = getattr(cfg, "global_rope_theta", getattr(cfg, "rope_theta", 160000.0))else:- base = getattr(cfg, "local_rope_theta", getattr(cfg, "rope_theta", 10000.0))+ base = _nested_rope_theta(cfg, "sliding_attention")+ if base is None:+ base = getattr(cfg, "local_rope_theta", getattr(cfg, "rope_theta", 10000.0))inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2, device=self._device).float() / head_dim))diff --git a/packages/sie_server/src/sie_server/adapters/docling/adapter.py b/packages/sie_server/src/sie_server/adapters/docling/adapter.pyindex ab663dc76..7ec3162df 100644--- a/packages/sie_server/src/sie_server/adapters/docling/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/docling/adapter.py@@ -156,6 +156,8 @@ class DoclingAdapter(BaseAdapter):# Pre-warm: triggers Docling's lazy download of layout/table models so# the first real request doesn't block on a multi-hundred-MB pull.# Models cache globally, so subsequent per-task converters are cheap.+ # This is the born-digital parse path that BOTH profiles depend on, so+ # a staged artifact root keeps it fail-closed.try:warm_converter = self._get_converter(ocr_enabled=False)_payload, _pages, warm_error = self._convert_bytes(@@ -165,9 +167,19 @@ class DoclingAdapter(BaseAdapter):)if warm_error is not None:raise RuntimeError(warm_error.message)- # DocumentConverter construction is lazy, so exercise the OCR- # converter too. This initializes its OCR assets during readiness- # instead of deferring a missing staged file to the first request.+ except Exception as exc:+ if self._artifacts_path is not None:+ raise RuntimeError("Docling staged artifact initialization failed") from exc+ logger.exception("Docling pre-warm failed; first real request may be slow")+ # DocumentConverter construction is lazy, so exercise the OCR converter+ # too — but only as a readiness PROBE, never as a load gate. OCR assets+ # are an ``ocr``-profile dependency: Docling threads ``do_ocr`` into the+ # OCR model's ``enabled`` flag, so the ``default`` profile never opens+ # one. Gating load() on this turned a missing OCR file into a total+ # outage for both profiles, including the cheaper and more commonly+ # used born-digital path (#2872). Drop the failed converter instead, so+ # an ``ocr`` request rebuilds it and surfaces a per-item error.+ try:ocr_converter = self._get_converter(ocr_enabled=True)_payload, _pages, ocr_warm_error = self._convert_bytes(ocr_converter,@@ -176,10 +188,12 @@ class DoclingAdapter(BaseAdapter):)if ocr_warm_error is not None:raise RuntimeError(ocr_warm_error.message)- except Exception as exc:- if self._artifacts_path is not None:- raise RuntimeError("Docling staged artifact initialization failed") from exc- logger.exception("Docling pre-warm failed; first real request may be slow")+ except Exception:+ self._converters.pop(True, None)+ logger.exception(+ "Docling OCR pre-warm failed; the 'ocr' profile will error per request "+ "until its OCR assets resolve. The 'default' profile is unaffected."+ )self._loaded = Truedef _resolve_artifacts_path(self) -> Path | None:diff --git a/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/adapter.py b/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/adapter.pyindex 91618a61b..0f7029f45 100644--- a/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/adapter.py@@ -1,5 +1,6 @@from __future__ import annotations+import inspectimport ioimport loggingfrom pathlib import Path@@ -96,7 +97,7 @@ class Qwen3VLRerankerAdapter(BaseAdapter):spec: ClassVar[AdapterSpec] = AdapterSpec(inputs=("text", "image"),outputs=("score",),- unload_fields=("_model", "_processor", "_yes_token_id", "_no_token_id"),+ unload_fields=("_model", "_processor", "_yes_token_id", "_no_token_id", "_image_token_id"),default_preprocessor="image",)@@ -127,6 +128,8 @@ class Qwen3VLRerankerAdapter(BaseAdapter):self._yes_token_id: int | None = Noneself._attn_implementation: str | None = Noneself._no_token_id: int | None = None+ self._image_token_id: int | None = None+ self._accepts_mm_token_type_ids: bool = Falsedef load(self, device: str) -> None:from transformers import AutoProcessor, AutoTokenizer, Qwen3VLForConditionalGeneration@@ -230,6 +233,29 @@ class Qwen3VLRerankerAdapter(BaseAdapter):)raise ValueError(msg)+ # FIX[#2856]: transformers 5.3+ moved the vision-RoPE modality map out of+ # the model and onto the processor/forward contract. Resolve both halves+ # once at load time so a version that needs the map cannot quietly serve+ # image pairs with text-only positions.+ self._accepts_mm_token_type_ids = "mm_token_type_ids" in inspect.signature(self._model.forward).parameters+ image_token = getattr(self._processor, "image_token", None)+ if not image_token:+ msg = f"Processor for {self._model_name_or_path} does not expose an image token"+ raise ValueError(msg)+ image_token_id = tokenizer.convert_tokens_to_ids(image_token)+ if (+ image_token_id is None+ or image_token_id == unk_id+ or tokenizer.convert_ids_to_tokens(image_token_id) != image_token+ ):+ msg = (+ f"Tokenizer for {self._model_name_or_path} does not contain the processor image token "+ f"{image_token!r} (resolved to id={image_token_id}, unk_id={unk_id}). "+ "Multimodal reranking cannot place image tokens without it."+ )+ raise ValueError(msg)+ self._image_token_id = int(image_token_id)+def _resolve_dtype(self) -> torch.dtype:if not self._device or not str(self._device).startswith("cuda"):return torch.float32@@ -409,6 +435,15 @@ class Qwen3VLRerankerAdapter(BaseAdapter):"return_tensors": None,"padding": False,"truncation": False,+ # FIX[#2856]: transformers 5.3.0 flipped Qwen3VLProcessorKwargs'+ # ``return_mm_token_type_ids`` default from False to True. The+ # processor then runs ``np.array(input_ids)`` over this deliberately+ # unpadded batch, which raises ValueError on any two prompts of+ # unequal length — every multi-pair request, while single-pair ones+ # slipped through. We pad and trim per document ourselves, so ask+ # the processor to stay out of it and rebuild the tensor in+ # ``_prepare_model_inputs`` against the ids the model actually sees.+ "return_mm_token_type_ids": False,}if max_length is not None:proc_kwargs["return_offsets_mapping"] = True@@ -524,11 +559,29 @@ class Qwen3VLRerankerAdapter(BaseAdapter):)inputs = dict(padded)for key, value in processor_inputs.items():- if key in {"input_ids", "attention_mask", "offset_mapping"}:+ if key in {"input_ids", "attention_mask", "offset_mapping", "mm_token_type_ids"}:continueinputs[key] = value if isinstance(value, torch.Tensor) else torch.as_tensor(np.asarray(value))+ mm_token_type_ids = self._derive_mm_token_type_ids(inputs["input_ids"])+ if mm_token_type_ids is not None:+ inputs["mm_token_type_ids"] = mm_token_type_idsreturn inputs, [len(ids) for ids in trimmed_ids]+ def _derive_mm_token_type_ids(self, input_ids: torch.Tensor) -> torch.Tensor | None:+ """Rebuild the modality map transformers 5.3+ needs for 3D vision RoPE.++ FIX[#2856]: from transformers 5.3.0 ``Qwen3VLModel`` only computes mrope+ positions when it is handed ``mm_token_type_ids``; without it, image+ tokens silently fall back to 1D positions. Up to 5.2 the model derived+ the same map itself from ``input_ids`` and the image token id, so+ deriving it here reproduces the pre-5.3 positions exactly — and it is+ the only version that survives our per-document trimming, which the+ processor's own (pre-trim) map would not line up with.+ """+ if not self._accepts_mm_token_type_ids or self._image_token_id is None:+ return None+ return (input_ids == self._image_token_id).to(torch.int32)+def _expand_image_placeholders(self,prompts: list[str],diff --git a/packages/sie_server/src/sie_server/adapters/sglang/_compat/__init__.py b/packages/sie_server/src/sie_server/adapters/sglang/_compat/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/packages/sie_server/src/sie_server/adapters/sglang/_compat/sitecustomize.py b/packages/sie_server/src/sie_server/adapters/sglang/_compat/sitecustomize.pynew file mode 100644index 000000000..738ac103a--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/sglang/_compat/sitecustomize.py@@ -0,0 +1,92 @@+"""Backport SGLang multimodal processor configuration forwarding.++SGLang 0.5.10 parses ``--mm-process-config`` and stores its per-modality+settings, but its base processor does not forward the image settings to the+Hugging Face processor. Upstream #18467 now passes them as ``images_kwargs``.+This site hook runs only in the SGLang generation subprocess and can be removed+when the shared bundle advances to a release containing that fix.+"""++from __future__ import annotations++import builtins+import os+import sys+from collections.abc import Mapping, Sequence+from functools import wraps+from types import ModuleType+from typing import Any++_BASE_PROCESSOR_MODULE = "sglang.srt.multimodal.processors.base_processor"+_CLASS_PATCH_MARKER = "_sie_mm_process_config_compat"+_IMPORT_HOOK_MARKER = "_sie_mm_process_config_deferred_compat"+++def _patch_base_processor_module(module: ModuleType) -> None:+ processor_class = getattr(module, "BaseMultimodalProcessor", None)+ if processor_class is None:+ raise RuntimeError(f"{_BASE_PROCESSOR_MODULE} does not expose BaseMultimodalProcessor")+ if getattr(processor_class, _CLASS_PATCH_MARKER, False):+ return++ original_process = processor_class.process_mm_data++ @wraps(original_process)+ def compat_process(+ self: Any,+ input_text: Any,+ images: Any = None,+ videos: Any = None,+ audios: Any = None,+ **kwargs: Any,+ ) -> dict[str, Any]:+ image_config = getattr(self, "image_config", None)+ if images and isinstance(image_config, dict) and image_config:+ kwargs.setdefault("images_kwargs", {}).update(image_config)+ return original_process(+ self,+ input_text,+ images=images,+ videos=videos,+ audios=audios,+ **kwargs,+ )++ processor_class.process_mm_data = compat_process+ setattr(processor_class, _CLASS_PATCH_MARKER, True)+++def _install_mm_process_config_compat() -> None:+ loaded = sys.modules.get(_BASE_PROCESSOR_MODULE)+ if isinstance(loaded, ModuleType):+ _patch_base_processor_module(loaded)+ return++ current_import = builtins.__import__+ if getattr(current_import, _IMPORT_HOOK_MARKER, False):+ return++ def deferred_import(+ name: str,+ globals: Mapping[str, object] | None = None,+ locals: Mapping[str, object] | None = None,+ fromlist: Sequence[str] | None = (),+ level: int = 0,+ ) -> ModuleType:+ module = current_import(name, globals, locals, fromlist, level)+ loaded_module = sys.modules.get(_BASE_PROCESSOR_MODULE)+ if not isinstance(loaded_module, ModuleType) or not hasattr(loaded_module, "BaseMultimodalProcessor"):+ return module+ try:+ _patch_base_processor_module(loaded_module)+ finally:+ if builtins.__import__ is deferred_import:+ setattr(builtins, "__import__", current_import) # noqa: B010+ return module++ setattr(deferred_import, _IMPORT_HOOK_MARKER, True)+ setattr(builtins, "__import__", deferred_import) # noqa: B010+++if os.environ.get("SIE_SGLANG_MM_PROCESS_CONFIG_COMPAT") == "1":+ _install_mm_process_config_compat()diff --git a/packages/sie_server/src/sie_server/adapters/sglang/cuda13.py b/packages/sie_server/src/sie_server/adapters/sglang/cuda13.pynew file mode 100644index 000000000..bafd688a9--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/sglang/cuda13.py@@ -0,0 +1,29 @@+from typing import Any++from sie_server.adapters.sglang.generation import SGLangGenerationAdapter+++class SGLangStrictThinkingAdapter(SGLangGenerationAdapter):+ """CUDA 13 SGLang lane that guarantees a closed private thought block.++ SGLang 0.5.13 can suppress premature EOS tokens until the model emits its+ reasoning terminator. The older shared SGLang bundle does not expose this+ launch option, so reasoning profiles that need the guarantee route through+ the existing CUDA 13 bundle while retaining the generic generation adapter.+ """++ def __init__(+ self,+ model_name_or_path: str,+ *,+ extra_launch_args: list[str] | None = None,+ **kwargs: Any,+ ) -> None:+ launch_args = list(extra_launch_args or [])+ if "--enable-strict-thinking" not in launch_args:+ launch_args.append("--enable-strict-thinking")+ super().__init__(+ model_name_or_path,+ extra_launch_args=launch_args,+ **kwargs,+ )diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.pyindex fc16e6461..877fc6181 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py@@ -156,6 +156,19 @@ def _encode_image_data(images: list[ImageInput] | None) -> list[str] | None:return encoded+def _raise_for_sglang_event_error(event: Any) -> None:+ """Propagate an error carried inside SGLang's HTTP-200 SSE stream."""+ if not isinstance(event, dict) or "error" not in event:+ return+ error = event["error"]+ message = error.get("message") if isinstance(error, dict) else error+ if not isinstance(message, str) or not message.strip():+ message = "unknown in-band SGLang error"+ message = message.strip()[:500]+ logger.error("SGLang /generate in-band error: %s", message)+ raise RuntimeError(f"SGLang /generate error: {message}")++def _tail_file(path: str, *, max_lines: int = 200) -> str:"""Return the final lines from a startup log for diagnostics."""try:@@ -402,6 +415,33 @@ class SGLangGenerationAdapter(GenerationAdapter):)return MLXGenerationAdapter(**_translate_to_mlx_kwargs(kwargs))+ @property+ def server_url(self) -> str | None:+ """Return the managed child's loopback base URL when loaded."""+ return self._server_url++ @property+ def served_model_name(self) -> str:+ """Return the exact model identity registered with the SGLang child."""+ return self._served_model_name++ @property+ def reasoning_parser(self) -> str | None:+ """Return the child parser used to separate private reasoning output."""+ return self._reasoning_parser++ def _compat_pythonpath_entries(self) -> tuple[str, ...]:+ """Return trusted compatibility paths for the SGLang child.++ Model configuration may supply other child environment variables, but+ it must not select interpreter startup hooks through ``PYTHONPATH``.+ Subclasses can prepend code-owned compatibility directories by+ overriding this method with paths derived from their own source tree.+ """+ compat_dir = os.path.join(os.path.dirname(__file__), "_compat")+ inherited_pythonpath = os.environ.get("PYTHONPATH", "")+ return tuple(path for path in (compat_dir, inherited_pythonpath) if path)+def load(self, device: str) -> None:self._device = devicedevice_index = _server.parse_device_index(device)@@ -498,6 +538,10 @@ class SGLangGenerationAdapter(GenerationAdapter):"speculative_needs_extra_buffer=false (non-DeltaNet models e.g. Gemma 4 ""MTP), or disable speculative.enabled in the model config.")+ # Keep SIE compatibility hooks deterministic and code-owned: Python+ # auto-imports sitecustomize from PYTHONPATH during child startup.+ extra_env["PYTHONPATH"] = os.pathsep.join(self._compat_pythonpath_entries())+ extra_env["SIE_SGLANG_MM_PROCESS_CONFIG_COMPAT"] = "1"logger.warning("Resolved SGLang generation command: %s"," ".join(shlex.quote(str(arg)) for arg in cmd),@@ -959,6 +1003,16 @@ class SGLangGenerationAdapter(GenerationAdapter):"temperature": temperature,"top_p": top_p,}+ if self._reasoning_parser == "gemma4":+ # Gemma 4's private reasoning boundary uses special channel+ # tokens. SGLang's default detokenization drops those tokens from+ # the native /generate text while leaving the ordinary+ # ``thought\n`` label and reasoning body visible, so SIE's+ # family-aware privacy filter can no longer identify the block.+ # Preserve the markers at this internal boundary; every public+ # generation surface removes the complete reasoning block before+ # returning content to the caller.+ sampling_params["skip_special_tokens"] = False# SGLang accepts ``top_k`` (int) and ``repetition_penalty`` (float)# natively under ``sampling_params``. Forward only when the gateway# provided a value so model defaults stay in effect otherwise.@@ -1112,6 +1166,7 @@ class SGLangGenerationAdapter(GenerationAdapter):event = json.loads(line)except json.JSONDecodeError:continue+ _raise_for_sglang_event_error(event)idx = int(event.get("index", 0))cumulative = event.get("text", "")if not isinstance(cumulative, str):@@ -1402,6 +1457,7 @@ class SGLangGenerationAdapter(GenerationAdapter):logger.warning("SGLang stream: skipping non-JSON line: %s", line[:200])continue+ _raise_for_sglang_event_error(event)chunk = _chunk_from_sglang_event(event,previous_cumulative_text=last_cumulative_text,diff --git a/packages/sie_server/src/sie_server/adapters/sglang_vision_extract/adapter.py b/packages/sie_server/src/sie_server/adapters/sglang_vision_extract/adapter.pyindex 7c394b32c..fa579fb67 100644--- a/packages/sie_server/src/sie_server/adapters/sglang_vision_extract/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/sglang_vision_extract/adapter.py@@ -10,7 +10,6 @@ from __future__ import annotationsimport asyncioimport logging-import osimport threadingfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any@@ -78,11 +77,6 @@ class SGLangVisionExtractAdapter(SGLangGenerationAdapter):startup_timeout_s: float | None = None,**kwargs: Any,) -> None:- compat_dir = Path(__file__).with_name("_compat")- child_env = dict(extra_env or {})- inherited_pythonpath = child_env.get("PYTHONPATH", os.environ.get("PYTHONPATH", ""))- child_env["PYTHONPATH"] = os.pathsep.join(path for path in (str(compat_dir), inherited_pythonpath) if path)-super().__init__(model_name_or_path=str(model_name_or_path),max_seq_length=max_seq_length,@@ -95,7 +89,7 @@ class SGLangVisionExtractAdapter(SGLangGenerationAdapter):attention_backend=attention_backend,grammar_backend=None,extra_launch_args=extra_launch_args,- extra_env=child_env,+ extra_env=extra_env,startup_timeout_s=startup_timeout_s,**kwargs,)@@ -114,6 +108,10 @@ class SGLangVisionExtractAdapter(SGLangGenerationAdapter):self._request_loop: asyncio.AbstractEventLoop | None = Noneself._request_loop_thread: threading.Thread | None = None+ def _compat_pythonpath_entries(self) -> tuple[str, ...]:+ """Prepend the code-owned LightOn hook to the generic SGLang path."""+ return (str(Path(__file__).with_name("_compat")), *super()._compat_pythonpath_entries())+@classmethoddef create_for_device(cls, device: str, **kwargs: Any) -> SGLangVisionExtractAdapter:"""Keep the OCR profile CUDA-only instead of applying the MLX text swap."""diff --git a/packages/sie_server/src/sie_server/api/generate.py b/packages/sie_server/src/sie_server/api/generate.pyindex bc53231b5..c6d2433b3 100644--- a/packages/sie_server/src/sie_server/api/generate.py+++ b/packages/sie_server/src/sie_server/api/generate.py@@ -58,7 +58,15 @@ from fastapi import APIRouter, Header, HTTPException, Request, statusfrom fastapi.responses import JSONResponse, StreamingResponsefrom sie_sdk.queue_types import denormalize_model_id-from sie_server.adapters._generation_base import GenerationAdapter, collect_generation+from sie_server.adapters._generation_base import (+ GenerationAdapter,+ ReasoningFormat,+ collect_generation,+ reasoning_starts_in_prompt,+ resolve_reasoning_format,+ suppress_thinking_blocks,+ thinking_blocks_must_be_hidden,+)from sie_server.api.helpers import ModelStateCheckerfrom sie_server.api.validation import validate_machine_profile_header, validate_signed_i64from sie_server.core.runtime_options import apply_generation_runtime_options@@ -571,9 +579,25 @@ def _parse_native_grammar(value: Any) -> GrammarSpec | None:async def _render_native_image_prompt(config: Any, prompt: str, image_count: int) -> str:"""Render one image-aware user turn with the model's own chat template."""+ message = image_first_chat_message(role="user", text=prompt, image_count=image_count)+ return await _render_native_messages_prompt(config, [message], param="images")+++async def _render_native_messages_prompt(+ config: Any,+ messages: list[dict[str, Any]],+ *,+ param: str = "input",+) -> str:+ """Render validated direct-route messages through the model tokenizer.++ Native image generation and direct OpenAI Responses share this bounded,+ pinned tokenizer path so both direct message surfaces use the same model+ template defaults before calling ``GenerationAdapter.generate``.+ """source = config.hf_id or config.weights_pathif not isinstance(source, str | Path):- raise _bad_request("model has no tokenizer source for image generation", param="images")+ raise _bad_request("model has no tokenizer source for message generation", param=param)revision = config.hf_revision if config.hf_id else Nonetry:tokenizer = await asyncio.to_thread(@@ -581,21 +605,24 @@ async def _render_native_image_prompt(config: Any, prompt: str, image_count: intstr(source),revision,)- message = image_first_chat_message(role="user", text=prompt, image_count=image_count)kwargs = dict(config.tasks.generate.chat_template_kwargs or {})- apply_chat_template = cast("Any", tokenizer.apply_chat_template)+ apply_chat_template = tokenizer.apply_chat_templaterendered = await asyncio.to_thread(apply_chat_template,- [message],+ messages,tokenize=False,add_generation_prompt=True,**kwargs,)except Exception as exc:- logger.info("native image prompt render failed for %s: %s", config.name, exc)- raise _bad_request("failed to render the model-native image prompt", param="images") from exc+ logger.info(+ "native message prompt render failed for %s (%s)",+ config.name,+ type(exc).__name__,+ )+ raise _bad_request("failed to render the model-native message prompt", param=param) from excif not isinstance(rendered, str) or not rendered:- raise _bad_request("model-native image prompt rendering returned no text", param="images")+ raise _bad_request("model-native message prompt rendering returned no text", param=param)return rendered@@ -658,6 +685,9 @@ async def _stream_generate_events(logit_bias: dict[str, float] | None,logprobs: bool,top_logprobs: int | None,+ suppress_thinking: bool = False,+ thinking_starts_in_prompt: bool = False,+ reasoning_format: ReasoningFormat = "qwen3",images: list[ImageInput] | None = None,) -> AsyncIterator[str]:"""Yield SIE-native ``GenerateChunk`` SSE lines for ``SIEClient.stream_generate``.@@ -685,7 +715,7 @@ async def _stream_generate_events(if images is not None:optional_adapter_inputs["images"] = imagestry:- async for chunk in adapter.generate(+ chunks = adapter.generate(prompt=prompt,max_new_tokens=max_new_tokens,temperature=temperature,@@ -700,7 +730,14 @@ async def _stream_generate_events(logprobs=logprobs,top_logprobs=top_logprobs,**optional_adapter_inputs,- ):+ )+ if suppress_thinking:+ chunks = suppress_thinking_blocks(+ chunks,+ start_inside=thinking_starts_in_prompt,+ reasoning_format=reasoning_format,+ )+ async for chunk in chunks:if chunk.done:saw_terminal = Truefinish_reason = chunk.finish_reason or "stop"@@ -1031,6 +1068,7 @@ async def generate(generation_prompt = promptif images:generation_prompt = await _render_native_image_prompt(config, prompt, len(images))+ suppress_thinking = thinking_blocks_must_be_hidden(config)# Do not start a potentially expensive model load until the complete# request has passed validation.@@ -1042,6 +1080,11 @@ async def generate(f"Model '{model}' adapter does not support generate (not a GenerationAdapter)",code=ErrorCode.MODEL_NOT_FOUND.value,)+ reasoning_format = resolve_reasoning_format(config, adapter)+ thinking_starts_in_prompt = suppress_thinking and reasoning_starts_in_prompt(+ generation_prompt,+ reasoning_format,+ )if stream_raw:return StreamingResponse(@@ -1061,6 +1104,9 @@ async def generate(grammar=grammar,logprobs=logprobs,top_logprobs=top_logprobs,+ suppress_thinking=suppress_thinking,+ thinking_starts_in_prompt=thinking_starts_in_prompt,+ reasoning_format=reasoning_format,images=images,),media_type="text/event-stream",@@ -1091,6 +1137,12 @@ async def generate(logit_bias=logit_bias,**optional_adapter_inputs,)+ if suppress_thinking:+ chunks = suppress_thinking_blocks(+ chunks,+ start_inside=thinking_starts_in_prompt,+ reasoning_format=reasoning_format,+ )result = await collect_generation(chunks)except Exception as e:logger.warning("generate failed for %s", model, exc_info=True)diff --git a/packages/sie_server/src/sie_server/api/openai_completions.py b/packages/sie_server/src/sie_server/api/openai_completions.pynew file mode 100644index 000000000..ae5e2db31--- /dev/null+++ b/packages/sie_server/src/sie_server/api/openai_completions.py@@ -0,0 +1,672 @@+"""Direct OpenAI-compatible ``/v1/completions`` generation surface.++The cluster gateway remains the production ingress. This route gives the+single-process ``sie-server serve`` topology the same raw-prompt compatibility+surface by calling the loaded :class:`GenerationAdapter` directly, just like+the SIE-native ``/v1/generate/{model}`` route. It deliberately does not proxy a+backend subprocess API: model caps, profile runtime defaults, output parsing,+and adapter fixes therefore remain authoritative in every deployment shape.+"""++from __future__ import annotations++import hashlib+import json+import logging+import math+import os+import time+import uuid+from collections.abc import AsyncIterator+from dataclasses import dataclass+from importlib.metadata import PackageNotFoundError+from importlib.metadata import version as package_version+from typing import Annotated, Any++from fastapi import APIRouter, Header, HTTPException, Request, status+from fastapi.responses import JSONResponse, StreamingResponse+from sie_sdk.queue_types import denormalize_model_id++from sie_server.adapters._generation_base import (+ GenerationAdapter,+ GenerationChunk,+ reasoning_starts_in_prompt,+ resolve_reasoning_format,+ suppress_thinking_blocks,+ thinking_blocks_must_be_hidden,+)+from sie_server.api.helpers import ModelStateChecker, check_sdk_version+from sie_server.api.validation import validate_machine_profile_header, validate_signed_i64+from sie_server.core.runtime_options import apply_generation_runtime_options+from sie_server.observability.tracing import tracer+from sie_server.types.openapi import OpenAICompletionResponseModel++logger = logging.getLogger(__name__)++router = APIRouter(prefix="/v1", tags=["openai-compat"])++_MAX_COMPLETIONS_BODY_BYTES = int(os.environ.get("SIE_GENERATE_MAX_BODY_BYTES", str(24 * 1024 * 1024)))+_MAX_PROMPT_BYTES = int(os.environ.get("SIE_GENERATE_MAX_PROMPT_BYTES", str(4 * 1024 * 1024)))+_MAX_U32 = (1 << 32) - 1+_MAX_F32 = 3.4028234663852886e38+_SUPPORTED_FIELDS = frozenset(+ {+ "model",+ "prompt",+ "max_tokens",+ "temperature",+ "top_p",+ "stop",+ "frequency_penalty",+ "presence_penalty",+ "seed",+ "stream",+ "stream_options",+ "n",+ }+)+_KNOWN_UNSUPPORTED_FIELDS = frozenset({"echo", "suffix", "logprobs", "best_of"})+++class _CompletionError(Exception):+ def __init__(+ self,+ message: str,+ *,+ status_code: int = status.HTTP_400_BAD_REQUEST,+ param: str | None = None,+ code: str = "invalid_request",+ error_type: str | None = None,+ headers: dict[str, str] | None = None,+ ) -> None:+ super().__init__(message)+ self.message = message+ self.status_code = status_code+ self.param = param+ self.code = code+ self.error_type = error_type or (+ "invalid_request_error" if status_code < status.HTTP_500_INTERNAL_SERVER_ERROR else "server_error"+ )+ self.headers = headers+++@dataclass(frozen=True, slots=True)+class _CompletionParams:+ model: str+ prompt: str+ max_tokens: int+ temperature: float | None+ top_p: float | None+ stop: list[str] | None+ frequency_penalty: float | None+ presence_penalty: float | None+ seed: int | None+ stream: bool+ include_usage: bool+++def _error_response(error: _CompletionError) -> JSONResponse:+ return JSONResponse(+ status_code=error.status_code,+ content={+ "error": {+ "message": error.message,+ "type": error.error_type,+ "param": error.param,+ "code": error.code,+ }+ },+ headers=error.headers,+ )+++def _from_http_exception(exc: HTTPException) -> _CompletionError:+ detail = exc.detail+ if isinstance(detail, dict):+ nested = detail.get("error")+ if isinstance(nested, dict):+ detail = nested+ message = str(detail.get("message", "request failed"))+ code = str(detail.get("code", "invalid_request"))+ param = detail.get("param")+ param = param if isinstance(param, str) else None+ else:+ message = str(detail)+ code = "invalid_request"+ param = None+ return _CompletionError(+ message,+ status_code=exc.status_code,+ param=param,+ code=code,+ headers=dict(exc.headers) if exc.headers is not None else None,+ )+++async def _read_json_body(request: Request) -> dict[str, Any]:+ content_length = request.headers.get("content-length")+ if content_length is not None:+ try:+ declared_length = int(content_length)+ except ValueError:+ declared_length = -1+ if declared_length > _MAX_COMPLETIONS_BODY_BYTES:+ raise _CompletionError(+ f"request body exceeds the limit of {_MAX_COMPLETIONS_BODY_BYTES} bytes",+ status_code=status.HTTP_413_CONTENT_TOO_LARGE,+ )++ raw = bytearray()+ async for chunk in request.stream():+ if len(chunk) > _MAX_COMPLETIONS_BODY_BYTES - len(raw):+ raise _CompletionError(+ f"request body exceeds the limit of {_MAX_COMPLETIONS_BODY_BYTES} bytes",+ status_code=status.HTTP_413_CONTENT_TOO_LARGE,+ )+ raw.extend(chunk)+ try:+ body = json.loads(raw)+ except (json.JSONDecodeError, UnicodeDecodeError, ValueError) as exc:+ raise _CompletionError("request body must be a JSON object") from exc+ if not isinstance(body, dict):+ raise _CompletionError("request body must be a JSON object")+ return body+++def _number(value: Any, *, param: str, minimum: float, maximum: float | None = None) -> float | None:+ if value is None:+ return None+ if isinstance(value, bool) or not isinstance(value, int | float):+ raise _CompletionError(f"'{param}' must be a number", param=param)+ try:+ parsed = float(value)+ except (OverflowError, ValueError) as exc:+ raise _CompletionError(f"'{param}' must be a finite number", param=param) from exc+ if not math.isfinite(parsed) or parsed < minimum or (maximum is not None and parsed > maximum):+ interval = f"[{minimum:g}, {maximum:g}]" if maximum is not None else f">= {minimum:g}"+ raise _CompletionError(f"'{param}' must be a finite number in {interval}", param=param)+ return parsed+++def _parse_params(body: dict[str, Any]) -> _CompletionParams:+ for field in _KNOWN_UNSUPPORTED_FIELDS:+ if field in body:+ raise _CompletionError(+ f"'{field}' is not supported by this endpoint",+ param=field,+ code="unsupported_field",+ )+ unknown = set(body) - _SUPPORTED_FIELDS+ if unknown:+ field = sorted(unknown)[0]+ raise _CompletionError(+ f"'{field}' is not supported by this endpoint",+ param=field,+ code="unsupported_field",+ )++ model = body.get("model")+ if not isinstance(model, str) or not model:+ raise _CompletionError('field "model" is required', param="model")++ prompt_raw = body.get("prompt")+ if isinstance(prompt_raw, str):+ prompt = prompt_raw+ elif isinstance(prompt_raw, list) and len(prompt_raw) == 1 and isinstance(prompt_raw[0], str):+ prompt = prompt_raw[0]+ elif isinstance(prompt_raw, list):+ if len(prompt_raw) != 1:+ raise _CompletionError(+ "batched array prompts are not supported; send one prompt string",+ param="prompt",+ code="unsupported_field",+ )+ raise _CompletionError("'prompt' array entries must be strings", param="prompt")+ else:+ raise _CompletionError('field "prompt" is required and must be a string', param="prompt")+ prompt_bytes = len(prompt.encode("utf-8"))+ if prompt_bytes > _MAX_PROMPT_BYTES:+ raise _CompletionError(+ f"'prompt' is {prompt_bytes} bytes, exceeds the limit of {_MAX_PROMPT_BYTES} bytes",+ status_code=status.HTTP_413_CONTENT_TOO_LARGE,+ param="prompt",+ code="context_exceeded",+ )++ stream_raw = body.get("stream")+ if stream_raw is not None and not isinstance(stream_raw, bool):+ raise _CompletionError("'stream' must be a boolean", param="stream")+ stream = bool(stream_raw)++ include_usage = False+ stream_options = body.get("stream_options")+ if stream_options is not None:+ if not isinstance(stream_options, dict):+ raise _CompletionError("'stream_options' must be a JSON object", param="stream_options")+ unknown_options = set(stream_options) - {"include_usage"}+ if unknown_options:+ key = sorted(unknown_options)[0]+ raise _CompletionError(+ f"'stream_options.{key}' is not supported by this endpoint",+ param=f"stream_options.{key}",+ code="unsupported_field",+ )+ include_usage_raw = stream_options.get("include_usage")+ if include_usage_raw is not None and not isinstance(include_usage_raw, bool):+ raise _CompletionError(+ "'stream_options.include_usage' must be a boolean",+ param="stream_options.include_usage",+ )+ include_usage = bool(include_usage_raw)++ n = body.get("n")+ if n is not None:+ if isinstance(n, bool) or not isinstance(n, int):+ raise _CompletionError("'n' must be an integer", param="n")+ if n <= 0:+ raise _CompletionError("'n' must be a positive integer", param="n")+ if n != 1:+ raise _CompletionError(+ "'n' > 1 is not yet supported on /v1/completions",+ param="n",+ code="unsupported_field",+ )++ max_tokens = body.get("max_tokens", 16)+ if max_tokens is None:+ max_tokens = 16+ if isinstance(max_tokens, bool) or not isinstance(max_tokens, int) or not (1 <= max_tokens <= _MAX_U32):+ raise _CompletionError("'max_tokens' must be a positive integer", param="max_tokens")++ temperature = _number(body.get("temperature"), param="temperature", minimum=0, maximum=_MAX_F32)+ top_p = _number(body.get("top_p"), param="top_p", minimum=0)+ if top_p is not None and top_p == 0:+ raise _CompletionError("'top_p' must be a number in (0, 1]", param="top_p")+ if top_p is not None and top_p > 1:+ raise _CompletionError("'top_p' must be a number in (0, 1]", param="top_p")+ frequency_penalty = _number(+ body.get("frequency_penalty"),+ param="frequency_penalty",+ minimum=-2,+ maximum=2,+ )+ presence_penalty = _number(+ body.get("presence_penalty"),+ param="presence_penalty",+ minimum=-2,+ maximum=2,+ )++ try:+ seed = validate_signed_i64(body.get("seed"), param="seed")+ except ValueError as exc:+ raise _CompletionError(str(exc), param="seed") from exc++ stop_raw = body.get("stop")+ if stop_raw is None:+ stop = None+ elif isinstance(stop_raw, str):+ if not stop_raw:+ raise _CompletionError("'stop' must not contain empty strings", param="stop")+ stop = [stop_raw]+ elif isinstance(stop_raw, list) and all(isinstance(item, str) for item in stop_raw):+ if any(not item for item in stop_raw):+ raise _CompletionError("'stop' must not contain empty strings", param="stop")+ stop = [str(item) for item in stop_raw] or None+ else:+ raise _CompletionError("'stop' must be a string or array of strings", param="stop")++ return _CompletionParams(+ model=model,+ prompt=prompt,+ max_tokens=max_tokens,+ temperature=temperature,+ top_p=top_p,+ stop=stop,+ frequency_penalty=frequency_penalty,+ presence_penalty=presence_penalty,+ seed=seed,+ stream=stream,+ include_usage=include_usage,+ )+++def _system_fingerprint(model: str) -> str:+ try:+ version = package_version("sie-server")+ except PackageNotFoundError: # pragma: no cover - editable source always has metadata in tests+ version = "unknown"+ payload = f"{model}\0{version}".encode()+ return f"fp_{hashlib.blake2b(payload, digest_size=8).hexdigest()}"+++def _finish_reason(value: str | None) -> str:+ if value in {"length", "tool_calls", "content_filter", "function_call"}:+ return value+ return "stop"+++def _chunk_body(+ *,+ completion_id: str,+ created: int,+ model: str,+ text: str,+ finish_reason: str | None,+) -> dict[str, Any]:+ return {+ "id": completion_id,+ "object": "text_completion",+ "created": created,+ "model": model,+ "system_fingerprint": _system_fingerprint(model),+ "choices": [{"text": text, "index": 0, "finish_reason": finish_reason}],+ }+++async def _stream_completion(+ chunks: AsyncIterator[GenerationChunk],+ *,+ completion_id: str,+ created: int,+ model: str,+ include_usage: bool,+) -> AsyncIterator[str]:+ terminal: GenerationChunk | None = None+ try:+ async for chunk in chunks:+ if chunk.done:+ terminal = chunk+ cancelled = chunk.done and chunk.finish_reason == "cancelled"+ body = _chunk_body(+ completion_id=completion_id,+ created=created,+ model=model,+ text=chunk.text_delta,+ finish_reason=None if cancelled else (_finish_reason(chunk.finish_reason) if chunk.done else None),+ )+ if cancelled:+ body["error"] = {+ "message": "generation was cancelled before completion",+ "type": "server_error",+ "param": None,+ "code": "generation_cancelled",+ }+ elif chunk.done and (chunk.finish_reason == "error" or chunk.error_code or chunk.error_message):+ body["error"] = {+ "message": chunk.error_message or "generation terminated with an upstream error",+ "type": "server_error",+ "param": None,+ "code": chunk.error_code or "inference_error",+ }+ yield f"data: {json.dumps(body)}\n\n"+ if chunk.done:+ break+ except Exception: # noqa: BLE001 - the stream must terminate in-band after headers are committed+ logger.warning("OpenAI completion failed mid-stream", exc_info=True)+ body = _chunk_body(+ completion_id=completion_id,+ created=created,+ model=model,+ text="",+ finish_reason="stop",+ )+ body["error"] = {+ "message": "internal error during generation",+ "type": "server_error",+ "param": None,+ "code": "inference_error",+ }+ yield f"data: {json.dumps(body)}\n\n"+ yield "data: [DONE]\n\n"+ return+ finally:+ aclose = getattr(chunks, "aclose", None)+ if aclose is not None:+ await aclose()++ if terminal is None:+ body = _chunk_body(+ completion_id=completion_id,+ created=created,+ model=model,+ text="",+ finish_reason="stop",+ )+ body["error"] = {+ "message": "generation stream ended before a terminal event",+ "type": "server_error",+ "param": None,+ "code": "inference_error",+ }+ yield f"data: {json.dumps(body)}\n\n"+ elif (+ terminal.finish_reason not in {"cancelled", "error"}+ and not terminal.error_code+ and not terminal.error_message+ and include_usage+ and terminal.prompt_tokens is not None+ and terminal.completion_tokens is not None+ ):+ usage = {+ "prompt_tokens": terminal.prompt_tokens,+ "completion_tokens": terminal.completion_tokens,+ "total_tokens": terminal.prompt_tokens + terminal.completion_tokens,+ }+ yield f"data: {+ json.dumps(+ {+ 'id': completion_id,+ 'object': 'text_completion',+ 'created': created,+ 'model': model,+ 'system_fingerprint': _system_fingerprint(model),+ 'choices': [],+ 'usage': usage,+ }+ )+ }\n\n"+ yield "data: [DONE]\n\n"+++async def _collect_completion(chunks: AsyncIterator[GenerationChunk]) -> tuple[str, GenerationChunk]:+ text_parts: list[str] = []+ terminal: GenerationChunk | None = None+ try:+ async for chunk in chunks:+ if chunk.text_delta:+ text_parts.append(chunk.text_delta)+ if chunk.done:+ terminal = chunk+ break+ finally:+ aclose = getattr(chunks, "aclose", None)+ if aclose is not None:+ await aclose()+ if terminal is None:+ raise _CompletionError(+ "generation stream ended before a terminal event",+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ code="inference_error",+ )+ if terminal.finish_reason == "error" or terminal.error_code or terminal.error_message:+ raise _CompletionError(+ terminal.error_message or "generation terminated with an upstream error",+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ code=terminal.error_code or "inference_error",+ )+ if terminal.finish_reason == "cancelled":+ raise _CompletionError(+ "generation was cancelled before completion",+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ code="generation_cancelled",+ )+ return "".join(text_parts), terminal+++ "/completions",+ response_model=None,+ responses={+ 200: {+ "description": "OpenAI text completion, or text_completion Server-Sent Events when stream is true",+ "model": OpenAICompletionResponseModel,+ "content": {+ "text/event-stream": {+ "schema": {"type": "string", "description": "OpenAI text_completion events ending in [DONE]"}+ }+ },+ },+ 400: {"description": "Invalid or unsupported request"},+ 404: {"description": "Model not found"},+ 413: {"description": "Request body or prompt is too large"},+ 500: {"description": "Generation failed"},+ 503: {"description": "Model loading or temporarily unavailable"},+ },+ openapi_extra={+ "requestBody": {+ "required": True,+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/OpenAICompletionRequestModel"}}},+ }+ },+)+async def completions(+ http_request: Request,+ x_machine_profile: Annotated[str | None, Header(alias="X-SIE-MACHINE-PROFILE")] = None,+) -> JSONResponse | StreamingResponse:+ """Generate one raw-prompt OpenAI legacy completion."""+ try:+ validate_machine_profile_header(x_machine_profile)+ check_sdk_version(http_request)+ params = _parse_params(await _read_json_body(http_request))++ registry = http_request.app.state.registry+ registry_key = denormalize_model_id(params.model)+ with tracer.start_as_current_span("openai_completions") as span:+ span.set_attribute("model", params.model)+ checker = ModelStateChecker(registry, registry_key, span)+ checker.check_exists()+ checker.check_not_failed()+ checker.check_not_unloading()+ checker.check_not_loading()++ config = registry.get_config(registry_key)+ generate_task = getattr(config.tasks, "generate", None)+ if generate_task is None:+ raise _CompletionError(+ f"Model '{params.model}' does not support generation",+ param="model",+ code="model_not_found",+ )+ if params.max_tokens > generate_task.max_output_tokens:+ raise _CompletionError(+ f"max_tokens ({params.max_tokens}) exceeds model cap ({generate_task.max_output_tokens})",+ param="max_tokens",+ code="context_exceeded",+ )++ runtime_params: dict[str, Any] = {+ "prompt": params.prompt,+ "max_new_tokens": params.max_tokens,+ **{+ key: value+ for key, value in (+ ("temperature", params.temperature),+ ("top_p", params.top_p),+ ("stop", params.stop),+ ("frequency_penalty", params.frequency_penalty),+ ("presence_penalty", params.presence_penalty),+ ("seed", params.seed),+ )+ if value is not None+ },+ }+ try:+ runtime_params = apply_generation_runtime_options(config, None, runtime_params)+ except ValueError as exc:+ raise _CompletionError(str(exc), code="invalid_request") from exc++ await checker.ensure_loaded(registry.device)+ adapter = registry.get(registry_key)+ registry.touch_lru(registry_key)+ if not isinstance(adapter, GenerationAdapter):+ raise _CompletionError(+ f"Model '{params.model}' adapter does not support generation",+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ param="model",+ code="inference_error",+ )++ canonical_model = getattr(config, "name", None) or registry_key+ completion_id = f"cmpl-{uuid.uuid4().hex}"+ created = int(time.time())+ chunks = adapter.generate(+ prompt=params.prompt,+ max_new_tokens=params.max_tokens,+ temperature=float(runtime_params.get("temperature", 1.0)),+ top_p=float(runtime_params.get("top_p", 1.0)),+ stop=runtime_params.get("stop"),+ frequency_penalty=runtime_params.get("frequency_penalty"),+ presence_penalty=runtime_params.get("presence_penalty"),+ top_k=runtime_params.get("top_k"),+ min_new_tokens=runtime_params.get("min_tokens"),+ seed=runtime_params.get("seed"),+ )+ if thinking_blocks_must_be_hidden(config):+ reasoning_format = resolve_reasoning_format(config, adapter)+ chunks = suppress_thinking_blocks(+ chunks,+ start_inside=reasoning_starts_in_prompt(params.prompt, reasoning_format),+ reasoning_format=reasoning_format,+ )+ if params.stream:+ return StreamingResponse(+ _stream_completion(+ chunks,+ completion_id=completion_id,+ created=created,+ model=canonical_model,+ include_usage=params.include_usage,+ ),+ media_type="text/event-stream",+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},+ )++ try:+ text, terminal = await _collect_completion(chunks)+ except _CompletionError:+ raise+ except Exception as exc:+ logger.warning("OpenAI completion failed for %s", params.model, exc_info=True)+ raise _CompletionError(+ "internal error during generation",+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ code="inference_error",+ ) from exc+ prompt_tokens = terminal.prompt_tokens or 0+ completion_tokens = terminal.completion_tokens or 0+ return JSONResponse(+ content={+ "id": completion_id,+ "object": "text_completion",+ "created": created,+ "model": canonical_model,+ "choices": [+ {+ "text": text,+ "index": 0,+ "finish_reason": _finish_reason(terminal.finish_reason),+ }+ ],+ "system_fingerprint": _system_fingerprint(canonical_model),+ "usage": {+ "prompt_tokens": prompt_tokens,+ "completion_tokens": completion_tokens,+ "total_tokens": prompt_tokens + completion_tokens,+ },+ }+ )+ except _CompletionError as exc:+ return _error_response(exc)+ except HTTPException as exc:+ return _error_response(_from_http_exception(exc))diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.pyindex 07579bf44..71dce87ba 100644--- a/packages/sie_server/src/sie_server/api/openai_local.py+++ b/packages/sie_server/src/sie_server/api/openai_local.py@@ -1,43 +1,57 @@-"""Mac-local OpenAI-compatible surfaces: ``/v1/chat/completions`` + ``/v1/rerank``.+"""Direct OpenAI-compatible surfaces: ``/v1/chat/completions`` + ``/v1/rerank``.-These complete the local OpenAI surface for Apple-Silicon serving (alongside the-existing ``/v1/embeddings``), so any OpenAI/Cohere client or tool can hit the-local endpoint.+These complete the single-node OpenAI surface (alongside the existing+``/v1/embeddings``), so OpenAI/Cohere clients can use the worker HTTP server+directly in either the Apple-Silicon or CUDA image.-- ``/v1/chat/completions`` proxies the managed MLX generation subprocess- (``mlx_lm.server``). Chat templating, streaming, and structured output come- free from the child; we just resolve the model, ensure it is loaded, and- stream-proxy. Only available where generation runs via MLX (Apple Silicon) —- elsewhere it returns 501 (the production ingress is the Rust gateway).+- ``/v1/chat/completions`` proxies the managed generation subprocess: MLX on+ Apple Silicon and SGLang on CUDA. Chat templating, streaming, tool parsing,+ and structured output remain owned by that already-loaded child. The proxy+ pins the request to the child's loopback URL and served model identity; a+ client cannot select another upstream.- ``/v1/rerank`` wraps the in-process score adapter in the Cohere/OpenAI rerankshape (``{query, documents, top_n}`` -> ``{results: [{index, relevance_score}]}``).-These routes are mounted on the worker's own FastAPI app and are a local-dev /+These routes are mounted on the worker's own FastAPI app as a direct-container /single-node convenience, mirroring the existing direct ``/v1/generate`` and-``/v1/embeddings`` routes — no traffic reaches them in a real cluster.+``/v1/embeddings`` routes. The Rust gateway remains the production cluster API+authority."""from __future__ import annotations+import asyncioimport jsonimport logging+import mathimport os-from typing import Annotated, Any+from collections.abc import AsyncIterator+from typing import Annotated, Any, cast+from urllib.parse import urlsplitimport httpxfrom fastapi import APIRouter, Header, HTTPException, Request, statusfrom fastapi.responses import JSONResponse, Response, StreamingResponsefrom sie_sdk.queue_types import denormalize_model_id+from sie_server.adapters._generation_base import (+ ReasoningFormat,+ ThinkingBlockStripper,+ resolve_reasoning_format,+ thinking_blocks_must_be_hidden,+)from sie_server.adapters.mlx.generation import MLXGenerationAdapter, normalize_mlx_seed+from sie_server.adapters.sglang.generation import SGLangGenerationAdapterfrom sie_server.api.helpers import ModelStateCheckerfrom sie_server.api.options import resolve_runtime_optionsfrom sie_server.api.score import score_usage_from_outputfrom sie_server.api.validation import validate_machine_profile_header, validate_signed_i64+from sie_server.config.model import validate_chat_template_kwargsfrom sie_server.core.inference_output import ScoreOutputfrom sie_server.core.score_cost import MAX_SCORE_ITEMS, build_score_prepared_itemsfrom sie_server.core.timing import RequestTimingfrom sie_server.observability.tracing import tracer+from sie_server.processors.streaming import _decode_data_uri_imagefrom sie_server.types.inputs import Itemfrom sie_server.types.responses import ErrorCode@@ -45,17 +59,109 @@ logger = logging.getLogger(__name__)router = APIRouter(prefix="/v1", tags=["openai-compat"])-# Inter-chunk read timeout — bounded so a wedged child can't hang the request forever-# (this proxy is the direct ingress on Mac; there is no worker/abort layer behind it).-# Override via SIE_MLX_READ_TIMEOUT_S. Connect/write/pool stay short.+# Inter-chunk read timeout — bounded so a wedged child cannot hang the direct+# ingress forever. Keep the established MLX override name for compatibility;+# it applies to either managed generation child on this route._PROXY_READ_TIMEOUT_S = float(os.environ.get("SIE_MLX_READ_TIMEOUT_S", "300"))_PROXY_TIMEOUT = httpx.Timeout(connect=10.0, read=_PROXY_READ_TIMEOUT_S, write=10.0, pool=10.0)# Cap the request body so a huge messages/documents array can't be buffered/forwarded# unbounded (the gateway caps prod ingress; these local routes must cap themselves)._MAX_BODY_BYTES = int(os.environ.get("SIE_CHAT_MAX_BODY_BYTES", str(8 * 1024 * 1024)))+# Bound even a misbehaving local child independently from its token limit. The+# token cap below remains authoritative for normal output; this is a final byte+# fence for malformed/non-token responses.+_MAX_CHAT_RESPONSE_BYTES = int(os.environ.get("SIE_CHAT_MAX_RESPONSE_BYTES", str(32 * 1024 * 1024)))+_MAX_CHAT_MESSAGES = 4096+_MAX_CHAT_CHOICES = 128+_MAX_U32 = (1 << 32) - 1+_ALLOWED_CHAT_ROLES = frozenset({"system", "user", "assistant", "tool", "developer"})# Compatibility requests project onto the same native score bound._MAX_RERANK_DOCS = MAX_SCORE_ITEMS+# Mirror the gateway's public chat field boundary, minus controls that require+# gateway-owned admission/routing translation (best_of, LoRA selection, cache+# keys). Most importantly this excludes SGLang's backend/DP/custom-processor+# extensions, so the public body cannot steer the managed child or execute a+# client-supplied logit processor.+_CUDA_CHAT_FIELDS = frozenset(+ {+ "model",+ "messages",+ "max_completion_tokens",+ "max_tokens",+ "temperature",+ "top_p",+ "stop",+ "frequency_penalty",+ "presence_penalty",+ "top_k",+ "repetition_penalty",+ "min_tokens",+ "chat_template_kwargs",+ "n",+ "user",+ "safety_identifier",+ "seed",+ "logprobs",+ "top_logprobs",+ "logit_bias",+ "response_format",+ "stream",+ "tools",+ "tool_choice",+ "parallel_tool_calls",+ "stream_options",+ }+)++# mlx_lm's public chat request fields, excluding child process controls such as+# model adapters and speculative-decoding configuration. Validate this boundary+# before a potentially expensive MLX model download.+_MLX_CHAT_FIELDS = frozenset(+ {+ "model",+ "messages",+ "max_completion_tokens",+ "max_tokens",+ "temperature",+ "top_p",+ "top_k",+ "min_p",+ "repetition_penalty",+ "repetition_context_size",+ "logit_bias",+ "logprobs",+ "top_logprobs",+ "seed",+ "chat_template_kwargs",+ "stop",+ "stream",+ "stream_options",+ "tools",+ "role_mapping",+ }+)++_DEFAULT_SAMPLING_TO_CHAT_FIELD = {+ "temperature": "temperature",+ "top_p": "top_p",+ "top_k": "top_k",+ "min_p": "min_p",+ "min_new_tokens": "min_tokens",+ "frequency_penalty": "frequency_penalty",+ "presence_penalty": "presence_penalty",+ "repetition_penalty": "repetition_penalty",+ "seed": "seed",+ "sampling_seed": "seed",+}++# ``mlx_lm.server`` accepts this subset of model-config sampling defaults on+# its OpenAI chat route. Keep parity with the MLX adapter's native generation+# path and do not forward CUDA-only penalty knobs.+_MLX_DEFAULT_SAMPLING_FIELDS = frozenset(+ {"temperature", "top_p", "top_k", "min_p", "repetition_penalty", "seed", "sampling_seed"}+)+def _bad_request(message: str, *, param: str | None = None, code: str | None = None) -> HTTPException:detail: dict[str, Any] = {"code": code or ErrorCode.INVALID_INPUT.value, "message": message}@@ -64,12 +170,17 @@ def _bad_request(message: str, *, param: str | None = None, code: str | None = Nreturn HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)-def _validate_mlx_seed(value: Any) -> int | None:- """Validate the public signed-i64 seed and convert it for MLX's uint64 API."""+def _validate_chat_seed(value: Any) -> int | None:+ """Validate the public signed-i64 seed without changing its bit pattern."""try:- validated = validate_signed_i64(value, param="seed")+ return validate_signed_i64(value, param="seed")except ValueError as exc:raise _bad_request(str(exc), param="seed") from exc+++def _validate_mlx_seed(value: Any) -> int | None:+ """Validate the public signed-i64 seed and convert it for MLX's uint64 API."""+ validated = _validate_chat_seed(value)return None if validated is None else normalize_mlx_seed(validated)@@ -85,12 +196,14 @@ async def _read_json_body(http_request: Request) -> dict[str, Any]:status_code=status.HTTP_413_CONTENT_TOO_LARGE,detail={"code": ErrorCode.INPUT_TOO_LONG.value, "message": "request body too large"},)- raw = await http_request.body()- if len(raw) > _MAX_BODY_BYTES:- raise HTTPException(- status_code=status.HTTP_413_CONTENT_TOO_LARGE,- detail={"code": ErrorCode.INPUT_TOO_LONG.value, "message": "request body too large"},- )+ raw = bytearray()+ async for chunk in http_request.stream():+ if len(raw) + len(chunk) > _MAX_BODY_BYTES:+ raise HTTPException(+ status_code=status.HTTP_413_CONTENT_TOO_LARGE,+ detail={"code": ErrorCode.INPUT_TOO_LONG.value, "message": "request body too large"},+ )+ raw.extend(chunk)try:body = json.loads(raw)except (ValueError, TypeError) as exc:@@ -100,20 +213,540 @@ async def _read_json_body(http_request: Request) -> dict[str, Any]:return body-def _unsupported_chat(model: str) -> HTTPException:+def _unsupported_chat(model: str, device: object) -> HTTPException:return HTTPException(status_code=status.HTTP_501_NOT_IMPLEMENTED,detail={"code": "unsupported_operation","message": (- f"/v1/chat/completions for '{model}' is only served by the local MLX "- "generation backend (Apple Silicon). Use the Rust gateway in a cluster."+ f"/v1/chat/completions for '{model}' has no supported managed generation "+ f"child on device '{device}'. Use an MLX or SGLang generation profile."),},)-# -- /v1/chat/completions (proxy to the MLX subprocess) ----------------------+def _upstream_error_response(+ message: str = "upstream generation request failed",+ *,+ response_status: int = status.HTTP_502_BAD_GATEWAY,+) -> JSONResponse:+ return JSONResponse(+ status_code=response_status,+ content={+ "error": {+ "message": message,+ "type": "upstream_error",+ "param": None,+ "code": "upstream_error",+ }+ },+ )+++def _translated_upstream_status(upstream_status: int) -> int:+ """Preserve child request errors; collapse engine failures to 502."""+ if status.HTTP_400_BAD_REQUEST <= upstream_status < status.HTTP_500_INTERNAL_SERVER_ERROR:+ return upstream_status+ return status.HTTP_502_BAD_GATEWAY+++def _upstream_error_event(message: str = "upstream stream error") -> bytes:+ payload = json.dumps(+ {+ "error": {+ "message": message,+ "type": "upstream_error",+ "param": None,+ "code": "upstream_error",+ }+ },+ separators=(",", ":"),+ )+ return f"data: {payload}\n\ndata: [DONE]\n\n".encode()+++def _validate_optional_positive_int(body: dict[str, Any], field: str) -> int | None:+ value = body.get(field)+ if value is None:+ return None+ if isinstance(value, bool) or not isinstance(value, int) or not (1 <= value <= _MAX_U32):+ raise _bad_request(f"'{field}' must be a positive integer", param=field)+ return value+++def _validate_chat_messages(messages: list[Any]) -> None:+ """Reject malformed message structure before loading a model child."""+ for index, message in enumerate(messages):+ path = f"messages[{index}]"+ if not isinstance(message, dict):+ raise _bad_request(f"'{path}' must be an object", param=path)++ role = message.get("role")+ if not isinstance(role, str) or role not in _ALLOWED_CHAT_ROLES:+ raise _bad_request(+ f"'{path}.role' must be one of {sorted(_ALLOWED_CHAT_ROLES)!r}",+ param=f"{path}.role",+ )++ tool_calls = message.get("tool_calls")+ if tool_calls is not None:+ if not isinstance(tool_calls, list):+ raise _bad_request(f"'{path}.tool_calls' must be an array", param=f"{path}.tool_calls")+ for call_index, tool_call in enumerate(tool_calls):+ if not isinstance(tool_call, dict):+ call_path = f"{path}.tool_calls[{call_index}]"+ raise _bad_request(f"'{call_path}' must be an object", param=call_path)++ tool_call_id = message.get("tool_call_id")+ if role == "tool":+ if not isinstance(tool_call_id, str) or not tool_call_id:+ raise _bad_request(+ f"'{path}.tool_call_id' is required and must be a non-empty string",+ param=f"{path}.tool_call_id",+ )+ elif tool_call_id is not None:+ raise _bad_request(+ f"'{path}.tool_call_id' is only valid on role 'tool' messages",+ param=f"{path}.tool_call_id",+ )++ content = message.get("content")+ if content is None and role == "assistant" and tool_calls is not None:+ continue+ if isinstance(content, str):+ continue+ if not isinstance(content, list):+ raise _bad_request(+ f"'{path}.content' must be a string or content-part array",+ param=f"{path}.content",+ )+ for part_index, part in enumerate(content):+ part_path = f"{path}.content[{part_index}]"+ if not isinstance(part, dict):+ raise _bad_request(f"'{part_path}' must be an object", param=part_path)+ part_obj = cast("dict[str, Any]", part)+ part_type = part_obj.get("type")+ if part_type in {"text", "input_text"}:+ if not isinstance(part_obj.get("text"), str):+ raise _bad_request(+ f"'{part_path}.text' is required and must be a string",+ param=f"{part_path}.text",+ )+ elif part_type in {"image_url", "input_image"}:+ if "image_url" not in part_obj:+ raise _bad_request(+ f"'{part_path}.image_url' is required for image content parts",+ param=f"{part_path}.image_url",+ )+ else:+ raise _bad_request(+ f"unsupported content part type {part_type!r}",+ param=f"{part_path}.type",+ code="unsupported_field",+ )+++def _validate_cuda_chat_body(body: dict[str, Any]) -> None:+ unknown_fields = body.keys() - _CUDA_CHAT_FIELDS+ if unknown_fields:+ unknown = sorted(unknown_fields)[0]+ raise _bad_request(f"field '{unknown}' is not supported", param=unknown, code="unsupported_field")++ n = body.get("n")+ if n is not None and (isinstance(n, bool) or not isinstance(n, int) or not (1 <= n <= _MAX_CHAT_CHOICES)):+ raise _bad_request(f"'n' must be an integer in [1, {_MAX_CHAT_CHOICES}]", param="n")++ min_tokens = body.get("min_tokens")+ if min_tokens is not None and (+ isinstance(min_tokens, bool) or not isinstance(min_tokens, int) or not (0 <= min_tokens <= _MAX_U32)+ ):+ raise _bad_request("'min_tokens' must be an integer >= 0", param="min_tokens")++ for field, lower, upper, lower_inclusive in (+ ("temperature", 0.0, math.inf, True),+ ("top_p", 0.0, 1.0, False),+ ("frequency_penalty", -2.0, 2.0, True),+ ("presence_penalty", -2.0, 2.0, True),+ ("repetition_penalty", 0.0, 2.0, False),+ ):+ value = body.get(field)+ if value is None:+ continue+ numeric = isinstance(value, int | float) and not isinstance(value, bool)+ try:+ float_value = float(value) if numeric else math.nan+ except (OverflowError, ValueError):+ float_value = math.nan+ in_range = math.isfinite(float_value) and float_value <= upper+ in_range = in_range and (float_value >= lower if lower_inclusive else float_value > lower)+ if not in_range:+ left = "[" if lower_inclusive else "("+ raise _bad_request(f"'{field}' must be a finite number in {left}{lower}, {upper}]", param=field)++ top_k = body.get("top_k")+ if top_k is not None and (isinstance(top_k, bool) or not isinstance(top_k, int) or top_k < 1):+ raise _bad_request("'top_k' must be an integer >= 1", param="top_k")+++def _validate_mlx_chat_body(body: dict[str, Any]) -> None:+ unknown_fields = body.keys() - _MLX_CHAT_FIELDS+ if unknown_fields:+ unknown = sorted(unknown_fields)[0]+ raise _bad_request(f"field '{unknown}' is not supported", param=unknown, code="unsupported_field")+++def _validate_chat_message_media(messages: Any) -> None:+ """Reject child-side remote media fetches before proxying to a child."""++ def _walk(value: Any, path: str) -> None:+ if isinstance(value, list):+ for index, item in enumerate(value):+ _walk(item, f"{path}[{index}]")+ return+ if not isinstance(value, dict):+ return+ for key, item in value.items():+ item_path = f"{path}.{key}"+ if key == "image_url":+ url = item.get("url") if isinstance(item, dict) else item+ if not isinstance(url, str) or not url:+ raise _bad_request(+ f"'{item_path}' must be a non-empty string or an object with a non-empty 'url'",+ param=item_path,+ )+ try:+ _decode_data_uri_image(url)+ except ValueError as exc:+ raise _bad_request(str(exc), param=item_path) from exc+ continue+ if key in {"audio_url", "video_url"}:+ raise _bad_request(+ f"'{item_path}' is not supported; remote media fetching is disabled",+ param=item_path,+ code="unsupported_field",+ )+ _walk(item, item_path)++ _walk(messages, "messages")+++def _validated_child_chat_url(server_url: object) -> str:+ """Build the only allowed upstream URL from an adapter-owned loopback URL."""+ if not isinstance(server_url, str):+ raise ValueError("generation child did not publish a server URL")+ parsed = urlsplit(server_url)+ try:+ port = parsed.port+ except ValueError as exc:+ raise ValueError("generation child published an invalid server port") from exc+ if (+ parsed.scheme != "http"+ or parsed.hostname not in {"localhost", "127.0.0.1", "::1"}+ or port is None+ or parsed.username is not None+ or parsed.password is not None+ or parsed.path not in {"", "/"}+ or parsed.query+ or parsed.fragment+ ):+ raise ValueError("generation child URL must be an explicit loopback HTTP origin")+ return f"{server_url.rstrip('/')}/v1/chat/completions"+++def _merge_stops(request_stop: Any, configured: Any) -> Any:+ defaults = [item for item in configured or [] if isinstance(item, str) and item]+ if not defaults:+ return request_stop+ if request_stop is None:+ return defaults+ if isinstance(request_stop, str):+ merged = [request_stop]+ elif isinstance(request_stop, list):+ merged = list(request_stop)+ else:+ # Let the child produce the contract error for a malformed client stop.+ return request_stop+ merged.extend(item for item in defaults if item not in merged)+ return merged+++def _prepare_sglang_body(+ body: dict[str, Any],+ *,+ config: Any,+ adapter: SGLangGenerationAdapter,+ max_completion_tokens: int | None,+ max_tokens: int | None,+ seed: int | None,+) -> dict[str, Any]:+ proxied = dict(body)+ proxied["model"] = adapter.served_model_name+ # SIE owns these edge-only identifiers; do not send unknown metadata into+ # the engine process.+ proxied.pop("safety_identifier", None)++ cap = config.tasks.generate.max_output_tokens+ requested_cap = max_completion_tokens if max_completion_tokens is not None else max_tokens+ if requested_cap is not None and requested_cap > cap:+ field = "max_completion_tokens" if max_completion_tokens is not None else "max_tokens"+ raise _bad_request(+ f"{field} ({requested_cap}) exceeds model cap ({cap})",+ param=field,+ )+ if max_completion_tokens is not None:+ proxied["max_completion_tokens"] = max_completion_tokens+ # Preferred field wins. Do not forward an ignored legacy value that+ # could exceed the cap or trigger version-specific child validation.+ proxied.pop("max_tokens", None)+ effective_cap = max_completion_tokens+ else:+ proxied["max_tokens"] = max_tokens if max_tokens is not None else cap+ effective_cap = proxied["max_tokens"]+ if seed is not None:+ proxied["seed"] = seed++ profile = config.resolve_profile("default")+ runtime = dict(profile.runtime)+ default_sampling = runtime.get("default_sampling")+ if isinstance(default_sampling, dict):+ for config_field, chat_field in _DEFAULT_SAMPLING_TO_CHAT_FIELD.items():+ if config_field in default_sampling and proxied.get(chat_field) is None:+ proxied[chat_field] = default_sampling[config_field]++ min_tokens = proxied.get("min_tokens")+ if isinstance(min_tokens, int) and not isinstance(min_tokens, bool) and min_tokens > effective_cap:+ if body.get("min_tokens") is not None:+ raise _bad_request(+ f"min_tokens ({min_tokens}) must not exceed the output cap ({effective_cap})",+ param="min_tokens",+ )+ # Profile minimums are soft defaults, matching GenerationAdapter.+ proxied["min_tokens"] = effective_cap++ configured_stops = runtime.get("stop_tokens")+ merged_stop = _merge_stops(body.get("stop"), configured_stops)+ if merged_stop is not None:+ proxied["stop"] = merged_stop++ request_template_kwargs = body.get("chat_template_kwargs")+ merged_template_kwargs = dict(request_template_kwargs or {})+ operator_template_kwargs = config.tasks.generate.chat_template_kwargs+ if isinstance(operator_template_kwargs, dict):+ # Match queued generation: operator YAML is authoritative on conflict.+ merged_template_kwargs.update(operator_template_kwargs)+ if merged_template_kwargs:+ proxied["chat_template_kwargs"] = merged_template_kwargs++ # The public contract is final-answer-only. Ask the child parser to split+ # reasoning from visible content, then strip that private field again on+ # both response paths below. Raw-tag fallback covers models with no parser.+ proxied["separate_reasoning"] = True+ proxied["stream_reasoning"] = True+ return proxied+++def _prepare_mlx_body(+ body: dict[str, Any],+ *,+ config: Any,+ adapter: MLXGenerationAdapter,+ cap: int,+ max_completion_tokens: int | None,+ max_tokens: int | None,+ seed: int | None,+) -> dict[str, Any]:+ proxied = dict(body)+ proxied["model"] = adapter.mlx_repo+ requested_cap = max_completion_tokens if max_completion_tokens is not None else max_tokens+ if requested_cap is not None and requested_cap > cap:+ field = "max_completion_tokens" if max_completion_tokens is not None else "max_tokens"+ raise _bad_request(+ f"{field} ({requested_cap}) exceeds model cap ({cap})",+ param=field,+ )+ proxied["max_tokens"] = requested_cap if requested_cap is not None else cap+ # mlx_lm versions used by the Mac bundle consume the legacy field.+ proxied.pop("max_completion_tokens", None)+ if seed is not None:+ proxied["seed"] = seed++ profile = config.resolve_profile("default")+ runtime = dict(profile.runtime)+ default_sampling = runtime.get("default_sampling")+ if isinstance(default_sampling, dict):+ for config_field, chat_field in _DEFAULT_SAMPLING_TO_CHAT_FIELD.items():+ if (+ config_field in _MLX_DEFAULT_SAMPLING_FIELDS+ and config_field in default_sampling+ and proxied.get(chat_field) is None+ ):+ proxied[chat_field] = default_sampling[config_field]+ if isinstance(proxied.get("seed"), int) and not isinstance(proxied["seed"], bool):+ proxied["seed"] = normalize_mlx_seed(proxied["seed"])++ configured_stops = runtime.get("stop_tokens")+ merged_stop = _merge_stops(body.get("stop"), configured_stops)+ if merged_stop is not None:+ proxied["stop"] = merged_stop++ request_template_kwargs = body.get("chat_template_kwargs")+ merged_template_kwargs = dict(request_template_kwargs or {})+ operator_template_kwargs = config.tasks.generate.chat_template_kwargs+ if isinstance(operator_template_kwargs, dict):+ # Match queued generation: operator YAML is authoritative on conflict.+ merged_template_kwargs.update(operator_template_kwargs)+ if merged_template_kwargs:+ proxied["chat_template_kwargs"] = merged_template_kwargs+ return proxied+++def _sanitize_chat_payload(+ payload: Any,+ *,+ requested_model: str,+ hide_thinking_blocks: bool,+ initial_inside_thinking: bool,+ reasoning_format: ReasoningFormat,+ states: dict[int, ThinkingBlockStripper] | None = None,+ terminal: bool,+) -> dict[str, Any]:+ if not isinstance(payload, dict):+ raise ValueError("child chat response must be a JSON object")+ payload["model"] = requested_model+ choices = payload.get("choices")+ if not isinstance(choices, list):+ return payload++ state_map = states if states is not None else {}+ 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+ message = choice_obj.get("message")+ delta = choice_obj.get("delta")+ container = message if isinstance(message, dict) else delta if isinstance(delta, dict) else None+ if container is None:+ continue+ reasoning_content = container.pop("reasoning_content", None)+ reasoning = container.pop("reasoning", None)+ reasoning_was_present = (reasoning_content is not None and reasoning_content != "") or (+ reasoning is not None and reasoning != ""+ )++ if not hide_thinking_blocks:+ continue+ stripper = state_map.setdefault(+ index,+ ThinkingBlockStripper(+ inside=initial_inside_thinking,+ reasoning_format=reasoning_format,+ ),+ )+ raw_content = container.get("content")+ content = raw_content if isinstance(raw_content, str) else ""+ visible = stripper.feed(content) if content else ""+ is_terminal_choice = terminal or choice_obj.get("finish_reason") is not None+ if is_terminal_choice:+ visible += stripper.finish()+ if isinstance(raw_content, str) or visible:+ container["content"] = visible+ if (reasoning_was_present or visible != content) and "logprobs" in choice_obj:+ choice_obj["logprobs"] = None+ return payload+++async def _read_upstream_body(response: httpx.Response) -> bytes:+ body = bytearray()+ async for chunk in response.aiter_bytes():+ if len(body) + len(chunk) > _MAX_CHAT_RESPONSE_BYTES:+ raise ValueError("upstream response exceeded the byte limit")+ body.extend(chunk)+ return bytes(body)+++def _new_proxy_client() -> httpx.AsyncClient:+ # Ignore HTTP(S)_PROXY: even a loopback URL must connect directly to the+ # adapter-managed child rather than an operator-shell proxy.+ return httpx.AsyncClient(timeout=_PROXY_TIMEOUT, trust_env=False)+++async def _sanitize_sse_stream(+ response: httpx.Response,+ client: httpx.AsyncClient,+ *,+ requested_model: str,+ hide_thinking_blocks: bool,+ initial_inside_thinking: bool,+ reasoning_format: ReasoningFormat,+ slot: asyncio.Semaphore | None,+) -> AsyncIterator[bytes]:+ states: dict[int, ThinkingBlockStripper] = {}+ buffered = bytearray()+ received = 0+ saw_done = False+ try:+ async for chunk in response.aiter_bytes():+ received += len(chunk)+ if received > _MAX_CHAT_RESPONSE_BYTES:+ logger.error("generation child SSE exceeded %d bytes", _MAX_CHAT_RESPONSE_BYTES)+ yield _upstream_error_event("upstream response exceeded the byte limit")+ return+ buffered.extend(chunk)+ while True:+ newline_at = buffered.find(b"\n")+ if newline_at < 0:+ break+ line = bytes(buffered[:newline_at]).removesuffix(b"\r")+ del buffered[: newline_at + 1]+ if not line.startswith(b"data:"):+ yield line + b"\n"+ continue+ data = line[len(b"data:") :].lstrip()+ if data == b"[DONE]":+ saw_done = True+ yield b"data: [DONE]\n"+ continue+ if not data:+ yield line + b"\n"+ continue+ parsed = json.loads(data)+ sanitized = _sanitize_chat_payload(+ parsed,+ requested_model=requested_model,+ hide_thinking_blocks=hide_thinking_blocks,+ initial_inside_thinking=initial_inside_thinking,+ reasoning_format=reasoning_format,+ states=states,+ terminal=False,+ )+ encoded = json.dumps(sanitized, separators=(",", ":"), ensure_ascii=False).encode()+ yield b"data: " + encoded + b"\n"++ if buffered:+ line = bytes(buffered).removesuffix(b"\r")+ if line.startswith(b"data:") and line[len(b"data:") :].lstrip() == b"[DONE]":+ saw_done = True+ yield b"data: [DONE]\n"+ elif line:+ raise ValueError("upstream SSE ended with an incomplete event")+ if not saw_done:+ logger.warning("generation child SSE ended without [DONE]")+ yield _upstream_error_event("upstream stream ended unexpectedly")+ except (httpx.HTTPError, UnicodeError, ValueError, json.JSONDecodeError):+ logger.warning("generation child chat proxy stream failed", exc_info=True)+ if not saw_done:+ yield _upstream_error_event()+ finally:+ await response.aclose()+ await client.aclose()+ if slot is not None:+ slot.release()+++# -- /v1/chat/completions (proxy to the managed generation child) ------------@router.post("/chat/completions", response_model=None)@@ -121,35 +754,44 @@ async def chat_completions(http_request: Request,x_machine_profile: Annotated[str | None, Header(alias="X-SIE-MACHINE-PROFILE")] = None,) -> Response | StreamingResponse:- """OpenAI-compatible chat completions, proxied to the local MLX subprocess.+ """OpenAI-compatible chat completions through the loaded generation child.- Resolves the requested model, ensures it is loaded, then forwards the body- to the child ``mlx_lm.server``'s ``/v1/chat/completions`` (rewriting the- ``model`` field to the child's served MLX repo so it does not try to hot-swap- models). Supports both streaming (SSE pass-through) and non-streaming.+ MLX remains the non-CUDA backend. CUDA profiles proxy to the exact SGLang+ subprocess the registry loaded for the requested model/profile. The child+ URL and served model name always come from that adapter, never the body."""validate_machine_profile_header(x_machine_profile)body = await _read_json_body(http_request)model = body.get("model")- if not isinstance(model, str) or not model:+ if not isinstance(model, str) or not model.strip():raise _bad_request("'model' must be a non-empty string", param="model")- if not isinstance(body.get("messages"), list) or not body["messages"]:+ messages = body.get("messages")+ if not isinstance(messages, list) or not messages:raise _bad_request("'messages' must be a non-empty array", param="messages")- # Validate the fields this route interprets locally (the rest pass through to- # mlx_lm.server, which validates them) — reject rather than coerce, matching the gateway- # parser. `bool("false")` is True, so an unvalidated `stream` would silently stream; an- # invalid `max_tokens` must 400 rather than be silently clamped to the model cap.+ if len(messages) > _MAX_CHAT_MESSAGES:+ raise _bad_request(+ f"'messages' exceeds the maximum of {_MAX_CHAT_MESSAGES} per request",+ param="messages",+ )+ _validate_chat_messages(messages)+ _validate_chat_message_media(messages)+ chat_template_kwargs = body.get("chat_template_kwargs")+ if chat_template_kwargs is not None and not isinstance(chat_template_kwargs, dict):+ raise _bad_request("'chat_template_kwargs' must be an object", param="chat_template_kwargs")+ if isinstance(chat_template_kwargs, dict):+ try:+ validate_chat_template_kwargs(chat_template_kwargs)+ except ValueError as exc:+ code = "unsupported_field" if str(exc).startswith("unsupported ") else "invalid_request"+ raise _bad_request(str(exc), param="chat_template_kwargs", code=code) from excstream_opt = body.get("stream")if stream_opt is not None and not isinstance(stream_opt, bool):raise _bad_request("'stream' must be a boolean", param="stream")- max_tokens_opt = body.get("max_tokens")- if max_tokens_opt is not None and (- isinstance(max_tokens_opt, bool) or not isinstance(max_tokens_opt, int) or max_tokens_opt <= 0- ):- raise _bad_request("'max_tokens' must be a positive integer", param="max_tokens")- mlx_seed = _validate_mlx_seed(body.get("seed"))+ max_completion_tokens = _validate_optional_positive_int(body, "max_completion_tokens")+ max_tokens = _validate_optional_positive_int(body, "max_tokens")+ seed = _validate_chat_seed(body.get("seed"))registry = http_request.app.state.registrydevice = registry.device@@ -160,10 +802,7 @@ async def chat_completions(checker = ModelStateChecker(registry, registry_key, span)checker.check_exists()- # Validate generation capability + backend BEFORE loading: a chat request for an- # embedding/reranker model (or on a non-MLX/CUDA device) must fail fast instead of- # kicking off a real model load/download that only 501s afterwards. Mirrors the- # rerank route's tasks.score gate.+ # Validate capability and all CUDA edge fields before a model download.config = registry.get_config(registry_key)gen_task = getattr(config.tasks, "generate", None)if gen_task is None:@@ -171,7 +810,9 @@ async def chat_completions(f"Model '{model}' does not support generation (no generate task). Use a generation model.")if str(device).startswith("cuda"):- raise _unsupported_chat(model)+ _validate_cuda_chat_body(body)+ else:+ _validate_mlx_chat_body(body)checker.check_not_failed()checker.check_not_unloading()@@ -179,80 +820,155 @@ async def chat_completions(await checker.ensure_loaded(device)adapter = registry.get(registry_key)- server_url = getattr(adapter, "server_url", None)- if not isinstance(adapter, MLXGenerationAdapter) or server_url is None:- # Defensive backstop — the capability/device gates above catch the common cases.- raise _unsupported_chat(model)-- # Rewrite the model to the child's served repo so mlx_lm.server does not attempt to- # load a different model per request, and clamp max_tokens to the model's output cap- # so a huge value can't drive an unbounded generation / OOM (gen_task is non-None here).- proxied = dict(body)- proxied["model"] = adapter.mlx_repo- if mlx_seed is not None:- proxied["seed"] = mlx_seed- cap = gen_task.max_output_tokens- # max_tokens_opt is a positive int or None (validated above). Make the per-model cap- # authoritative: clamp a valid value, and fill the cap in when omitted so the child's- # own (large) default can't bypass it.- proxied["max_tokens"] = min(max_tokens_opt, cap) if max_tokens_opt is not None else cap- url = f"{server_url}/v1/chat/completions"- stream = bool(stream_opt) # validated above (bool or None)- # Single-flight: the child is single-tenant; serialize with /v1/generate.- slot = adapter.generation_slot()+ registry.touch_lru(registry_key)+ slot: asyncio.Semaphore | None = None+ reasoning_parser: str | None = None+ if isinstance(adapter, MLXGenerationAdapter) and not str(device).startswith("cuda"):+ if adapter.mlx_repo is None:+ raise _unsupported_chat(model, device)+ server_url = adapter.server_url+ proxied = _prepare_mlx_body(+ body,+ config=config,+ adapter=adapter,+ cap=gen_task.max_output_tokens,+ max_completion_tokens=max_completion_tokens,+ max_tokens=max_tokens,+ seed=seed,+ )+ slot = adapter.generation_slot()+ elif isinstance(adapter, SGLangGenerationAdapter) and str(device).startswith("cuda"):+ server_url = adapter.server_url+ reasoning_parser = adapter.reasoning_parser+ proxied = _prepare_sglang_body(+ body,+ config=config,+ adapter=adapter,+ max_completion_tokens=max_completion_tokens,+ max_tokens=max_tokens,+ seed=seed,+ )+ else:+ raise _unsupported_chat(model, device)- if stream:+ try:+ url = _validated_child_chat_url(server_url)+ except ValueError:+ logger.exception("generation adapter exposed an unsafe or missing child URL")+ return _upstream_error_response("generation child is unavailable")- async def _proxy_sse() -> Any:- async with slot:- try:- async with (- httpx.AsyncClient(timeout=_PROXY_TIMEOUT) as client,- client.stream("POST", url, json=proxied) as resp,- ):- if resp.status_code != status.HTTP_200_OK:- # The 200 text/event-stream status is already committed, so- # surface the child error as a terminal SSE event. Do NOT call- # aiter_raw() after aread() (raises httpx.StreamConsumed).- preview = (await resp.aread())[:500]- logger.error("MLX chat proxy error %d: %s", resp.status_code, preview)- err = json.dumps(- {- "error": {- "code": "upstream_error",- "message": preview.decode("utf-8", "replace"),- "status": resp.status_code,- }- }- )- yield f"data: {err}\n\n".encode()- yield b"data: [DONE]\n\n"- return- async for chunk in resp.aiter_raw():- yield chunk- except httpx.HTTPError as exc:- # Child died / connection reset mid-stream — emit a terminal error- # event so the client doesn't get a silently-truncated body.- logger.warning("MLX chat proxy stream error: %s", exc)- # Generic client message — detail is logged above; don't leak- # the exception text to the client (CodeQL info-exposure).- err = json.dumps({"error": {"code": "upstream_error", "message": "upstream stream error"}})- yield f"data: {err}\n\n".encode()- yield b"data: [DONE]\n\n"+ stream = bool(stream_opt) # validated above (bool or None)+ hide_thinking_blocks = thinking_blocks_must_be_hidden(config)+ reasoning_format = resolve_reasoning_format(config, adapter)+ configured_template_kwargs = gen_task.chat_template_kwargs+ thinking_enabled = (+ isinstance(configured_template_kwargs, dict) and configured_template_kwargs.get("enable_thinking") is True+ )+ # A parser returns final content separately from reasoning_content. A+ # parser-less Qwen template may seed <think> in the prompt, so its first+ # generated byte is already private reasoning and only </think> appears+ # in output.+ initial_inside_thinking = hide_thinking_blocks and thinking_enabled and reasoning_parser is None+ if stream:+ if slot is not None:+ await slot.acquire()+ client = _new_proxy_client()+ try:+ upstream_request = client.build_request("POST", url, json=proxied)+ upstream = await client.send(upstream_request, stream=True)+ except asyncio.CancelledError:+ await client.aclose()+ if slot is not None:+ slot.release()+ raise+ except httpx.HTTPError:+ logger.warning("generation child chat stream connection failed", exc_info=True)+ await client.aclose()+ if slot is not None:+ slot.release()+ return _upstream_error_response("generation child is unavailable")+ if upstream.status_code != status.HTTP_200_OK:+ try:+ await _read_upstream_body(upstream)+ except (httpx.HTTPError, ValueError):+ # The body is intentionally discarded; never log child+ # validation details because they can include user input.+ pass+ finally:+ await upstream.aclose()+ await client.aclose()+ if slot is not None:+ slot.release()+ logger.error("generation child chat error status=%d", upstream.status_code)+ return _upstream_error_response(+ response_status=_translated_upstream_status(upstream.status_code),+ )+ content_type = upstream.headers.get("content-type", "").partition(";")[0].strip().lower()+ if content_type != "text/event-stream":+ try:+ await _read_upstream_body(upstream)+ except (httpx.HTTPError, ValueError):+ # Drain only for connection reuse and bounded cleanup; the+ # unexpected response body is intentionally discarded.+ pass+ finally:+ await upstream.aclose()+ await client.aclose()+ if slot is not None:+ slot.release()+ logger.error("generation child returned non-SSE content for a streaming request")+ return _upstream_error_response("generation child returned an invalid streaming response")return StreamingResponse(- _proxy_sse(),+ _sanitize_sse_stream(+ upstream,+ client,+ requested_model=model,+ hide_thinking_blocks=hide_thinking_blocks,+ initial_inside_thinking=initial_inside_thinking,+ reasoning_format=reasoning_format,+ slot=slot,+ ),media_type="text/event-stream",headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},)- async with slot, httpx.AsyncClient(timeout=_PROXY_TIMEOUT) as client:- resp = await client.post(url, json=proxied)- return Response(- content=resp.content,- status_code=resp.status_code,- media_type=resp.headers.get("content-type", "application/json"),- )+ if slot is not None:+ await slot.acquire()+ try:+ async with _new_proxy_client() as client:+ try:+ async with client.stream("POST", url, json=proxied) as upstream:+ raw = await _read_upstream_body(upstream)+ upstream_status = upstream.status_code+ except httpx.HTTPError:+ logger.warning("generation child chat request failed", exc_info=True)+ return _upstream_error_response("generation child is unavailable")+ except ValueError:+ logger.error("generation child chat response exceeded its byte limit")+ return _upstream_error_response("upstream response exceeded the byte limit")+ finally:+ if slot is not None:+ slot.release()++ if upstream_status != status.HTTP_200_OK:+ logger.error("generation child chat error status=%d", upstream_status)+ return _upstream_error_response(+ response_status=_translated_upstream_status(upstream_status),+ )+ try:+ payload = _sanitize_chat_payload(+ json.loads(raw),+ requested_model=model,+ hide_thinking_blocks=hide_thinking_blocks,+ initial_inside_thinking=initial_inside_thinking,+ reasoning_format=reasoning_format,+ terminal=True,+ )+ 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")+ return JSONResponse(content=payload)# -- /v1/rerank (Cohere/OpenAI shape over the score adapter) -----------------diff --git a/packages/sie_server/src/sie_server/api/openai_responses.py b/packages/sie_server/src/sie_server/api/openai_responses.pynew file mode 100644index 000000000..0e3f27854--- /dev/null+++ b/packages/sie_server/src/sie_server/api/openai_responses.py@@ -0,0 +1,375 @@+"""Direct OpenAI-compatible ``/v1/responses`` generation surface.++This is the direct-server counterpart of the gateway's stateless, text-only+Responses MVP. Both raw string input and validated message input are reduced to+one rendered prompt and executed through ``GenerationAdapter.generate``.+"""++from __future__ import annotations++import logging+import time+import uuid+from dataclasses import dataclass+from typing import Annotated, Any, cast++from fastapi import APIRouter, Header, HTTPException, Request, status+from fastapi.responses import JSONResponse+from sie_sdk.queue_types import denormalize_model_id++from sie_server.adapters._generation_base import (+ GenerationAdapter,+ reasoning_starts_in_prompt,+ resolve_reasoning_format,+ suppress_thinking_blocks,+ thinking_blocks_must_be_hidden,+)+from sie_server.api.generate import _render_native_messages_prompt+from sie_server.api.helpers import ModelStateChecker, check_sdk_version+from sie_server.api.openai_completions import (+ _MAX_F32,+ _MAX_PROMPT_BYTES,+ _collect_completion,+ _CompletionError,+ _error_response,+ _from_http_exception,+ _number,+ _read_json_body,+)+from sie_server.api.validation import validate_machine_profile_header, validate_signed_i64+from sie_server.core.runtime_options import apply_generation_runtime_options+from sie_server.observability.tracing import tracer+from sie_server.types.openapi import OpenAIResponsesResponseModel++router = APIRouter(prefix="/v1", tags=["openai-compat"])+logger = logging.getLogger(__name__)++_MAX_U32 = (1 << 32) - 1+_SUPPORTED_FIELDS = frozenset(+ {+ "model",+ "input",+ "max_output_tokens",+ "temperature",+ "top_p",+ "seed",+ "stream",+ }+)+_KNOWN_UNSUPPORTED_FIELDS = frozenset(+ {+ "previous_response_id",+ "tools",+ "tool_choice",+ "reasoning",+ "background",+ "metadata",+ "instructions",+ }+)+_ALLOWED_ROLES = frozenset({"system", "user", "assistant", "developer"})+_ALLOWED_CONTENT_TYPES = frozenset({"text", "input_text", "output_text"})+++@dataclass(frozen=True, slots=True)+class _ResponsesParams:+ model: str+ prompt: str | None+ messages: list[dict[str, str]] | None+ max_output_tokens: int+ temperature: float | None+ top_p: float | None+ seed: int | None+++def _unsupported(field: str) -> _CompletionError:+ return _CompletionError(+ f"'{field}' is not supported by this endpoint",+ param=field,+ code="unsupported_field",+ )+++def _parse_message_content(value: Any, *, index: int) -> str:+ path = f"input[{index}].content"+ if isinstance(value, str):+ return value+ if not isinstance(value, list):+ raise _CompletionError(f"'{path}' must be a string or text parts", param=path)++ text: list[str] = []+ for part_index, part in enumerate(value):+ part_path = f"{path}[{part_index}]"+ if not isinstance(part, dict):+ raise _CompletionError(f"'{part_path}' must be an object", param=part_path)+ part_obj = cast("dict[str, Any]", part)+ unknown = set(part_obj) - {"type", "text"}+ if unknown:+ field = sorted(unknown)[0]+ raise _unsupported(f"{part_path}.{field}")+ part_type = part_obj.get("type")+ if not isinstance(part_type, str):+ raise _CompletionError(f"'{part_path}.type' is required and must be a string", param=f"{part_path}.type")+ if part_type not in _ALLOWED_CONTENT_TYPES:+ raise _CompletionError(+ f"unsupported content part type '{part_type}'",+ param=f"{part_path}.type",+ code="unsupported_field",+ )+ part_text = part_obj.get("text")+ if not isinstance(part_text, str):+ raise _CompletionError(+ f"'{part_path}.text' is required and must be a string",+ param=f"{part_path}.text",+ )+ text.append(part_text)+ return "".join(text)+++def _parse_input(value: Any) -> tuple[str | None, list[dict[str, str]] | None]:+ if isinstance(value, str):+ return value, None+ if not isinstance(value, list) or not value:+ raise _CompletionError(+ 'field "input" is required (a string or a non-empty list of messages)',+ param="input",+ )++ messages: list[dict[str, str]] = []+ for index, item in enumerate(value):+ path = f"input[{index}]"+ if not isinstance(item, dict):+ raise _CompletionError(f"'{path}' must be an object", param=path)+ item_obj = cast("dict[str, Any]", item)+ unknown = set(item_obj) - {"role", "content"}+ if unknown:+ field = sorted(unknown)[0]+ raise _unsupported(f"{path}.{field}")+ role = item_obj.get("role")+ if not isinstance(role, str):+ raise _CompletionError(f"'{path}.role' is required and must be a string", param=f"{path}.role")+ if role not in _ALLOWED_ROLES:+ raise _CompletionError(f"'{path}.role' is invalid", param=f"{path}.role")+ messages.append(+ {+ "role": "system" if role == "developer" else role,+ "content": _parse_message_content(item_obj.get("content"), index=index),+ }+ )+ return None, messages+++def _parse_params(body: dict[str, Any]) -> _ResponsesParams:+ for field in _KNOWN_UNSUPPORTED_FIELDS:+ if field in body:+ raise _unsupported(field)+ unknown = set(body) - _SUPPORTED_FIELDS+ if unknown:+ raise _unsupported(sorted(unknown)[0])++ model = body.get("model")+ if not isinstance(model, str) or not model:+ raise _CompletionError('field "model" is required', param="model")++ prompt, messages = _parse_input(body.get("input"))++ stream = body.get("stream")+ if stream is not None and not isinstance(stream, bool):+ raise _CompletionError("'stream' must be a boolean", param="stream")+ if stream:+ raise _unsupported("stream")++ max_output_tokens = body.get("max_output_tokens", 16)+ if max_output_tokens is None:+ max_output_tokens = 16+ if (+ isinstance(max_output_tokens, bool)+ or not isinstance(max_output_tokens, int)+ or not (1 <= max_output_tokens <= _MAX_U32)+ ):+ raise _CompletionError("'max_output_tokens' must be a positive integer", param="max_output_tokens")++ temperature = _number(body.get("temperature"), param="temperature", minimum=0, maximum=_MAX_F32)+ top_p = _number(body.get("top_p"), param="top_p", minimum=0, maximum=1)+ if top_p is not None and top_p == 0:+ raise _CompletionError("'top_p' must be a number in (0, 1]", param="top_p")+ try:+ seed = validate_signed_i64(body.get("seed"), param="seed")+ except ValueError as exc:+ raise _CompletionError(str(exc), param="seed") from exc++ return _ResponsesParams(+ model=model,+ prompt=prompt,+ messages=messages,+ max_output_tokens=max_output_tokens,+ temperature=temperature,+ top_p=top_p,+ seed=seed,+ )+++ "/responses",+ response_model=OpenAIResponsesResponseModel,+ responses={+ 400: {"description": "Invalid or unsupported request"},+ 404: {"description": "Model not found"},+ 413: {"description": "Request body or rendered input is too large"},+ 500: {"description": "Generation failed"},+ 503: {"description": "Model loading or temporarily unavailable"},+ },+ openapi_extra={+ "requestBody": {+ "required": True,+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/OpenAIResponsesRequestModel"}}},+ }+ },+)+async def responses(+ http_request: Request,+ x_machine_profile: Annotated[str | None, Header(alias="X-SIE-MACHINE-PROFILE")] = None,+) -> JSONResponse:+ """Create one stateless, text-only OpenAI Responses result."""+ try:+ validate_machine_profile_header(x_machine_profile)+ check_sdk_version(http_request)+ params = _parse_params(await _read_json_body(http_request))++ registry = http_request.app.state.registry+ registry_key = denormalize_model_id(params.model)+ with tracer.start_as_current_span("openai_responses") as span:+ span.set_attribute("model", params.model)+ checker = ModelStateChecker(registry, registry_key, span)+ checker.check_exists()+ checker.check_not_failed()+ checker.check_not_unloading()+ checker.check_not_loading()++ config = registry.get_config(registry_key)+ generate_task = getattr(config.tasks, "generate", None)+ if generate_task is None:+ raise _CompletionError(+ f"Model '{params.model}' does not support generation",+ param="model",+ code="model_not_found",+ )+ if params.max_output_tokens > generate_task.max_output_tokens:+ raise _CompletionError(+ f"max_output_tokens ({params.max_output_tokens}) exceeds model cap "+ f"({generate_task.max_output_tokens})",+ param="max_output_tokens",+ code="context_exceeded",+ )++ prompt = params.prompt+ if params.messages is not None:+ prompt = await _render_native_messages_prompt(config, params.messages)+ if prompt is None: # pragma: no cover - parser invariant+ raise _CompletionError("input did not resolve to a prompt", param="input")+ prompt_bytes = len(prompt.encode("utf-8"))+ if prompt_bytes > _MAX_PROMPT_BYTES:+ raise _CompletionError(+ f"rendered input is {prompt_bytes} bytes, exceeds the limit of {_MAX_PROMPT_BYTES} bytes",+ status_code=status.HTTP_413_CONTENT_TOO_LARGE,+ param="input",+ code="context_exceeded",+ )++ runtime_params: dict[str, Any] = {+ "prompt": prompt,+ "max_new_tokens": params.max_output_tokens,+ **{+ key: value+ for key, value in (+ ("temperature", params.temperature),+ ("top_p", params.top_p),+ ("seed", params.seed),+ )+ if value is not None+ },+ }+ try:+ runtime_params = apply_generation_runtime_options(config, None, runtime_params)+ except ValueError as exc:+ raise _CompletionError(str(exc), code="invalid_request") from exc++ await checker.ensure_loaded(registry.device)+ adapter = registry.get(registry_key)+ registry.touch_lru(registry_key)+ if not isinstance(adapter, GenerationAdapter):+ raise _CompletionError(+ f"Model '{params.model}' adapter does not support generation",+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ param="model",+ code="inference_error",+ )++ chunks = adapter.generate(+ prompt=prompt,+ max_new_tokens=params.max_output_tokens,+ temperature=float(runtime_params.get("temperature", 1.0)),+ top_p=float(runtime_params.get("top_p", 1.0)),+ stop=runtime_params.get("stop"),+ frequency_penalty=runtime_params.get("frequency_penalty"),+ presence_penalty=runtime_params.get("presence_penalty"),+ top_k=runtime_params.get("top_k"),+ min_new_tokens=runtime_params.get("min_tokens"),+ seed=runtime_params.get("seed"),+ )+ if thinking_blocks_must_be_hidden(config):+ reasoning_format = resolve_reasoning_format(config, adapter)+ chunks = suppress_thinking_blocks(+ chunks,+ start_inside=reasoning_starts_in_prompt(prompt, reasoning_format),+ reasoning_format=reasoning_format,+ )+ try:+ text, terminal = await _collect_completion(chunks)+ except _CompletionError:+ raise+ except Exception as exc:+ logger.warning("OpenAI Responses generation failed for %s", params.model, exc_info=True)+ raise _CompletionError(+ "internal error during generation",+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ code="inference_error",+ ) from exc++ canonical_model = getattr(config, "name", None) or registry_key+ response_id = f"resp-{uuid.uuid4().hex}"+ if terminal.prompt_tokens is None or terminal.completion_tokens is None:+ raise _CompletionError(+ "generation terminal event omitted required usage",+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ code="malformed_worker_response",+ )+ prompt_tokens = terminal.prompt_tokens+ completion_tokens = terminal.completion_tokens+ return JSONResponse(+ content={+ "id": response_id,+ "object": "response",+ "created_at": int(time.time()),+ "model": canonical_model,+ "status": "completed",+ "output": [+ {+ "type": "message",+ "id": f"msg-{response_id.removeprefix('resp-')}",+ "role": "assistant",+ "status": "completed",+ "content": [{"type": "output_text", "text": text, "annotations": []}],+ }+ ],+ "usage": {+ "input_tokens": prompt_tokens,+ "output_tokens": completion_tokens,+ "total_tokens": prompt_tokens + completion_tokens,+ },+ }+ )+ except _CompletionError as exc:+ return _error_response(exc)+ except HTTPException as exc:+ return _error_response(_from_http_exception(exc))diff --git a/packages/sie_server/src/sie_server/api/openapi.py b/packages/sie_server/src/sie_server/api/openapi.pyindex 88395e704..7431308c9 100644--- a/packages/sie_server/src/sie_server/api/openapi.py+++ b/packages/sie_server/src/sie_server/api/openapi.py@@ -14,6 +14,8 @@ from sie_server.types.openapi import (ExtractRequestModel,GenerateChunk,GenerateRequestModel,+ OpenAICompletionRequestModel,+ OpenAIResponsesRequestModel,ScoreRequestModel,)@@ -65,6 +67,8 @@ def _add_request_body_schemas(openapi_schema: dict[str, Any]) -> None:ExtractRequestModel,GenerateChunk,GenerateRequestModel,+ OpenAICompletionRequestModel,+ OpenAIResponsesRequestModel,ScoreRequestModel,]:model_name = model_class.__name__diff --git a/packages/sie_server/src/sie_server/api/root.py b/packages/sie_server/src/sie_server/api/root.pyindex d9897b8d0..0ef04d97d 100644--- a/packages/sie_server/src/sie_server/api/root.py+++ b/packages/sie_server/src/sie_server/api/root.py@@ -1,17 +1,12 @@"""Root endpoint router."""-from importlib.resources import files-from fastapi import APIRouter-from fastapi.responses import HTMLResponse+from fastapi.responses import RedirectResponserouter = APIRouter()-# Load static HTML file at module load time-_index_html = files("sie_server.static").joinpath("index.html").read_text()-[email protected]("/", response_class=HTMLResponse)-async def root() -> HTMLResponse:- """Basic HTML status page for the root endpoint."""- return HTMLResponse(content=_index_html)[email protected]("/", include_in_schema=False)+async def root() -> RedirectResponse:+ """Redirect the root path to the interactive OpenAPI docs."""+ return RedirectResponse(url="/docs")diff --git a/packages/sie_server/src/sie_server/app/app_factory.py b/packages/sie_server/src/sie_server/app/app_factory.pyindex f72ae76be..a1d0ef0b8 100644--- a/packages/sie_server/src/sie_server/app/app_factory.py+++ b/packages/sie_server/src/sie_server/app/app_factory.py@@ -15,7 +15,9 @@ from sie_server.api.health import router as health_routerfrom sie_server.api.models import router as models_routerfrom sie_server.api.openai_audio import router as openai_audio_routerfrom sie_server.api.openai_compat import router as openai_router+from sie_server.api.openai_completions import router as openai_completions_routerfrom sie_server.api.openai_local import router as openai_local_router+from sie_server.api.openai_responses import router as openai_responses_routerfrom sie_server.api.openapi import setup_custom_openapi_schemafrom sie_server.api.root import router as root_routerfrom sie_server.api.score import router as score_router@@ -90,7 +92,7 @@ class AppFactory:# Queue is the only supported routing mode: the worker-sidecar# drives NATS and talks to Python over UDS IPC. We still mount# the HTTP routers for /healthz and /readyz (K8s probes), the- # landing page, and /ws/status — which is+ # root redirect to /docs, and /ws/status — which is# the gateway's worker-registration channel: the gateway dials# `ws://<pod>/ws/status` to learn pool_name, bundle,# machine_profile, and readiness. The inference endpoints@@ -110,6 +112,8 @@ class AppFactory:app.include_router(models_router)app.include_router(openai_audio_router) # OpenAI-compatible /v1/audio/transcriptionsapp.include_router(openai_router) # OpenAI-compatible /v1/embeddings+ app.include_router(openai_completions_router) # OpenAI-compatible /v1/completions+ app.include_router(openai_responses_router) # OpenAI-compatible /v1/responses# Local-only convenience (single-node/dev); intentionally NOT in the published# openapi.json — see cli.openapi_export. The Rust gateway is the prod API authority.app.include_router(openai_local_router) # local /v1/chat/completions + /v1/rerankdiff --git a/packages/sie_server/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.pyindex 9cc7ae069..f817ac3dc 100644--- a/packages/sie_server/src/sie_server/cli.py+++ b/packages/sie_server/src/sie_server/cli.py@@ -224,17 +224,19 @@ def openapi_export(from sie_server.api.health import router as health_routerfrom sie_server.api.models import router as models_routerfrom sie_server.api.openai_compat import router as openai_router+ from sie_server.api.openai_completions import router as openai_completions_router+ from sie_server.api.openai_responses import router as openai_responses_routerfrom sie_server.api.openapi import setup_custom_openapi_schemafrom sie_server.api.root import router as root_routerfrom sie_server.api.score import router as score_routerfrom sie_server.api.ws import router as ws_router# Build a lightweight FastAPI app for the PUBLISHED API surface — no lifespan (no GPU- # init, model registry, telemetry, or NATS). NOTE: the local-only convenience routes are- # intentionally excluded from the committed openapi.json — the ``openai_local`` router- # (/v1/chat/completions + /v1/rerank) is a single-node/dev convenience surface. The- # SIE-native ``generate`` route is part of the worker contract and is published here even- # though the Rust gateway remains the production cluster API authority.+ # init, model registry, telemetry, or NATS). NOTE: the direct-container convenience routes+ # are intentionally excluded from the committed openapi.json — the ``openai_local`` router+ # (/v1/chat/completions + /v1/rerank) proxies managed MLX/SGLang children for single-node+ # serving, while the Rust gateway owns the published production chat contract. The+ # SIE-native ``generate`` route is part of the worker contract and is published here.app_ = FastAPI(title="SIE Server",description="Search Inference Engine - GPU inference server for search workloads",@@ -250,6 +252,8 @@ def openapi_export(app_.include_router(ws_router)app_.include_router(openai_audio_router)app_.include_router(openai_router)+ app_.include_router(openai_completions_router)+ app_.include_router(openai_responses_router)setup_custom_openapi_schema(app_)spec = app_.openapi()@@ -518,10 +522,9 @@ def serve(typer.echo(f"Devices: {', '.join(resolved_devices)}")if resolved_device == "mps":# Apple-Silicon banner: surface the one-command local OpenAI endpoint so the- # first-run experience points at the playground / docs / OpenAI base URL.+ # first-run experience points at the docs / OpenAI base URL.typer.echo("")typer.echo(" Apple Silicon (Metal) — one local OpenAI-compatible endpoint:")- typer.echo(f" → Playground http://localhost:{port}/")typer.echo(f" → API docs http://localhost:{port}/docs")typer.echo(f" → OpenAI base http://localhost:{port}/v1 (embeddings · rerank; chat/completions with -b sglang)"diff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.pyindex f79b8b435..34e150f5b 100644--- a/packages/sie_server/src/sie_server/config/model.py+++ b/packages/sie_server/src/sie_server/config/model.py@@ -7,7 +7,7 @@ from pathlib import Pathfrom types import MappingProxyTypefrom typing import Any, Literal-from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, model_validator+from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator, model_validatorfrom sie_server.config.engine import ComputePrecisionfrom sie_server.config.package_artifacts import (@@ -23,6 +23,48 @@ PoolingStrategy = Literal["cls", "mean", "last_token", "splade", "none"]_MODALITY_NAMES = ("text", "image", "audio", "video", "document")_MAX_POOL_NAME_LEN = 128+_CHAT_TEMPLATE_KWARGS = frozenset({"enable_thinking", "guardian_config"})+_GUARDIAN_CONFIG_KWARGS = frozenset({"risk_name"})+_MAX_GUARDIAN_RISK_NAME_LEN = 128+++def validate_chat_template_kwargs(value: dict[str, Any] | None) -> dict[str, Any] | None:+ """Validate the bounded operator-owned tokenizer template contract.++ These values cross from model YAML into ``apply_chat_template(**kwargs)``.+ Keeping the accepted keys and nested shapes explicit prevents a catalog+ edit from silently enabling a tokenizer-specific extension with arbitrary+ behavior or unbounded data.+ """+ if value is None:+ return None++ unsupported = set(value) - _CHAT_TEMPLATE_KWARGS+ if unsupported:+ names = ", ".join(sorted(unsupported))+ raise ValueError(f"unsupported chat_template_kwargs key(s): {names}")++ enable_thinking = value.get("enable_thinking")+ if "enable_thinking" in value and not isinstance(enable_thinking, bool):+ raise ValueError("chat_template_kwargs.enable_thinking must be a boolean")++ guardian_config = value.get("guardian_config")+ if "guardian_config" in value:+ if not isinstance(guardian_config, dict):+ raise ValueError("chat_template_kwargs.guardian_config must be an object")+ unsupported_guardian = set(guardian_config) - _GUARDIAN_CONFIG_KWARGS+ if unsupported_guardian:+ names = ", ".join(sorted(unsupported_guardian))+ raise ValueError(f"unsupported chat_template_kwargs.guardian_config key(s): {names}")+ risk_name = guardian_config.get("risk_name")+ if not isinstance(risk_name, str) or not risk_name or len(risk_name) > _MAX_GUARDIAN_RISK_NAME_LEN:+ raise ValueError(+ "chat_template_kwargs.guardian_config.risk_name must be a non-empty string "+ f"of at most {_MAX_GUARDIAN_RISK_NAME_LEN} characters"+ )++ return value+# Served-model version identity. An *immutable* HF revision is a full 40-char git# commit SHA (SHA-1, lowercase hex). Branch/tag names ("main", "v1.0") resolve to@@ -173,12 +215,12 @@ class GenerateTask(BaseModel):model can process. ``max_output_tokens`` is the per-request hard cap on``max_new_tokens`` enforced by the gateway.- ``chat_template_kwargs`` are forwarded verbatim to the tokenizer's- ``apply_chat_template(**kwargs)`` call when the worker renders an- OpenAI-shaped ``messages`` request. The Qwen3 family for- example accepts ``enable_thinking: false`` to suppress its reasoning- block. Empty dict by default — non-chat / prompt-shape requests- ignore the field.+ ``chat_template_kwargs`` are a bounded operator-owned mapping forwarded+ to the tokenizer's ``apply_chat_template(**kwargs)`` call when the worker+ renders an OpenAI-shaped ``messages`` request. The accepted schema covers+ ``enable_thinking`` and Granite Guardian's bounded ``guardian_config``;+ unknown keys and invalid nested shapes fail at config load. Empty dict by+ default — non-chat / prompt-shape requests ignore the field.``prewarm_grammars`` is an optional list of grammars to compile atmodel-load time so the cold-start TTFT for these schemas excludes@@ -218,6 +260,11 @@ class GenerateTask(BaseModel):prewarm_grammars: list[PrewarmGrammar] = Field(default_factory=list)grammar_profile: str | None = None+ @field_validator("chat_template_kwargs")+ @classmethod+ def validate_chat_template_kwargs(cls, value: dict[str, Any]) -> dict[str, Any]:+ return validate_chat_template_kwargs(value) or {}+class Tasks(BaseModel):model_config = ConfigDict(extra="forbid")@@ -321,6 +368,18 @@ class ProfileConfig(BaseModel):var (default-off until the calibration ablation flips it); explicit``True`` / ``False`` wins unless the env var is set to ``on`` or``off`` (which override the profile in both directions).++ ``max_output_tokens`` optionally overrides the model-level generation cap+ for the materialized ``model:profile`` variant. This lets a long-context+ reasoning profile expose the checkpoint's supported decode budget without+ weakening the conservative cap on the bare model or shorter profiles.++ ``chat_template_kwargs`` optionally overrides the same bounded model-level+ :class:`GenerateTask` defaults for the materialized ``model:profile``+ variant. This keeps tokenizer render presets such as explicit thinking+ mode on the profile identity while preserving the bare model's safer+ non-thinking default. The profile mapping is merged over the task mapping;+ request-time kwargs are still applied later by the generation processor."""model_config = ConfigDict(extra="forbid")@@ -333,6 +392,13 @@ class ProfileConfig(BaseModel):adaptive_batching: ProfileAdaptiveBatching | None = Nonekv_budget_tokens: int | None = Noneadmission_enabled: bool | None = None+ max_output_tokens: int | None = Field(default=None, gt=0)+ chat_template_kwargs: dict[str, Any] | None = None++ @field_validator("chat_template_kwargs")+ @classmethod+ def validate_chat_template_kwargs(cls, value: dict[str, Any] | None) -> dict[str, Any] | None:+ return validate_chat_template_kwargs(value)class ResolvedProfile(BaseModel):@@ -346,6 +412,8 @@ class ResolvedProfile(BaseModel):adaptive_batching: ProfileAdaptiveBatching | None = Nonekv_budget_tokens: int | None = Noneadmission_enabled: bool | None = None+ max_output_tokens: int | None = None+ chat_template_kwargs: MappingProxyType[str, Any] | None = None# Coarse per-family KV-bytes-per-token constants used by the derived-budget@@ -637,6 +705,12 @@ class ModelConfig(BaseModel):raise ValueError(msg)for name, profile in self.profiles.items():+ if profile.chat_template_kwargs is not None and self.tasks.generate is None:+ msg = f"Profile '{name}' sets 'chat_template_kwargs' on a model without a generation task"+ raise ValueError(msg)+ if profile.max_output_tokens is not None and self.tasks.generate is None:+ msg = f"Profile '{name}' sets 'max_output_tokens' on a model without a generation task"+ raise ValueError(msg)if profile.extends is not None:if profile.extends not in self.profiles:msg = f"Profile '{name}' extends unknown profile '{profile.extends}'"@@ -697,6 +771,30 @@ class ModelConfig(BaseModel):profile=profile,parent=self.profiles[profile.extends] if profile.extends is not None else None,)++ parent = self.profiles[profile.extends] if profile.extends is not None else None+ effective_output_cap = (+ profile.max_output_tokens+ if profile.max_output_tokens is not None+ else parent.max_output_tokens+ if parent is not None+ else None+ )+ if effective_output_cap is not None:+ effective_loadtime = profile.adapter_options.loadtime or (+ parent.adapter_options.loadtime if parent is not None else {}+ )+ effective_context = effective_loadtime.get(+ "max_seq_length",+ self.tasks.generate.context_length,+ )+ if effective_output_cap > effective_context:+ msg = (+ f"Profile '{name}' on generation model '{self.sie_id}' sets "+ f"max_output_tokens={effective_output_cap}, exceeding its "+ f"context_length={effective_context}"+ )+ raise ValueError(msg)return self@model_validator(mode="after")@@ -759,6 +857,12 @@ class ModelConfig(BaseModel):adaptive_batching=profile.adaptive_batching,kv_budget_tokens=profile.kv_budget_tokens,admission_enabled=profile.admission_enabled,+ max_output_tokens=profile.max_output_tokens,+ chat_template_kwargs=(+ MappingProxyType(dict(profile.chat_template_kwargs))+ if profile.chat_template_kwargs is not None+ else None+ ),)# Resolve via parent — validators guarantee parent exists and has no chaining@@ -794,6 +898,12 @@ class ModelConfig(BaseModel):admission_enabled = (profile.admission_enabled if profile.admission_enabled is not None else parent.admission_enabled)+ max_output_tokens = (+ profile.max_output_tokens if profile.max_output_tokens is not None else parent.max_output_tokens+ )+ chat_template_kwargs = (+ profile.chat_template_kwargs if profile.chat_template_kwargs is not None else parent.chat_template_kwargs+ )if max_batch_tokens is None:msg = f"Resolved profile '{name}': max_batch_tokens must be set"@@ -811,6 +921,10 @@ class ModelConfig(BaseModel):adaptive_batching=adaptive_batching,kv_budget_tokens=kv_budget_tokens,admission_enabled=admission_enabled,+ max_output_tokens=max_output_tokens,+ chat_template_kwargs=(+ MappingProxyType(dict(chat_template_kwargs)) if chat_template_kwargs is not None else None+ ),)@propertydiff --git a/packages/sie_server/src/sie_server/core/loader.py b/packages/sie_server/src/sie_server/core/loader.pyindex 8940a5320..3c69c1cf2 100644--- a/packages/sie_server/src/sie_server/core/loader.py+++ b/packages/sie_server/src/sie_server/core/loader.py@@ -198,6 +198,32 @@ def _expand_profile_variants(configs: dict[str, ModelConfig]) -> None:remove_base_names: list[str] = []for base_name, config in configs.items():+ default_profile = config.profiles.get("default")+ if (+ default_profile is not None+ and config.tasks.generate is not None+ and (default_profile.chat_template_kwargs is not None or default_profile.max_output_tokens is not None)+ ):+ generate_updates: dict[str, Any] = {}+ if default_profile.chat_template_kwargs is not None:+ generate_updates["chat_template_kwargs"] = {+ **config.tasks.generate.chat_template_kwargs,+ **default_profile.chat_template_kwargs,+ }+ if default_profile.max_output_tokens is not None:+ generate_updates["max_output_tokens"] = default_profile.max_output_tokens+ bare_config = config.model_copy(+ update={+ "tasks": config.tasks.model_copy(+ update={+ "generate": config.tasks.generate.model_copy(update=generate_updates),+ },+ ),+ },+ )+ bare_config._resolved_cache = {}+ bare_config._resolved_lock = threading.Lock()+ configs[base_name] = bare_configif "default" not in config.profiles:remove_base_names.append(base_name)for profile_name, profile in config.profiles.items():@@ -220,6 +246,10 @@ def _expand_profile_variants(configs: dict[str, ModelConfig]) -> None:adaptive_batching=resolved.adaptive_batching,kv_budget_tokens=resolved.kv_budget_tokens,admission_enabled=resolved.admission_enabled,+ max_output_tokens=resolved.max_output_tokens,+ chat_template_kwargs=(+ dict(resolved.chat_template_kwargs) if resolved.chat_template_kwargs is not None else None+ ),)else:variant_default = profile.model_copy(update={"extends": None})@@ -234,17 +264,31 @@ def _expand_profile_variants(configs: dict[str, ModelConfig]) -> None:"profiles": variant_profiles,}loadtime = resolved.loadtime if resolved is not None else profile.adapter_options.loadtime+ profile_chat_template_kwargs = (+ resolved.chat_template_kwargs if resolved is not None else profile.chat_template_kwargs+ )+ generate_updates: dict[str, Any] = {}profile_max_seq = loadtime.get("max_seq_length")if isinstance(profile_max_seq, int) and profile_max_seq > 0:variant_updates["max_sequence_length"] = profile_max_seqif config.tasks.generate is not None:- variant_updates["tasks"] = config.tasks.model_copy(- update={- "generate": config.tasks.generate.model_copy(- update={"context_length": profile_max_seq},- ),- },- )+ generate_updates["context_length"] = profile_max_seq+ if profile_chat_template_kwargs is not None and config.tasks.generate is not None:+ generate_updates["chat_template_kwargs"] = {+ **config.tasks.generate.chat_template_kwargs,+ **dict(profile_chat_template_kwargs),+ }+ profile_max_output_tokens = (+ resolved.max_output_tokens if resolved is not None else profile.max_output_tokens+ )+ if profile_max_output_tokens is not None and config.tasks.generate is not None:+ generate_updates["max_output_tokens"] = profile_max_output_tokens+ if generate_updates and config.tasks.generate is not None:+ variant_updates["tasks"] = config.tasks.model_copy(+ update={+ "generate": config.tasks.generate.model_copy(update=generate_updates),+ },+ )variant_config = config.model_copy(update=variant_updates,)diff --git a/packages/sie_server/src/sie_server/core/runtime_options.py b/packages/sie_server/src/sie_server/core/runtime_options.pyindex 453ce1a45..8493c5b42 100644--- a/packages/sie_server/src/sie_server/core/runtime_options.py+++ b/packages/sie_server/src/sie_server/core/runtime_options.py@@ -94,12 +94,23 @@ _GENERATION_RUNTIME_KEYS = frozenset(_GENERATION_SAMPLING_KEYS = {"temperature": "temperature","top_p": "top_p",+ "frequency_penalty": "frequency_penalty","presence_penalty": "presence_penalty","top_k": "top_k","min_new_tokens": "min_tokens",+ "seed": "seed",}+def _is_finite_number(value: object) -> bool:+ if isinstance(value, bool) or not isinstance(value, int | float):+ return False+ try:+ return math.isfinite(float(value))+ except OverflowError:+ return False++def apply_generation_runtime_options(config: ModelConfig,request_options: dict[str, Any] | None,@@ -165,18 +176,20 @@ def apply_generation_runtime_options(if unknown_sampling:raise ValueError(f"unsupported generation sampling option(s): {sorted(unknown_sampling)}")for key, value in sampling.items():- numeric = isinstance(value, int | float) and not isinstance(value, bool)- valid = numeric and math.isfinite(float(value))+ if key == "seed":+ valid = isinstance(value, int) and not isinstance(value, bool) and -(1 << 63) <= value <= (1 << 63) - 1+ else:+ valid = _is_finite_number(value)if key == "temperature":valid = valid and value >= 0elif key == "top_p":valid = valid and 0 < value <= 1- elif key == "presence_penalty":+ elif key in {"frequency_penalty", "presence_penalty"}:valid = valid and -2 <= value <= 2elif key == "top_k":- valid = isinstance(value, int) and not isinstance(value, bool) and value >= 1+ valid = valid and isinstance(value, int) and not isinstance(value, bool) and value >= 1elif key == "min_new_tokens":- valid = isinstance(value, int) and not isinstance(value, bool) and value >= 0+ valid = valid and isinstance(value, int) and not isinstance(value, bool) and value >= 0if not valid:raise ValueError(f"'options.default_sampling.{key}' has an invalid value")@@ -204,12 +217,7 @@ def apply_generation_runtime_options(for key in ("first_chunk_timeout_s", "inter_chunk_timeout_s", "overall_timeout_s"):value = runtime.get(key)- if value is not None and (- isinstance(value, bool)- or not isinstance(value, int | float)- or not math.isfinite(float(value))- or value <= 0- ):+ if value is not None and (not _is_finite_number(value) or value <= 0):raise ValueError(f"'options.{key}' must be a positive number")return resultdiff --git a/packages/sie_server/src/sie_server/local_ingest_client.py b/packages/sie_server/src/sie_server/local_ingest_client.pynew file mode 100644index 000000000..f908b2992--- /dev/null+++ b/packages/sie_server/src/sie_server/local_ingest_client.py@@ -0,0 +1,185 @@+"""Bounded Python client for the Rust sidecar's local-ingest protocol."""++from __future__ import annotations++import asyncio+import hashlib+from collections.abc import AsyncIterator+from typing import Any++import msgpack++MAX_LOCAL_INGEST_FRAME_BYTES = 64 * 1024 * 1024+PAYLOAD_DIGEST_BYTES = 32+PAYLOAD_DIGEST_DOMAIN = b"sie-local-ingest-v1\0"+INTERNAL_DISPATCH_CONTEXT = msgpack.packb({"source": "internal"}, use_bin_type=True)+LOCAL_INGEST_CONNECT_TIMEOUT_S = 5.0+DEFAULT_LOCAL_INGEST_RESPONSE_IDLE_TIMEOUT_S = 900.0+LOCAL_INGEST_RESPONSE_CLEANUP_GRACE_S = 11.0+++class LocalIngestStreamError(RuntimeError):+ """The colocated Rust sidecar rejected or broke a generation stream."""+++def _update_digest_field(hasher: Any, value: bytes) -> None:+ hasher.update(len(value).to_bytes(8, "big"))+ hasher.update(value)+++def compute_payload_digest(body: dict[str, Any]) -> bytes:+ """Compute the v0.2 trusted-peer consistency digest for one request."""+ hasher = hashlib.sha256()+ hasher.update(PAYLOAD_DIGEST_DOMAIN)+ for value in (+ body["dispatch_context"],+ body["lane"].encode(),+ body["endpoint"].encode(),+ body["model"].encode(),+ body["engine"].encode(),+ body["admission_pool"].encode(),+ body["bundle_config_hash"].encode(),+ body["request_id"].encode(),+ body["params"],+ body["items"],+ ):+ _update_digest_field(hasher, value)+ hasher.update(body["timeout_ms"].to_bytes(8, "big", signed=True))+ return hasher.digest()+++def build_generation_request_body(items: bytes, params: bytes, meta: dict[str, Any]) -> dict[str, Any]:+ """Build one generation body while preserving gateway-provided bindings."""+ request_id = meta.get("request_id")+ lane = meta.get("lane")+ if not isinstance(request_id, str) or not request_id:+ raise ValueError("local-ingest generation metadata missing request_id")+ if not isinstance(lane, str) or not lane:+ raise ValueError("local-ingest generation metadata missing lane")++ dispatch_context = meta.get("dispatch_context")+ payload_digest = meta.get("payload_digest")+ timeout_ms = meta.get("timeout_ms", 0)+ bound_transport = dispatch_context is not None or payload_digest is not None+ if not isinstance(timeout_ms, int) or isinstance(timeout_ms, bool) or timeout_ms < 0:+ raise ValueError("local-ingest generation timeout_ms must be a non-negative integer")+ if bound_transport:+ if not isinstance(dispatch_context, bytes) or not dispatch_context:+ raise ValueError("local-ingest generation dispatch_context must be bytes")+ if not isinstance(payload_digest, bytes) or len(payload_digest) != PAYLOAD_DIGEST_BYTES:+ raise ValueError(f"local-ingest generation payload_digest must be {PAYLOAD_DIGEST_BYTES} bytes")+ else:+ dispatch_context = INTERNAL_DISPATCH_CONTEXT+ payload_digest = b""++ body = {+ "lane": lane,+ "endpoint": str(meta.get("endpoint") or "generate"),+ "model": str(meta.get("model") or ""),+ "engine": str(meta.get("engine") or ""),+ "admission_pool": str(meta.get("admission_pool") or ""),+ "bundle_config_hash": str(meta.get("bundle_config_hash") or ""),+ "request_id": request_id,+ "params": params,+ "items": items,+ "dispatch_context": dispatch_context,+ "payload_digest": payload_digest,+ "timeout_ms": timeout_ms,+ }+ if not bound_transport:+ body["payload_digest"] = compute_payload_digest(body)+ return body+++async def _read_frame(reader: asyncio.StreamReader) -> dict[str, Any]:+ try:+ header = await reader.readexactly(4)+ except asyncio.IncompleteReadError as exc:+ raise LocalIngestStreamError("local-ingest generation response header is truncated") from exc+ length = int.from_bytes(header, "little")+ if length > MAX_LOCAL_INGEST_FRAME_BYTES:+ raise LocalIngestStreamError(+ f"local-ingest generation response frame is {length} bytes; maximum is {MAX_LOCAL_INGEST_FRAME_BYTES}"+ )+ try:+ payload = await reader.readexactly(length)+ except asyncio.IncompleteReadError as exc:+ raise LocalIngestStreamError("local-ingest generation response payload is truncated") from exc+ try:+ response = msgpack.unpackb(payload, raw=False)+ except (ValueError, msgpack.ExtraData) as exc:+ raise LocalIngestStreamError(f"local-ingest generation response is invalid MessagePack: {exc}") from exc+ if not isinstance(response, dict):+ raise LocalIngestStreamError("local-ingest generation response is not a map")+ return response+++async def stream_generate(+ socket_path: str,+ items: bytes,+ params: bytes,+ meta: dict[str, Any],+) -> AsyncIterator[bytes]:+ """Map one caller operation onto sidecar protocol v0.2.++ Pulling one response before requesting the next naturally propagates+ caller backpressure through the sidecar. Closing+ the generator closes this connection; local ingest treats EOF as+ cancellation for the connection-owned request.+ """+ body = build_generation_request_body(items, params, meta)+ operation_id = 1+ payload = msgpack.packb(+ {"id": operation_id, "op": "publish_generate_stream", "body": body},+ use_bin_type=True,+ )+ if len(payload) > MAX_LOCAL_INGEST_FRAME_BYTES:+ raise ValueError(+ f"local-ingest generation frame is {len(payload)} bytes; maximum is {MAX_LOCAL_INGEST_FRAME_BYTES}"+ )++ timeout_ms = body["timeout_ms"]+ response_timeout_s = (+ timeout_ms / 1_000 + LOCAL_INGEST_RESPONSE_CLEANUP_GRACE_S+ if timeout_ms > 0+ else DEFAULT_LOCAL_INGEST_RESPONSE_IDLE_TIMEOUT_S+ )+ try:+ reader, writer = await asyncio.wait_for(+ asyncio.open_unix_connection(socket_path),+ timeout=LOCAL_INGEST_CONNECT_TIMEOUT_S,+ )+ except TimeoutError as exc:+ raise LocalIngestStreamError("local-ingest generation connection timed out") from exc+ try:+ writer.write(len(payload).to_bytes(4, "little") + payload)+ await writer.drain()+ expected_seq = 0+ while True:+ try:+ response = await asyncio.wait_for(_read_frame(reader), timeout=response_timeout_s)+ except TimeoutError as exc:+ raise LocalIngestStreamError("local-ingest generation response timed out") from exc+ if response.get("id") != operation_id:+ raise LocalIngestStreamError("local-ingest generation response id mismatch")+ if response.get("ok") is not True:+ raise LocalIngestStreamError(str(response.get("error") or "sidecar generation failed"))+ response_body = response.get("body")+ if not isinstance(response_body, dict):+ raise LocalIngestStreamError("local-ingest generation response body is not a map")+ if response_body.get("final") is True:+ outcome = response_body.get("outcome")+ if not isinstance(outcome, dict) or outcome.get("chunks") != expected_seq:+ raise LocalIngestStreamError("local-ingest generation terminal chunk count mismatch")+ return+ chunk = response_body.get("chunk")+ seq = response_body.get("seq")+ if not isinstance(chunk, bytes):+ raise LocalIngestStreamError("local-ingest generation chunk is not bytes")+ if isinstance(seq, bool) or not isinstance(seq, int) or seq != expected_seq:+ raise LocalIngestStreamError(f"local-ingest generation sequence {seq!r} is not expected {expected_seq}")+ expected_seq += 1+ yield chunk+ finally:+ writer.close()+ await writer.wait_closed()diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.pyindex e7e76f4be..68032fbd4 100644--- a/packages/sie_server/src/sie_server/processors/streaming.py+++ b/packages/sie_server/src/sie_server/processors/streaming.py@@ -53,8 +53,14 @@ from sie_server.adapters._generation_base import (FinishReason,GenerationAdapter,GenerationChunk,+ ReasoningFormat,ToolCallDelta,+ reasoning_starts_in_prompt,+ resolve_reasoning_format,+ suppress_thinking_blocks,+ thinking_blocks_must_be_hidden,)+from sie_server.config.model import validate_chat_template_kwargsfrom sie_server.core.runtime_options import apply_generation_runtime_optionsfrom sie_server.core.text_tokens import estimate_tokens_from_charsfrom sie_server.core.tokenizer import image_first_chat_message, load_tokenizer@@ -248,10 +254,12 @@ _MAX_IMAGES_PER_REQUEST = 16# admission reservation. The chat template renders each image as a short# placeholder, but the vision encoder expands it into many tokens (Qwen-VL:# up to ~1280 at max_pixels). Exact counts need the image dimensions + the-# model's vision tokenizer, which we don't have at this layer — so we use a-# conservative constant. Over-reserving is safe; under-counting risks a-# context-window overflow (opaque SGLang error) and admission over-admit.-_VISION_TOKENS_PER_IMAGE_ESTIMATE = 1024+# model's vision tokenizer, which we don't have at this layer. Qwen SGLang+# profiles cap preprocessing at 1280 visual tokens, so this value is both a+# conservative reservation and a hard upper bound for the image-capable+# generation family. Under-counting risks a context-window overflow and+# admission over-admit.+_VISION_TOKENS_PER_IMAGE_ESTIMATE = 1280# Hard ceiling on a single decoded image's bytes. Bounds worker memory on the# decode path even for the direct-queue caller that bypasses the gateway's@@ -323,11 +331,11 @@ def _parse_message_images_field(raw: object, idx: int) -> tuple[ImageInput, ...]"""Parse a message-level ``images`` field of gateway-forwarded images.The gateway extracts OpenAI ``image_url`` data URIs and forwards them as- ``messages[i].images = [{"data": <base64-str>, "format": <str?>}, ...]``.- ``data`` is the **base64 payload string**, not raw bytes — that's what- survives the sidecar's ``WorkItem.generate: serde_json::Value`` (msgpack- ``bin`` does not; see the gateway ``ChatImage`` doc). We base64-decode here- into the ``bytes`` the adapter expects. Missing/``None`` → no images.+ ``messages[i].images = [{"data": <bytes-or-base64>, "format": <str?>},+ ...]``. The Rust sidecar normalizes legacy base64 strings to msgpack+ binary before Python execution. Accepting both representations here keeps+ direct execution and mixed-version workers compatible while preserving+ the same byte limits. Missing/``None`` means no images."""if raw is None:return ()@@ -341,40 +349,56 @@ def _parse_message_images_field(raw: object, idx: int) -> tuple[ImageInput, ...]message=f"messages[{idx}].images[{i}] must be an object",)entry_dict = cast("dict[str, Any]", entry)- b64 = entry_dict.get("data")- if not isinstance(b64, str) or not b64:- return _ValidationError(- code="invalid_request",- message=f"messages[{idx}].images[{i}].data must be a non-empty base64 string",- )- stripped = b64.strip()- if (len(stripped) * 3) // 4 > _MAX_DECODE_IMAGE_BYTES:- return _ValidationError(- code="invalid_request",- message=(- f"messages[{idx}].images[{i}]: image too large; exceeds the "- f"{_MAX_DECODE_IMAGE_BYTES // (1024 * 1024)} MiB limit"- ),- )- try:- data = base64.b64decode(stripped, validate=True)- except (binascii.Error, ValueError) as exc:- return _ValidationError(- code="invalid_request",- message=f"messages[{idx}].images[{i}]: invalid base64 image data: {exc}",- )- if not data:- return _ValidationError(- code="invalid_request",- message=f"messages[{idx}].images[{i}]: image data is empty",- )- if len(data) > _MAX_DECODE_IMAGE_BYTES:+ raw_data = entry_dict.get("data")+ if isinstance(raw_data, bytes):+ data = raw_data+ if not data:+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].images[{i}]: image data is empty",+ )+ if len(data) > _MAX_DECODE_IMAGE_BYTES:+ return _ValidationError(+ code="invalid_request",+ message=(+ f"messages[{idx}].images[{i}]: image too large ({len(data)} bytes); exceeds the "+ f"{_MAX_DECODE_IMAGE_BYTES // (1024 * 1024)} MiB limit"+ ),+ )+ elif isinstance(raw_data, str) and raw_data:+ stripped = raw_data.strip()+ if (len(stripped) * 3) // 4 > _MAX_DECODE_IMAGE_BYTES:+ return _ValidationError(+ code="invalid_request",+ message=(+ f"messages[{idx}].images[{i}]: image too large; exceeds the "+ f"{_MAX_DECODE_IMAGE_BYTES // (1024 * 1024)} MiB limit"+ ),+ )+ try:+ data = base64.b64decode(stripped, validate=True)+ except (binascii.Error, ValueError) as exc:+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].images[{i}]: invalid base64 image data: {exc}",+ )+ if not data:+ return _ValidationError(+ code="invalid_request",+ message=f"messages[{idx}].images[{i}]: image data is empty",+ )+ if len(data) > _MAX_DECODE_IMAGE_BYTES:+ return _ValidationError(+ code="invalid_request",+ message=(+ f"messages[{idx}].images[{i}]: image too large ({len(data)} bytes); exceeds the "+ f"{_MAX_DECODE_IMAGE_BYTES // (1024 * 1024)} MiB limit"+ ),+ )+ else:return _ValidationError(code="invalid_request",- message=(- f"messages[{idx}].images[{i}]: image too large ({len(data)} bytes); exceeds the "- f"{_MAX_DECODE_IMAGE_BYTES // (1024 * 1024)} MiB limit"- ),+ message=f"messages[{idx}].images[{i}].data must be non-empty bytes or a base64 string",)fmt = entry_dict.get("format")out.append({"data": data, "format": fmt if isinstance(fmt, str) else None})@@ -1571,6 +1595,8 @@ class StreamingProcessor:)returnparams = validation+ suppress_thinking = thinking_blocks_must_be_hidden(config)+ reasoning_format = resolve_reasoning_format(config, adapter)# Resolve ``tool_choice`` mode up front. When the caller set# ``tool_choice == "none"`` the OpenAI contract is that the model@@ -1637,6 +1663,10 @@ class StreamingProcessor:prompt_str = renderedelse:prompt_str = params.input.prompt+ thinking_starts_in_prompt = suppress_thinking and reasoning_starts_in_prompt(+ prompt_str,+ reasoning_format,+ )# Cancel may have arrived during chat-template rendering (CPU-bound# on a large message list).@@ -1825,6 +1855,9 @@ class StreamingProcessor:repetition_penalty=params.repetition_penalty,min_tokens=params.min_tokens,chat_template_kwargs=params.chat_template_kwargs,+ suppress_thinking=suppress_thinking,+ thinking_starts_in_prompt=thinking_starts_in_prompt,+ reasoning_format=reasoning_format,grammar=effective_grammar,tools=effective_tools,enable_tool_parser=enable_tool_parser,@@ -1883,6 +1916,9 @@ class StreamingProcessor:# caller can forward the whole ``params`` block without sniffing# which fields belong to which stage.chat_template_kwargs: dict[str, Any] | None = None,+ suppress_thinking: bool = False,+ thinking_starts_in_prompt: bool = False,+ reasoning_format: ReasoningFormat = "qwen3",grammar: GrammarSpec | None = None,tools: tuple[dict[str, Any], ...] | None = None,enable_tool_parser: bool | None = None,@@ -1970,6 +2006,15 @@ class StreamingProcessor:"AsyncGenerator[GenerationChunk, None]",adapter.generate(**gen_kwargs),)+ if suppress_thinking:+ chunks_iter = cast(+ "AsyncGenerator[GenerationChunk, None]",+ suppress_thinking_blocks(+ chunks_iter,+ start_inside=thinking_starts_in_prompt,+ reasoning_format=reasoning_format,+ ),+ )# OpenAI tools: when enabled, wrap the adapter iterator with the# tool-call parser so ``<tool_call>{...}</tool_call>`` blocks# emitted by the chat template surface as ``ToolCallDelta``s on@@ -2917,15 +2962,23 @@ class StreamingProcessor:else:min_tokens = min_tokens_val if min_tokens_val >= 0 else None- # Per-request chat-template kwargs. Gateway has already validated- # this is an object (or absent); store as-is and merge with the- # model YAML defaults in ``_render_chat_template`` below.+ # Per-request chat-template kwargs. Revalidate the bounded shape at+ # the worker boundary before it can reach ``apply_chat_template``;+ # this protects queue-bypass and mixed-version callers too.chat_template_kwargs_raw = params.get("chat_template_kwargs")chat_template_kwargs: dict[str, Any] | None- if isinstance(chat_template_kwargs_raw, dict):- chat_template_kwargs = dict(chat_template_kwargs_raw)- else:+ if chat_template_kwargs_raw is None:chat_template_kwargs = None+ elif isinstance(chat_template_kwargs_raw, dict):+ try:+ chat_template_kwargs = validate_chat_template_kwargs(dict(chat_template_kwargs_raw))+ except ValueError as exc:+ return _ValidationError(code="invalid_request", message=str(exc))+ else:+ return _ValidationError(+ code="invalid_request",+ message="'chat_template_kwargs' must be an object",+ )# OpenAI ``seed`` / ``logit_bias`` / ``logprobs`` / ``top_logprobs``# round-trips. Gateway is the authority for shape validationdiff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.pyindex 5ee37301e..e51c430be 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -15,8 +15,9 @@ import yamlfrom sie_server.api.ws import compute_bundle_config_hash_cachedfrom sie_server.config.model import ModelConfigfrom sie_server.core.encode_pipeline import EncodePipeline, resolve_encode_output_types+from sie_server.core.extract_cost import build_extract_prepared_itemsfrom sie_server.core.oom import is_oom_error-from sie_server.core.prepared import AudioPayload, AudioPreparedItem, ExtractPreparedItem+from sie_server.core.prepared import AudioPayload, AudioPreparedItemfrom sie_server.core.registry import ModelRegistryfrom sie_server.core.runtime_options import merge_runtime_options, merge_runtime_options_with_profilefrom sie_server.core.score_cost import build_score_prepared_items_timed@@ -1441,10 +1442,35 @@ class QueueExecutor:AudioPreparedItem(payload=payload, cost=payload.duration_cost_ms, original_index=0)]else:- # Batching proxy only; authoritative text billing comes- # from the adapter's real tokenizer count on ExtractOutput.- char_count = len(server_item.text) if server_item.text else 0- prepared_items = [ExtractPreparedItem(cost=char_count, original_index=0)]+ # Match the in-process HTTP extract path: vision adapters+ # consume their registered image preprocessor payloads,+ # not cost-only batching placeholders. Passing an+ # ExtractPreparedItem to a payload-aware adapter makes a+ # valid image look like an empty preprocessed batch (and+ # caused Grounding DINO / OWLv2 to return ``objects: []``+ # without ever running inference).+ preprocessor_registry = getattr(self._registry, "preprocessor_registry", None)+ has_image_preprocessor = False+ if preprocessor_registry is not None and server_item.images:+ try:+ has_image_preprocessor = preprocessor_registry.has_preprocessor(model_id, "image") is True+ except (AttributeError, TypeError):+ pass++ if has_image_preprocessor and preprocessor_registry is not None:+ task = options.get("task") if options else None+ prepared_batch = await preprocessor_registry.prepare(+ model_id,+ [server_item],+ config,+ instruction=bi.instruction,+ task=task,+ )+ prepared_items = prepared_batch.items+ else:+ # Batching proxy only; authoritative text/page billing+ # comes from the adapter's ExtractOutput unit counts.+ prepared_items = build_extract_prepared_items([server_item])timing.end_tokenization()lora = self._extract_lora(options)diff --git a/packages/sie_server/src/sie_server/static/__init__.py b/packages/sie_server/src/sie_server/static/__init__.pydeleted file mode 100644index 50e543d2a..000000000--- a/packages/sie_server/src/sie_server/static/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""Static assets for SIE Server."""diff --git a/packages/sie_server/src/sie_server/static/index.html b/packages/sie_server/src/sie_server/static/index.htmldeleted file mode 100644index 6af59b213..000000000--- a/packages/sie_server/src/sie_server/static/index.html+++ /dev/null@@ -1,181 +0,0 @@-<!doctype html>-<html lang="en">- <head>- <meta charset="utf-8" />- <meta name="viewport" content="width=device-width, initial-scale=1" />- <title>SIE Server</title>- <style>- :root { color-scheme: dark; }- body { font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background:#050816; color:#e5e7eb; }- .wrap { max-width: 860px; margin: 2rem auto; padding: 0 1.25rem; }- header { display:flex; align-items:center; justify-content:space-between; gap:1rem; margin-bottom: 0.5rem; }- h1 { font-size: 1.6rem; margin: 0; }- p.sub { margin: 0.25rem 0 1.25rem; color:#9ca3af; }- .pill { display:inline-flex; align-items:center; gap:0.4rem; padding:0.2rem 0.6rem; border-radius:999px; background:#022c22; color:#6ee7b7; font-size:0.72rem; text-transform:uppercase; letter-spacing:0.08em; }- .badge-dot { width:0.4rem; height:0.4rem; border-radius:999px; background:#22c55e; box-shadow:0 0 0 4px rgba(34,197,94,0.35); }- .tabs { display:flex; gap:0.4rem; margin-bottom: 0.9rem; }- .tab { padding:0.45rem 0.9rem; border-radius:0.6rem 0.6rem 0 0; background:#0b1220; color:#9ca3af; cursor:pointer; border:1px solid #1f2937; border-bottom:none; font-size:0.9rem; }- .tab.active { background:#020617; color:#e5e7eb; }- .panel { display:none; background:#020617; border:1px solid #1f2937; border-radius:0 0.75rem 0.75rem 0.75rem; padding:1.1rem; }- .panel.active { display:block; }- label { display:block; font-size:0.78rem; color:#9ca3af; margin:0.6rem 0 0.25rem; text-transform:uppercase; letter-spacing:0.05em; }- input, textarea { width:100%; box-sizing:border-box; background:#0b1220; color:#e5e7eb; border:1px solid #1f2937; border-radius:0.5rem; padding:0.55rem 0.7rem; font-size:0.95rem; font-family:inherit; }- textarea { resize:vertical; min-height:3.5rem; }- button { margin-top:0.8rem; padding:0.55rem 1.1rem; border-radius:0.5rem; border:none; background:#2563eb; color:white; font-weight:600; cursor:pointer; font-size:0.95rem; }- button:disabled { opacity:0.5; cursor:default; }- .out { margin-top:1rem; padding:0.8rem; background:#0b1220; border:1px solid #1f2937; border-radius:0.5rem; white-space:pre-wrap; word-break:break-word; min-height:2.5rem; font-size:0.95rem; }- .meta { margin-top:0.5rem; font-size:0.8rem; color:#6ee7b7; }- .err { color:#fca5a5; }- .links { margin-top:1.25rem; display:flex; flex-wrap:wrap; gap:1rem; }- a { color:#93c5fd; text-decoration:none; font-size:0.88rem; }- a:hover { text-decoration:underline; }- .row { display:flex; gap:0.75rem; } .row > div { flex:1; }- code { background:#111827; padding:0.1rem 0.3rem; border-radius:0.3rem; font-size:0.85em; }- </style>- </head>- <body>- <div class="wrap">- <header>- <h1>SIE Server</h1>- <span class="pill"><span class="badge-dot"></span><span id="status">running</span></span>- </header>- <p class="sub">One local OpenAI-compatible endpoint — embeddings, reranking, and generation. Try it below or point any OpenAI/Cohere client at <code>/v1</code>.</p>-- <div class="tabs" role="tablist" aria-label="Playground modes">- <div class="tab active" data-tab="chat" role="tab" tabindex="0" aria-selected="true">Chat</div>- <div class="tab" data-tab="embed" role="tab" tabindex="0" aria-selected="false">Embeddings</div>- <div class="tab" data-tab="rerank" role="tab" tabindex="0" aria-selected="false">Rerank</div>- </div>-- <div class="panel active" id="panel-chat">- <label for="chat-model">Model</label>- <input id="chat-model" value="Qwen/Qwen3.5-4B" />- <label for="chat-input">Message</label>- <textarea id="chat-input">Write one sentence about Apple Silicon.</textarea>- <button id="chat-send">Send</button>- <div class="out" id="chat-out"></div>- <div class="meta" id="chat-meta"></div>- </div>-- <div class="panel" id="panel-embed">- <label for="embed-model">Model</label>- <input id="embed-model" value="BAAI/bge-m3" />- <label for="embed-input">Texts (one per line)</label>- <textarea id="embed-input">hello world-apple silicon inference</textarea>- <button id="embed-send">Embed</button>- <div class="out" id="embed-out"></div>- <div class="meta" id="embed-meta"></div>- </div>-- <div class="panel" id="panel-rerank">- <label for="rerank-model">Model</label>- <input id="rerank-model" value="BAAI/bge-reranker-v2-m3" />- <div class="row">- <div><label for="rerank-query">Query</label><input id="rerank-query" value="apple silicon" /></div>- </div>- <label for="rerank-docs">Documents (one per line)</label>- <textarea id="rerank-docs">M-series chips power Macs-the weather is nice today-Metal GPU inference on Apple</textarea>- <button id="rerank-send">Rerank</button>- <div class="out" id="rerank-out"></div>- <div class="meta" id="rerank-meta"></div>- </div>-- <div class="links">- <a href="/docs">OpenAPI docs</a>- <a href="/v1/models">List models</a>- <a href="/healthz">/healthz</a>- <a href="/readyz">/readyz</a>- </div>- </div>-- <script>- const $ = (id) => document.getElementById(id);- const tabs = [...document.querySelectorAll(".tab")];- const activateTab = (t) => {- tabs.forEach((x) => { x.classList.remove("active"); x.setAttribute("aria-selected", "false"); });- document.querySelectorAll(".panel").forEach((x) => x.classList.remove("active"));- t.classList.add("active");- t.setAttribute("aria-selected", "true");- $("panel-" + t.dataset.tab).classList.add("active");- t.focus();- };- tabs.forEach((t, i) => {- t.onclick = () => activateTab(t);- t.onkeydown = (e) => {- if (e.key === "Enter" || e.key === " ") { e.preventDefault(); activateTab(t); }- else if (e.key === "ArrowRight" || e.key === "ArrowLeft") {- e.preventDefault();- activateTab(tabs[(i + (e.key === "ArrowRight" ? 1 : -1) + tabs.length) % tabs.length]);- }- };- });- fetch("/readyz").then((r) => { $("status").textContent = r.ok ? "ready" : "loading"; }).catch(() => {});-- // Chat (streaming /v1/chat/completions)- $("chat-send").onclick = async () => {- const btn = $("chat-send"), out = $("chat-out"), meta = $("chat-meta");- out.textContent = ""; out.classList.remove("err"); meta.textContent = ""; btn.disabled = true;- const t0 = performance.now(); let ttft = null, toks = 0;- try {- const resp = await fetch("/v1/chat/completions", {- method: "POST", headers: { "Content-Type": "application/json" },- body: JSON.stringify({ model: $("chat-model").value, messages: [{ role: "user", content: $("chat-input").value }], max_tokens: 256, temperature: 0.7, stream: true, stream_options: { include_usage: true } }),- });- if (!resp.ok) { out.classList.add("err"); out.textContent = "HTTP " + resp.status + ": " + (await resp.text()); btn.disabled = false; return; }- const reader = resp.body.getReader(); const dec = new TextDecoder(); let buf = "";- for (;;) {- const { value, done } = await reader.read(); if (done) break;- buf += dec.decode(value, { stream: true }); const lines = buf.split("\n"); buf = lines.pop();- for (let line of lines) {- line = line.trim(); if (!line.startsWith("data:")) continue; line = line.slice(5).trim();- if (!line || line === "[DONE]") continue;- let e; try { e = JSON.parse(line); } catch { continue; }- const d = (e.choices && e.choices[0] && e.choices[0].delta) || {};- if (d.content) { if (ttft === null) ttft = performance.now() - t0; toks++; out.textContent += d.content; }- if (e.usage && e.usage.completion_tokens) toks = e.usage.completion_tokens;- }- }- const dt = (performance.now() - t0) / 1000;- meta.textContent = `${toks} tokens · ${(toks / dt).toFixed(1)} tok/s` + (ttft !== null ? ` · ttft ${ttft.toFixed(0)} ms` : "");- } catch (err) { out.classList.add("err"); out.textContent = String(err); }- btn.disabled = false;- };-- // Embeddings- $("embed-send").onclick = async () => {- const btn = $("embed-send"), out = $("embed-out"), meta = $("embed-meta");- out.textContent = "…"; out.classList.remove("err"); meta.textContent = ""; btn.disabled = true;- const texts = $("embed-input").value.split("\n").map((s) => s.trim()).filter(Boolean);- const t0 = performance.now();- try {- const resp = await fetch("/v1/embeddings", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: $("embed-model").value, input: texts }) });- const data = await resp.json();- if (!resp.ok) { out.classList.add("err"); out.textContent = JSON.stringify(data, null, 2); btn.disabled = false; return; }- const dim = data.data[0].embedding.length;- out.textContent = data.data.map((d, i) => `[${i}] dim=${dim} [${d.embedding.slice(0, 6).map((x) => x.toFixed(4)).join(", ")}, …]`).join("\n");- meta.textContent = `${data.data.length} vectors · ${((performance.now() - t0) / 1000).toFixed(2)}s`;- } catch (err) { out.classList.add("err"); out.textContent = String(err); }- btn.disabled = false;- };-- // Rerank- $("rerank-send").onclick = async () => {- const btn = $("rerank-send"), out = $("rerank-out"), meta = $("rerank-meta");- out.textContent = "…"; out.classList.remove("err"); meta.textContent = ""; btn.disabled = true;- const docs = $("rerank-docs").value.split("\n").map((s) => s.trim()).filter(Boolean);- const t0 = performance.now();- try {- const resp = await fetch("/v1/rerank", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: $("rerank-model").value, query: $("rerank-query").value, documents: docs, return_documents: true }) });- const data = await resp.json();- if (!resp.ok) { out.classList.add("err"); out.textContent = JSON.stringify(data, null, 2); btn.disabled = false; return; }- out.textContent = data.results.map((r) => `${r.relevance_score.toFixed(4)} ${(r.document && r.document.text) || "#" + r.index}`).join("\n");- meta.textContent = `${data.results.length} ranked · ${((performance.now() - t0) / 1000).toFixed(2)}s`;- } catch (err) { out.classList.add("err"); out.textContent = String(err); }- btn.disabled = false;- };- </script>- </body>-</html>diff --git a/packages/sie_server/src/sie_server/types/openapi.py b/packages/sie_server/src/sie_server/types/openapi.pyindex 9c8d198f9..3ad1ccb4c 100644--- a/packages/sie_server/src/sie_server/types/openapi.py+++ b/packages/sie_server/src/sie_server/types/openapi.py@@ -408,6 +408,150 @@ class GenerateResponseModel(BaseModel):usage: GenerateUsageModel = Field(..., description="Token usage")+class OpenAICompletionStreamOptionsModel(BaseModel):+ """Supported OpenAI legacy-completions stream controls."""++ include_usage: bool | None = Field(+ default=None,+ description="Emit one usage-only chunk immediately before the [DONE] terminator",+ )+ model_config = {"extra": "forbid"}+++class OpenAICompletionRequestModel(BaseModel):+ """Strict single-candidate subset of the OpenAI legacy Completions API."""++ model: str = Field(..., min_length=1, description="Generation model id")+ prompt: str | list[str] = Field(+ ...,+ description="One raw prompt string, or a one-element string array; no chat template is applied",+ )+ max_tokens: int | None = Field(+ default=16,+ ge=1,+ le=(1 << 32) - 1,+ description="Maximum generated tokens",+ )+ temperature: float | None = Field(+ default=None,+ ge=0,+ le=3.4028234663852886e38,+ description="Sampling temperature override",+ )+ top_p: float | None = Field(default=None, gt=0, le=1, description="Nucleus-sampling probability override")+ stop: str | list[str] | None = Field(default=None, description="One stop sequence or an array of stop sequences")+ frequency_penalty: float | None = Field(default=None, ge=-2, le=2, description="Frequency penalty")+ presence_penalty: float | None = Field(default=None, ge=-2, le=2, description="Presence penalty")+ seed: int | None = Field(+ default=None,+ ge=-(1 << 63),+ le=(1 << 63) - 1,+ description="Optional signed 64-bit sampling seed",+ json_schema_extra={"format": "int64"},+ )+ stream: bool | None = Field(default=None, description="Return OpenAI text_completion Server-Sent Events")+ stream_options: OpenAICompletionStreamOptionsModel | None = None+ n: Literal[1] | None = Field(default=None, description="Only one completion candidate is supported")+ model_config = {"extra": "forbid"}+++class OpenAICompletionChoiceModel(BaseModel):+ """One choice in a blocking OpenAI legacy completion."""++ text: str+ index: int+ finish_reason: str+++class OpenAICompletionResponseModel(BaseModel):+ """Blocking OpenAI legacy-completions response."""++ id: str+ object: Literal["text_completion"]+ created: int+ model: str+ choices: list[OpenAICompletionChoiceModel]+ system_fingerprint: str | None = None+ usage: GenerateUsageModel+++class OpenAIResponseInputContentPartModel(BaseModel):+ """One text-only content part accepted by the Responses MVP."""++ type: Literal["text", "input_text", "output_text"]+ text: str+ model_config = {"extra": "forbid"}+++class OpenAIResponseInputMessageModel(BaseModel):+ """One stateless text message accepted by the Responses MVP."""++ role: Literal["system", "user", "assistant", "developer"]+ content: str | list[OpenAIResponseInputContentPartModel]+ model_config = {"extra": "forbid"}+++class OpenAIResponsesRequestModel(BaseModel):+ """Strict stateless, text-only subset of the OpenAI Responses API."""++ model: str = Field(..., min_length=1, description="Generation model id")+ input: str | Annotated[list[OpenAIResponseInputMessageModel], Field(min_length=1)]+ max_output_tokens: int | None = Field(+ default=16,+ ge=1,+ le=(1 << 32) - 1,+ description="Maximum generated tokens",+ )+ temperature: float | None = Field(+ default=None,+ ge=0,+ le=3.4028234663852886e38,+ description="Sampling temperature override",+ )+ top_p: float | None = Field(default=None, gt=0, le=1, description="Nucleus-sampling probability override")+ seed: int | None = Field(+ default=None,+ ge=-(1 << 63),+ le=(1 << 63) - 1,+ description="Optional signed 64-bit sampling seed",+ json_schema_extra={"format": "int64"},+ )+ stream: Literal[False] | None = Field(default=None, description="Responses streaming is not supported")+ model_config = {"extra": "forbid"}+++class OpenAIResponseOutputTextModel(BaseModel):+ type: Literal["output_text"]+ text: str+ annotations: list[dict[str, Any]]+++class OpenAIResponseOutputMessageModel(BaseModel):+ type: Literal["message"]+ id: str+ role: Literal["assistant"]+ status: Literal["completed"]+ content: list[OpenAIResponseOutputTextModel]+++class OpenAIResponseUsageModel(BaseModel):+ input_tokens: int = Field(..., ge=0)+ output_tokens: int = Field(..., ge=0)+ total_tokens: int = Field(..., ge=0)+++class OpenAIResponsesResponseModel(BaseModel):+ """One completed direct OpenAI Responses result."""++ id: str+ object: Literal["response"]+ created_at: int+ model: str+ status: Literal["completed"]+ output: list[OpenAIResponseOutputMessageModel]+ usage: OpenAIResponseUsageModel++class GenerateInputTooLongDetailModel(BaseModel):"""Detail returned when a generation prompt exceeds the worker limit."""diff --git a/packages/sie_server/tests/adapters/test_colbert_modernbert_flash_projection.py b/packages/sie_server/tests/adapters/test_colbert_modernbert_flash_projection.pyindex 5156594b9..4677ec948 100644--- a/packages/sie_server/tests/adapters/test_colbert_modernbert_flash_projection.py+++ b/packages/sie_server/tests/adapters/test_colbert_modernbert_flash_projection.py@@ -88,3 +88,106 @@ def test_compute_rope_uses_layer_appropriate_theta() -> None:# Positions >= 1 rotate at different frequencies for different bases.assert not torch.allclose(global_cos[1:], local_cos[1:])assert not torch.allclose(global_sin[1:], local_sin[1:])+++_POSITIONS = torch.tensor([0, 1, 2, 3])+++def _reference_cos_sin(theta: float, head_dim: int) -> tuple[torch.Tensor, torch.Tensor]:+ """Mirror of the adapter's rope math for a known theta."""+ inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))+ freqs = torch.outer(_POSITIONS.float(), inv_freq)+ emb = torch.cat([freqs, freqs], dim=-1)+ return emb.cos(), emb.sin()+++def _rope_adapter(**config_extra) -> ColBERTModernBERTFlashAdapter:+ """CPU/fp32 adapter stub with flat rope attrs plus any nested extras."""+ adapter = _bare_adapter()+ adapter._device = "cpu"+ adapter._compute_precision = "float32"+ adapter._model = _fake_model(+ hidden_size=8,+ num_attention_heads=2,+ global_rope_theta=160000.0,+ local_rope_theta=10000.0,+ **config_extra,+ )+ return adapter+++def test_compute_rope_prefers_nested_rope_parameters() -> None:+ """A transformers>=5 nested ``rope_parameters`` mapping wins over the flat+ attrs for BOTH layer kinds (5.x-serialized configs are authoritative about+ themselves; 4.x ModernBertConfig fills the flat attrs from class defaults).+ """+ adapter = _rope_adapter(+ rope_parameters={+ "full_attention": {"rope_theta": 111000.0, "rope_type": "default"},+ "sliding_attention": {"rope_theta": 222000.0, "rope_type": "default"},+ },+ )++ global_cos, global_sin = adapter._compute_rope(_POSITIONS, use_global=True)+ local_cos, local_sin = adapter._compute_rope(_POSITIONS, use_global=False)++ expected_global_cos, expected_global_sin = _reference_cos_sin(111000.0, head_dim=4)+ expected_local_cos, expected_local_sin = _reference_cos_sin(222000.0, head_dim=4)+ assert torch.equal(global_cos, expected_global_cos)+ assert torch.equal(global_sin, expected_global_sin)+ assert torch.equal(local_cos, expected_local_cos)+ assert torch.equal(local_sin, expected_local_sin)+++def test_compute_rope_flat_attrs_when_nested_absent() -> None:+ """No ``rope_parameters`` key (every 4.x-written config): the flat-attr+ path stays byte-identical — regression pin for GTE/Reason/mxbai-edge.+ """+ adapter = _rope_adapter()++ global_cos, _ = adapter._compute_rope(_POSITIONS, use_global=True)+ local_cos, _ = adapter._compute_rope(_POSITIONS, use_global=False)++ expected_global_cos, _ = _reference_cos_sin(160000.0, head_dim=4)+ expected_local_cos, _ = _reference_cos_sin(10000.0, head_dim=4)+ assert torch.equal(global_cos, expected_global_cos)+ assert torch.equal(local_cos, expected_local_cos)+++def test_compute_rope_malformed_nested_falls_back_to_flat() -> None:+ """Malformed nested declarations degrade to the flat attrs, never crash:+ non-mapping rope_parameters, non-mapping layer entry, non-numeric theta,+ and bool theta (bool is an int subclass but not a rope base).+ """+ malformed_variants = [+ {"rope_parameters": "sans_pos"},+ {"rope_parameters": {"full_attention": None, "sliding_attention": 42}},+ {"rope_parameters": {"full_attention": {"rope_theta": "fast"}, "sliding_attention": {}}},+ {"rope_parameters": {"full_attention": {"rope_theta": True}, "sliding_attention": {"rope_theta": True}}},+ ]+ expected_global_cos, _ = _reference_cos_sin(160000.0, head_dim=4)+ expected_local_cos, _ = _reference_cos_sin(10000.0, head_dim=4)++ for config_extra in malformed_variants:+ adapter = _rope_adapter(**config_extra)+ global_cos, _ = adapter._compute_rope(_POSITIONS, use_global=True)+ local_cos, _ = adapter._compute_rope(_POSITIONS, use_global=False)+ assert torch.equal(global_cos, expected_global_cos), config_extra+ assert torch.equal(local_cos, expected_local_cos), config_extra+++def test_compute_rope_partial_nested_mixes_sources() -> None:+ """A nested mapping declaring only one layer kind covers that kind; the+ other keeps the flat attr.+ """+ adapter = _rope_adapter(+ rope_parameters={"sliding_attention": {"rope_theta": 222000.0}},+ )++ global_cos, _ = adapter._compute_rope(_POSITIONS, use_global=True)+ local_cos, _ = adapter._compute_rope(_POSITIONS, use_global=False)++ expected_global_cos, _ = _reference_cos_sin(160000.0, head_dim=4) # flat+ expected_local_cos, _ = _reference_cos_sin(222000.0, head_dim=4) # nested+ assert torch.equal(global_cos, expected_global_cos)+ assert torch.equal(local_cos, expected_local_cos)diff --git a/packages/sie_server/tests/adapters/test_docling.py b/packages/sie_server/tests/adapters/test_docling.pyindex 149dba889..f07e21efd 100644--- a/packages/sie_server/tests/adapters/test_docling.py+++ b/packages/sie_server/tests/adapters/test_docling.py@@ -472,6 +472,13 @@ class TestDoclingSpec:assert not adapter._loadeddef test_staged_artifact_prewarm_exercises_ocr_converter(self, tmp_path: Path) -> None:+ """The OCR pre-warm is a probe, not a load gate (#2872).++ Missing OCR assets are an ``ocr``-profile dependency. They must not+ take down the born-digital ``default`` profile, which never opens an+ OCR file. The probe still runs, load() still succeeds, and the failed+ OCR converter is dropped so an ``ocr`` request rebuilds it.+ """adapter = DoclingAdapter(package_artifact_root=tmp_path)default_converter = _stub_converter("default")ocr_converter = _stub_converter("ocr")@@ -480,12 +487,29 @@ class TestDoclingSpec:side_effect=[default_converter, ocr_converter])- with pytest.raises(RuntimeError, match="staged artifact initialization failed"):- adapter.load("cpu")+ adapter.load("cpu")assert default_converter.convert.call_count == 1assert ocr_converter.convert.call_count == 1- assert not adapter._loaded+ assert adapter._loaded+ # The default (non-OCR) converter stays cached; the failed OCR one does not.+ assert set(adapter._converters) == {False}++ def test_default_profile_survives_missing_ocr_assets(self, tmp_path: Path) -> None:+ """A born-digital parse still serves when only the OCR assets are missing."""+ adapter = DoclingAdapter(package_artifact_root=tmp_path)+ default_converter = _stub_converter("default")+ ocr_converter = _stub_converter("ocr")+ ocr_converter.convert.side_effect = FileNotFoundError("missing staged OCR model")+ adapter._make_converter = MagicMock( # type: ignore[method-assign]+ side_effect=[default_converter, ocr_converter]+ )+ adapter.load("cpu")++ result = adapter.extract([Item(document={"data": b"%PDF-1.4", "format": "pdf"})])++ assert result.errors is None+ assert adapter._make_converter.call_count == 2 # cached default converter reuseddef test_local_model_source_is_used_as_artifact_root(self, tmp_path: Path) -> None:adapter = DoclingAdapter(model_name_or_path=tmp_path)diff --git a/packages/sie_server/tests/adapters/test_generation_base.py b/packages/sie_server/tests/adapters/test_generation_base.pynew file mode 100644index 000000000..d0b565b37--- /dev/null+++ b/packages/sie_server/tests/adapters/test_generation_base.py@@ -0,0 +1,275 @@+from __future__ import annotations++from collections.abc import AsyncIterator++import pytest+from sie_server.adapters._generation_base import (+ GenerationChunk,+ reasoning_starts_in_prompt,+ suppress_thinking_blocks,+)++_GEMMA_OPEN = "<" + "|channel" + ">" + "thought\n"+_GEMMA_CLOSE = "<" + "channel|" + ">"+++async def _chunks(*chunks: GenerationChunk) -> AsyncIterator[GenerationChunk]:+ for chunk in chunks:+ yield chunk+++async def test_suppress_thinking_blocks_handles_delimiters_split_across_chunks() -> None:+ raw = "<think>private chain of thought</think>Visible answer"+ source = _chunks(+ *(GenerationChunk(text_delta=char, is_first=index == 0) for index, char in enumerate(raw)),+ GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="stop",+ prompt_tokens=3,+ completion_tokens=11,+ ),+ )++ normalized = [chunk async for chunk in suppress_thinking_blocks(source)]++ assert "".join(chunk.text_delta for chunk in normalized) == "Visible answer"+ assert sum(chunk.is_first for chunk in normalized) == 1+ first_visible = next(chunk for chunk in normalized if chunk.text_delta)+ assert first_visible.is_first is True+ terminal = normalized[-1]+ assert terminal.done is True+ assert terminal.finish_reason == "stop"+ assert terminal.prompt_tokens == 3+ assert terminal.completion_tokens == 11+++async def test_suppress_gemma_thinking_handles_boundaries_split_across_chunks() -> None:+ raw = _GEMMA_OPEN + "private chain of thought" + _GEMMA_CLOSE + "Visible answer"+ source = _chunks(+ *(GenerationChunk(text_delta=char, is_first=index == 0) for index, char in enumerate(raw)),+ GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="stop",+ prompt_tokens=5,+ completion_tokens=13,+ ),+ )++ normalized = [chunk async for chunk in suppress_thinking_blocks(source, reasoning_format="gemma4")]++ assert "".join(chunk.text_delta for chunk in normalized) == "Visible answer"+ assert sum(chunk.is_first for chunk in normalized) == 1+ terminal = normalized[-1]+ assert terminal.done is True+ assert terminal.finish_reason == "stop"+ assert terminal.prompt_tokens == 5+ assert terminal.completion_tokens == 13+++async def test_suppress_gemma_thinking_can_start_inside_prompt_seeded_reasoning() -> None:+ prompt = "prefix" + _GEMMA_OPEN.removesuffix("thought\n")+ source = _chunks(+ GenerationChunk(text_delta="thought\nprivate reasoning" + _GEMMA_CLOSE[:5], is_first=True),+ GenerationChunk(text_delta=_GEMMA_CLOSE[5:] + "Visible answer"),+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),+ )++ normalized = [+ chunk+ async for chunk in suppress_thinking_blocks(+ source,+ start_inside=reasoning_starts_in_prompt(prompt, "gemma4"),+ reasoning_format="gemma4",+ )+ ]++ assert "".join(chunk.text_delta for chunk in normalized) == "Visible answer"+++async def test_suppress_thinking_blocks_can_start_inside_prompt_seeded_reasoning() -> None:+ source = _chunks(+ GenerationChunk(text_delta="private reasoning</thi", is_first=True),+ GenerationChunk(text_delta="nk>Visible answer"),+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),+ )++ normalized = [chunk async for chunk in suppress_thinking_blocks(source, start_inside=True)]++ assert "".join(chunk.text_delta for chunk in normalized) == "Visible answer"+++async def test_suppress_thinking_blocks_preserves_normal_text_and_logprobs() -> None:+ logprobs = (+ {+ "token": "hello",+ "logprob": -0.1,+ "bytes": list(b"hello"),+ "top_logprobs": [],+ },+ )+ ordinary = GenerationChunk(text_delta="hello", is_first=True, logprobs=logprobs)+ terminal = GenerationChunk(text_delta="", done=True, finish_reason="stop")++ normalized = [chunk async for chunk in suppress_thinking_blocks(_chunks(ordinary, terminal))]++ assert normalized == [ordinary, terminal]++[email protected]("text", ["answer <", "answer </", "answer <thi"])+async def test_suppress_thinking_blocks_flushes_partial_marker_prefix_at_end(text: str) -> None:+ source = _chunks(+ GenerationChunk(text_delta=text, is_first=True),+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),+ )++ normalized = [chunk async for chunk in suppress_thinking_blocks(source)]++ assert "".join(chunk.text_delta for chunk in normalized) == text+ assert normalized[-1].done is True+++async def test_suppress_thinking_blocks_hides_truncated_reasoning_and_its_logprobs() -> None:+ reasoning_logprobs = (+ {+ "token": "private",+ "logprob": -0.1,+ "bytes": list(b"private"),+ "top_logprobs": [],+ },+ )+ source = _chunks(+ GenerationChunk(text_delta="<think>private", is_first=True, logprobs=reasoning_logprobs),+ GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="length",+ completion_tokens=2,+ logprobs=reasoning_logprobs,+ ),+ )++ normalized = [chunk async for chunk in suppress_thinking_blocks(source)]++ assert len(normalized) == 1+ assert normalized[0].done is True+ assert normalized[0].finish_reason == "length"+ assert normalized[0].completion_tokens == 2+ assert normalized[0].text_delta == ""+ assert normalized[0].logprobs is None+++async def test_suppress_thinking_blocks_normalizes_non_streaming_candidates() -> None:+ candidate_logprobs = [{"token": "<think>", "logprob": -0.2}]+ terminal = GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="stop",+ candidates=(+ {+ "text": "<think>secret</think>answer one",+ "finish_reason": "stop",+ "logprobs": candidate_logprobs,+ },+ {+ "text": "answer two",+ "finish_reason": "stop",+ "logprobs": None,+ },+ {+ "text": "answer <thi",+ "finish_reason": "stop",+ "logprobs": [{"token": "<thi", "logprob": -0.3}],+ },+ ),+ )++ [normalized] = [chunk async for chunk in suppress_thinking_blocks(_chunks(terminal))]++ assert normalized.candidates is not None+ assert normalized.candidates[0]["text"] == "answer one"+ assert normalized.candidates[0]["logprobs"] is None+ assert normalized.candidates[1]["text"] == "answer two"+ assert normalized.candidates[2]["text"] == "answer <thi"+ assert normalized.candidates[2]["logprobs"] == [{"token": "<thi", "logprob": -0.3}]+++async def test_suppress_thinking_blocks_normalizes_prompt_seeded_reasoning_candidate() -> None:+ terminal = GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="stop",+ candidates=(+ {+ "text": "private reasoning</think>Visible answer",+ "finish_reason": "stop",+ "logprobs": [{"token": "private", "logprob": -0.2}],+ },+ ),+ )++ [normalized] = [chunk async for chunk in suppress_thinking_blocks(_chunks(terminal), start_inside=True)]++ assert normalized.candidates is not None+ assert normalized.candidates[0]["text"] == "Visible answer"+ assert normalized.candidates[0]["logprobs"] is None+++async def test_suppress_gemma_thinking_normalizes_blocking_candidate() -> None:+ terminal = GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="stop",+ candidates=(+ {+ "text": _GEMMA_OPEN + "private reasoning" + _GEMMA_CLOSE + "Visible answer",+ "finish_reason": "stop",+ "logprobs": [{"token": "private", "logprob": -0.2}],+ },+ ),+ )++ [normalized] = [chunk async for chunk in suppress_thinking_blocks(_chunks(terminal), reasoning_format="gemma4")]++ assert normalized.candidates is not None+ assert normalized.candidates[0]["text"] == "Visible answer"+ assert normalized.candidates[0]["logprobs"] is None+++def test_reasoning_starts_in_prompt_uses_family_specific_unmatched_boundary() -> None:+ assert reasoning_starts_in_prompt("prefix" + _GEMMA_OPEN, "gemma4") is True+ assert reasoning_starts_in_prompt("prefix" + _GEMMA_OPEN.removesuffix("thought\n"), "gemma4") is True+ assert reasoning_starts_in_prompt("prefix" + _GEMMA_OPEN.removesuffix("thought\n") + "final\n", "gemma4") is False+ assert reasoning_starts_in_prompt("prefix" + _GEMMA_OPEN + "done" + _GEMMA_CLOSE, "gemma4") is False+ assert reasoning_starts_in_prompt("ordinary prompt", "gemma4") is False+++async def test_suppress_thinking_blocks_closes_upstream_on_client_cancel() -> None:+ closed = False++ async def source() -> AsyncIterator[GenerationChunk]:+ nonlocal closed+ try:+ yield GenerationChunk(text_delta="visible", is_first=True)+ yield GenerationChunk(text_delta="still running")+ finally:+ closed = True++ normalized = suppress_thinking_blocks(source())+ first = await normalized.__anext__()+ assert first.text_delta == "visible"+ await normalized.aclose()++ assert closed is Truediff --git a/packages/sie_server/tests/adapters/test_pylate_dense.py b/packages/sie_server/tests/adapters/test_pylate_dense.pyindex 3a9557ff3..e2350ef43 100644--- a/packages/sie_server/tests/adapters/test_pylate_dense.py+++ b/packages/sie_server/tests/adapters/test_pylate_dense.py@@ -122,10 +122,41 @@ def test_bias_true_rejected(tmp_path: Path) -> None:assert chain is None-def test_use_residual_true_rejected(tmp_path: Path) -> None:- path = _write_checkpoint(tmp_path / "ckpt", [(768, 128)], config_overrides={1: {"use_residual": True}})+def test_dimension_changing_residual_is_composed(tmp_path: Path) -> None:+ linear = torch.randn(6, 8)+ residual = torch.randn(6, 8)+ path = _write_checkpoint(+ tmp_path / "ckpt",+ [(8, 6)],+ config_overrides={1: {"use_residual": True}},+ state_overrides={1: {"linear.weight": linear, "residual.weight": residual}},+ )- chain = load_pylate_dense_chain(path, hidden_size=768, token_dim=128, device="cpu", dtype=torch.float32)+ chain = load_pylate_dense_chain(path, hidden_size=8, token_dim=6, device="cpu", dtype=torch.float32)++ assert chain is not None+ assert torch.equal(chain[0], linear + residual)+++def test_same_dimension_residual_is_composed_with_identity(tmp_path: Path) -> None:+ linear = torch.randn(8, 8)+ path = _write_checkpoint(+ tmp_path / "ckpt",+ [(8, 8)],+ config_overrides={1: {"use_residual": True}},+ state_overrides={1: {"linear.weight": linear}},+ )++ chain = load_pylate_dense_chain(path, hidden_size=8, token_dim=8, device="cpu", dtype=torch.float32)++ assert chain is not None+ assert torch.equal(chain[0], linear + torch.eye(8))+++def test_dimension_changing_residual_missing_weight_rejected(tmp_path: Path) -> None:+ path = _write_checkpoint(tmp_path / "ckpt", [(8, 6)], config_overrides={1: {"use_residual": True}})++ chain = load_pylate_dense_chain(path, hidden_size=8, token_dim=6, device="cpu", dtype=torch.float32)assert chain is None@@ -142,9 +173,7 @@ def test_missing_use_residual_key_ok(tmp_path: Path) -> None:def test_non_identity_activation_rejected(tmp_path: Path) -> None:- """Reject a non-Identity activation_function: pylate never applies it, but its- presence means the checkpoint was trained with math we would not reproduce.- """+ """Reject an activation that cannot be reduced to the stored linear weights."""path = _write_checkpoint(tmp_path / "ckpt",[(768, 128)],diff --git a/packages/sie_server/tests/adapters/test_qwen3_vl_reranker.py b/packages/sie_server/tests/adapters/test_qwen3_vl_reranker.pyindex 43a7b3ea4..8fd2e14ae 100644--- a/packages/sie_server/tests/adapters/test_qwen3_vl_reranker.py+++ b/packages/sie_server/tests/adapters/test_qwen3_vl_reranker.py@@ -6,6 +6,7 @@ from concurrent.futures import ThreadPoolExecutorfrom types import SimpleNamespacefrom typing import Any, ClassVar+import numpy as npimport pytestimport torchfrom sie_server.adapters.qwen3_vl_reranker.adapter import (@@ -227,6 +228,55 @@ class _FakeProcessor:return output+class _Transformers53Processor(_FakeProcessor):+ """Stand-in for the transformers>=5.3.0 ``Qwen3VLProcessor`` contract.++ 5.3.0 flipped ``Qwen3VLProcessorKwargs._defaults["text_kwargs"]+ ["return_mm_token_type_ids"]`` from False to True and builds that map with+ ``np.array(input_ids)`` — which cannot represent an unpadded batch of+ unequal-length prompts, so it raises for every multi-pair request while+ single-pair ones slip through (issue #2856).+ """++ image_token_id = 1++ def _tokenize(self, prompt: str) -> tuple[list[int], list[tuple[int, int]]]:+ ids: list[int] = []+ offsets: list[tuple[int, int]] = []+ cursor = 0+ while cursor < len(prompt):+ if prompt.startswith(self.image_token, cursor):+ ids.append(self.image_token_id)+ offsets.append((cursor, cursor + len(self.image_token)))+ cursor += len(self.image_token)+ else:+ ids.append(2 + ord(prompt[cursor]) % 120)+ offsets.append((cursor, cursor + 1))+ cursor += 1+ return ids, offsets++ def __call__(self, **kwargs: Any) -> dict[str, Any]:+ self.calls.append(kwargs)+ tokenized = [self._tokenize(prompt) for prompt in kwargs["text"]]+ rows = [ids for ids, _ in tokenized]+ output: dict[str, Any] = {+ "input_ids": rows,+ "attention_mask": [[1] * len(row) for row in rows],+ "offset_mapping": [offsets for _, offsets in tokenized],+ }+ if kwargs.get("images"):+ image_count = len(kwargs["images"])+ output["pixel_values"] = torch.ones((image_count, 1))+ output["image_grid_thw"] = torch.ones((image_count, 3), dtype=torch.long)+ if kwargs.get("return_mm_token_type_ids", True):+ # Verbatim shape of the 5.3.0 processor body: this is what raises.+ array_ids = np.array(rows)+ mm_token_type_ids = np.zeros_like(array_ids)+ mm_token_type_ids[array_ids == self.image_token_id] = 1+ output["mm_token_type_ids"] = mm_token_type_ids.tolist()+ return output++class _RaceDetectingProcessor(_FakeProcessor):"""Emulate shared fast-tokenizer mutation across processor methods."""@@ -285,6 +335,7 @@ class _FakeModel:self.calls = 0self.attention_implementations: list[str] = []self.last_input_ids: torch.Tensor | None = None+ self.last_kwargs: dict[str, Any] = {}def set_attn_implementation(self, attention: str) -> None:self.attention_implementations.append(attention)@@ -292,6 +343,7 @@ class _FakeModel:def __call__(self, **kwargs: Any) -> SimpleNamespace:self.calls += 1self.last_input_ids = kwargs["input_ids"]+ self.last_kwargs = kwargsbatch_size, sequence_length = kwargs["input_ids"].shapelogits = torch.zeros((batch_size, sequence_length, 4))for index in range(batch_size):@@ -330,11 +382,79 @@ def test_vl_score_pairs_batches_forward_and_surfaces_measured_units(monkeypatch:assert processor.calls[0]["padding"] is Falseassert processor.calls[0]["return_tensors"] is Noneassert processor.calls[0]["return_offsets_mapping"] is True+ assert processor.calls[0]["return_mm_token_type_ids"] is Falseassert output.scores.tolist() == pytest.approx([0.880797, 0.119203])assert output.input_token_counts == [len(prompt) for prompt in processed_prompts]assert output.input_image_counts == [0, 1]+def test_vl_multi_pair_scoring_survives_transformers_5_3_processor_defaults() -> None:+ """FIX[#2856]: a ragged multi-pair batch must not trip the 5.3 mm-id default.++ Single-pair scoring passed throughout the outage because one prompt is never+ ragged, so this asserts the ``items >= 2`` shape that actually broke.+ """+ adapter = Qwen3VLRerankerAdapter("unused")+ model = _FakeModel()+ processor = _Transformers53Processor()+ adapter._model = model # ty: ignore[invalid-assignment]+ adapter._processor = processor # ty: ignore[invalid-assignment]+ adapter._device = "cpu"+ adapter._yes_token_id = 1+ adapter._no_token_id = 2++ output = adapter.score_pairs(+ [Item(text="query"), Item(text="query")],+ [Item(text="short"), Item(text="a document long enough to make the batch ragged")],+ )++ assert model.calls == 1+ assert len(output.scores) == 2+ assert output.input_token_counts[0] != output.input_token_counts[1]+ assert processor.calls[0]["return_mm_token_type_ids"] is False+ # transformers <5.3 has no such forward parameter, so nothing is sent.+ assert "mm_token_type_ids" not in model.last_kwargs+++def test_vl_mm_token_type_ids_track_the_trimmed_and_padded_ids(monkeypatch: pytest.MonkeyPatch) -> None:+ """FIX[#2856]: 5.3+ derives vision RoPE from mm_token_type_ids, so ours must align.++ The processor's own map is built before per-document truncation and padding,+ so the adapter rebuilds it against the ids the model is actually handed.+ """+ adapter = Qwen3VLRerankerAdapter("unused")+ model = _FakeModel()+ processor = _Transformers53Processor()+ adapter._model = model # ty: ignore[invalid-assignment]+ adapter._processor = processor # ty: ignore[invalid-assignment]+ adapter._device = "cpu"+ adapter._yes_token_id = 1+ adapter._no_token_id = 2+ adapter._image_token_id = processor.image_token_id+ adapter._accepts_mm_token_type_ids = True+ monkeypatch.setattr(adapter, "_load_first_image", lambda _item: object())++ output = adapter.score_pairs(+ [Item(text="query"), Item(text="query")],+ [+ Item(text="short"),+ Item(+ text="a document long enough to be truncated by the window",+ images=[{"data": b"doc-image"}],+ ),+ ],+ options={"max_seq_length": 250},+ )++ input_ids = model.last_kwargs["input_ids"]+ mm_token_type_ids = model.last_kwargs["mm_token_type_ids"]+ assert mm_token_type_ids.shape == input_ids.shape+ assert torch.equal(mm_token_type_ids, (input_ids == processor.image_token_id).to(mm_token_type_ids.dtype))+ # The image pair keeps its image token; the text-only pair has none.+ assert mm_token_type_ids.sum(dim=1).tolist() == [0, 1]+ assert max(output.input_token_counts) == 250++def test_vl_processor_tokenization_is_thread_safe() -> None:adapter = Qwen3VLRerankerAdapter("unused")model = _FakeModel()diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.pyindex cc8d24073..b0e2ef82e 100644--- a/packages/sie_server/tests/adapters/test_sglang_generation.py+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py@@ -13,11 +13,16 @@ from __future__ import annotationsimport asyncioimport base64+import os+import subprocess+import sys+from pathlib import Pathfrom typing import Any, Selffrom unittest.mock import AsyncMock, MagicMock, patchimport pytest-from sie_server.adapters._generation_base import GenerationChunk, collect_generation+from sie_server.adapters._generation_base import GenerationChunk, collect_generation, suppress_thinking_blocks+from sie_server.adapters.sglang.cuda13 import SGLangStrictThinkingAdapterfrom sie_server.adapters.sglang.generation import (SGLangGenerationAdapter,_chunk_from_sglang_event,@@ -52,6 +57,25 @@ def test_load_contract_flags() -> None:assert SGLangGenerationAdapter.manages_own_load_timeout is True+def test_cuda13_strict_thinking_adapter_adds_launch_guard_once() -> None:+ added = SGLangStrictThinkingAdapter(+ "test-model",+ extra_launch_args=["--quantization", "fp8"],+ )+ retained = SGLangStrictThinkingAdapter(+ "test-model",+ extra_launch_args=["--quantization", "fp8", "--enable-strict-thinking"],+ )++ expected = [+ "--quantization",+ "fp8",+ "--enable-strict-thinking",+ ]+ assert added._extra_launch_args == expected+ assert retained._extra_launch_args == expected++def test_load_required_memory_bytes_uses_mem_fraction_static() -> None:gb = 1024**3adapter = SGLangGenerationAdapter("test-model", mem_fraction_static=0.8)@@ -124,6 +148,40 @@ def test_load_drops_is_embedding(assert cmd[cmd.index("--grammar-backend") + 1] == "outlines"assert "--served-model-name" in cmdassert adapter._server_url == "http://localhost:30005"+ child_env = mock_popen.call_args.kwargs["env"]+ assert child_env["SIE_SGLANG_MM_PROCESS_CONFIG_COMPAT"] == "1"+ expected_compat_dir = Path(__file__).resolve().parents[2] / "src/sie_server/adapters/sglang/_compat"+ assert child_env["PYTHONPATH"].split(os.pathsep)[0] == str(expected_compat_dir)+++@patch("sie_server.adapters.sglang._server.subprocess.Popen")+@patch("sie_server.adapters.sglang._server.requests.get")+@patch("sie_server.adapters.sglang._server.find_free_port")+def test_load_ignores_configured_pythonpath(+ mock_find_port: MagicMock,+ mock_requests_get: MagicMock,+ mock_popen: MagicMock,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ mock_find_port.return_value = 30005+ mock_process = MagicMock()+ mock_process.poll.return_value = None+ mock_popen.return_value = mock_process+ mock_requests_get.return_value = MagicMock(status_code=200)+ inherited = os.pathsep.join(("/operator/one", "/operator/two"))+ monkeypatch.setenv("PYTHONPATH", inherited)+ adapter = SGLangGenerationAdapter(+ model_name_or_path="Qwen/Qwen3-4B-Instruct",+ extra_env={"PYTHONPATH": "/checkpoint-controlled", "SAFE_FLAG": "1"},+ )++ adapter.load("cuda:0")++ child_env = mock_popen.call_args.kwargs["env"]+ expected_compat_dir = Path(__file__).resolve().parents[2] / "src/sie_server/adapters/sglang/_compat"+ assert child_env["PYTHONPATH"] == os.pathsep.join((str(expected_compat_dir), inherited))+ assert "/checkpoint-controlled" not in child_env["PYTHONPATH"]+ assert child_env["SAFE_FLAG"] == "1"@patch("sie_server.adapters.sglang._server.wait_for_server", return_value=True)@@ -298,6 +356,28 @@ def test_generate_streams_sse_into_chunks(mock_async_client: MagicMock, adapter)assert chunks[-1].completion_tokens == 3+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_generate_surfaces_in_band_sglang_error(mock_async_client: MagicMock, adapter) -> None:+ stream = _FakeStreamingResponse(+ [+ 'data: {"error": {"message": "vision processor rejected image"}}',+ "data: [DONE]",+ ]+ )+ mock_async_client.return_value = _make_client_with_stream(stream)+ adapter._server_url = "http://localhost:30005"++ async def _collect() -> None:+ async for _ in adapter.generate(prompt="Hi", max_new_tokens=8):+ pass++ with pytest.raises(+ RuntimeError,+ match="SGLang /generate error: vision processor rejected image",+ ):+ asyncio.run(_collect())++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")def test_generate_collect_into_result(mock_async_client: MagicMock, adapter) -> None:sse_lines = [@@ -613,9 +693,38 @@ def test_generate_request_body_uses_stream_true(mock_async_client: MagicMock, adassert body["stream"] is Trueassert body["sampling_params"]["max_new_tokens"] == 64assert body["sampling_params"]["temperature"] == pytest.approx(0.7)+ assert "skip_special_tokens" not in body["sampling_params"]assert "rid" in body # cancellation handle+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_gemma_generate_preserves_reasoning_markers_for_sie_suppression(mock_async_client: MagicMock) -> None:+ sse_lines = [+ 'data: {"text": "<|channel>thought\\nprivate<channel|>answer", "meta_info": {"prompt_tokens": 1, "completion_tokens": 4, "finish_reason": {"type": "stop"}}}',+ ]+ client_instance = _make_client_with_stream(_FakeStreamingResponse(sse_lines))+ mock_async_client.return_value = client_instance+ adapter = SGLangGenerationAdapter(+ model_name_or_path="google/gemma-4-31B-it",+ served_model_name="google/gemma-4-31B-it",+ reasoning_parser="gemma4",+ )+ adapter._server_url = "http://localhost:30005"++ result = asyncio.run(+ collect_generation(+ suppress_thinking_blocks(+ adapter.generate(prompt="Hi", max_new_tokens=8),+ reasoning_format="gemma4",+ )+ )+ )++ body = client_instance.stream.call_args.kwargs["json"]+ assert body["sampling_params"]["skip_special_tokens"] is False+ assert result.text == "answer"++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")def test_generate_logprobs_request_sets_return_text_in_logprobs(mock_async_client: MagicMock, adapter) -> None:"""A logprobs request must ask SGLang for decoded token TEXT.@@ -1775,3 +1884,64 @@ def test_non_guard_model_streaming_unaffected(mock_async_client: MagicMock, adap# Client didn't request logprobs and the model isn't a guard → all None.assert all(c.logprobs is None for c in chunks)assert any(c.done for c in chunks)+++def test_mm_process_config_compat_forwards_image_kwargs(tmp_path: Path) -> None:+ package_root = tmp_path / "fake-package"+ processors = package_root / "sglang" / "srt" / "multimodal" / "processors"+ processors.mkdir(parents=True)+ package_dirs = (+ package_root / "sglang",+ package_root / "sglang" / "srt",+ package_root / "sglang" / "srt" / "multimodal",+ processors,+ )+ for package in package_dirs:+ (package / "__init__.py").write_text("", encoding="utf-8")+ (processors / "base_processor.py").write_text(+ """class BaseMultimodalProcessor:+ def __init__(self):+ self.image_config = {"min_pixels": 65536, "max_pixels": 1003520}++ def process_mm_data(self, input_text, images=None, videos=None, audios=None, **kwargs):+ return kwargs+""",+ encoding="utf-8",+ )++ compat_dir = Path(__file__).resolve().parents[2] / "src/sie_server/adapters/sglang/_compat"+ script = """import sitecustomize++sitecustomize._install_mm_process_config_compat()+sitecustomize._install_mm_process_config_compat()++from sglang.srt.multimodal.processors.base_processor import BaseMultimodalProcessor++sitecustomize._patch_base_processor_module(__import__(+ "sglang.srt.multimodal.processors.base_processor",+ fromlist=["BaseMultimodalProcessor"],+))+processor = BaseMultimodalProcessor()+assert processor.process_mm_data("x", images=[b"image"]) == {+ "images_kwargs": {"min_pixels": 65536, "max_pixels": 1003520}+}+assert processor.process_mm_data("x", images=None) == {}+assert not hasattr(BaseMultimodalProcessor.process_mm_data.__wrapped__, "__wrapped__")+print("mm-process-config-ready")+"""+ env = dict(os.environ)+ env["PYTHONPATH"] = os.pathsep.join((str(compat_dir), str(package_root)))+ env["SIE_SGLANG_MM_PROCESS_CONFIG_COMPAT"] = "1"++ completed = subprocess.run( # noqa: S603 - executes the fixed local interpreter+ [sys.executable, "-c", script],+ env=env,+ capture_output=True,+ text=True,+ timeout=15,+ check=False,+ )++ assert completed.returncode == 0, completed.stderr+ assert "Error in sitecustomize" not in completed.stderr+ assert completed.stdout.strip() == "mm-process-config-ready"diff --git a/packages/sie_server/tests/adapters/test_sglang_vision_extract.py b/packages/sie_server/tests/adapters/test_sglang_vision_extract.pyindex 784935a00..1c2650756 100644--- a/packages/sie_server/tests/adapters/test_sglang_vision_extract.py+++ b/packages/sie_server/tests/adapters/test_sglang_vision_extract.py@@ -12,6 +12,7 @@ from unittest.mock import MagicMock, patchimport pytestimport yamlfrom sie_server.adapters._generation_base import GenerationChunk+from sie_server.adapters.sglang.generation import SGLangGenerationAdapterfrom sie_server.adapters.sglang_vision_extract.adapter import SGLangVisionExtractAdapterfrom sie_server.config.model import ModelConfigfrom sie_server.types.inputs import ImageInput, InvalidMediaError, Item@@ -78,14 +79,48 @@ def test_device_factory_does_not_apply_text_only_mlx_fallback() -> None:assert isinstance(instance, SGLangVisionExtractAdapter)-def test_compat_path_is_prepended_to_inherited_pythonpath(monkeypatch: pytest.MonkeyPatch) -> None:+def test_compat_paths_are_fixed_and_prepend_lighton_hook(monkeypatch: pytest.MonkeyPatch) -> None:inherited = os.pathsep.join(("/inherited/one", "/inherited/two"))monkeypatch.setenv("PYTHONPATH", inherited)- instance = SGLangVisionExtractAdapter("lightonai/LightOnOCR-2-1B")+ instance = SGLangVisionExtractAdapter(+ "lightonai/LightOnOCR-2-1B",+ extra_env={"PYTHONPATH": "/checkpoint-controlled"},+ )- compat_dir = Path(__file__).resolve().parents[2] / "src/sie_server/adapters/sglang_vision_extract/_compat"- assert instance._extra_env["PYTHONPATH"] == os.pathsep.join((str(compat_dir), inherited))+ source_root = Path(__file__).resolve().parents[2] / "src/sie_server/adapters"+ assert os.pathsep.join(instance._compat_pythonpath_entries()) == os.pathsep.join(+ (str(source_root / "sglang_vision_extract/_compat"), str(source_root / "sglang/_compat"), inherited)+ )+++@patch("sie_server.adapters.sglang._server.subprocess.Popen")+@patch("sie_server.adapters.sglang._server.requests.get")+@patch("sie_server.adapters.sglang._server.find_free_port")+def test_engine_launch_preserves_lighton_sitecustomize_precedence(+ mock_find_port: MagicMock,+ mock_requests_get: MagicMock,+ mock_popen: MagicMock,+) -> None:+ mock_find_port.return_value = 30005+ mock_process = MagicMock()+ mock_process.poll.return_value = None+ mock_popen.return_value = mock_process+ mock_requests_get.return_value = MagicMock(status_code=200)+ instance = SGLangVisionExtractAdapter(+ "lightonai/LightOnOCR-2-1B",+ extra_env={"SIE_SGLANG_LIGHTON_OCR_COMPAT": "1", "PYTHONPATH": "/checkpoint-controlled"},+ )++ SGLangGenerationAdapter.load(instance, "cuda:0")++ child_env = mock_popen.call_args.kwargs["env"]+ source_root = Path(__file__).resolve().parents[2] / "src/sie_server/adapters"+ assert child_env["PYTHONPATH"].split(os.pathsep)[:2] == [+ str(source_root / "sglang_vision_extract/_compat"),+ str(source_root / "sglang/_compat"),+ ]+ assert "/checkpoint-controlled" not in child_env["PYTHONPATH"]def test_lighton_default_profile_enables_compat_hook() -> None:diff --git a/packages/sie_server/tests/api/test_generate.py b/packages/sie_server/tests/api/test_generate.pyindex b3e1155ed..542c25278 100644--- a/packages/sie_server/tests/api/test_generate.py+++ b/packages/sie_server/tests/api/test_generate.py@@ -9,6 +9,7 @@ calls the adapter directly (no NATS, no gateway). The gateway-side handlerfrom __future__ import annotationsimport asyncio+import jsonfrom collections.abc import AsyncIteratorfrom typing import Literalfrom unittest.mock import AsyncMock, MagicMock@@ -34,6 +35,9 @@ from sie_server.core.registry import ModelRegistryfrom sie_server.types.grammar import GrammarSpecfrom sie_server.types.inputs import ImageInput+_GEMMA_OPEN = "<" + "|channel" + ">" + "thought\n"+_GEMMA_CLOSE = "<" + "channel|" + ">"+class _FakeGenAdapter(GenerationAdapter):"""Minimal in-memory GenerationAdapter for route tests."""@@ -158,13 +162,52 @@ class _LegacyTextGenAdapter(_FakeGenAdapter):)+class _ThinkingGenAdapter(_FakeGenAdapter):+ """Script reasoning delimiters across engine chunk boundaries."""++ def __init__(self, *, prompt_seeded: bool = False, gemma: bool = False) -> None:+ super().__init__()+ self._prompt_seeded = prompt_seeded+ self._opening = _GEMMA_OPEN if gemma else "<think>"+ self._closing = _GEMMA_CLOSE if gemma else "</think>"++ async def generate(+ self,+ prompt: str,+ *,+ max_new_tokens: int,+ **kwargs: object,+ ) -> AsyncIterator[GenerationChunk]:+ _ = (prompt, max_new_tokens, kwargs)+ text_chunks = (+ ("private", " reasoning" + self._closing[:5], self._closing[5:] + "Visible answer")+ if self._prompt_seeded+ else (+ self._opening[:5],+ self._opening[5:] + "private",+ " reasoning" + self._closing[:5],+ self._closing[5:] + "Visible answer",+ )+ )+ for text in text_chunks:+ yield GenerationChunk(text_delta=text)+ yield GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="stop",+ prompt_tokens=1,+ completion_tokens=8,+ )++def _make_config(*,+ model_id: str = "Qwen/Qwen3-4B-Instruct",grammar: list[Literal["json_schema", "regex", "ebnf"]] | None = None,) -> ModelConfig:return ModelConfig(- sie_id="Qwen/Qwen3-4B-Instruct",- hf_id="Qwen/Qwen3-4B-Instruct",+ sie_id=model_id,+ hf_id=model_id,tasks=Tasks(generate=GenerateTask(context_length=32768,@@ -177,6 +220,9 @@ def _make_config(adapter_path="sie_server.adapters.sglang:SGLangGenerationAdapter",max_batch_tokens=16384,kv_budget_tokens=8192,+ adapter_options=AdapterOptions(+ loadtime={"reasoning_parser": "gemma4" if model_id.startswith("google/gemma") else "qwen3"}+ ),),},)@@ -213,6 +259,57 @@ def client(registry: MagicMock) -> TestClient:class TestGenerateEndpoint:+ @pytest.mark.parametrize("stream", [False, True])+ @pytest.mark.parametrize("enable_thinking", [False, True])+ @pytest.mark.parametrize("model_id", ["Qwen/Qwen3.5-4B", "google/gemma-4-E2B-it"])+ def test_reasoning_output_is_hidden_for_every_resolved_profile(+ self,+ client: TestClient,+ registry: MagicMock,+ monkeypatch: pytest.MonkeyPatch,+ stream: bool,+ enable_thinking: bool,+ model_id: str,+ ) -> None:+ config = _make_config(model_id=model_id)+ gemma = model_id.startswith("google/gemma")+ opening = _GEMMA_OPEN if gemma else "<think>"+ assert config.tasks.generate is not None+ config.tasks.generate.chat_template_kwargs = {"enable_thinking": enable_thinking}+ if enable_thinking:+ config.inputs = InputModalities(text=True, image=True)++ async def render(_config: object, prompt: str, image_count: int) -> str:+ assert prompt == "Hello"+ assert image_count == 1+ return "rendered thinking prompt" + opening++ monkeypatch.setattr(generate_api, "_render_native_image_prompt", render)+ registry.get_config.return_value = config+ registry.get.return_value = _ThinkingGenAdapter(prompt_seeded=enable_thinking, gemma=gemma)++ request: dict[str, object] = {"prompt": "Hello", "max_new_tokens": 16, "stream": stream}+ if enable_thinking:+ request["images"] = [{"data": "aGVsbG8=", "format": "png"}]++ response = client.post(+ f"/v1/generate/{model_id.replace('/', '__')}",+ json=request,+ )++ assert response.status_code == 200, response.text+ if stream:+ events = [+ json.loads(line.removeprefix("data: "))+ for line in response.text.splitlines()+ if line.startswith("data: ") and line != "data: [DONE]"+ ]+ streamed_text = "".join(event.get("text_delta", "") for event in events)+ assert streamed_text == "Visible answer"+ assert "private reasoning" not in streamed_text+ else:+ assert response.json()["text"] == "Visible answer"+@pytest.mark.parametrize("stream", [False, True])def test_text_only_generate_preserves_legacy_adapter_call_signature(self,@@ -284,14 +381,16 @@ class TestGenerateEndpoint:assert fake_adapter.last_call["prompt"] == "<image>Read the image"assert fake_adapter.last_call["images"] == [{"data": b"hello", "format": "png"}]+ @pytest.mark.parametrize("enable_thinking", [False, True])def test_native_image_prompt_uses_pinned_trusted_model_tokenizer(self,monkeypatch: pytest.MonkeyPatch,+ enable_thinking: bool,) -> None:config = _make_config()config.hf_revision = "0123456789abcdef0123456789abcdef01234567"assert config.tasks.generate is not None- config.tasks.generate.chat_template_kwargs = {"enable_thinking": False}+ config.tasks.generate.chat_template_kwargs = {"enable_thinking": enable_thinking}captured: dict[str, object] = {}class _Tokenizer:@@ -321,7 +420,7 @@ class TestGenerateEndpoint:assert captured["template_kwargs"] == {"tokenize": False,"add_generation_prompt": True,- "enable_thinking": False,+ "enable_thinking": enable_thinking,}def test_native_image_prompt_coalesces_and_caches_tokenizer_loads(diff --git a/packages/sie_server/tests/api/test_openai_completions.py b/packages/sie_server/tests/api/test_openai_completions.pynew file mode 100644index 000000000..f687b0355--- /dev/null+++ b/packages/sie_server/tests/api/test_openai_completions.py@@ -0,0 +1,362 @@+"""Regression tests for direct ``/v1/completions`` generation."""++from __future__ import annotations++import json+from collections.abc import AsyncIterator+from unittest.mock import MagicMock++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from sie_server.adapters._generation_base import FinishReason, GenerationAdapter, GenerationChunk+from sie_server.adapters._spec import AdapterSpec+from sie_server.api.openai_completions import router+from sie_server.config.model import AdapterOptions, GenerateTask, ModelConfig, ProfileConfig, Tasks+from sie_server.core.registry import ModelRegistry+from sie_server.types.grammar import GrammarSpec+from sie_server.types.inputs import ImageInput++_GEMMA_OPEN = "<" + "|channel" + ">" + "thought\n"+_GEMMA_CLOSE = "<" + "channel|" + ">"+++class _FakeCompletionAdapter(GenerationAdapter):+ spec = AdapterSpec(inputs=("text",), outputs=("tokens",), unload_fields=())++ def __init__(self) -> None:+ self.last_call: dict[str, object] | None = None+ self.text_chunks = ["hello", " world"]+ self.finish_reason: FinishReason = "stop"++ def load(self, device: str) -> None: # pragma: no cover - registry is mocked loaded+ _ = device++ async def generate(+ self,+ prompt: str,+ *,+ max_new_tokens: int,+ temperature: float = 1.0,+ top_p: float = 1.0,+ stop: list[str] | None = None,+ frequency_penalty: float | None = None,+ presence_penalty: float | None = None,+ top_k: int | None = None,+ repetition_penalty: float | None = None,+ min_new_tokens: int | None = None,+ grammar: GrammarSpec | None = None,+ seed: int | None = None,+ logit_bias: dict[str, float] | None = None,+ logprobs: bool = False,+ top_logprobs: int | None = None,+ images: list[ImageInput] | None = None,+ ) -> AsyncIterator[GenerationChunk]:+ self.last_call = {+ "prompt": prompt,+ "max_new_tokens": max_new_tokens,+ "temperature": temperature,+ "top_p": top_p,+ "stop": stop,+ "frequency_penalty": frequency_penalty,+ "presence_penalty": presence_penalty,+ "top_k": top_k,+ "min_new_tokens": min_new_tokens,+ "seed": seed,+ }+ _ = repetition_penalty, grammar, logit_bias, logprobs, top_logprobs, images+ for index, text in enumerate(self.text_chunks):+ yield GenerationChunk(text_delta=text, is_first=index == 0)+ yield GenerationChunk(+ text_delta="",+ done=True,+ finish_reason=self.finish_reason,+ prompt_tokens=3,+ completion_tokens=2,+ )+++def _config(model_id: str = "Qwen/Qwen3-4B-Instruct") -> ModelConfig:+ return ModelConfig(+ sie_id=model_id,+ hf_id=model_id,+ tasks=Tasks(generate=GenerateTask(context_length=32768, max_output_tokens=64)),+ profiles={+ "default": ProfileConfig(+ adapter_path="test:FakeCompletionAdapter",+ max_batch_tokens=8192,+ kv_budget_tokens=4096,+ adapter_options=AdapterOptions(+ loadtime={"reasoning_parser": "gemma4" if model_id.startswith("google/gemma") else "qwen3"},+ runtime={+ "default_sampling": {+ "temperature": 0.25,+ "top_p": 0.8,+ "frequency_penalty": 0.75,+ "top_k": 12,+ "min_new_tokens": 2,+ "seed": 23,+ },+ "stop_tokens": ["</s>"],+ },+ ),+ )+ },+ )+++def adapter() -> _FakeCompletionAdapter:+ return _FakeCompletionAdapter()+++def registry(adapter: _FakeCompletionAdapter) -> MagicMock:+ reg = MagicMock(spec=ModelRegistry)+ reg.has_model.return_value = True+ reg.is_loaded.return_value = True+ reg.is_loading.return_value = False+ reg.is_unloading.return_value = False+ reg.is_failed.return_value = False+ reg.get_failure.return_value = None+ reg.get_config.return_value = _config()+ reg.get.return_value = adapter+ reg.device = "cpu"+ return reg+++def client(registry: MagicMock) -> TestClient:+ app = FastAPI()+ app.include_router(router)+ app.state.registry = registry+ return TestClient(app)+++def test_blocking_completion_uses_direct_adapter_and_openai_shape(+ client: TestClient,+ adapter: _FakeCompletionAdapter,+) -> None:+ response = client.post(+ "/v1/completions",+ json={+ "model": "Qwen/Qwen3-4B-Instruct",+ "prompt": ["Continue this"],+ "max_tokens": 8,+ "frequency_penalty": 0.5,+ "seed": -1,+ },+ )++ assert response.status_code == 200, response.text+ body = response.json()+ assert body["id"].startswith("cmpl-")+ assert body["object"] == "text_completion"+ assert body["model"] == "Qwen/Qwen3-4B-Instruct"+ assert body["choices"] == [{"text": "hello world", "index": 0, "finish_reason": "stop"}]+ assert body["usage"] == {"prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5}+ assert body["system_fingerprint"].startswith("fp_")+ assert adapter.last_call == {+ "prompt": "Continue this",+ "max_new_tokens": 8,+ "temperature": 0.25,+ "top_p": 0.8,+ "stop": ["</s>"],+ "frequency_penalty": 0.5,+ "presence_penalty": None,+ "top_k": 12,+ "min_new_tokens": 2,+ "seed": -1,+ }+++def test_completion_uses_profile_frequency_penalty_and_seed_defaults(+ client: TestClient,+ adapter: _FakeCompletionAdapter,+) -> None:+ response = client.post(+ "/v1/completions",+ json={+ "model": "Qwen/Qwen3-4B-Instruct",+ "prompt": "Continue this",+ "max_tokens": 8,+ },+ )++ assert response.status_code == 200, response.text+ assert adapter.last_call is not None+ assert adapter.last_call["frequency_penalty"] == 0.75+ assert adapter.last_call["seed"] == 23+++def test_completion_request_frequency_penalty_and_seed_override_profile_defaults(+ client: TestClient,+ adapter: _FakeCompletionAdapter,+) -> None:+ response = client.post(+ "/v1/completions",+ json={+ "model": "Qwen/Qwen3-4B-Instruct",+ "prompt": "Continue this",+ "max_tokens": 8,+ "frequency_penalty": -0.5,+ "seed": -1,+ },+ )++ assert response.status_code == 200, response.text+ assert adapter.last_call is not None+ assert adapter.last_call["frequency_penalty"] == -0.5+ assert adapter.last_call["seed"] == -1+++def test_streaming_completion_emits_openai_chunks_usage_and_done(client: TestClient) -> None:+ response = client.post(+ "/v1/completions",+ json={+ "model": "Qwen/Qwen3-4B-Instruct",+ "prompt": "Continue this",+ "max_tokens": 8,+ "stream": True,+ "stream_options": {"include_usage": True},+ },+ )++ assert response.status_code == 200, response.text+ payloads = [line.removeprefix("data: ") for line in response.text.splitlines() if line.startswith("data: ")]+ assert payloads[-1] == "[DONE]"+ events = [json.loads(payload) for payload in payloads[:-1]]+ assert [event["choices"][0]["text"] for event in events[:-1]] == ["hello", " world", ""]+ assert events[0]["choices"][0]["finish_reason"] is None+ assert events[2]["choices"][0]["finish_reason"] == "stop"+ assert events[-1]["choices"] == []+ assert events[-1]["usage"] == {"prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5}+ assert len({event["id"] for event in events}) == 1+++def test_streaming_completion_surfaces_cancelled_terminal_as_error(+ client: TestClient,+ adapter: _FakeCompletionAdapter,+) -> None:+ adapter.finish_reason = "cancelled"++ response = client.post(+ "/v1/completions",+ json={+ "model": "Qwen/Qwen3-4B-Instruct",+ "prompt": "Continue this",+ "max_tokens": 8,+ "stream": True,+ "stream_options": {"include_usage": True},+ },+ )++ assert response.status_code == 200, response.text+ payloads = [line.removeprefix("data: ") for line in response.text.splitlines() if line.startswith("data: ")]+ assert payloads[-1] == "[DONE]"+ events = [json.loads(payload) for payload in payloads[:-1]]+ terminal = events[-1]+ assert terminal["choices"] == [{"text": "", "index": 0, "finish_reason": None}]+ assert terminal["error"] == {+ "message": "generation was cancelled before completion",+ "type": "server_error",+ "param": None,+ "code": "generation_cancelled",+ }+ assert all("usage" not in event for event in events)++[email protected]("stream", [False, True])[email protected]("enable_thinking", [False, True])[email protected]("model_id", ["Qwen/Qwen3.5-4B", "google/gemma-4-E2B-it"])+def test_completion_hides_reasoning_for_every_resolved_profile(+ client: TestClient,+ registry: MagicMock,+ adapter: _FakeCompletionAdapter,+ stream: bool,+ enable_thinking: bool,+ model_id: str,+) -> None:+ config = _config(model_id)+ assert config.tasks.generate is not None+ config.tasks.generate.chat_template_kwargs = {"enable_thinking": enable_thinking}+ registry.get_config.return_value = config+ if model_id.startswith("google/gemma"):+ raw = _GEMMA_OPEN + "secret" + _GEMMA_CLOSE + "answer"+ adapter.text_chunks = [raw[:7], raw[7:19], raw[19:]]+ else:+ adapter.text_chunks = ["<thi", "nk>secret</th", "ink>answer"]++ response = client.post(+ "/v1/completions",+ json={+ "model": model_id,+ "prompt": "Continue this",+ "max_tokens": 8,+ "stream": stream,+ },+ )++ assert response.status_code == 200, response.text+ assert "secret" not in response.text+ assert "answer" in response.text+++ ("body", "param", "code"),+ [+ ({"model": "m", "prompt": "x", "tools": []}, "tools", "unsupported_field"),+ ({"model": "m", "prompt": ["x", "y"]}, "prompt", "unsupported_field"),+ ({"model": "m", "prompt": "x", "n": 2}, "n", "unsupported_field"),+ ({"model": "m", "prompt": "x", "max_tokens": True}, "max_tokens", "invalid_request"),+ ({"model": "m", "prompt": "x", "temperature": 1e100}, "temperature", "invalid_request"),+ ({"model": "m", "prompt": "x", "top_p": 0}, "top_p", "invalid_request"),+ ({"model": "m", "prompt": "x", "stop": ""}, "stop", "invalid_request"),+ ({"model": "m", "prompt": "x", "stop": ["ok", ""]}, "stop", "invalid_request"),+ ],+)+def test_invalid_requests_fail_before_registry_lookup(+ client: TestClient,+ registry: MagicMock,+ body: dict[str, object],+ param: str,+ code: str,+) -> None:+ response = client.post("/v1/completions", json=body)++ assert response.status_code == 400+ assert response.json()["error"]["param"] == param+ assert response.json()["error"]["code"] == code+ registry.has_model.assert_not_called()+++def test_model_output_cap_rejects_before_load(client: TestClient, registry: MagicMock) -> None:+ registry.is_loaded.return_value = False++ response = client.post(+ "/v1/completions",+ json={"model": "Qwen/Qwen3-4B-Instruct", "prompt": "x", "max_tokens": 65},+ )++ assert response.status_code == 400+ assert response.json()["error"]["code"] == "context_exceeded"+ registry.start_load_async.assert_not_called()+++def test_model_state_errors_use_openai_error_envelope(client: TestClient, registry: MagicMock) -> None:+ registry.has_model.return_value = False++ response = client.post(+ "/v1/completions",+ json={"model": "missing/model", "prompt": "x"},+ )++ assert response.status_code == 404+ assert response.json() == {+ "error": {+ "message": "Model 'missing/model' not found",+ "type": "invalid_request_error",+ "param": None,+ "code": "MODEL_NOT_FOUND",+ }+ }diff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.pyindex 01062d6cc..d500bdc78 100644--- a/packages/sie_server/tests/api/test_openai_local.py+++ b/packages/sie_server/tests/api/test_openai_local.py@@ -1,19 +1,31 @@-"""Input-contract tests for the Mac-local OpenAI routes (/v1/chat/completions, /v1/rerank).+"""Contract tests for the direct OpenAI routes (/v1/chat/completions, /v1/rerank).-These run on any platform — they exercise the request validation that happens-BEFORE the registry/model is touched, so no MLX subprocess or torch is needed.-The happy paths are covered live by ``mise run mac-smoke`` (Apple Silicon).+These run without a real model subprocess. Mock transports cover the CUDA+SGLang proxy and ordinary validation; the MLX happy path remains covered live+by ``mise run mac-smoke`` on Apple Silicon."""from __future__ import annotations+import json+from collections.abc import AsyncIterator, Callable+from types import SimpleNamespace+from typing import Anyfrom unittest.mock import MagicMock+import httpximport pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from openai.types.chat import ChatCompletion, ChatCompletionChunk+from sie_server.adapters.mlx.generation import MLXGenerationAdapter+from sie_server.adapters.sglang.generation import SGLangGenerationAdapter+from sie_server.api import openai_localfrom sie_server.api.openai_local import _validate_mlx_seed, router+_GEMMA_OPEN = "<" + "|channel" + ">" + "thought\n"+_GEMMA_CLOSE = "<" + "channel|" + ">"+def _client() -> TestClient:app = FastAPI()@@ -23,6 +35,116 @@ def _client() -> TestClient:return TestClient(app, raise_server_exceptions=False)+class _ChunkedAsyncStream(httpx.AsyncByteStream):+ def __init__(self, chunks: list[bytes]) -> None:+ self._chunks = chunks+ self.closed = False++ async def __aiter__(self) -> AsyncIterator[bytes]:+ for chunk in self._chunks:+ yield chunk++ async def aclose(self) -> None:+ self.closed = True+++def _cuda_chat_client(+ monkeypatch: pytest.MonkeyPatch,+ handler: Callable[[httpx.Request], httpx.Response],+ *,+ reasoning_parser: str | None = None,+ chat_template_kwargs: dict[str, Any] | None = None,+ default_sampling: dict[str, Any] | None = None,+ max_output_tokens: int = 64,+ server_url: str = "http://127.0.0.1:30400",+) -> tuple[TestClient, MagicMock]:+ adapter = SGLangGenerationAdapter(+ model_name_or_path="upstream/repo",+ served_model_name="upstream-served-model",+ reasoning_parser=reasoning_parser,+ )+ adapter._server_url = server_url+ generate_task = SimpleNamespace(+ max_output_tokens=max_output_tokens,+ chat_template_kwargs=chat_template_kwargs or {},+ )+ profile = SimpleNamespace(+ runtime={+ "default_sampling": default_sampling or {},+ "stop_tokens": ["<configured-stop>"],+ },+ loadtime={},+ )+ config = SimpleNamespace(+ tasks=SimpleNamespace(generate=generate_task, score=None),+ resolve_profile=MagicMock(return_value=profile),+ )+ registry = MagicMock()+ registry.device = "cuda:0"+ registry.has_model.return_value = True+ registry.get_config.return_value = config+ registry.is_failed.return_value = False+ registry.is_unloading.return_value = False+ registry.is_loading.return_value = False+ registry.is_loaded.return_value = True+ registry.get.return_value = adapter++ def _client_factory() -> httpx.AsyncClient:+ return httpx.AsyncClient(transport=httpx.MockTransport(handler))++ monkeypatch.setattr(openai_local, "_new_proxy_client", _client_factory)+ client = _client()+ client.app.state.registry = registry+ return client, registry+++def _mlx_chat_client(+ monkeypatch: pytest.MonkeyPatch,+ handler: Callable[[httpx.Request], httpx.Response],+ *,+ chat_template_kwargs: dict[str, Any],+ default_sampling: dict[str, Any] | None = None,+ max_output_tokens: int = 64,+) -> tuple[TestClient, MagicMock]:+ adapter = MLXGenerationAdapter(+ model_name_or_path="Qwen/Qwen3.5-4B",+ mlx_repo="mlx-community/Qwen3.5-4B-4bit",+ )+ adapter._server_url = "http://127.0.0.1:30401"+ generate_task = SimpleNamespace(+ max_output_tokens=max_output_tokens,+ chat_template_kwargs=chat_template_kwargs,+ )+ profile = SimpleNamespace(+ runtime={+ "default_sampling": default_sampling or {},+ "stop_tokens": ["<configured-stop>"],+ },+ loadtime={},+ )+ config = SimpleNamespace(+ tasks=SimpleNamespace(generate=generate_task, score=None),+ resolve_profile=MagicMock(return_value=profile),+ )+ registry = MagicMock()+ registry.device = "mps"+ registry.has_model.return_value = True+ registry.get_config.return_value = config+ registry.is_failed.return_value = False+ registry.is_unloading.return_value = False+ registry.is_loading.return_value = False+ registry.is_loaded.return_value = True+ registry.get.return_value = adapter++ def _client_factory() -> httpx.AsyncClient:+ return httpx.AsyncClient(transport=httpx.MockTransport(handler))++ monkeypatch.setattr(openai_local, "_new_proxy_client", _client_factory)+ client = _client()+ client.app.state.registry = registry+ return client, registry++# -- /v1/chat/completions validation -----------------------------------------@@ -43,6 +165,31 @@ def test_chat_requires_nonempty_messages() -> None:assert r.json()["detail"]["param"] == "messages"+ ("messages", "param"),+ [+ ([0], "messages[0]"),+ ([{"role": "invalid", "content": "hi"}], "messages[0].role"),+ ([{"role": "user", "content": 7}], "messages[0].content"),+ ],+)+def test_chat_rejects_malformed_message_structure_before_model_load(+ monkeypatch: pytest.MonkeyPatch,+ messages: list[Any],+ param: str,+) -> None:+ client, registry = _cuda_chat_client(+ monkeypatch,+ lambda _request: pytest.fail("malformed messages must not reach upstream"),+ )+ response = client.post("/v1/chat/completions", json={"model": "Qwen/Qwen3.5-4B", "messages": messages})++ assert response.status_code == 400+ assert response.json()["detail"]["param"] == param+ registry.get_config.assert_not_called()+ registry.get.assert_not_called()++def test_chat_rejects_non_generation_model_before_load() -> None:# An embedding/reranker model (no generate task) must be rejected BEFORE ensure_loaded()# so a chat request can't kick off a real model load that only 501s afterwards.@@ -108,6 +255,669 @@ def test_validate_mlx_seed_preserves_absent_value() -> None:assert _validate_mlx_seed(None) is None+ ("requested_model", "enable_thinking", "child_content", "request_seed", "expected_seed"),+ [+ (+ "Qwen/Qwen3.5-4B",+ False,+ "<think>private default reasoning</think>Visible answer",+ None,+ (1 << 64) - 1,+ ),+ (+ "Qwen/Qwen3.5-4B:thinking",+ True,+ "private enabled reasoning</think>Visible answer",+ -2,+ (1 << 64) - 2,+ ),+ ],+)+def test_mlx_chat_applies_profile_defaults_and_hides_reasoning(+ monkeypatch: pytest.MonkeyPatch,+ requested_model: str,+ enable_thinking: bool,+ child_content: str,+ request_seed: int | None,+ expected_seed: int,+) -> None:+ seen: dict[str, Any] = {}++ def _handler(request: httpx.Request) -> httpx.Response:+ seen["url"] = str(request.url)+ seen["body"] = json.loads(request.content)+ return httpx.Response(+ 200,+ json={+ "id": "chatcmpl-mlx",+ "object": "chat.completion",+ "created": 1,+ "model": "mlx-community/Qwen3.5-4B-4bit",+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": child_content},+ "finish_reason": "stop",+ }+ ],+ },+ )++ client, registry = _mlx_chat_client(+ monkeypatch,+ _handler,+ chat_template_kwargs={"enable_thinking": enable_thinking},+ default_sampling={+ "temperature": 0.7,+ "top_p": 0.8,+ "presence_penalty": 1.5,+ "seed": -1,+ },+ )+ request_body: dict[str, Any] = {+ "model": requested_model,+ "messages": [{"role": "user", "content": "Hello"}],+ "max_completion_tokens": 8,+ "temperature": 0.2,+ "stop": ["client-stop"],+ "chat_template_kwargs": {+ "enable_thinking": not enable_thinking,+ "guardian_config": {"risk_name": "harm"},+ },+ }+ if request_seed is not None:+ request_body["seed"] = request_seed+ response = client.post("/v1/chat/completions", json=request_body)++ assert response.status_code == 200+ assert seen["url"] == "http://127.0.0.1:30401/v1/chat/completions"+ assert seen["body"] == {+ "model": "mlx-community/Qwen3.5-4B-4bit",+ "messages": [{"role": "user", "content": "Hello"}],+ "max_tokens": 8,+ "temperature": 0.2,+ "top_p": 0.8,+ "seed": expected_seed,+ "stop": ["client-stop", "<configured-stop>"],+ "chat_template_kwargs": {+ "enable_thinking": enable_thinking,+ "guardian_config": {"risk_name": "harm"},+ },+ }+ assert response.json()["choices"][0]["message"]["content"] == "Visible answer"+ assert "private" not in response.text+ registry.touch_lru.assert_called_once_with(requested_model)+++def test_mlx_chat_rejects_child_process_controls_before_model_load(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ client, registry = _mlx_chat_client(+ monkeypatch,+ lambda _request: pytest.fail("rejected request must not reach upstream"),+ chat_template_kwargs={"enable_thinking": False},+ )++ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "Qwen/Qwen3.5-4B",+ "messages": [{"role": "user", "content": "Hello"}],+ "draft_model": "untrusted/model",+ },+ )++ assert response.status_code == 400+ assert response.json()["detail"] == {+ "code": "unsupported_field",+ "message": "field 'draft_model' is not supported",+ "param": "draft_model",+ }+ registry.is_loaded.assert_not_called()+ registry.get.assert_not_called()+++ ("chat_template_kwargs", "code"),+ [+ ({"arbitrary_tokenizer_kwarg": True}, "unsupported_field"),+ ({"enable_thinking": "false"}, "invalid_request"),+ ({"guardian_config": {"risk_name": "harm", "extra": True}}, "unsupported_field"),+ ],+)+def test_chat_rejects_unbounded_template_kwargs_before_model_load(+ monkeypatch: pytest.MonkeyPatch,+ chat_template_kwargs: dict[str, Any],+ code: str,+) -> None:+ client, registry = _mlx_chat_client(+ monkeypatch,+ lambda _request: pytest.fail("rejected request must not reach upstream"),+ chat_template_kwargs={"enable_thinking": False},+ )++ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "Qwen/Qwen3.5-4B",+ "messages": [{"role": "user", "content": "Hello"}],+ "chat_template_kwargs": chat_template_kwargs,+ },+ )++ assert response.status_code == 400+ assert response.json()["detail"]["code"] == code+ assert response.json()["detail"]["param"] == "chat_template_kwargs"+ registry.is_loaded.assert_not_called()+ registry.get.assert_not_called()+++def test_cuda_chat_blocking_proxies_profile_defaults_and_returns_openai_shape(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ seen: dict[str, Any] = {}++ def _handler(request: httpx.Request) -> httpx.Response:+ seen["url"] = str(request.url)+ seen["body"] = json.loads(request.content)+ return httpx.Response(+ 200,+ json={+ "id": "chatcmpl-test",+ "object": "chat.completion",+ "created": 1,+ "model": "upstream-served-model",+ "choices": [+ {+ "index": 0,+ "message": {+ "role": "assistant",+ "content": "private chain</think>Visible answer",+ "reasoning_content": "private chain",+ },+ "logprobs": {+ "content": [{"token": "private", "logprob": -0.1, "bytes": None, "top_logprobs": []}]+ },+ "finish_reason": "stop",+ }+ ],+ "usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7},+ },+ )++ client, registry = _cuda_chat_client(+ monkeypatch,+ _handler,+ chat_template_kwargs={"enable_thinking": True},+ default_sampling={"temperature": 0.7, "top_p": 0.8, "min_new_tokens": 2},+ )+ requested_model = "Qwen/Qwen3-0.6B:thinking"+ response = client.post(+ "/v1/chat/completions",+ json={+ "model": requested_model,+ "messages": [{"role": "user", "content": "Hello"}],+ "max_completion_tokens": 8,+ "temperature": 0.2,+ "stop": ["client-stop"],+ "chat_template_kwargs": {+ "enable_thinking": False,+ "guardian_config": {"risk_name": "harm"},+ },+ },+ )++ assert response.status_code == 200+ assert seen["url"] == "http://127.0.0.1:30400/v1/chat/completions"+ assert seen["body"] == {+ "model": "upstream-served-model",+ "messages": [{"role": "user", "content": "Hello"}],+ "max_completion_tokens": 8,+ "temperature": 0.2,+ "top_p": 0.8,+ "min_tokens": 2,+ "stop": ["client-stop", "<configured-stop>"],+ "chat_template_kwargs": {+ "enable_thinking": True,+ "guardian_config": {"risk_name": "harm"},+ },+ "separate_reasoning": True,+ "stream_reasoning": True,+ }+ payload = response.json()+ parsed = ChatCompletion.model_validate(payload)+ assert parsed.model == requested_model+ assert parsed.choices[0].message.content == "Visible answer"+ assert "reasoning_content" not in payload["choices"][0]["message"]+ assert payload["choices"][0]["logprobs"] is None+ registry.get.assert_called_once_with(requested_model)+ registry.touch_lru.assert_called_once_with(requested_model)+++def test_cuda_chat_stream_sanitizes_split_reasoning_and_closes_upstream(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ requested_model = "Qwen/Qwen3-0.6B:thinking"+ events = [+ {+ "id": "chatcmpl-stream",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": "upstream-served-model",+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": None}],+ },+ {+ "id": "chatcmpl-stream",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": "upstream-served-model",+ "choices": [+ {+ "index": 0,+ "delta": {"reasoning_content": "private", "content": "private chain</thi"},+ "finish_reason": None,+ }+ ],+ },+ {+ "id": "chatcmpl-stream",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": "upstream-served-model",+ "choices": [{"index": 0, "delta": {"content": "nk>Visible answer"}, "finish_reason": None}],+ },+ {+ "id": "chatcmpl-stream",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": "upstream-served-model",+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],+ },+ {+ "id": "chatcmpl-stream",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": "upstream-served-model",+ "choices": [],+ "usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7},+ },+ ]+ wire = b"".join(f"data: {json.dumps(event)}\n\n".encode() for event in events) + b"data: [DONE]\n\n"+ upstream_stream = _ChunkedAsyncStream([wire[:37], wire[37:121], wire[121:]])++ 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,+ chat_template_kwargs={"enable_thinking": True},+ )+ response = client.post(+ "/v1/chat/completions",+ json={+ "model": requested_model,+ "messages": [{"role": "user", "content": "Hello"}],+ "max_tokens": 8,+ "stream": True,+ "stream_options": {"include_usage": True},+ },+ )++ assert response.status_code == 200+ assert response.headers["content-type"].startswith("text/event-stream")+ data_lines = [line.removeprefix("data: ") for line in response.text.splitlines() if line.startswith("data: ")]+ assert data_lines[-1] == "[DONE]"+ chunks = [json.loads(line) for line in data_lines[:-1]]+ parsed = [ChatCompletionChunk.model_validate(chunk) for chunk in chunks]+ visible = "".join(choice.delta.content or "" for chunk in parsed for choice in chunk.choices)+ assert visible == "Visible answer"+ assert all(chunk.model == requested_model for chunk in parsed)+ assert "reasoning_content" not in response.text+ assert "private chain" not in response.text+ assert "</think>" not in response.text+ assert upstream_stream.closed is True+++def test_cuda_chat_reasoning_parser_field_is_private_but_final_content_survives(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def _handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={+ "id": "chatcmpl-parser",+ "object": "chat.completion",+ "created": 1,+ "model": "upstream-served-model",+ "choices": [+ {+ "index": 0,+ "message": {+ "role": "assistant",+ "content": "Visible answer",+ "reasoning_content": "private chain",+ },+ "finish_reason": "stop",+ }+ ],+ "usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7},+ },+ )++ client, _ = _cuda_chat_client(+ monkeypatch,+ _handler,+ reasoning_parser="qwen3",+ chat_template_kwargs={"enable_thinking": True},+ )+ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "Qwen/Qwen3.5-4B:thinking",+ "messages": [{"role": "user", "content": "Hello"}],+ },+ )++ assert response.status_code == 200+ message = response.json()["choices"][0]["message"]+ assert message == {"role": "assistant", "content": "Visible answer"}+++def test_cuda_chat_blocking_hides_gemma_reasoning_boundaries(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def _handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={+ "id": "chatcmpl-gemma",+ "object": "chat.completion",+ "created": 1,+ "model": "upstream-served-model",+ "choices": [+ {+ "index": 0,+ "message": {+ "role": "assistant",+ "content": _GEMMA_OPEN + "private chain" + _GEMMA_CLOSE + "Visible answer",+ },+ "finish_reason": "stop",+ }+ ],+ },+ )++ client, _ = _cuda_chat_client(+ monkeypatch,+ _handler,+ reasoning_parser="gemma4",+ chat_template_kwargs={"enable_thinking": True},+ )+ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "google/gemma-4-E2B-it:thinking",+ "messages": [{"role": "user", "content": "Hello"}],+ },+ )++ assert response.status_code == 200+ assert response.json()["choices"][0]["message"]["content"] == "Visible answer"+ assert "private chain" not in response.text+++def test_cuda_chat_stream_hides_split_gemma_reasoning_boundaries(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ raw = _GEMMA_OPEN + "private chain" + _GEMMA_CLOSE + "Visible answer"+ content_chunks = [raw[:6], raw[6:18], raw[18:31], raw[31:]]+ events = [+ {+ "id": "chatcmpl-gemma-stream",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": "upstream-served-model",+ "choices": [{"index": 0, "delta": {"content": content}, "finish_reason": None}],+ }+ for content in content_chunks+ ]+ events.append(+ {+ "id": "chatcmpl-gemma-stream",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": "upstream-served-model",+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],+ }+ )+ wire = b"".join(f"data: {json.dumps(event)}\n\n".encode() for event in events) + b"data: [DONE]\n\n"+ upstream_stream = _ChunkedAsyncStream([wire[:41], wire[41:137], wire[137:]])++ 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,+ reasoning_parser="gemma4",+ chat_template_kwargs={"enable_thinking": True},+ )+ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "google/gemma-4-E2B-it:thinking",+ "messages": [{"role": "user", "content": "Hello"}],+ "stream": True,+ },+ )++ assert response.status_code == 200+ data_lines = [line.removeprefix("data: ") for line in response.text.splitlines() if line.startswith("data: ")]+ chunks = [json.loads(line) for line in data_lines[:-1]]+ visible = "".join(+ choice.get("delta", {}).get("content", "") for chunk in chunks for choice in chunk.get("choices", [])+ )+ assert visible == "Visible answer"+ assert "private chain" not in response.text+ assert upstream_stream.closed is True+++def test_cuda_chat_stream_rejects_non_sse_success_and_closes_upstream(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ upstream_stream = _ChunkedAsyncStream([b'{"unexpected":"json"}'])++ def _handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, stream=upstream_stream, headers={"content-type": "application/json"})++ client, _ = _cuda_chat_client(monkeypatch, _handler)+ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "Qwen/Qwen3.5-4B",+ "messages": [{"role": "user", "content": "Hello"}],+ "stream": True,+ },+ )++ assert response.status_code == 502+ assert response.json()["error"]["message"] == "generation child returned an invalid streaming response"+ assert upstream_stream.closed is True+++def test_cuda_chat_rejects_non_loopback_child_without_opening_proxy(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ client, _ = _cuda_chat_client(+ monkeypatch,+ lambda _request: pytest.fail("unsafe upstream must not be contacted"),+ server_url="http://example.com:8080",+ )+ response = client.post(+ "/v1/chat/completions",+ json={"model": "Qwen/Qwen3.5-4B", "messages": [{"role": "user", "content": "Hello"}]},+ )+ assert response.status_code == 502+ assert response.json()["error"]["code"] == "upstream_error"++[email protected]("stream", [False, True])+def test_cuda_chat_does_not_log_upstream_error_body(+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+ stream: bool,+) -> None:+ private_marker = "private-message-must-not-be-logged"++ def _handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(400, json={"detail": [{"input": private_marker}]})++ client, _ = _cuda_chat_client(monkeypatch, _handler)+ with caplog.at_level("ERROR", logger="sie_server.api.openai_local"):+ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "Qwen/Qwen3.5-4B",+ "messages": [{"role": "user", "content": private_marker}],+ "stream": stream,+ },+ )++ assert response.status_code == 400+ assert response.json()["error"]["message"] == "upstream generation request failed"+ assert private_marker not in caplog.text+++def test_cuda_chat_rejects_engine_control_and_output_above_model_cap(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ client, _ = _cuda_chat_client(+ monkeypatch,+ lambda _request: pytest.fail("rejected request must not reach upstream"),+ max_output_tokens=32,+ )+ messages = [{"role": "user", "content": "Hello"}]++ response = client.post(+ "/v1/chat/completions",+ json={"model": "Qwen/Qwen3.5-4B", "messages": messages, "routed_dp_rank": 2},+ )+ assert response.status_code == 400+ assert response.json()["detail"] == {+ "code": "unsupported_field",+ "message": "field 'routed_dp_rank' is not supported",+ "param": "routed_dp_rank",+ }++ response = client.post(+ "/v1/chat/completions",+ json={"model": "Qwen/Qwen3.5-4B", "messages": messages, "max_completion_tokens": 33},+ )+ assert response.status_code == 400+ assert response.json()["detail"]["param"] == "max_completion_tokens"+++def test_mlx_chat_rejects_output_above_model_cap(monkeypatch: pytest.MonkeyPatch) -> None:+ client, _ = _mlx_chat_client(+ monkeypatch,+ lambda _request: pytest.fail("rejected request must not reach upstream"),+ chat_template_kwargs={"enable_thinking": False},+ max_output_tokens=32,+ )++ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "Qwen/Qwen3.5-4B",+ "messages": [{"role": "user", "content": "Hello"}],+ "max_completion_tokens": 33,+ },+ )++ assert response.status_code == 400+ assert response.json()["detail"]["param"] == "max_completion_tokens"+++def test_cuda_chat_rejects_remote_media_before_model_load(monkeypatch: pytest.MonkeyPatch) -> None:+ client, registry = _cuda_chat_client(+ monkeypatch,+ lambda _request: pytest.fail("remote media request must not reach upstream"),+ )+ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "Qwen/Qwen3.5-4B",+ "messages": [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "Describe this image"},+ {+ "type": "image_url",+ "image_url": {"url": "http://169.254.169.254/latest/meta-data/"},+ },+ ],+ }+ ],+ },+ )++ assert response.status_code == 400+ assert response.json()["detail"]["param"] == "messages[0].content[1].image_url"+ registry.get.assert_not_called()+++def test_cuda_chat_preserves_visible_logprobs_when_reasoning_is_null(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ visible_logprobs = {"content": [{"token": "answer", "logprob": -0.1, "bytes": None, "top_logprobs": []}]}++ def _handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ json={+ "id": "chatcmpl-visible",+ "object": "chat.completion",+ "created": 1,+ "model": "upstream-served-model",+ "choices": [+ {+ "index": 0,+ "message": {+ "role": "assistant",+ "content": "Visible answer",+ "reasoning_content": None,+ },+ "logprobs": visible_logprobs,+ "finish_reason": "stop",+ }+ ],+ },+ )++ client, _ = _cuda_chat_client(+ monkeypatch,+ _handler,+ reasoning_parser="qwen3",+ chat_template_kwargs={"enable_thinking": False},+ )+ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "Qwen/Qwen3.5-4B",+ "messages": [{"role": "user", "content": "Hello"}],+ "logprobs": True,+ },+ )++ assert response.status_code == 200+ choice = response.json()["choices"][0]+ assert choice["message"] == {"role": "assistant", "content": "Visible answer"}+ assert choice["logprobs"] == visible_logprobs++# -- /v1/rerank validation ----------------------------------------------------@@ -148,8 +958,6 @@ def test_rerank_top_n_must_be_positive_int() -> None:def test_rerank_rejects_too_many_documents() -> None:- from sie_server.api import openai_local-docs = ["d"] * (openai_local._MAX_RERANK_DOCS + 1)r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": docs})assert r.status_code == 400diff --git a/packages/sie_server/tests/api/test_openai_responses.py b/packages/sie_server/tests/api/test_openai_responses.pynew file mode 100644index 000000000..19b7ed998--- /dev/null+++ b/packages/sie_server/tests/api/test_openai_responses.py@@ -0,0 +1,294 @@+"""Regression tests for direct ``/v1/responses`` generation."""++from __future__ import annotations++import json+from collections.abc import AsyncIterator+from pathlib import Path+from unittest.mock import AsyncMock, MagicMock++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from sie_server.adapters._generation_base import GenerationAdapter, GenerationChunk+from sie_server.adapters._spec import AdapterSpec+from sie_server.api import openai_responses+from sie_server.api.openai_completions import _CompletionError+from sie_server.config.model import AdapterOptions, GenerateTask, ModelConfig, ProfileConfig, Tasks+from sie_server.core.registry import ModelRegistry+from sie_server.types.grammar import GrammarSpec+from sie_server.types.inputs import ImageInput++_VECTORS = Path(__file__).parents[4] / "conformance" / "openai_generation" / "responses_request_vectors.json"+++class _FakeResponsesAdapter(GenerationAdapter):+ spec = AdapterSpec(inputs=("text",), outputs=("tokens",), unload_fields=())++ def __init__(self) -> None:+ self.last_call: dict[str, object] | None = None+ self.text_chunks = ["hello", " world"]+ self.include_usage = True++ def load(self, device: str) -> None: # pragma: no cover - registry is mocked loaded+ _ = device++ async def generate(+ self,+ prompt: str,+ *,+ max_new_tokens: int,+ temperature: float = 1.0,+ top_p: float = 1.0,+ stop: list[str] | None = None,+ frequency_penalty: float | None = None,+ presence_penalty: float | None = None,+ top_k: int | None = None,+ repetition_penalty: float | None = None,+ min_new_tokens: int | None = None,+ grammar: GrammarSpec | None = None,+ seed: int | None = None,+ logit_bias: dict[str, float] | None = None,+ logprobs: bool = False,+ top_logprobs: int | None = None,+ images: list[ImageInput] | None = None,+ ) -> AsyncIterator[GenerationChunk]:+ self.last_call = {+ "prompt": prompt,+ "max_new_tokens": max_new_tokens,+ "temperature": temperature,+ "top_p": top_p,+ "stop": stop,+ "frequency_penalty": frequency_penalty,+ "presence_penalty": presence_penalty,+ "top_k": top_k,+ "min_new_tokens": min_new_tokens,+ "seed": seed,+ }+ _ = repetition_penalty, grammar, logit_bias, logprobs, top_logprobs, images+ for index, text in enumerate(self.text_chunks):+ yield GenerationChunk(text_delta=text, is_first=index == 0)+ yield GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="stop",+ prompt_tokens=3 if self.include_usage else None,+ completion_tokens=2 if self.include_usage else None,+ )+++def _config(*, chat_template_kwargs: dict[str, object] | None = None) -> ModelConfig:+ return ModelConfig(+ sie_id="Qwen/Qwen3-4B-Instruct",+ hf_id="Qwen/Qwen3-4B-Instruct",+ tasks=Tasks(+ generate=GenerateTask(+ context_length=32768,+ max_output_tokens=64,+ chat_template_kwargs=chat_template_kwargs or {},+ )+ ),+ profiles={+ "default": ProfileConfig(+ adapter_path="test:FakeResponsesAdapter",+ max_batch_tokens=8192,+ kv_budget_tokens=4096,+ adapter_options=AdapterOptions(+ loadtime={"reasoning_parser": "qwen3"},+ runtime={+ "default_sampling": {+ "temperature": 0.25,+ "top_p": 0.8,+ "top_k": 12,+ "min_new_tokens": 2,+ "seed": 23,+ },+ "stop_tokens": ["</s>"],+ },+ ),+ )+ },+ )+++def adapter() -> _FakeResponsesAdapter:+ return _FakeResponsesAdapter()+++def registry(adapter: _FakeResponsesAdapter) -> MagicMock:+ reg = MagicMock(spec=ModelRegistry)+ reg.has_model.return_value = True+ reg.is_loaded.return_value = True+ reg.is_loading.return_value = False+ reg.is_unloading.return_value = False+ reg.is_failed.return_value = False+ reg.get_failure.return_value = None+ reg.get_config.return_value = _config()+ reg.get.return_value = adapter+ reg.device = "cpu"+ return reg+++def client(registry: MagicMock) -> TestClient:+ app = FastAPI()+ app.include_router(openai_responses.router)+ app.state.registry = registry+ return TestClient(app)+++def test_blocking_responses_uses_direct_adapter_and_openai_shape(+ client: TestClient,+ adapter: _FakeResponsesAdapter,+) -> None:+ response = client.post(+ "/v1/responses",+ json={+ "model": "Qwen/Qwen3-4B-Instruct",+ "input": "Say hello",+ "max_output_tokens": 8,+ "temperature": 0.5,+ "seed": -1,+ },+ )++ assert response.status_code == 200, response.text+ body = response.json()+ assert body["id"].startswith("resp-")+ assert body["object"] == "response"+ assert body["status"] == "completed"+ assert body["model"] == "Qwen/Qwen3-4B-Instruct"+ assert body["output"][0]["content"] == [{"type": "output_text", "text": "hello world", "annotations": []}]+ assert body["usage"] == {"input_tokens": 3, "output_tokens": 2, "total_tokens": 5}+ assert adapter.last_call == {+ "prompt": "Say hello",+ "max_new_tokens": 8,+ "temperature": 0.5,+ "top_p": 0.8,+ "stop": ["</s>"],+ "frequency_penalty": None,+ "presence_penalty": None,+ "top_k": 12,+ "min_new_tokens": 2,+ "seed": -1,+ }+++def test_message_input_uses_model_native_template(+ client: TestClient,+ adapter: _FakeResponsesAdapter,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ render = AsyncMock(return_value="<rendered>Hi there</rendered>")+ monkeypatch.setattr(openai_responses, "_render_native_messages_prompt", render)++ response = client.post(+ "/v1/responses",+ json={+ "model": "Qwen/Qwen3-4B-Instruct",+ "input": [+ {"role": "developer", "content": "Be concise"},+ {+ "role": "user",+ "content": [+ {"type": "input_text", "text": "Hi "},+ {"type": "text", "text": "there"},+ ],+ },+ ],+ },+ )++ assert response.status_code == 200, response.text+ render.assert_awaited_once()+ assert render.await_args.args[1] == [+ {"role": "system", "content": "Be concise"},+ {"role": "user", "content": "Hi there"},+ ]+ assert adapter.last_call is not None+ assert adapter.last_call["prompt"] == "<rendered>Hi there</rendered>"+++def test_responses_hides_family_reasoning_without_changing_usage(+ client: TestClient,+ registry: MagicMock,+ adapter: _FakeResponsesAdapter,+) -> None:+ registry.get_config.return_value = _config(chat_template_kwargs={"enable_thinking": True})+ adapter.text_chunks = ["<thi", "nk>private</think>answer"]++ response = client.post(+ "/v1/responses",+ json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"},+ )++ assert response.status_code == 200, response.text+ body = response.json()+ assert body["output"][0]["content"][0]["text"] == "answer"+ assert body["usage"] == {"input_tokens": 3, "output_tokens": 2, "total_tokens": 5}+++def test_shared_responses_request_conformance_vectors() -> None:+ vectors = json.loads(_VECTORS.read_text())++ for case in vectors["accepted"]:+ params = openai_responses._parse_params(case["body"])+ observed = {+ "model": params.model,+ "prompt": params.prompt,+ "messages": params.messages,+ "max_output_tokens": params.max_output_tokens,+ "temperature": params.temperature,+ "top_p": params.top_p,+ "seed": params.seed,+ }+ assert observed == case["expected"], case["name"]++ for case in vectors["rejected"]:+ with pytest.raises(_CompletionError) as exc_info:+ openai_responses._parse_params(case["body"])+ assert exc_info.value.param == case["param"], case["name"]+ assert exc_info.value.code == case["code"], case["name"]+++def test_responses_rejects_model_output_cap(client: TestClient) -> None:+ response = client.post(+ "/v1/responses",+ json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x", "max_output_tokens": 65},+ )++ assert response.status_code == 400+ assert response.json()["error"]["param"] == "max_output_tokens"+++def test_responses_rejects_terminal_event_without_usage(+ client: TestClient,+ adapter: _FakeResponsesAdapter,+) -> None:+ adapter.include_usage = False++ response = client.post(+ "/v1/responses",+ json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"},+ )++ assert response.status_code == 500+ assert response.json()["error"]["code"] == "malformed_worker_response"+++def test_responses_rejects_oversized_rendered_input(+ client: TestClient,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(openai_responses, "_MAX_PROMPT_BYTES", 4)++ response = client.post(+ "/v1/responses",+ json={"model": "Qwen/Qwen3-4B-Instruct", "input": "12345"},+ )++ assert response.status_code == 413+ assert response.json()["error"]["param"] == "input"+ assert response.json()["error"]["code"] == "context_exceeded"diff --git a/packages/sie_server/tests/app/test_app_factory.py b/packages/sie_server/tests/app/test_app_factory.pyindex 40267115d..5efc43f9b 100644--- a/packages/sie_server/tests/app/test_app_factory.py+++ b/packages/sie_server/tests/app/test_app_factory.py@@ -126,6 +126,8 @@ class TestAllRoutersAlwaysMounted:"/v1/score/{model:path}","/v1/extract/{model:path}","/v1/embeddings",+ "/v1/completions",+ "/v1/responses","/v1/models",):assert path in paths, f"{path} router missing"diff --git a/packages/sie_server/tests/config/test_config.py b/packages/sie_server/tests/config/test_config.pyindex 464a7a2ae..3cb0caa88 100644--- a/packages/sie_server/tests/config/test_config.py+++ b/packages/sie_server/tests/config/test_config.py@@ -667,6 +667,19 @@ class TestProfileConfig:)assert profile.compute_precision == "bfloat16"+ def test_chat_template_kwargs(self) -> None:+ """Generation profiles can carry tokenizer-render overrides."""+ profile = ProfileConfig(+ extends="default",+ chat_template_kwargs={"enable_thinking": True},+ )+ assert profile.chat_template_kwargs == {"enable_thinking": True}++ def test_max_output_tokens_must_be_positive(self) -> None:+ """Generation profile decode caps are positive when present."""+ with pytest.raises(ValidationError):+ ProfileConfig(extends="default", max_output_tokens=0)+def test_extra_fields_rejected(self) -> None:"""ProfileConfig rejects unknown fields."""with pytest.raises(ValidationError):@@ -777,6 +790,135 @@ class TestModelConfigProfiles:assert config.resolve_profile("child").runtime == {"output_similarity": {"dense": "dot"}}+ def test_resolve_child_profile_overrides_chat_template_kwargs(self) -> None:+ """A child profile replaces its parent's tokenizer-render preset."""+ config = ModelConfig(+ sie_id="test-model",+ hf_id="org/model",+ tasks=Tasks(generate=GenerateTask(context_length=8192, max_output_tokens=512)),+ profiles={+ "default": ProfileConfig(+ adapter_path="mod:Cls",+ max_batch_tokens=8192,+ kv_budget_tokens=8192,+ chat_template_kwargs={"enable_thinking": False},+ ),+ "thinking": ProfileConfig(+ extends="default",+ chat_template_kwargs={"enable_thinking": True},+ ),+ },+ )++ assert config.resolve_profile("default").chat_template_kwargs == {"enable_thinking": False}+ assert config.resolve_profile("thinking").chat_template_kwargs == {"enable_thinking": True}++ def test_resolve_child_profile_overrides_max_output_tokens(self) -> None:+ """A long-context child can raise the model-level decode cap."""+ config = ModelConfig(+ sie_id="test-model",+ hf_id="org/model",+ tasks=Tasks(generate=GenerateTask(context_length=8192, max_output_tokens=4096)),+ profiles={+ "default": ProfileConfig(+ adapter_path="mod:Cls",+ max_batch_tokens=8192,+ kv_budget_tokens=8192,+ ),+ "long": ProfileConfig(+ extends="default",+ max_output_tokens=16384,+ adapter_options=AdapterOptions(loadtime={"max_seq_length": 32768}),+ ),+ },+ )++ assert config.resolve_profile("default").max_output_tokens is None+ assert config.resolve_profile("long").max_output_tokens == 16384++ def test_profile_max_output_tokens_require_generation_task(self) -> None:+ """Decode caps are invalid on non-generation profiles."""+ with pytest.raises(ValidationError, match="without a generation task"):+ ModelConfig(+ sie_id="test-model",+ hf_id="org/model",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=768))),+ profiles={+ "default": ProfileConfig(+ adapter_path="mod:Cls",+ max_batch_tokens=8192,+ max_output_tokens=4096,+ ),+ },+ )++ def test_profile_max_output_tokens_cannot_exceed_profile_context(self) -> None:+ """A materialized profile cannot advertise more output than total context."""+ with pytest.raises(ValidationError, match="exceeding its context_length"):+ ModelConfig(+ sie_id="test-model",+ hf_id="org/model",+ tasks=Tasks(generate=GenerateTask(context_length=8192, max_output_tokens=4096)),+ profiles={+ "default": ProfileConfig(+ adapter_path="mod:Cls",+ max_batch_tokens=8192,+ kv_budget_tokens=8192,+ max_output_tokens=16384,+ ),+ },+ )++ def test_chat_template_kwargs_require_generation_task(self) -> None:+ """Tokenizer-render presets are invalid on non-generation profiles."""+ with pytest.raises(ValidationError, match="without a generation task"):+ ModelConfig(+ sie_id="test-model",+ hf_id="org/model",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=768))),+ profiles={+ "default": ProfileConfig(+ adapter_path="mod:Cls",+ max_batch_tokens=8192,+ chat_template_kwargs={"enable_thinking": True},+ ),+ },+ )++ @pytest.mark.parametrize(+ ("kwargs", "message"),+ [+ ({"arbitrary_extension": True}, "unsupported chat_template_kwargs key"),+ ({"enable_thinking": "yes"}, "enable_thinking must be a boolean"),+ ({"guardian_config": {"risk_name": "harm", "extra": True}}, "unsupported.*guardian_config key"),+ ({"guardian_config": {"risk_name": ""}}, "risk_name must be a non-empty string"),+ ],+ )+ def test_generation_task_chat_template_kwargs_fail_closed(+ self,+ kwargs: dict[str, object],+ message: str,+ ) -> None:+ with pytest.raises(ValidationError, match=message):+ GenerateTask(+ context_length=8192,+ max_output_tokens=512,+ chat_template_kwargs=kwargs,+ )++ def test_generation_task_accepts_bounded_guardian_config(self) -> None:+ task = GenerateTask(+ context_length=8192,+ max_output_tokens=512,+ chat_template_kwargs={"guardian_config": {"risk_name": "harm"}},+ )++ assert task.chat_template_kwargs == {"guardian_config": {"risk_name": "harm"}}++ def test_profile_chat_template_kwargs_fail_closed(self) -> None:+ with pytest.raises(ValidationError, match="unsupported chat_template_kwargs key"):+ ProfileConfig(chat_template_kwargs={"arbitrary_extension": True})+def test_resolve_missing_profile_raises(self) -> None:"""resolve_profile raises for unknown profile."""config = _make_config()diff --git a/packages/sie_server/tests/config/test_generation_mode_profiles.py b/packages/sie_server/tests/config/test_generation_mode_profiles.pynew file mode 100644index 000000000..f289a2aa9--- /dev/null+++ b/packages/sie_server/tests/config/test_generation_mode_profiles.py@@ -0,0 +1,249 @@+from __future__ import annotations++from pathlib import Path++import pytest+from sie_server.adapters._generation_base import thinking_blocks_must_be_hidden, thinking_mode_is_enabled+from sie_server.core.loader import expand_profile_variants, load_model_config++MODELS_DIR = Path(__file__).resolve().parents[2] / "models"++_THINKING_MODELS = (+ ("Qwen__Qwen3-0.6B.yaml", "Qwen/Qwen3-0.6B"),+ ("Qwen__Qwen3.5-4B.yaml", "Qwen/Qwen3.5-4B"),+ ("Qwen__Qwen3.6-27B.yaml", "Qwen/Qwen3.6-27B"),+ ("Qwen__Qwen3.6-35B-A3B.yaml", "Qwen/Qwen3.6-35B-A3B"),+ ("google__gemma-4-E2B-it.yaml", "google/gemma-4-E2B-it"),+ ("google__gemma-4-E4B-it.yaml", "google/gemma-4-E4B-it"),+ ("google__gemma-4-26B-A4B-it.yaml", "google/gemma-4-26B-A4B-it"),+ ("google__gemma-4-31B-it.yaml", "google/gemma-4-31B-it"),+)++_LONG_CONTEXT_MODELS = (+ ("Qwen__Qwen3-0.6B.yaml", "Qwen/Qwen3-0.6B", 32768),+ ("Qwen__Qwen3.5-4B.yaml", "Qwen/Qwen3.5-4B", 32768),+ ("Qwen__Qwen3.6-27B.yaml", "Qwen/Qwen3.6-27B", 262144),+ ("Qwen__Qwen3.6-35B-A3B.yaml", "Qwen/Qwen3.6-35B-A3B", 262144),+ ("google__gemma-4-E2B-it.yaml", "google/gemma-4-E2B-it", 32768),+ ("google__gemma-4-E4B-it.yaml", "google/gemma-4-E4B-it", 32768),+ ("google__gemma-4-26B-A4B-it.yaml", "google/gemma-4-26B-A4B-it", 32768),+ ("google__gemma-4-31B-it.yaml", "google/gemma-4-31B-it", 262144),+ ("defog__sqlcoder-7b-2.yaml", "defog/sqlcoder-7b-2", 16384),+)++_LONG_CONTEXT_THINKING_MODELS = (+ ("Qwen__Qwen3.6-27B.yaml", "Qwen/Qwen3.6-27B"),+ ("Qwen__Qwen3.6-35B-A3B.yaml", "Qwen/Qwen3.6-35B-A3B"),+ ("google__gemma-4-31B-it.yaml", "google/gemma-4-31B-it"),+)++_LONG_CONTEXT_THINKING_IDS = {model_id for _, model_id in _LONG_CONTEXT_THINKING_MODELS}++_HARDWARE_THINKING_PROFILES = {+ "Qwen/Qwen3.6-27B": ("h100-256k-thinking",),+ "Qwen/Qwen3.6-35B-A3B": ("h100-256k-thinking",),+ "google/gemma-4-31B-it": ("h100-96k-thinking", "h200-256k-thinking"),+}++[email protected](("model_file", "model_id"), _THINKING_MODELS)+def test_thinking_profiles_are_explicit_and_other_variants_are_non_thinking(+ model_file: str,+ model_id: str,+) -> None:+ configs = expand_profile_variants([load_model_config(MODELS_DIR / model_file)])++ thinking_routes = {f"{model_id}:thinking"}+ if model_id in _LONG_CONTEXT_THINKING_IDS:+ thinking_routes.add(f"{model_id}:long-context-thinking")+ thinking_routes.update(f"{model_id}:{profile}" for profile in _HARDWARE_THINKING_PROFILES.get(model_id, ()))++ for route, config in configs.items():+ assert config.tasks.generate is not None+ expected = route in thinking_routes+ assert config.tasks.generate.chat_template_kwargs["enable_thinking"] is expected, route+ assert thinking_blocks_must_be_hidden(config) is True+ assert thinking_mode_is_enabled(config) is expected+++def test_qwen_instruct_checkpoint_does_not_advertise_thinking_profile() -> None:+ """Qwen3-4B-Instruct-2507 is explicitly a non-thinking-only checkpoint."""+ config = load_model_config(MODELS_DIR / "Qwen__Qwen3-4B-Instruct-2507.yaml")++ assert "thinking" not in config.profiles+ assert config.tasks.generate is not None+ assert config.tasks.generate.chat_template_kwargs == {"enable_thinking": False}++[email protected](("model_file", "model_id", "expected_context"), _LONG_CONTEXT_MODELS)+def test_long_context_profile_promotes_request_and_adapter_limits(+ model_file: str,+ model_id: str,+ expected_context: int,+) -> None:+ configs = expand_profile_variants([load_model_config(MODELS_DIR / model_file)])++ base = configs[model_id]+ long_context = configs[f"{model_id}:long-context"]+ assert base.tasks.generate is not None+ assert long_context.tasks.generate is not None+ assert base.tasks.generate.context_length < expected_context+ assert long_context.tasks.generate.context_length == expected_context+ assert long_context.max_sequence_length == expected_context+ assert long_context.resolve_profile("default").loadtime["max_seq_length"] == expected_context++[email protected](("model_file", "model_id"), _LONG_CONTEXT_THINKING_MODELS)+def test_long_context_thinking_profile_reuses_256k_launch_shape(+ model_file: str,+ model_id: str,+) -> None:+ configs = expand_profile_variants([load_model_config(MODELS_DIR / model_file)])++ non_thinking = configs[f"{model_id}:long-context"]+ thinking = configs[f"{model_id}:long-context-thinking"]+ assert non_thinking.tasks.generate is not None+ assert thinking.tasks.generate is not None+ assert non_thinking.tasks.generate.context_length == 262144+ assert thinking.tasks.generate.context_length == 262144+ expected_non_thinking_cap = 4096 if model_id == "google/gemma-4-31B-it" else 32768+ expected_thinking_cap = 32768 if model_id == "google/gemma-4-31B-it" else 81920+ assert non_thinking.tasks.generate.max_output_tokens == expected_non_thinking_cap+ assert thinking.tasks.generate.max_output_tokens == expected_thinking_cap+ assert non_thinking.max_sequence_length == thinking.max_sequence_length == 262144+ assert non_thinking.resolve_profile("default").loadtime == thinking.resolve_profile("default").loadtime+ assert non_thinking.resolve_profile("default").kv_budget_tokens == 262144+ assert thinking.resolve_profile("default").kv_budget_tokens == 262144+ assert non_thinking.tasks.generate.chat_template_kwargs == {"enable_thinking": False}+ assert thinking.tasks.generate.chat_template_kwargs == {"enable_thinking": True}+++def test_generic_thinking_aliases_use_the_validated_hardware_context() -> None:+ expectations = (+ ("Qwen__Qwen3.6-27B.yaml", "Qwen/Qwen3.6-27B", "h100-256k-thinking", 262144, 81920),+ ("Qwen__Qwen3.6-35B-A3B.yaml", "Qwen/Qwen3.6-35B-A3B", "h100-256k-thinking", 262144, 81920),+ ("google__gemma-4-31B-it.yaml", "google/gemma-4-31B-it", "h100-96k-thinking", 98304, 32768),+ )++ for model_file, model_id, hardware_profile, context, output_cap in expectations:+ configs = expand_profile_variants([load_model_config(MODELS_DIR / model_file)])+ generic = configs[f"{model_id}:thinking"]+ hardware = configs[f"{model_id}:{hardware_profile}"]++ assert generic.tasks.generate is not None+ assert hardware.tasks.generate is not None+ assert generic.tasks.generate.context_length == hardware.tasks.generate.context_length == context+ assert generic.tasks.generate.max_output_tokens == output_cap+ assert generic.resolve_profile("default") == hardware.resolve_profile("default")+++def test_gemma_31b_large_context_profiles_use_measured_kv_precision() -> None:+ configs = expand_profile_variants([load_model_config(MODELS_DIR / "google__gemma-4-31B-it.yaml")])++ for suffix in (+ "long-context",+ "long-context-thinking",+ "h100-96k",+ "h100-96k-thinking",+ "h200-256k",+ "h200-256k-thinking",+ ):+ loadtime = configs[f"google/gemma-4-31B-it:{suffix}"].resolve_profile("default").loadtime+ assert loadtime["extra_launch_args"] == [+ "--quantization",+ "fp8",+ "--kv-cache-dtype",+ "fp8_e4m3",+ ]+++ ("model_file", "model_id"),+ [+ ("Qwen__Qwen3.6-27B.yaml", "Qwen/Qwen3.6-27B"),+ ("Qwen__Qwen3.6-35B-A3B.yaml", "Qwen/Qwen3.6-35B-A3B"),+ ],+)+def test_qwen_h100_256k_aliases_match_long_context_profiles(model_file: str, model_id: str) -> None:+ configs = expand_profile_variants([load_model_config(MODELS_DIR / model_file)])++ for hardware_suffix, generic_suffix in (+ ("h100-256k", "long-context"),+ ("h100-256k-thinking", "long-context-thinking"),+ ):+ hardware = configs[f"{model_id}:{hardware_suffix}"]+ generic = configs[f"{model_id}:{generic_suffix}"]+ assert hardware.resolve_profile("default") == generic.resolve_profile("default")+ assert hardware.tasks.generate == generic.tasks.generate++ assert configs[f"{model_id}:h100-256k"].tasks.generate.max_output_tokens == 32768+ assert configs[f"{model_id}:h100-256k-thinking"].tasks.generate.max_output_tokens == 81920+++def test_qwen_35b_profiles_use_runtime_compatible_grammar_backend() -> None:+ configs = expand_profile_variants([load_model_config(MODELS_DIR / "Qwen__Qwen3.6-35B-A3B.yaml")])++ for suffix in ("default", "h100-256k", "h100-256k-thinking"):+ model_id = "Qwen/Qwen3.6-35B-A3B"+ config = configs[model_id] if suffix == "default" else configs[f"{model_id}:{suffix}"]+ assert config.resolve_profile("default").loadtime["grammar_backend"] == "xgrammar"+++def test_qwen_27b_profiles_use_runtime_compatible_grammar_backend() -> None:+ configs = expand_profile_variants([load_model_config(MODELS_DIR / "Qwen__Qwen3.6-27B.yaml")])+ model_id = "Qwen/Qwen3.6-27B"++ for suffix in ("default", "h100", "h100-fp8", "rtx-pro-6000", "h100-256k", "batch", "no-spec"):+ config = configs[model_id] if suffix == "default" else configs[f"{model_id}:{suffix}"]+ assert config.resolve_profile("default").loadtime["grammar_backend"] == "xgrammar"+++def test_gemma_31b_hardware_profiles_expose_measured_context_caps() -> None:+ configs = expand_profile_variants([load_model_config(MODELS_DIR / "google__gemma-4-31B-it.yaml")])+ model_id = "google/gemma-4-31B-it"++ for hardware_suffix, generic_suffix in (+ ("h200-256k", "long-context"),+ ("h200-256k-thinking", "long-context-thinking"),+ ):+ hardware = configs[f"{model_id}:{hardware_suffix}"]+ generic = configs[f"{model_id}:{generic_suffix}"]+ assert hardware.resolve_profile("default") == generic.resolve_profile("default")+ assert hardware.tasks.generate == generic.tasks.generate+ for suffix in ("h100-96k", "h100-96k-thinking"):+ config = configs[f"{model_id}:{suffix}"]+ assert config.tasks.generate is not None+ assert config.tasks.generate.context_length == 98304+ assert config.max_sequence_length == 98304+ profile = config.resolve_profile("default")+ assert profile.max_batch_tokens == 98304+ assert profile.kv_budget_tokens == 98304+ assert profile.loadtime["max_seq_length"] == 98304+ assert configs[f"{model_id}:h100-96k"].tasks.generate.max_output_tokens == 4096+ assert configs[f"{model_id}:h100-96k-thinking"].tasks.generate.max_output_tokens == 32768+++ ("model_file", "model_id", "temperature", "top_p", "top_k", "presence_penalty"),+ [+ ("Qwen__Qwen3-0.6B.yaml", "Qwen/Qwen3-0.6B", 0.6, 0.95, 20, None),+ ("Qwen__Qwen3.5-4B.yaml", "Qwen/Qwen3.5-4B", 1.0, 0.95, 20, 1.5),+ ("Qwen__Qwen3.6-27B.yaml", "Qwen/Qwen3.6-27B", 1.0, 0.95, 20, 0.0),+ ("Qwen__Qwen3.6-35B-A3B.yaml", "Qwen/Qwen3.6-35B-A3B", 1.0, 0.95, 20, 1.5),+ ],+)+def test_qwen_thinking_profiles_use_thinking_sampling_recipe(+ model_file: str,+ model_id: str,+ temperature: float,+ top_p: float,+ top_k: int,+ presence_penalty: float | None,+) -> None:+ configs = expand_profile_variants([load_model_config(MODELS_DIR / model_file)])+ sampling = configs[f"{model_id}:thinking"].resolve_profile("default").runtime["default_sampling"]++ assert sampling["temperature"] == temperature+ assert sampling["top_p"] == top_p+ assert sampling["top_k"] == top_k+ assert sampling.get("presence_penalty") == presence_penaltydiff --git a/packages/sie_server/tests/config/test_h100_fp8_generation_profiles.py b/packages/sie_server/tests/config/test_h100_fp8_generation_profiles.pyindex d5b33e0bd..52f6a4a75 100644--- a/packages/sie_server/tests/config/test_h100_fp8_generation_profiles.py+++ b/packages/sie_server/tests/config/test_h100_fp8_generation_profiles.py@@ -10,19 +10,26 @@ MODELS_DIR = Path(__file__).resolve().parents[2] / "models"@pytest.mark.parametrize(- ("model_file", "model_id", "adapter_path", "grammar_backend"),+ ("model_file", "model_id", "adapter_path", "grammar_backend", "extra_launch_args"),[("Qwen__Qwen3.6-35B-A3B.yaml","Qwen/Qwen3.6-35B-A3B","sie_server.adapters.sglang.generation:SGLangGenerationAdapter",- "outlines",+ "xgrammar",+ [+ "--mm-process-config",+ '{"image":{"min_pixels":65536,"max_pixels":1003520}}',+ "--quantization",+ "fp8",+ ],),("google__gemma-4-31B-it.yaml","google/gemma-4-31B-it","sie_server.adapters.sglang.gemma:SGLangGemmaAdapter","xgrammar",+ ["--quantization", "fp8"],),],)@@ -31,6 +38,7 @@ def test_new_generation_models_resolve_h100_fp8_alias(model_id: str,adapter_path: str,grammar_backend: str,+ extra_launch_args: list[str],) -> None:config = ModelConfig.model_validate(yaml.safe_load((MODELS_DIR / model_file).read_text()))default = config.resolve_profile("default")@@ -51,4 +59,4 @@ def test_new_generation_models_resolve_h100_fp8_alias(assert default.loadtime["disable_cuda_graph"] is Trueassert default.loadtime["grammar_backend"] == grammar_backendassert default.loadtime["speculative"] == {"enabled": False}- assert default.loadtime["extra_launch_args"] == ["--quantization", "fp8"]+ assert default.loadtime["extra_launch_args"] == extra_launch_argsdiff --git a/packages/sie_server/tests/config/test_qwen_generation_profiles.py b/packages/sie_server/tests/config/test_qwen_generation_profiles.pyindex a843e2818..7f05688f1 100644--- a/packages/sie_server/tests/config/test_qwen_generation_profiles.py+++ b/packages/sie_server/tests/config/test_qwen_generation_profiles.py@@ -1,14 +1,25 @@from __future__ import annotations+import jsonfrom pathlib import Pathimport yaml+from PIL import Imagefrom sie_server.config.model import ModelConfig, ResolvedProfile+from transformers import Qwen2VLImageProcessorFast_QWEN35_MODEL_PATH = Path(__file__).resolve().parents[2] / "models" / "Qwen__Qwen3.5-4B.yaml"_ADAPTER = "sie_server.adapters.sglang.generation:SGLangGenerationAdapter"+_STRICT_THINKING_ADAPTER = "sie_server.adapters.sglang.cuda13:SGLangStrictThinkingAdapter"_MLX_REPO = "mlx-community/Qwen3.5-4B-4bit"_QWEN36_MODEL_PATH = Path(__file__).resolve().parents[2] / "models" / "Qwen__Qwen3.6-27B.yaml"+_QWEN36_35B_MODEL_PATH = Path(__file__).resolve().parents[2] / "models" / "Qwen__Qwen3.6-35B-A3B.yaml"+_QWEN_IMAGE_MIN_PIXELS = 65536+_QWEN_IMAGE_MAX_PIXELS = 1280 * 28 * 28+_MM_PROCESS_CONFIG_ARGS = [+ "--mm-process-config",+ '{"image":{"min_pixels":65536,"max_pixels":1003520}}',+]def _qwen35_config() -> ModelConfig:@@ -46,6 +57,7 @@ def test_qwen35_default_resolves_to_measured_a100_shape() -> None:"num_draft_tokens": 4,}assert default.loadtime["extra_launch_args"] == [+ *_MM_PROCESS_CONFIG_ARGS,"--mamba-scheduler-strategy","extra_buffer",]@@ -63,6 +75,7 @@ def test_qwen35_l4_smoke_preserves_constrained_c1_shape() -> None:assert l4_smoke.loadtime["mem_fraction_static"] == 0.90assert l4_smoke.loadtime["speculative"]["enabled"] is Trueassert l4_smoke.loadtime["extra_launch_args"] == [+ *_MM_PROCESS_CONFIG_ARGS,"--mamba-scheduler-strategy","extra_buffer","--disable-overlap-schedule",@@ -127,8 +140,12 @@ def test_qwen36_grammar_requests_route_to_no_spec() -> None:assert h100_fp8.adapter_path == no_spec.adapter_pathassert h100_fp8.runtime == no_spec.runtimeassert h100_fp8.loadtime["speculative"] == {"enabled": False}- assert h100_fp8.loadtime["extra_launch_args"] == ["--quantization", "fp8"]- assert default.loadtime["grammar_backend"] == no_spec.loadtime["grammar_backend"] == "outlines"+ assert h100_fp8.loadtime["extra_launch_args"] == [+ *_MM_PROCESS_CONFIG_ARGS,+ "--quantization",+ "fp8",+ ]+ assert default.loadtime["grammar_backend"] == no_spec.loadtime["grammar_backend"] == "xgrammar"assert default.loadtime["speculative"] == {"enabled": False,"algorithm": "nextn",@@ -139,18 +156,21 @@ def test_qwen36_grammar_requests_route_to_no_spec() -> None:assert no_spec.loadtime["speculative"] == {"enabled": False}-def test_qwen36_profiles_use_official_non_thinking_sampling_defaults() -> None:+def test_qwen36_minimum_tokens_are_limited_to_free_text_profiles() -> None:config = ModelConfig.model_validate(yaml.safe_load(_QWEN36_MODEL_PATH.read_text()))- expected = {+ base_sampling = {"temperature": 0.7,"top_p": 0.8,"top_k": 20,"presence_penalty": 1.5,- "min_new_tokens": 10,}- for profile_name in ("default", "h100", "h100-fp8", "rtx-pro-6000", "batch", "no-spec"):- assert config.resolve_profile(profile_name).runtime["default_sampling"] == expected+ for profile_name in ("default", "h100", "rtx-pro-6000", "batch"):+ assert config.resolve_profile(profile_name).runtime["default_sampling"] == (+ base_sampling | {"min_new_tokens": 10}+ )+ for profile_name in ("no-spec", "h100-fp8"):+ assert config.resolve_profile(profile_name).runtime["default_sampling"] == base_samplingdef test_qwen36_base_profiles_expose_8k_context() -> None:@@ -164,3 +184,47 @@ def test_qwen36_base_profiles_expose_8k_context() -> None:assert config.resolve_profile("h100-fp8").kv_budget_tokens == 16384assert config.resolve_profile("batch").kv_budget_tokens == 32768assert config.resolve_profile("no-spec").kv_budget_tokens == 65536+++def test_all_qwen_vlm_profiles_pair_pinned_image_bounds() -> None:+ for model_path in (+ _QWEN35_MODEL_PATH,+ _QWEN36_MODEL_PATH,+ _QWEN36_35B_MODEL_PATH,+ ):+ config = ModelConfig.model_validate(yaml.safe_load(model_path.read_text()))+ assert config.inputs.image is True+ for profile_name in config.profiles:+ profile = config.resolve_profile(profile_name)+ if profile.adapter_path not in {_ADAPTER, _STRICT_THINKING_ADAPTER}:+ continue+ args = profile.loadtime["extra_launch_args"]+ assert args.count("--mm-process-config") == 1, (model_path.name, profile_name, args)+ index = args.index("--mm-process-config")+ assert json.loads(args[index + 1]) == {+ "image": {+ # Transformers 4.57.6 only applies the per-call maximum+ # when the Qwen fast processor receives both bounds.+ "min_pixels": _QWEN_IMAGE_MIN_PIXELS,+ "max_pixels": _QWEN_IMAGE_MAX_PIXELS,+ }+ }+++def test_qwen_fast_processor_applies_paired_image_bounds() -> None:+ processor = Qwen2VLImageProcessorFast(+ size={"shortest_edge": _QWEN_IMAGE_MIN_PIXELS, "longest_edge": 16777216},+ patch_size=16,+ temporal_patch_size=2,+ merge_size=2,+ )++ result = processor(+ images=Image.new("RGB", (2048, 2048), (255, 0, 0)),+ return_tensors="pt",+ min_pixels=_QWEN_IMAGE_MIN_PIXELS,+ max_pixels=_QWEN_IMAGE_MAX_PIXELS,+ )++ assert result["image_grid_thw"].tolist() == [[1, 62, 62]]+ assert result["image_grid_thw"].prod().item() // (2**2) <= 1280diff --git a/packages/sie_server/tests/core/test_loader.py b/packages/sie_server/tests/core/test_loader.pyindex f63680178..05d857606 100644--- a/packages/sie_server/tests/core/test_loader.py+++ b/packages/sie_server/tests/core/test_loader.py@@ -190,6 +190,7 @@ profiles:adapter_path: "sie_server.adapters.sglang.generation:SGLangGenerationAdapter"max_batch_tokens: 32768kv_budget_tokens: 65536+ max_output_tokens: 16384adapter_options:loadtime:max_seq_length: 32768@@ -222,8 +223,10 @@ profiles:assert long_startup_variant.tasks.generate is not Noneassert extended_startup_variant.tasks.generate is not Noneassert base.tasks.generate.context_length == 4096+ assert base.tasks.generate.max_output_tokens == 4096assert base.max_sequence_length == 4096assert variant.tasks.generate.context_length == 32768+ assert variant.tasks.generate.max_output_tokens == 16384assert variant.max_sequence_length == 32768assert long_startup_variant.tasks.generate.context_length == 32768assert long_startup_variant.max_sequence_length == 32768@@ -250,6 +253,122 @@ profiles:assert extended_startup_variant._resolved_lock is not variant._resolved_lockassert extended_startup_variant._resolved_lock is not long_startup_variant._resolved_lock+ def test_profile_chat_template_kwargs_are_promoted_to_variant_task(self, tmp_path: Path) -> None:+ """A profile can opt into thinking without changing the bare model default."""+ (tmp_path / "thinking.yaml").write_text("""+sie_id: org/reasoning-model+hf_id: org/reasoning-model+tasks:+ generate:+ context_length: 8192+ max_output_tokens: 4096+ chat_template_kwargs:+ enable_thinking: false+ guardian_config:+ risk_name: base+max_sequence_length: 8192+profiles:+ default:+ adapter_path: "sie_server.adapters.sglang.generation:SGLangGenerationAdapter"+ max_batch_tokens: 16384+ kv_budget_tokens: 8192+ thinking:+ extends: default+ chat_template_kwargs:+ enable_thinking: true+""")++ configs = load_model_configs(tmp_path)++ base = configs["org/reasoning-model"]+ thinking = configs["org/reasoning-model:thinking"]+ assert base.tasks.generate is not None+ assert thinking.tasks.generate is not None+ assert base.tasks.generate.chat_template_kwargs == {+ "enable_thinking": False,+ "guardian_config": {"risk_name": "base"},+ }+ assert thinking.tasks.generate.chat_template_kwargs == {+ "enable_thinking": True,+ "guardian_config": {"risk_name": "base"},+ }+ assert thinking.resolve_profile("default").chat_template_kwargs == {+ "enable_thinking": True,+ }++ def test_default_profile_chat_template_kwargs_are_promoted_to_bare_task(self, tmp_path: Path) -> None:+ """The bare identity materializes tokenizer presets declared on its default profile."""+ (tmp_path / "default-thinking.yaml").write_text("""+sie_id: org/default-reasoning-model+hf_id: org/default-reasoning-model+tasks:+ generate:+ context_length: 8192+ max_output_tokens: 4096+ chat_template_kwargs:+ guardian_config:+ risk_name: base+profiles:+ default:+ adapter_path: "sie_server.adapters.sglang.generation:SGLangGenerationAdapter"+ max_batch_tokens: 16384+ kv_budget_tokens: 8192+ max_output_tokens: 8192+ chat_template_kwargs:+ enable_thinking: true+""")++ configs = load_model_configs(tmp_path)++ bare = configs["org/default-reasoning-model"]+ assert bare.tasks.generate is not None+ assert bare.tasks.generate.chat_template_kwargs == {+ "guardian_config": {"risk_name": "base"},+ "enable_thinking": True,+ }+ assert bare.tasks.generate.max_output_tokens == 8192+ assert bare.resolve_profile("default").max_output_tokens == 8192+ assert bare.resolve_profile("default").chat_template_kwargs == {+ "enable_thinking": True,+ }++ def test_default_profile_chat_template_kwargs_do_not_bleed_into_standalone_variant(self, tmp_path: Path) -> None:+ """Standalone variants start from model task defaults, not the default profile."""+ (tmp_path / "standalone-long-context.yaml").write_text("""+sie_id: org/reasoning-model+hf_id: org/reasoning-model+tasks:+ generate:+ context_length: 8192+ max_output_tokens: 4096+ chat_template_kwargs:+ enable_thinking: false+profiles:+ default:+ adapter_path: "sie_server.adapters.sglang.generation:SGLangGenerationAdapter"+ max_batch_tokens: 16384+ kv_budget_tokens: 8192+ chat_template_kwargs:+ enable_thinking: true+ long-context:+ adapter_path: "sie_server.adapters.sglang.generation:SGLangGenerationAdapter"+ max_batch_tokens: 32768+ kv_budget_tokens: 32768+ adapter_options:+ loadtime:+ max_seq_length: 32768+""")++ configs = load_model_configs(tmp_path)++ bare = configs["org/reasoning-model"]+ long_context = configs["org/reasoning-model:long-context"]+ assert bare.tasks.generate is not None+ assert long_context.tasks.generate is not None+ assert bare.tasks.generate.chat_template_kwargs == {"enable_thinking": True}+ assert long_context.tasks.generate.chat_template_kwargs == {"enable_thinking": False}+ assert long_context.tasks.generate.context_length == 32768+def test_missing_models_dir(self, tmp_path: Path) -> None:"""Raises FileNotFoundError for missing models directory."""missing_dir = tmp_path / "nonexistent"diff --git a/packages/sie_server/tests/core/test_runtime_options.py b/packages/sie_server/tests/core/test_runtime_options.pyindex c217fbbc6..f095319d8 100644--- a/packages/sie_server/tests/core/test_runtime_options.py+++ b/packages/sie_server/tests/core/test_runtime_options.py@@ -214,6 +214,19 @@ def test_generation_request_runtime_overrides_profile_defaults() -> None:assert resolved["top_p"] == 0.8+def test_generation_frequency_penalty_and_seed_defaults_apply() -> None:+ config = _generation_config()+ config.profiles["default"].adapter_options.runtime["default_sampling"] |= {+ "frequency_penalty": 0.5,+ "seed": -(1 << 63),+ }++ resolved = apply_generation_runtime_options(config, None, {"prompt": "hi"})++ assert resolved["frequency_penalty"] == 0.5+ assert resolved["seed"] == -(1 << 63)++def test_generation_profile_default_min_new_tokens_caps_to_explicit_max() -> None:config = _generation_config()config.profiles["default"].adapter_options.runtime["default_sampling"]["min_new_tokens"] = 10@@ -279,8 +292,15 @@ def test_generation_unknown_option_fails_closed() -> None:{"temperature": "0.7"},{"top_p": None},{"presence_penalty": float("inf")},+ {"temperature": 1 << 1024},+ {"top_k": 1 << 1024},+ {"min_new_tokens": 1 << 1024},+ {"frequency_penalty": -2.1},{"top_k": True},{"min_new_tokens": -1},+ {"seed": True},+ {"seed": 1 << 63},+ {"seed": 1 << 1024},],)def test_generation_invalid_sampling_option_fails_closed(sampling: dict[str, object]) -> None:@@ -292,6 +312,7 @@ def test_generation_invalid_sampling_option_fails_closed(sampling: dict[str, obj)-def test_generation_non_finite_timeout_fails_closed() -> None:[email protected]("value", [float("inf"), 1 << 1024])+def test_generation_non_finite_timeout_fails_closed(value: float) -> None:with pytest.raises(ValueError, match="positive number"):- apply_generation_runtime_options(_generation_config(), {"overall_timeout_s": float("inf")}, {"prompt": "hi"})+ apply_generation_runtime_options(_generation_config(), {"overall_timeout_s": value}, {"prompt": "hi"})diff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.pyindex c01bcf142..698617c77 100644--- a/packages/sie_server/tests/processors/test_streaming.py+++ b/packages/sie_server/tests/processors/test_streaming.py@@ -34,6 +34,9 @@ from sie_server.observability import worker_telemetry as worker_metricsfrom sie_server.processors import streaming as streaming_modfrom sie_server.processors.streaming import StreamingProcessor, _ValidationError+_GEMMA_OPEN = "<" + "|channel" + ">" + "thought\n"+_GEMMA_CLOSE = "<" + "channel|" + ">"+class _FakeGenAdapter(GenerationAdapter):"""Yields a scripted sequence of chunks. Optionally blocks before each."""@@ -533,6 +536,7 @@ def _make_registry_with_chat_config(context_length: int = 32768,hf_id: str = "test/model",hf_revision: str | None = None,+ reasoning_parser: str | None = None,) -> MagicMock:"""Variant of :func:`_make_registry` that also fakes ``get_config``.@@ -544,16 +548,74 @@ def _make_registry_with_chat_config(registry = _make_registry(adapter)config = MagicMock()config.hf_id = hf_id+ config.name = hf_idconfig.hf_revision = hf_revisionconfig.weights_path = Noneconfig.tasks.generate.chat_template_kwargs = chat_template_kwargs or {}config.tasks.generate.context_length = context_length+ profile = MagicMock()+ profile.loadtime = {"reasoning_parser": reasoning_parser} if reasoning_parser is not None else {}+ config.resolve_profile.return_value = profileregistry.get_config.return_value = configreturn registry@pytest.mark.asyncio-async def test_streaming_processor_renders_chat_template(monkeypatch) -> None:[email protected]("enable_thinking", [False, True])[email protected]("model_id", ["Qwen/Qwen3.5-4B", "google/gemma-4-E2B-it"])+async def test_streaming_processor_hides_reasoning_for_every_resolved_profile(+ monkeypatch: pytest.MonkeyPatch,+ enable_thinking: bool,+ model_id: str,+) -> None:+ nc = AsyncMock()+ if model_id.startswith("google/gemma"):+ reasoning_parser = "gemma4"+ opening, closing = _GEMMA_OPEN, _GEMMA_CLOSE+ else:+ reasoning_parser = "qwen3"+ opening, closing = "<think>", "</think>"+ reasoning_chunks = (+ [+ GenerationChunk(text_delta="private reasoning" + closing[:5], is_first=True),+ GenerationChunk(text_delta=closing[5:] + "Visible answer"),+ ]+ if enable_thinking+ else [+ GenerationChunk(text_delta=opening[:5], is_first=True),+ GenerationChunk(text_delta=opening[5:] + "private reasoning" + closing[:5]),+ GenerationChunk(text_delta=closing[5:] + "Visible answer"),+ ]+ )+ adapter = _FakeGenAdapter(+ [+ *reasoning_chunks,+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=1, completion_tokens=8),+ ]+ )+ registry = _make_registry_with_chat_config(+ adapter,+ chat_template_kwargs={"enable_thinking": enable_thinking},+ hf_id=model_id,+ reasoning_parser=reasoning_parser,+ )+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))+ work_item = _make_work_item()+ if enable_thinking:+ monkeypatch.setattr(proc, "_render_chat_template", AsyncMock(return_value="rendered prompt" + opening))+ work_item = _make_work_item(messages=[{"role": "user", "content": "Hello"}])++ await proc.process(_make_msg(work_item), model_id)++ decoded = _decode_chunks(nc)+ visible = "".join(chunk.get("text_delta", "") for chunk in decoded)+ assert visible == "Visible answer"++[email protected]("enable_thinking", [False, True])+async def test_streaming_processor_renders_chat_template(monkeypatch, enable_thinking: bool) -> None:"""``Messages`` shape → adapter receives the rendered template string."""nc = AsyncMock()script = [@@ -574,7 +636,10 @@ async def test_streaming_processor_renders_chat_template(monkeypatch) -> None:adapter.generate = _capture_generate # type: ignore[method-assign]- registry = _make_registry_with_chat_config(adapter, chat_template_kwargs={"enable_thinking": False})+ registry = _make_registry_with_chat_config(+ adapter,+ chat_template_kwargs={"enable_thinking": enable_thinking},+ )# Patch ``load_tokenizer`` (called from a thread) with a stub that# records the kwargs forwarded to ``apply_chat_template``.@@ -601,8 +666,10 @@ async def test_streaming_processor_renders_chat_template(monkeypatch) -> None:assert len(captured_prompts) == 1assert captured_prompts[0] == "<rendered>ping</rendered>"- assert seen_kwargs == {"enable_thinking": False}+ assert seen_kwargs == {"enable_thinking": enable_thinking}decoded = _decode_chunks(nc)+ visible = "".join(chunk.get("text_delta", "") for chunk in decoded)+ assert visible == "hi"assert decoded[-1]["done"] is Trueassert decoded[-1]["finish_reason"] == "stop"@@ -2634,6 +2701,31 @@ def test_validate_generate_caps_profile_min_new_tokens_to_explicit_max() -> Noneassert result.min_tokens == 1+ "chat_template_kwargs",+ [+ "not-an-object",+ {"arbitrary_tokenizer_kwarg": True},+ {"enable_thinking": "false"},+ {"guardian_config": {"risk_name": "harm", "extra": True}},+ ],+)+def test_validate_generate_rejects_unbounded_template_kwargs(chat_template_kwargs: object) -> None:+ result = StreamingProcessor._validate_generate_params(+ _make_work_item(+ generate={+ "prompt": "Hello",+ "max_new_tokens": 8,+ "chat_template_kwargs": chat_template_kwargs,+ }+ )+ )++ assert isinstance(result, _ValidationError)+ assert result.code == "invalid_request"+ assert "chat_template_kwargs" in result.message++def test_validate_generate_rejects_explicit_min_tokens_above_max() -> None:result = StreamingProcessor._validate_generate_params(_make_work_item(@@ -2754,9 +2846,13 @@ def test_parse_message_images_field() -> None:assert not isinstance(out, _ValidationError)assert out[0]["data"] == b"catbytes"assert out[0]["format"] == "png"+ # New Rust sidecars prepare msgpack binary before backend IPC.+ prepared = _parse_message_images_field([{"data": b"prepared", "format": "jpeg"}], 0)+ assert not isinstance(prepared, _ValidationError)+ assert prepared[0] == {"data": b"prepared", "format": "jpeg"}# Non-list rejects.assert isinstance(_parse_message_images_field({"data": "x"}, 1), _ValidationError)- # Non-string data rejects (gateway sends a base64 string).+ # Values other than bytes or rolling-compatible base64 strings reject.bad = _parse_message_images_field([{"data": 123}], 2)assert isinstance(bad, _ValidationError)assert "messages[2].images[0]" in bad.message@@ -2767,7 +2863,7 @@ def test_parse_message_images_field() -> None:# Empty data rejects.empty = _parse_message_images_field([{"data": ""}], 0)assert isinstance(empty, _ValidationError)- assert "non-empty base64" in empty.message+ assert "non-empty bytes or a base64 string" in empty.message@pytest.mark.asyncio@@ -2910,3 +3006,48 @@ async def test_messages_image_reaches_adapter(monkeypatch: pytest.MonkeyPatch) -assert len(adapter.received_images) == 1assert adapter.received_images[0]["data"] == b"catbytes"assert adapter.received_images[0]["format"] == "png"+++async def test_streaming_processor_reserves_capped_visual_tokens(monkeypatch) -> None:+ nc = AsyncMock()+ adapter = _FakeGenAdapter([])+ registry = _make_registry_with_chat_config(adapter, context_length=1200)++ class _StubTok:+ def apply_chat_template(self, *args, **kwargs):+ return "rendered"++ def encode(self, text, *, add_special_tokens):+ return [0]++ from sie_server.processors import streaming as streaming_mod++ monkeypatch.setattr(streaming_mod, "load_tokenizer", lambda *args, **kwargs: _StubTok())++ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ wi = _make_work_item(+ generate={+ "messages": [+ {+ "role": "user",+ "content": "inspect this image",+ "images": [+ {+ "data": base64.b64encode(b"image").decode(),+ "format": "png",+ }+ ],+ }+ ],+ "max_new_tokens": 64,+ }+ )+ msg = _make_msg(wi)+ await proc.process(msg, "test/model")++ terminal = _decode_chunks(nc)[-1]+ assert terminal["done"] is True+ assert terminal["error"]["code"] == "context_exceeded"+ assert "~image_tokens (1280)" in terminal["error"]["message"]+ msg.ack.assert_awaited_once()diff --git a/packages/sie_server/tests/test_local_ingest_client.py b/packages/sie_server/tests/test_local_ingest_client.pynew file mode 100644index 000000000..578bc1ba1--- /dev/null+++ b/packages/sie_server/tests/test_local_ingest_client.py@@ -0,0 +1,181 @@+"""Python client -> Rust local-ingest generation protocol tests."""++from __future__ import annotations++import asyncio+import tempfile+from collections.abc import Iterator+from pathlib import Path+from typing import Any++import msgpack+import pytest+from sie_server import local_ingest_client+++def _frame(value: dict[str, Any]) -> bytes:+ payload = msgpack.packb(value, use_bin_type=True)+ return len(payload).to_bytes(4, "little") + payload+++async def _request(reader: asyncio.StreamReader) -> dict[str, Any]:+ length = int.from_bytes(await reader.readexactly(4), "little")+ return msgpack.unpackb(await reader.readexactly(length), raw=False)+++def _meta() -> dict[str, Any]:+ return {+ "lane": "default|a100-80gb|test/model",+ "request_id": "req-1",+ "endpoint": "generate",+ "model": "test/model",+ "engine": "sglang",+ "admission_pool": "default",+ "bundle_config_hash": "hash",+ }+++def unix_socket_dir() -> Iterator[Path]:+ # macOS limits AF_UNIX paths to 104 bytes; pytest's tmp_path can exceed it.+ with tempfile.TemporaryDirectory(prefix="sie-li-", dir="/tmp") as directory:+ yield Path(directory)+++def test_generation_body_preserves_gateway_transport_binding() -> None:+ meta = {+ **_meta(),+ "dispatch_context": b"authenticated-context",+ "payload_digest": b"d" * local_ingest_client.PAYLOAD_DIGEST_BYTES,+ "timeout_ms": 123,+ }++ body = local_ingest_client.build_generation_request_body(b"items", b"params", meta)++ assert body["dispatch_context"] == meta["dispatch_context"]+ assert body["payload_digest"] == meta["payload_digest"]+ assert body["timeout_ms"] == 123+++async def test_read_frame_normalizes_truncated_and_invalid_protocol_errors() -> None:+ truncated = asyncio.StreamReader()+ truncated.feed_data(b"\x01\x00")+ truncated.feed_eof()+ with pytest.raises(local_ingest_client.LocalIngestStreamError, match="header is truncated"):+ await local_ingest_client._read_frame(truncated)++ invalid = asyncio.StreamReader()+ invalid.feed_data((1).to_bytes(4, "little") + b"\xc1")+ invalid.feed_eof()+ with pytest.raises(local_ingest_client.LocalIngestStreamError, match="invalid MessagePack"):+ await local_ingest_client._read_frame(invalid)+++async def test_stream_generate_bounds_connect_wait(monkeypatch: pytest.MonkeyPatch) -> None:+ async def never_connect(_socket_path: str) -> tuple[asyncio.StreamReader, asyncio.StreamWriter]:+ await asyncio.Event().wait()+ raise AssertionError("unreachable")++ monkeypatch.setattr(local_ingest_client, "LOCAL_INGEST_CONNECT_TIMEOUT_S", 0.01)+ monkeypatch.setattr(local_ingest_client.asyncio, "open_unix_connection", never_connect)++ with pytest.raises(local_ingest_client.LocalIngestStreamError, match="connection timed out"):+ _ = [chunk async for chunk in local_ingest_client.stream_generate("unused.sock", b"items", b"params", _meta())]+++async def test_stream_generate_bounds_response_wait(unix_socket_dir: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ socket_path = unix_socket_dir / "timeout.sock"++ async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:+ await _request(reader)+ await asyncio.sleep(0.1)+ writer.close()+ await writer.wait_closed()++ monkeypatch.setattr(local_ingest_client, "DEFAULT_LOCAL_INGEST_RESPONSE_IDLE_TIMEOUT_S", 0.01)+ server = await asyncio.start_unix_server(handle, path=socket_path)+ async with server:+ with pytest.raises(local_ingest_client.LocalIngestStreamError, match="response timed out"):+ _ = [+ chunk+ async for chunk in local_ingest_client.stream_generate(str(socket_path), b"items", b"params", _meta())+ ]+++async def test_stream_generate_preserves_binding_order_and_terminal(unix_socket_dir: Path) -> None:+ socket_path = unix_socket_dir / "ingest.sock"+ observed: asyncio.Future[dict[str, Any]] = asyncio.get_running_loop().create_future()++ async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:+ request = await _request(reader)+ observed.set_result(request)+ writer.write(+ _frame({"id": 1, "ok": True, "error": None, "body": {"chunk": b"a", "seq": 0}})+ + _frame({"id": 1, "ok": True, "error": None, "body": {"chunk": b"b", "seq": 1}})+ + _frame(+ {+ "id": 1,+ "ok": True,+ "error": None,+ "body": {"final": True, "outcome": {"status": "complete", "chunks": 2}},+ }+ )+ )+ await writer.drain()+ writer.close()++ server = await asyncio.start_unix_server(handle, path=socket_path)+ async with server:+ chunks = [+ chunk async for chunk in local_ingest_client.stream_generate(str(socket_path), b"items", b"params", _meta())+ ]++ assert chunks == [b"a", b"b"]+ request = await observed+ assert request["op"] == "publish_generate_stream"+ body = request["body"]+ assert body["request_id"] == "req-1"+ assert body["payload_digest"] == local_ingest_client.compute_payload_digest(body)+++async def test_stream_generate_disconnect_cancels_connection_owned_stream(unix_socket_dir: Path) -> None:+ socket_path = unix_socket_dir / "cancel.sock"+ disconnected: asyncio.Future[bytes] = asyncio.get_running_loop().create_future()++ async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:+ await _request(reader)+ writer.write(_frame({"id": 1, "ok": True, "error": None, "body": {"chunk": b"first", "seq": 0}}))+ await writer.drain()+ disconnected.set_result(await reader.read())+ writer.close()++ server = await asyncio.start_unix_server(handle, path=socket_path)+ async with server:+ stream = local_ingest_client.stream_generate(str(socket_path), b"items", b"params", _meta())+ assert await anext(stream) == b"first"+ await stream.aclose()+ assert await asyncio.wait_for(disconnected, timeout=1.0) == b""+++async def test_stream_generate_rejects_transport_sequence_gap(unix_socket_dir: Path) -> None:+ socket_path = unix_socket_dir / "gap.sock"++ async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:+ await _request(reader)+ writer.write(_frame({"id": 1, "ok": True, "error": None, "body": {"chunk": b"late", "seq": 1}}))+ await writer.drain()+ writer.close()++ server = await asyncio.start_unix_server(handle, path=socket_path)+ async with server:+ with pytest.raises(local_ingest_client.LocalIngestStreamError, match="not expected 0"):+ _ = [+ chunk+ async for chunk in local_ingest_client.stream_generate(str(socket_path), b"items", b"params", _meta())+ ]diff --git a/packages/sie_server/tests/test_openapi_export.py b/packages/sie_server/tests/test_openapi_export.pyindex 298bc3b89..a216315ab 100644--- a/packages/sie_server/tests/test_openapi_export.py+++ b/packages/sie_server/tests/test_openapi_export.py@@ -27,6 +27,8 @@ def test_openapi_has_expected_paths() -> None:"/v1/encode/{model}","/v1/extract/{model}","/v1/generate/{model}",+ "/v1/completions",+ "/v1/responses","/v1/score/{model}","/v1/models",]:@@ -116,6 +118,47 @@ def test_openapi_documents_generate_contract() -> None:assert model_load_failed_detail["properties"]["code"]["const"] == "MODEL_LOAD_FAILED"+def test_openapi_documents_direct_completions_contract() -> None:+ result = runner.invoke(app, ["openapi"])+ assert result.exit_code == 0, result.output+ spec = json.loads(result.output)++ operation = spec["paths"]["/v1/completions"]["post"]+ assert operation["requestBody"]["content"]["application/json"]["schema"] == {+ "$ref": "#/components/schemas/OpenAICompletionRequestModel"+ }+ schema = spec["components"]["schemas"]["OpenAICompletionRequestModel"]+ assert schema["additionalProperties"] is False+ assert set(schema["required"]) == {"model", "prompt"}+ assert schema["properties"]["max_tokens"]["anyOf"][0]["minimum"] == 1+ assert schema["properties"]["stream"]["anyOf"][0] == {"type": "boolean"}+ response_content = operation["responses"]["200"]["content"]+ assert response_content["application/json"]["schema"] == {+ "$ref": "#/components/schemas/OpenAICompletionResponseModel"+ }+ assert response_content["text/event-stream"]["schema"]["type"] == "string"+++def test_openapi_documents_direct_responses_contract() -> None:+ result = runner.invoke(app, ["openapi"])+ assert result.exit_code == 0, result.output+ spec = json.loads(result.output)++ operation = spec["paths"]["/v1/responses"]["post"]+ assert operation["requestBody"]["content"]["application/json"]["schema"] == {+ "$ref": "#/components/schemas/OpenAIResponsesRequestModel"+ }+ schema = spec["components"]["schemas"]["OpenAIResponsesRequestModel"]+ assert schema["additionalProperties"] is False+ assert set(schema["required"]) == {"model", "input"}+ assert schema["properties"]["max_output_tokens"]["anyOf"][0]["minimum"] == 1+ assert schema["properties"]["stream"]["anyOf"][0]["const"] is False+ assert operation["responses"]["200"]["content"]["application/json"]["schema"] == {+ "$ref": "#/components/schemas/OpenAIResponsesResponseModel"+ }+ assert "413" in operation["responses"]++def test_openapi_audio_timestamp_contract() -> None:"""Audio compatibility documents word and segment timestamps."""result = runner.invoke(app, ["openapi"])diff --git a/packages/sie_server/tests/test_queue_executor.py b/packages/sie_server/tests/test_queue_executor.pyindex 051e61082..1354a92ab 100644--- a/packages/sie_server/tests/test_queue_executor.py+++ b/packages/sie_server/tests/test_queue_executor.py@@ -1267,6 +1267,45 @@ class TestProcessScoreBatch:class TestProcessExtractBatch:+ @pytest.mark.asyncio+ async def test_image_item_uses_registered_preprocessor_payload(self) -> None:+ reg = _make_registry()+ worker = AsyncMock()+ prepared_item = MagicMock(cost=1024, original_index=0, payload=object())+ reg.preprocessor_registry.has_preprocessor.return_value = True+ reg.preprocessor_registry.prepare = AsyncMock(return_value=MagicMock(items=[prepared_item], total_cost=1024))+ fut: asyncio.Future[WorkerResult] = asyncio.Future()+ fut.set_result(WorkerResult(output=ExtractOutput(entities=[[]], objects=[[]]), timing=RequestTiming()))+ worker.submit_extract_preformed_batch = AsyncMock(return_value=[fut])+ reg.start_worker = AsyncMock(return_value=worker)++ await QueueExecutor(reg).process_extract_batch(+ ProcessExtractBatchRequest(+ model_id="test/model",+ items=[+ ExtractBatchItem(+ work_item_id="req-1.0",+ request_id="req-1",+ item_index=0,+ total_items=1,+ timestamp=time.time(),+ item={"images": [{"data": b"image-bytes"}]},+ labels=["bottle"],+ instruction="find bottles",+ options={"task": "detect"},+ )+ ],+ )+ )++ reg.preprocessor_registry.prepare.assert_awaited_once()+ prepare_call = reg.preprocessor_registry.prepare.await_args+ assert prepare_call.args[0] == "test/model"+ assert prepare_call.args[1][0].images[0]["data"] == b"image-bytes"+ assert prepare_call.kwargs == {"instruction": "find bottles", "task": "detect"}+ requests = worker.submit_extract_preformed_batch.await_args.args[0]+ assert requests[0].prepared_items == [prepared_item]+@pytest.mark.asyncioasync def test_single_item_publish_and_ack(self) -> None:reg = _make_registry()diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.tomlindex bab35ea5b..92e225d35 100644--- a/packages/sie_server_sidecar/Cargo.toml+++ b/packages/sie_server_sidecar/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-server-sidecar"-version = "0.6.26"+version = "0.6.27"edition = "2021"publish = falsedescription = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."@@ -42,6 +42,7 @@ rmp = "0.8"# cannot round-trip through serde_json::Value.rmpv = { version = "1", features = ["with-serde"] }sha2 = "0.10"+base64 = "0.22"clap = { version = "4", features = ["derive", "env"] }thiserror = "2"diff --git a/packages/sie_server_sidecar/README.md b/packages/sie_server_sidecar/README.mdindex c863bbcf8..f5f2fb7b1 100644--- a/packages/sie_server_sidecar/README.md+++ b/packages/sie_server_sidecar/README.md@@ -18,5 +18,25 @@ Public and runtime names:- Metrics: push-only OTLP via the `sie.worker.*` contract; Prometheuscompatibility is a collector/exporter concern+The sidecar also has a brokerless local-ingest mode for trusted colocated+callers. Its length-prefixed MessagePack protocol sends ordinary primitives+through the same Rust preparation, scheduling, admission, and backend pipeline+without NATS. Generation uses a separate streaming operation: each semantic+chunk is validated and emitted through the canonical v0.2 bounded writer. Each+connection also has fixed operation-count and retained-request-byte budgets;+when either is full, the reader stops accepting frame bodies until capacity+returns. Active envelope IDs are unique, so concurrent responses cannot become+ambiguous. Exactly one transport+terminal closes each operation, and cancellation or client disconnect is+forwarded to the Python generation processor with a finite drain.+`timeout_ms=0` leaves generation timing to the gateway. Rust normalizes legacy+base64 generation images to bounded MessagePack binary; Python accepts binary+and the legacy representation for mixed-version compatibility.++The local socket is an access-controlled process boundary, not an+authentication protocol. The listener restricts its socket node, validates a+domain-separated request digest and route identity, caps frame/media/request+sizes, and rejects unresolved payload references.+See [`docs/architecture-guide.md`](docs/architecture-guide.md) for the runtimecontract and deployment caveats.diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex 487e1287c..264ee959c 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -178,6 +178,36 @@ Source: [`lib.rs`](../src/lib.rs), [`dispatcher.rs`](../src/dispatcher.rs),[`ipc_client.rs`](../src/ipc_client.rs), and[`packages/sie_gateway/src/handlers/proxy.rs`](../../sie_gateway/src/handlers/proxy.rs).+## Local Ingest++Brokerless deployments can select local ingest and send length-prefixed+MessagePack requests over an owner-only Unix socket. Non-generation work+enters the same dispatcher, Rust preparation, scheduler, admission, and IPC+pipeline as queue work. The request digest detects route and payload assembly+drift between trusted colocated processes; socket permissions provide access+control.++Generation uses the canonical v0.2 `publish_generate_stream` operation. Rust+normalizes legacy base64 images to bounded MessagePack binary, validates+request/attempt identity, contiguous chunk sequence, and terminal ordering,+and awaits every write through a count- and byte-bounded connection writer.+The local-ingest reader also enforces fixed in-flight operation and retained+request-byte budgets per connection. It acquires the declared frame bytes+before reading the body and stops reading while either budget is exhausted, so+slow socket writes cannot accumulate unbounded request bodies or tasks. Active+envelope IDs are unique until their terminal write completes; a duplicate+closes the connection rather than producing ambiguous multiplexed responses.+Active generation request IDs are also claimed process-wide because backend+cancellation is keyed by request ID alone.+Writes and cancellation drain have finite transport deadlines; they do not+override generation's gateway-owned semantic deadline (`timeout_ms=0`). A+`cancel` control request or client disconnect is forwarded through+`SignalGenerateCancel`. Deployments must map their outer transport onto this+contract rather than bypassing the sidecar for media or stream handling.++Source: [`local_ingest.rs`](../src/local_ingest.rs) and+[`dispatcher.rs`](../src/dispatcher.rs).+## IPCIPC framing is:diff --git a/packages/sie_server_sidecar/src/backend/adapter_pool.rs b/packages/sie_server_sidecar/src/backend/adapter_pool.rsindex 9451a801d..806aef0b6 100644--- a/packages/sie_server_sidecar/src/backend/adapter_pool.rs+++ b/packages/sie_server_sidecar/src/backend/adapter_pool.rs@@ -38,6 +38,21 @@ struct AdapterWorkerChild {models: Mutex<HashSet<String>>,}+struct ChildInflightGuard(Arc<AdapterWorkerChild>);++impl ChildInflightGuard {+ fn enter(child: Arc<AdapterWorkerChild>) -> Self {+ child.inflight_batches.fetch_add(1, Ordering::AcqRel);+ Self(child)+ }+}++impl Drop for ChildInflightGuard {+ fn drop(&mut self) {+ self.0.inflight_batches.fetch_sub(1, Ordering::AcqRel);+ }+}+impl AdapterWorkerChild {fn model_count(&self) -> usize {self.models@@ -337,9 +352,8 @@ impl AdapterWorkerPool {self.ensure_not_config_quarantined()?;let model_id = req.model_id.clone();let child = self.child_for_model(&model_id);- child.inflight_batches.fetch_add(1, Ordering::AcqRel);+ let _inflight_guard = ChildInflightGuard::enter(Arc::clone(&child));let result = child.ipc.process_generate(req, on_event).await;- child.inflight_batches.fetch_sub(1, Ordering::AcqRel);match &result {Ok(()) => self.mark_child_call_succeeded(&child),Err(_) => {diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex 44aa7b5c5..bd9133969 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -20,7 +20,6 @@ use std::time::{Duration, Instant};use async_nats::jetstream::Message;use futures_util::future::join_all;use rmpv::Value as MsgValue;-use serde_json::Value as Json;use thiserror::Error;use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore};use tokio::task::JoinHandle;@@ -74,6 +73,107 @@ const PAYLOAD_ERROR_CODE: &str = "payload_error";const PAYLOAD_RESOLVE_ERROR_MESSAGE: &str = "failed to resolve item";const PAYLOAD_TOO_LARGE_MESSAGE: &str = "referenced payload exceeds the worker size limit";+#[derive(Debug, Error)]+#[error("{code}: {message}")]+pub struct GenerateDispatchError {+ pub code: String,+ pub message: String,+}++impl GenerateDispatchError {+ fn new(code: impl Into<String>, message: impl Into<String>) -> Self {+ Self {+ code: code.into(),+ message: message.into(),+ }+ }+}++#[derive(Debug, Clone, Default)]+enum LocalGeneratePhase {+ #[default]+ Streaming,+ AwaitingChunkAck,+ AwaitingRetryAck {+ reason: String,+ },+ Complete,+ Retry {+ reason: String,+ },+}++#[derive(Default)]+struct LocalGenerateState {+ attempt_id: Option<String>,+ next_seq: u32,+ phase: LocalGeneratePhase,+}++impl LocalGenerateState {+ fn observe_ack(&mut self) -> Result<(), String> {+ self.phase = match &self.phase {+ LocalGeneratePhase::AwaitingChunkAck => LocalGeneratePhase::Complete,+ LocalGeneratePhase::AwaitingRetryAck { reason } => LocalGeneratePhase::Retry {+ reason: reason.clone(),+ },+ phase => {+ return Err(format!(+ "generation ACK violated publication/settlement ordering in phase {phase:?}"+ ));+ }+ };+ Ok(())+ }++ fn observe_transport_nak(&mut self) -> Result<(), String> {+ if !matches!(self.phase, LocalGeneratePhase::Streaming) || self.next_seq != 0 {+ return Err(format!(+ "generation NAK violated publication/settlement ordering in phase {:?}",+ self.phase+ ));+ }+ self.phase = LocalGeneratePhase::Retry {+ reason: "backend_redelivery".to_string(),+ };+ Ok(())+ }++ fn observe_progress(&self) -> Result<(), String> {+ if matches!(self.phase, LocalGeneratePhase::Streaming) {+ Ok(())+ } else {+ Err(format!(+ "generation progress violated terminal/settlement ordering in phase {:?}",+ self.phase+ ))+ }+ }+}++#[derive(Debug)]+enum LocalGeneratePublication {+ Chunk(Vec<u8>),+ Retry,+}++struct InflightBatchGuard {+ runtime_state: Arc<RuntimeState>,+}++impl InflightBatchGuard {+ fn enter(runtime_state: Arc<RuntimeState>) -> Self {+ runtime_state.inflight_batches.inc();+ Self { runtime_state }+ }+}++impl Drop for InflightBatchGuard {+ fn drop(&mut self) {+ decrement_gauge(&self.runtime_state.inflight_batches, 1);+ }+}+fn payload_error_contract(error: &PayloadError) -> (&'static str, &'static str) {match error {PayloadError::TooLarge { .. } => (PAYLOAD_TOO_LARGE_ERROR_CODE, PAYLOAD_TOO_LARGE_MESSAGE),@@ -585,6 +685,186 @@ impl Dispatcher {}impl Dispatcher {+ /// Execute one already-bound generation item without assuming a queue+ /// result substrate. The caller supplies a backpressured chunk sink;+ /// Python remains responsible for model semantics and chunk encoding.+ pub async fn process_local_generate<F, Fut>(+ &self,+ mut wi: WorkItem,+ on_chunk: F,+ ) -> Result<(), GenerateDispatchError>+ where+ F: Fn(Vec<u8>) -> Fut + Clone,+ Fut: std::future::Future<Output = Result<(), String>>,+ {+ let model_id = wi.model_id.clone();+ match self.backend.ensure_model_ready(&model_id).await {+ Ok(response) => match response.state {+ ReadinessState::Ready => {}+ ReadinessState::LoadingStarted+ | ReadinessState::LoadingInProgress+ | ReadinessState::RetryLater => {+ return Err(GenerateDispatchError::new(+ MODEL_LOADING_ERROR_CODE,+ format!("model {model_id:?} is loading"),+ ));+ }+ ReadinessState::Failed => {+ return Err(GenerateDispatchError::new(+ MODEL_LOAD_FAILED_ERROR_CODE,+ format!("model {model_id:?} failed to load"),+ ));+ }+ },+ Err(error) => {+ return Err(GenerateDispatchError::new(+ "BACKEND_UNAVAILABLE",+ format!("EnsureModelReady failed: {error}"),+ ));+ }+ }++ if let Some(generate) = wi.generate.as_mut() {+ crate::prep::media::normalize_generate_media(generate).map_err(|error| {+ GenerateDispatchError::new(INVALID_INPUT_ERROR_CODE, error.to_string())+ })?;+ } else {+ return Err(GenerateDispatchError::new(+ INVALID_INPUT_ERROR_CODE,+ "generate parameters are required",+ ));+ }++ let _execution_guard = if let Some(state) = self.config_apply_state.as_ref() {+ let guard = state.lock_execution().await;+ if !state.accepts_bundle_config_hash(&wi.bundle_config_hash) {+ return Err(GenerateDispatchError::new(+ "BUNDLE_CONFIG_MISMATCH",+ "worker configuration changed before generation execution",+ ));+ }+ Some(guard)+ } else {+ None+ };+ let executed_hash = wi.bundle_config_hash.clone();+ let reply_subject = wi.reply_subject.clone();+ let expected_request_id = wi.request_id.clone();+ let work_item_msgpack = rmp_serde::to_vec_named(&wi).map_err(|error| {+ GenerateDispatchError::new(+ "INTERNAL_ERROR",+ format!("failed to encode generate work item: {error}"),+ )+ })?;+ let state = Arc::new(Mutex::new(LocalGenerateState::default()));+ let callback_state = Arc::clone(&state);++ let _inflight_guard = InflightBatchGuard::enter(Arc::clone(&self.runtime_state));+ let result = self+ .worker_pool+ .process_generate(+ ProcessGenerateRequest {+ model_id,+ work_item_msgpack,+ },+ move |event| {+ let state = Arc::clone(&callback_state);+ let on_chunk = on_chunk.clone();+ let executed_hash = executed_hash.clone();+ let expected_request_id = expected_request_id.clone();+ let reply_subject = reply_subject.clone();+ async move {+ match event.kind.as_str() {+ "publish" => {+ if event.reply_subject != reply_subject {+ return Err(IpcError::Server(+ "generation publish reply_subject mismatch".to_string(),+ ));+ }+ let publication = {+ let mut state = state.lock().await;+ validate_local_generate_publication(+ event.payload,+ &expected_request_id,+ &executed_hash,+ &mut state,+ )+ .map_err(IpcError::Server)?+ };+ match publication {+ LocalGeneratePublication::Chunk(payload) => {+ on_chunk(payload).await.map_err(IpcError::Server)+ }+ LocalGeneratePublication::Retry => Ok(()),+ }+ }+ "ack" => {+ let mut state = state.lock().await;+ state.observe_ack().map_err(IpcError::Server)+ }+ "nak" => {+ let mut state = state.lock().await;+ state.observe_transport_nak().map_err(IpcError::Server)+ }+ "in_progress" => {+ let state = state.lock().await;+ state.observe_progress().map_err(IpcError::Server)+ }+ other => Err(IpcError::Server(format!(+ "unknown ProcessGenerate event {other:?}"+ ))),+ }+ }+ },+ )+ .await;++ if let Err(error) = result {+ let _ = self+ .worker_pool+ .signal_generate_cancel(wi.request_id.clone())+ .await;+ return Err(GenerateDispatchError::new(+ "TRANSPORT_FAILURE",+ format!("generation backend stream failed: {error}"),+ ));+ }+ let phase = state.lock().await.phase.clone();+ match phase {+ LocalGeneratePhase::Complete => Ok(()),+ LocalGeneratePhase::Retry { reason } => Err(GenerateDispatchError::new(+ "RETRY_LATER",+ format!("generation backend requested retry: {reason}"),+ )),+ phase => {+ let _ = self+ .worker_pool+ .signal_generate_cancel(wi.request_id.clone())+ .await;+ Err(GenerateDispatchError::new(+ "TRANSPORT_FAILURE",+ format!("generation ended in incomplete phase {phase:?}"),+ ))+ }+ }+ }++ pub async fn signal_local_generate_cancel(+ &self,+ request_id: &str,+ ) -> Result<bool, GenerateDispatchError> {+ self.worker_pool+ .signal_generate_cancel(request_id.to_string())+ .await+ .map(|response| response.matched)+ .map_err(|error| {+ GenerateDispatchError::new(+ "TRANSPORT_FAILURE",+ format!("generation cancel IPC failed: {error}"),+ )+ })+ }+fn current_bundle_config_hash(&self) -> Option<String> {self.config_apply_state.as_ref()@@ -1338,6 +1618,34 @@ impl Dispatcher {}}+ if let Some(generate) = wi.generate.as_mut() {+ if let Err(error) = crate::prep::media::normalize_generate_media(generate) {+ warn!(+ work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ model = %model_id,+ error = %error,+ "invalid generation media — publishing terminal error + ACK"+ );+ match self+ .publish_generate_terminal_error(+ &wi,+ INVALID_INPUT_ERROR_CODE,+ &error.to_string(),+ )+ .await+ {+ Ok(_) => {+ let _ = ack_msg(&msg, &self.runtime_state.telemetry).await;+ }+ Err(_) => {+ nak_msg(&msg, base_delay_ms, &self.runtime_state.telemetry).await;+ }+ }+ return;+ }+ }+// Bind the whole streaming execution to one stable worker config.// Config applies take the write side of this barrier; concurrent// inference takes shared guards. Re-check after payload resolution so@@ -3644,6 +3952,174 @@ fn stamp_generate_execution_hash(.map_err(|error| IpcError::Server(format!("encode generation chunk: {error}")).into())}+fn validate_local_generate_publication(+ payload: Vec<u8>,+ expected_request_id: &str,+ executed_bundle_config_hash: &str,+ state: &mut LocalGenerateState,+) -> Result<LocalGeneratePublication, String> {+ let mut value: MsgValue = rmp_serde::from_slice(&payload)+ .map_err(|error| format!("decode generation publication: {error}"))?;+ let MsgValue::Map(fields) = &value else {+ return Err("generation publication is not a msgpack map".to_string());+ };+ let kind = unique_generate_chunk_field(fields, "kind")?+ .and_then(MsgValue::as_str)+ .ok_or_else(|| "generation publication kind must be a string".to_string())?+ .to_string();++ match kind.as_str() {+ "chunk" => {+ validate_local_generate_chunk_fields(fields, expected_request_id, state)?;+ if !executed_bundle_config_hash.is_empty() {+ let MsgValue::Map(fields) = &mut value else {+ unreachable!("publication map was validated above")+ };+ fields.retain(|(key, _)| key.as_str() != Some("executed_bundle_config_hash"));+ fields.push((+ MsgValue::from("executed_bundle_config_hash"),+ MsgValue::from(executed_bundle_config_hash),+ ));+ }+ let payload = rmp_serde::to_vec_named(&value)+ .map_err(|error| format!("encode generation chunk: {error}"))?;+ Ok(LocalGeneratePublication::Chunk(payload))+ }+ "nak" => {+ validate_local_generate_nak_fields(fields, expected_request_id, state)?;+ Ok(LocalGeneratePublication::Retry)+ }+ other => Err(format!("unexpected generation publication kind {other:?}")),+ }+}++#[cfg(test)]+fn validate_local_generate_chunk(+ payload: &[u8],+ expected_request_id: &str,+ state: &mut LocalGenerateState,+) -> Result<(), String> {+ let value: MsgValue = rmp_serde::from_slice(payload)+ .map_err(|error| format!("decode generation chunk: {error}"))?;+ let MsgValue::Map(fields) = value else {+ return Err("generation chunk is not a msgpack map".to_string());+ };+ validate_local_generate_chunk_fields(&fields, expected_request_id, state)+}++fn validate_local_generate_chunk_fields(+ fields: &[(MsgValue, MsgValue)],+ expected_request_id: &str,+ state: &mut LocalGenerateState,+) -> Result<(), String> {+ if !matches!(state.phase, LocalGeneratePhase::Streaming) {+ return Err(format!(+ "generation emitted a chunk after terminal/settlement phase {:?}",+ state.phase+ ));+ }+ let kind = unique_generate_chunk_field(fields, "kind")?+ .and_then(MsgValue::as_str)+ .ok_or_else(|| "generation chunk kind must be a string".to_string())?;+ if kind != "chunk" {+ return Err(format!("unexpected generation chunk kind {kind:?}"));+ }+ let request_id = unique_generate_chunk_field(fields, "request_id")?+ .and_then(MsgValue::as_str)+ .ok_or_else(|| "generation chunk request_id must be a string".to_string())?;+ if request_id != expected_request_id {+ return Err("generation chunk request_id mismatch".to_string());+ }+ let attempt_id = unique_generate_chunk_field(fields, "attempt_id")?+ .and_then(MsgValue::as_str)+ .filter(|value| !value.is_empty() && value.len() <= 128)+ .ok_or_else(|| "generation chunk attempt_id is invalid".to_string())?;+ match state.attempt_id.as_deref() {+ Some(expected) if expected != attempt_id => {+ return Err("generation chunk attempt_id changed within stream".to_string());+ }+ None => state.attempt_id = Some(attempt_id.to_string()),+ _ => {}+ }+ let seq = unique_generate_chunk_field(fields, "seq")?+ .and_then(MsgValue::as_u64)+ .and_then(|value| u32::try_from(value).ok())+ .ok_or_else(|| "generation chunk seq must be a u32".to_string())?;+ if seq != state.next_seq {+ return Err(format!(+ "generation chunk seq gap: got {seq}, expected {}",+ state.next_seq+ ));+ }+ state.next_seq = state+ .next_seq+ .checked_add(1)+ .ok_or_else(|| "generation chunk sequence overflow".to_string())?;+ let done = unique_generate_chunk_field(fields, "done")?+ .and_then(MsgValue::as_bool)+ .ok_or_else(|| "generation chunk done must be a bool".to_string())?;+ if done {+ state.phase = LocalGeneratePhase::AwaitingChunkAck;+ }+ Ok(())+}++fn validate_local_generate_nak_fields(+ fields: &[(MsgValue, MsgValue)],+ expected_request_id: &str,+ state: &mut LocalGenerateState,+) -> Result<(), String> {+ if !matches!(state.phase, LocalGeneratePhase::Streaming) || state.next_seq != 0 {+ return Err(format!(+ "generation emitted a semantic NAK after output/settlement phase {:?}",+ state.phase+ ));+ }+ let request_id = unique_generate_chunk_field(fields, "request_id")?+ .and_then(MsgValue::as_str)+ .ok_or_else(|| "generation NAK request_id must be a string".to_string())?;+ if request_id != expected_request_id {+ return Err("generation NAK request_id mismatch".to_string());+ }+ let attempt_id = unique_generate_chunk_field(fields, "attempt_id")?+ .and_then(MsgValue::as_str)+ .filter(|value| !value.is_empty() && value.len() <= 128)+ .ok_or_else(|| "generation NAK attempt_id is invalid".to_string())?;+ match state.attempt_id.as_deref() {+ Some(expected) if expected != attempt_id => {+ return Err("generation NAK attempt_id changed within stream".to_string());+ }+ None => state.attempt_id = Some(attempt_id.to_string()),+ _ => {}+ }+ let reason = unique_generate_chunk_field(fields, "reason")?+ .and_then(MsgValue::as_str)+ .filter(|value| !value.is_empty() && value.len() <= 64)+ .ok_or_else(|| "generation NAK reason is invalid".to_string())?;+ state.phase = LocalGeneratePhase::AwaitingRetryAck {+ reason: reason.to_string(),+ };+ Ok(())+}++fn unique_generate_chunk_field<'a>(+ fields: &'a [(MsgValue, MsgValue)],+ expected: &str,+) -> Result<Option<&'a MsgValue>, String> {+ let mut found = None;+ for (key, value) in fields {+ if key.as_str() != Some(expected) {+ continue;+ }+ if found.replace(value).is_some() {+ return Err(format!(+ "generation chunk contains duplicate {expected:?} field"+ ));+ }+ }+ Ok(found)+}+async fn ack(delivery: &Delivery,telemetry: &crate::observability::metrics::SidecarTelemetry,@@ -4785,10 +5261,9 @@ pub(crate) async fn scheduler_drain_loop(/// Decode an offloaded generate payload blob (msgpack) into the inline/// `generate` value. Extracted so the transport contract is directly-/// testable: the gateway offloads `generate` carrying **base64-string** image-/// data, which round-trips through `serde_json::Value`; the original, buggy-/// msgpack-`bin` (`serde_bytes`) shape does NOT decode here.-fn decode_offloaded_generate(bytes: &[u8]) -> Result<Json, rmp_serde::decode::Error> {+/// testable: legacy gateway blobs carry base64-string images, while+/// sidecar-prepared or newer producers may already carry msgpack binary.+fn decode_offloaded_generate(bytes: &[u8]) -> Result<MsgValue, rmp_serde::decode::Error> {rmp_serde::from_slice(bytes)}@@ -5085,6 +5560,159 @@ mod tests {assert_eq!(decoded["text_delta"], "done");}+ fn local_chunk(request_id: &str, attempt_id: &str, seq: u32, done: bool) -> Vec<u8> {+ rmp_serde::to_vec_named(&serde_json::json!({+ "kind": "chunk",+ "request_id": request_id,+ "attempt_id": attempt_id,+ "seq": seq,+ "text_delta": "x",+ "done": done+ }))+ .unwrap()+ }++ fn local_nak(request_id: &str, attempt_id: &str, reason: &str) -> Vec<u8> {+ rmp_serde::to_vec_named(&serde_json::json!({+ "kind": "nak",+ "request_id": request_id,+ "attempt_id": attempt_id,+ "reason": reason+ }))+ .unwrap()+ }++ #[test]+ fn local_generation_chunk_validation_requires_exact_order_and_terminal() {+ let mut state = LocalGenerateState::default();+ validate_local_generate_chunk(+ &local_chunk("req-1", "attempt-1", 0, false),+ "req-1",+ &mut state,+ )+ .unwrap();+ validate_local_generate_chunk(+ &local_chunk("req-1", "attempt-1", 1, true),+ "req-1",+ &mut state,+ )+ .unwrap();+ assert!(matches!(state.phase, LocalGeneratePhase::AwaitingChunkAck));+ assert_eq!(state.next_seq, 2);++ let error = validate_local_generate_chunk(+ &local_chunk("req-1", "attempt-1", 2, false),+ "req-1",+ &mut state,+ )+ .unwrap_err();+ assert!(error.contains("after terminal"));+ }++ #[test]+ fn local_generation_semantic_nak_is_a_retry_terminal_after_ack() {+ let mut state = LocalGenerateState::default();+ let publication = validate_local_generate_publication(+ local_nak("req-1", "attempt-1", "kv_budget"),+ "req-1",+ "hash-a",+ &mut state,+ )+ .unwrap();+ assert!(matches!(publication, LocalGeneratePublication::Retry));+ assert!(matches!(+ state.phase,+ LocalGeneratePhase::AwaitingRetryAck { ref reason } if reason == "kv_budget"+ ));+ assert!(state.observe_progress().is_err());+ assert!(state.observe_transport_nak().is_err());+ state.observe_ack().unwrap();+ assert!(matches!(+ state.phase,+ LocalGeneratePhase::Retry { ref reason } if reason == "kv_budget"+ ));+ assert!(state.observe_ack().is_err());+ }++ #[test]+ fn local_generation_semantic_nak_rejects_partial_output_and_bad_identity() {+ let mut after_output = LocalGenerateState::default();+ validate_local_generate_chunk(+ &local_chunk("req-1", "attempt-1", 0, false),+ "req-1",+ &mut after_output,+ )+ .unwrap();+ let error = validate_local_generate_publication(+ local_nak("req-1", "attempt-1", "model_not_loaded"),+ "req-1",+ "",+ &mut after_output,+ )+ .unwrap_err();+ assert!(error.contains("after output"));++ let error = validate_local_generate_publication(+ local_nak("other", "attempt-1", "model_not_loaded"),+ "req-1",+ "",+ &mut LocalGenerateState::default(),+ )+ .unwrap_err();+ assert!(error.contains("request_id mismatch"));+ }++ #[test]+ fn local_generation_terminal_requires_one_ack_and_rejects_late_progress() {+ let mut state = LocalGenerateState::default();+ validate_local_generate_chunk(+ &local_chunk("req-1", "attempt-1", 0, true),+ "req-1",+ &mut state,+ )+ .unwrap();+ assert!(state.observe_progress().is_err());+ assert!(state.observe_transport_nak().is_err());+ state.observe_ack().unwrap();+ assert!(matches!(state.phase, LocalGeneratePhase::Complete));+ assert!(state.observe_ack().is_err());+ assert!(state.observe_progress().is_err());+ }++ #[test]+ fn local_generation_chunk_validation_rejects_identity_gap_and_duplicates() {+ let mut state = LocalGenerateState::default();+ assert!(validate_local_generate_chunk(+ &local_chunk("other", "attempt-1", 0, false),+ "req-1",+ &mut state,+ )+ .unwrap_err()+ .contains("request_id mismatch"));+ assert!(validate_local_generate_chunk(+ &local_chunk("req-1", "attempt-1", 1, false),+ "req-1",+ &mut state,+ )+ .unwrap_err()+ .contains("seq gap"));++ let duplicate = MsgValue::Map(vec![+ (MsgValue::from("kind"), MsgValue::from("chunk")),+ (MsgValue::from("request_id"), MsgValue::from("req-1")),+ (MsgValue::from("request_id"), MsgValue::from("req-1")),+ (MsgValue::from("attempt_id"), MsgValue::from("attempt-1")),+ (MsgValue::from("seq"), MsgValue::from(0)),+ (MsgValue::from("done"), MsgValue::from(false)),+ ]);+ let bytes = rmp_serde::to_vec_named(&duplicate).unwrap();+ assert!(+ validate_local_generate_chunk(&bytes, "req-1", &mut LocalGenerateState::default(),)+ .unwrap_err()+ .contains("duplicate")+ );+ }+#[cfg(target_os = "linux")]#[tokio::test]async fn offloaded_generate_blob_with_base64_images_resolves_via_object_store() {@@ -5111,9 +5739,18 @@ mod tests {.get("req-1_0.bin").await.expect("blob fetched from object store");- let decoded = decode_offloaded_generate(&bytes)- .expect("base64-image generate blob must decode as serde_json::Value");- assert_eq!(decoded["messages"][0]["images"][0]["data"], "aGVsbG8=");+ let mut decoded =+ decode_offloaded_generate(&bytes).expect("base64-image generate blob must decode");+ assert_eq!(+ decoded["messages"][0]["images"][0]["data"],+ MsgValue::from("aGVsbG8=")+ );+ crate::prep::media::normalize_generate_media(&mut decoded)+ .expect("sidecar normalizes generation media");+ assert_eq!(+ decoded["messages"][0]["images"][0]["data"],+ MsgValue::Binary(b"hello".to_vec())+ );// Inline into a WorkItem and re-encode → decode (the sidecar → Python// worker hop): the base64 image survives the full round trip.@@ -5123,15 +5760,16 @@ mod tests {let reencoded = rmp_serde::to_vec_named(&work).unwrap();let back: WorkItem = rmp_serde::from_slice(&reencoded).unwrap();let g = back.generate.expect("generate inlined onto the work item");- assert_eq!(g["messages"][0]["images"][0]["data"], "aGVsbG8=");+ assert_eq!(+ g["messages"][0]["images"][0]["data"],+ MsgValue::Binary(b"hello".to_vec())+ );}#[test]- fn bin_generate_blob_fails_to_decode_proving_base64_is_required() {- // The original (buggy) shape: image bytes as a msgpack `bin` via- // serde_bytes. `serde_json::Value` cannot hold `bin`, so the sidecar- // decode fails — this is exactly the transport bug the base64-string- // representation fixes.+ fn bin_generate_blob_decodes_for_rolling_prepared_media() {+ // Newer producers may send image bytes as msgpack `bin`; the+ // sidecar's wire-native generation value must preserve them.#[derive(serde::Serialize)]struct BinImage {#[serde(with = "serde_bytes")]@@ -5147,9 +5785,10 @@ mod tests {}],}).unwrap();- assert!(- decode_offloaded_generate(&blob).is_err(),- "msgpack bin must NOT decode as serde_json::Value — the exact bug base64 transport fixes"+ let decoded = decode_offloaded_generate(&blob).expect("msgpack binary must decode");+ assert_eq!(+ decoded["images"][0]["data"],+ MsgValue::Binary(vec![0xFF, 0xD8, 0xFF, 0xE0]));}diff --git a/packages/sie_server_sidecar/src/local_ingest.rs b/packages/sie_server_sidecar/src/local_ingest.rsindex 10b8ed1fa..199e2c98c 100644--- a/packages/sie_server_sidecar/src/local_ingest.rs+++ b/packages/sie_server_sidecar/src/local_ingest.rs@@ -13,11 +13,27 @@//! * Frame: `u32` little-endian length + msgpack map. 64 MiB cap.//! * Request: `{"id": u64, "op": str, "body": map}`; response//! `{"id": u64, "ok": bool, "error": str|nil, "body": map}`.-//! * Ops: `ping` → `{}`; `publish_work` → `{results: bin}`; `cancel` →-//! `{}` (accepted but a no-op here: the lane's one-shot batch calls-//! are dropped by the caller side on cancel, and the gateway already-//! discards late results — real in-flight cancellation lands with the-//! streaming ops later).+//! * Envelope IDs must be unique while an operation is active; a duplicate+//! closes the connection because its response cannot be correlated safely.+//! Retained data request frames share one 64 MiB byte budget per connection;+//! the reader keeps a separate small byte reserve so a valid `cancel` frame+//! can still be decoded when data bytes are saturated.+//! * Ops: `ping` → `{}`; `publish_work` → `{results: bin}`;+//! `publish_generate_stream` → an ordered sequence of `{chunk: bin,+//! seq: n}` responses followed by exactly one `{final: true, outcome:+//! {...}}` response or an `ok=false` response with an empty body; `cancel`+//! forwards `body.request_id` only when that generation is active on the same+//! connection and answers `{}`; unknown or terminal targets are no-ops.+//! * Generate streams are correlated by envelope `id`. One connection may+//! carry several streams and control calls. Active generation `request_id`s+//! are claimed process-wide because backend cancellation is keyed by that ID+//! alone. A byte- and count-bounded writer serializes frames; every backend+//! event awaits its finite socket write, so the local hop introduces no+//! unbounded chunk queue. Count and retained-byte admission bounds decoded+//! and active work. Data-operation saturation is rejected after one bounded+//! decode slot so it cannot prevent the reader from accepting a reserved+//! `cancel` control call. A terminal tombstones its stream. Client EOF signals+//! cancellation for every active stream on that connection.//! * `publish_work.body` carries opaque `params`, `items`, and//! `dispatch_context` bytes plus a domain-separated SHA-256//! `payload_digest`. This unkeyed checksum detects field-assembly drift@@ -47,7 +63,8 @@use std::collections::HashSet;use std::os::unix::fs::PermissionsExt;use std::path::Path;-use std::sync::Arc;+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::{Arc, Mutex as StdMutex};use std::time::{Duration, Instant};use anyhow::Context;@@ -55,7 +72,7 @@ use serde::{Deserialize, Serialize};use sha2::{Digest, Sha256};use tokio::io::{AsyncReadExt, AsyncWriteExt};use tokio::net::{UnixListener, UnixStream};-use tokio::sync::{mpsc, Mutex};+use tokio::sync::{mpsc, oneshot, Mutex, Notify, OwnedSemaphorePermit, Semaphore};use tracing::{debug, info, warn};use crate::delivery::{Delivery, LocalDelivery, LocalDeliveryEvent};@@ -73,6 +90,18 @@ pub const MAX_LOCAL_INGEST_FRAME_BYTES: usize = 64 * 1024 * 1024;const MAX_IMAGE_OR_DOCUMENT_BYTES: usize = 16 * 1024 * 1024;const MAX_AUDIO_BYTES: usize = 24 * 1024 * 1024;const MAX_WORK_ITEMS_PER_CALL: usize = 4_096;+const MAX_GENERATE_STREAMS_PER_CONNECTION: usize = 64;+const MAX_PENDING_WRITES_PER_CONNECTION: usize = MAX_GENERATE_STREAMS_PER_CONNECTION + 16;+const MAX_INFLIGHT_DATA_OPERATIONS_PER_CONNECTION: usize = MAX_PENDING_WRITES_PER_CONNECTION;+const MAX_INFLIGHT_CONTROL_OPERATIONS_PER_CONNECTION: usize = 1;+const MAX_DECODING_FRAMES_PER_CONNECTION: usize = 1;+const MAX_BUFFERED_WRITE_BYTES: usize = MAX_LOCAL_INGEST_FRAME_BYTES + 4;+const MAX_INFLIGHT_REQUEST_BYTES_PER_CONNECTION: usize = MAX_LOCAL_INGEST_FRAME_BYTES;+const MAX_RESERVED_CONTROL_REQUEST_BYTES_PER_CONNECTION: usize = 1_024;+const MAX_BUFFERED_REQUEST_BYTES_PER_CONNECTION: usize =+ MAX_INFLIGHT_REQUEST_BYTES_PER_CONNECTION + MAX_RESERVED_CONTROL_REQUEST_BYTES_PER_CONNECTION;+const LOCAL_WRITE_TIMEOUT: Duration = Duration::from_secs(5);+const LOCAL_GENERATE_CANCEL_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);/// Domain-separate the local-ingest consistency checksum from every other/// SHA-256 use in the sidecar. The context is caller-defined and discarded@@ -108,6 +137,7 @@ const POOL_ADMISSION_ERROR_CODE: &str = "pool_admission_rejected";const OP_PING: &str = "ping";const OP_PUBLISH_WORK: &str = "publish_work";+const OP_PUBLISH_GENERATE_STREAM: &str = "publish_generate_stream";const OP_CANCEL: &str = "cancel";// ---------------------------------------------------------------------------@@ -209,7 +239,32 @@ fn results_body(results_bytes: Vec<u8>) -> rmpv::Value {}/// Read one length-prefixed frame; `Ok(None)` on clean EOF between frames.+#[cfg(test)]async fn read_frame<R: AsyncReadExt + Unpin>(reader: &mut R) -> std::io::Result<Option<Vec<u8>>> {+ let Some(len) = read_frame_length(reader).await? else {+ return Ok(None);+ };+ read_frame_payload(reader, len).await.map(Some)+}++async fn read_frame_with_budget<R: AsyncReadExt + Unpin>(+ reader: &mut R,+ byte_budget: &Arc<Semaphore>,+) -> std::io::Result<Option<(Vec<u8>, OwnedSemaphorePermit)>> {+ let Some(len) = read_frame_length(reader).await? else {+ return Ok(None);+ };+ let permit = Arc::clone(byte_budget)+ .acquire_many_owned(len)+ .await+ .map_err(|_| std::io::Error::other("local-ingest request byte budget closed"))?;+ let payload = read_frame_payload(reader, len).await?;+ Ok(Some((payload, permit)))+}++async fn read_frame_length<R: AsyncReadExt + Unpin>(+ reader: &mut R,+) -> std::io::Result<Option<u32>> {let mut header = [0u8; 4];match reader.read_exact(&mut header).await {Ok(_) => {}@@ -223,6 +278,13 @@ async fn read_frame<R: AsyncReadExt + Unpin>(reader: &mut R) -> std::io::Result<format!("frame length {len} exceeds max {MAX_LOCAL_INGEST_FRAME_BYTES}"),));}+ Ok(Some(len))+}++async fn read_frame_payload<R: AsyncReadExt + Unpin>(+ reader: &mut R,+ len: u32,+) -> std::io::Result<Vec<u8>> {// Grow the buffer as bytes actually arrive rather than pre-allocating the// full declared length: a client can cheaply declare up to the 64 MiB cap,// so an eager `vec![0u8; len]` would let a 4-byte header pin 64 MiB before@@ -239,7 +301,7 @@ async fn read_frame<R: AsyncReadExt + Unpin>(reader: &mut R) -> std::io::Result<format!("frame truncated: read {read} of {len} declared bytes"),));}- Ok(Some(payload))+ Ok(payload)}// ---------------------------------------------------------------------------@@ -250,6 +312,7 @@ async fn read_frame<R: AsyncReadExt + Unpin>(reader: &mut R) -> std::io::Result<struct IngestShared {dispatcher: Arc<Dispatcher>,shutdown: Arc<Shutdown>,+ active_generate_request_ids: Arc<StdMutex<HashSet<String>>>,/// Physical pool this lane serves (`SIE_POOL`), pre-normalized.lane_pool: String,worker_id: String,@@ -297,6 +360,7 @@ pub async fn run_local_ingest(let shared = Arc::new(IngestShared {dispatcher,shutdown: Arc::clone(&shutdown),+ active_generate_request_ids: Arc::new(StdMutex::new(HashSet::new())),lane_pool: normalize_pool(pool),worker_id: worker_id.to_string(),});@@ -325,14 +389,371 @@ pub async fn run_local_ingest(Ok(())}+#[derive(Default)]+struct ConnectionLifecycle {+ closed: AtomicBool,+ closed_notify: Notify,+}++impl ConnectionLifecycle {+ fn close(&self) {+ if !self.closed.swap(true, Ordering::AcqRel) {+ self.closed_notify.notify_waiters();+ }+ }++ fn is_closed(&self) -> bool {+ self.closed.load(Ordering::Acquire)+ }++ async fn wait_closed(&self) {+ loop {+ let notified = self.closed_notify.notified();+ if self.is_closed() {+ return;+ }+ notified.await;+ }+ }+}++struct QueuedWrite {+ frame: Vec<u8>,+ deadline: tokio::time::Instant,+ accepting: Option<Arc<AtomicBool>>,+ cancelled: Arc<AtomicBool>,+ done: oneshot::Sender<Result<(), String>>,+ _byte_budget: OwnedSemaphorePermit,+}++struct QueuedWriteDropGuard {+ cancelled: Arc<AtomicBool>,+ armed: bool,+}++impl Drop for QueuedWriteDropGuard {+ fn drop(&mut self) {+ if self.armed {+ self.cancelled.store(true, Ordering::Release);+ }+ }+}++#[derive(Clone)]+struct ConnectionWriter {+ tx: mpsc::Sender<QueuedWrite>,+ byte_budget: Arc<Semaphore>,+ lifecycle: Arc<ConnectionLifecycle>,+}++impl ConnectionWriter {+ fn spawn(+ write_half: tokio::net::unix::OwnedWriteHalf,+ lifecycle: Arc<ConnectionLifecycle>,+ ) -> Self {+ let (tx, rx) = mpsc::channel(MAX_PENDING_WRITES_PER_CONNECTION);+ let byte_budget = Arc::new(Semaphore::new(MAX_BUFFERED_WRITE_BYTES));+ tokio::spawn(run_connection_writer(+ write_half,+ rx,+ Arc::clone(&lifecycle),+ ));+ Self {+ tx,+ byte_budget,+ lifecycle,+ }+ }++ async fn send(&self, frame: Vec<u8>) -> Result<(), String> {+ self.send_if(frame, None).await+ }++ async fn send_if(+ &self,+ frame: Vec<u8>,+ accepting: Option<Arc<AtomicBool>>,+ ) -> Result<(), String> {+ let result = self.send_inner(frame, accepting).await;+ if result.is_err() {+ self.lifecycle.close();+ }+ result+ }++ async fn send_inner(+ &self,+ frame: Vec<u8>,+ accepting: Option<Arc<AtomicBool>>,+ ) -> Result<(), String> {+ if self.lifecycle.is_closed() {+ return Err("local-ingest connection is closed".to_string());+ }+ let permits = u32::try_from(frame.len())+ .map_err(|_| "local-ingest response frame is too large".to_string())?;+ let deadline = tokio::time::Instant::now() + LOCAL_WRITE_TIMEOUT;+ let byte_budget = tokio::time::timeout_at(+ deadline,+ Arc::clone(&self.byte_budget).acquire_many_owned(permits),+ )+ .await+ .map_err(|_| "local-ingest response write queue timed out".to_string())?+ .map_err(|_| "local-ingest response writer stopped".to_string())?;+ let cancelled = Arc::new(AtomicBool::new(false));+ let (done, completed) = oneshot::channel();+ let command = QueuedWrite {+ frame,+ deadline,+ accepting,+ cancelled: Arc::clone(&cancelled),+ done,+ _byte_budget: byte_budget,+ };+ let mut drop_guard = QueuedWriteDropGuard {+ cancelled,+ armed: true,+ };+ tokio::time::timeout_at(deadline, self.tx.send(command))+ .await+ .map_err(|_| "local-ingest response write queue timed out".to_string())?+ .map_err(|_| "local-ingest response writer stopped".to_string())?;+ let result = tokio::time::timeout_at(deadline, completed)+ .await+ .map_err(|_| "local-ingest response write timed out".to_string())?+ .map_err(|_| "local-ingest response writer stopped".to_string())?;+ drop_guard.armed = false;+ result+ }+}++struct ActiveOperationIdGuard {+ operation_id: u64,+ active: Arc<StdMutex<HashSet<u64>>>,+}++impl ActiveOperationIdGuard {+ fn claim(operation_id: u64, active: Arc<StdMutex<HashSet<u64>>>) -> Option<Self> {+ let claimed = active+ .lock()+ .expect("local-ingest active operation ids mutex poisoned")+ .insert(operation_id);+ claimed.then_some(Self {+ operation_id,+ active,+ })+ }+}++impl Drop for ActiveOperationIdGuard {+ fn drop(&mut self) {+ self.active+ .lock()+ .expect("local-ingest active operation ids mutex poisoned")+ .remove(&self.operation_id);+ }+}++struct ActiveGenerateClaim {+ request_id: String,+ active: Arc<StdMutex<HashSet<String>>>,+}++impl ActiveGenerateClaim {+ fn claim(request_id: String, active: Arc<StdMutex<HashSet<String>>>) -> Option<Self> {+ let claimed = active+ .lock()+ .expect("local-ingest active generation request ids mutex poisoned")+ .insert(request_id.clone());+ claimed.then_some(Self { request_id, active })+ }+}++impl Drop for ActiveGenerateClaim {+ fn drop(&mut self) {+ self.active+ .lock()+ .expect("local-ingest active generation request ids mutex poisoned")+ .remove(&self.request_id);+ }+}++async fn acquire_connection_operation(+ operation_budget: &Arc<Semaphore>,+ lifecycle: &ConnectionLifecycle,+ shutdown: &Shutdown,+) -> Option<OwnedSemaphorePermit> {+ tokio::select! {+ biased;+ _ = shutdown.wait() => None,+ _ = lifecycle.wait_closed() => None,+ permit = Arc::clone(operation_budget).acquire_owned() => permit.ok(),+ }+}++enum DecodedOperationAdmission {+ Admitted(OwnedSemaphorePermit),+ DataCapacityExhausted,+ Closed,+}++async fn admit_decoded_operation(+ op: &str,+ data_budget: &Arc<Semaphore>,+ control_budget: &Arc<Semaphore>,+ lifecycle: &ConnectionLifecycle,+ shutdown: &Shutdown,+) -> DecodedOperationAdmission {+ if op == OP_CANCEL {+ return match acquire_connection_operation(control_budget, lifecycle, shutdown).await {+ Some(permit) => DecodedOperationAdmission::Admitted(permit),+ None => DecodedOperationAdmission::Closed,+ };+ }+ match Arc::clone(data_budget).try_acquire_owned() {+ Ok(permit) => DecodedOperationAdmission::Admitted(permit),+ Err(tokio::sync::TryAcquireError::NoPermits) => {+ DecodedOperationAdmission::DataCapacityExhausted+ }+ Err(tokio::sync::TryAcquireError::Closed) => DecodedOperationAdmission::Closed,+ }+}++async fn run_connection_writer(+ mut write_half: tokio::net::unix::OwnedWriteHalf,+ mut rx: mpsc::Receiver<QueuedWrite>,+ lifecycle: Arc<ConnectionLifecycle>,+) {+ loop {+ let command = tokio::select! {+ biased;+ _ = lifecycle.wait_closed() => break,+ command = rx.recv() => match command {+ Some(command) => command,+ None => break,+ },+ };+ if command.cancelled.load(Ordering::Acquire)+ || command+ .accepting+ .as_ref()+ .is_some_and(|accepting| !accepting.load(Ordering::Acquire))+ {+ let _ = command.done.send(Ok(()));+ continue;+ }+ let result =+ tokio::time::timeout_at(command.deadline, write_half.write_all(&command.frame))+ .await+ .map_err(|_| "local-ingest response write timed out".to_string())+ .and_then(|result| result.map_err(|error| error.to_string()));+ match result {+ Ok(()) => {+ let _ = command.done.send(Ok(()));+ }+ Err(error) => {+ let _ = command.done.send(Err(error.clone()));+ lifecycle.close();+ break;+ }+ }+ }+ lifecycle.close();+}++#[derive(Clone)]+struct GenerateStreamWriter {+ operation_id: u64,+ writer: ConnectionWriter,+ accepting_chunks: Arc<AtomicBool>,+ terminal: Arc<AtomicBool>,+ chunks_sent: Arc<AtomicU64>,+}++impl GenerateStreamWriter {+ fn new(operation_id: u64, writer: ConnectionWriter) -> Self {+ Self {+ operation_id,+ writer,+ accepting_chunks: Arc::new(AtomicBool::new(true)),+ terminal: Arc::new(AtomicBool::new(false)),+ chunks_sent: Arc::new(AtomicU64::new(0)),+ }+ }++ fn stop_chunks(&self) {+ self.accepting_chunks.store(false, Ordering::Release);+ }++ async fn send_chunk(&self, payload: Vec<u8>) -> Result<(), String> {+ if self.terminal.load(Ordering::Acquire) {+ return Err("generation emitted a chunk after its transport terminal".to_string());+ }+ if !self.accepting_chunks.load(Ordering::Acquire) {+ return Ok(());+ }+ let seq = self.chunks_sent.load(Ordering::Acquire);+ let frame = encode_generate_chunk(self.operation_id, seq, payload)?;+ self.writer+ .send_if(frame, Some(Arc::clone(&self.accepting_chunks)))+ .await?;+ if self.accepting_chunks.load(Ordering::Acquire) {+ self.chunks_sent.fetch_add(1, Ordering::AcqRel);+ }+ Ok(())+ }++ async fn finish_success(&self) -> Result<(), String> {+ self.finish(encode_generate_final(+ self.operation_id,+ self.chunks_sent.load(Ordering::Acquire),+ ))+ .await+ }++ async fn finish_error(+ &self,+ error: &crate::dispatcher::GenerateDispatchError,+ ) -> Result<(), String> {+ self.finish(encode_generate_error(self.operation_id, error))+ .await+ }++ async fn finish(&self, frame: Vec<u8>) -> Result<(), String> {+ if self.terminal.swap(true, Ordering::AcqRel) {+ return Err("generation transport terminal already emitted".to_string());+ }+ self.stop_chunks();+ self.writer.send(frame).await+ }+}+async fn handle_connection(stream: UnixStream, shared: Arc<IngestShared>) {- let (mut reader, writer) = stream.into_split();- let writer = Arc::new(Mutex::new(writer));+ let (mut reader, write_half) = stream.into_split();+ let lifecycle = Arc::new(ConnectionLifecycle::default());+ let writer = ConnectionWriter::spawn(write_half, Arc::clone(&lifecycle));+ let active_generate = Arc::new(Mutex::new(HashSet::<String>::new()));+ let decode_budget = Arc::new(Semaphore::new(MAX_DECODING_FRAMES_PER_CONNECTION));+ let data_operation_budget =+ Arc::new(Semaphore::new(MAX_INFLIGHT_DATA_OPERATIONS_PER_CONNECTION));+ let control_operation_budget = Arc::new(Semaphore::new(+ MAX_INFLIGHT_CONTROL_OPERATIONS_PER_CONNECTION,+ ));+ let request_byte_budget = Arc::new(Semaphore::new(MAX_BUFFERED_REQUEST_BYTES_PER_CONNECTION));+ let data_request_byte_budget =+ Arc::new(Semaphore::new(MAX_INFLIGHT_REQUEST_BYTES_PER_CONNECTION));+ let active_operation_ids = Arc::new(StdMutex::new(HashSet::<u64>::new()));loop {- let payload = tokio::select! {+ let Some(decode_permit) =+ acquire_connection_operation(&decode_budget, &lifecycle, &shared.shutdown).await+ else {+ break;+ };++ let (payload, inbound_permit) = tokio::select! {biased;_ = shared.shutdown.wait() => break,- frame = read_frame(&mut reader) => match frame {+ _ = lifecycle.wait_closed() => break,+ frame = read_frame_with_budget(&mut reader, &request_byte_budget) => match frame {Ok(Some(p)) => p,Ok(None) => break, // clean EOFErr(e) => {@@ -350,24 +771,263 @@ async fn handle_connection(stream: UnixStream, shared: Arc<IngestShared>) {break;}};+ let request_bytes = u32::try_from(payload.len()).expect("local-ingest frame length is u32");+ drop(payload);+ let Some(operation_id_guard) =+ ActiveOperationIdGuard::claim(request.id, Arc::clone(&active_operation_ids))+ else {+ warn!(+ id = request.id,+ "local-ingest: duplicate active envelope id; closing connection"+ );+ break;+ };+ let operation_permit = match admit_decoded_operation(+ &request.op,+ &data_operation_budget,+ &control_operation_budget,+ &lifecycle,+ &shared.shutdown,+ )+ .await+ {+ DecodedOperationAdmission::Admitted(permit) => permit,+ DecodedOperationAdmission::DataCapacityExhausted => {+ drop(decode_permit);+ let message = format!(+ "connection already has {MAX_INFLIGHT_DATA_OPERATIONS_PER_CONNECTION} active data operations"+ );+ let frame = if request.op == OP_PUBLISH_GENERATE_STREAM {+ encode_generate_error(+ request.id,+ &crate::dispatcher::GenerateDispatchError {+ code: "CAPACITY_EXHAUSTED".to_string(),+ message,+ },+ )+ } else {+ encode_response(+ request.id,+ false,+ Some(&format!("CapacityExhausted: {message}")),+ empty_body(),+ )+ };+ write_response(&writer, frame).await;+ continue;+ }+ DecodedOperationAdmission::Closed => break,+ };+ drop(decode_permit);+ let retained_data_permit = if request.op == OP_CANCEL {+ None+ } else {+ match Arc::clone(&data_request_byte_budget).try_acquire_many_owned(request_bytes) {+ Ok(permit) => Some(permit),+ Err(tokio::sync::TryAcquireError::NoPermits) => {+ let message = format!(+ "connection already retains {MAX_INFLIGHT_REQUEST_BYTES_PER_CONNECTION} request bytes"+ );+ let frame = if request.op == OP_PUBLISH_GENERATE_STREAM {+ encode_generate_error(+ request.id,+ &crate::dispatcher::GenerateDispatchError {+ code: "CAPACITY_EXHAUSTED".to_string(),+ message,+ },+ )+ } else {+ encode_response(+ request.id,+ false,+ Some(&format!("CapacityExhausted: {message}")),+ empty_body(),+ )+ };+ write_response(&writer, frame).await;+ continue;+ }+ Err(tokio::sync::TryAcquireError::Closed) => break,+ }+ };+ if request.op == OP_PUBLISH_GENERATE_STREAM {+ let request_id = request.body.request_id.clone();+ let mut active = active_generate.lock().await;+ let claim = if !valid_request_id(&request_id) {+ Err((+ "INVALID_TRANSPORT_BINDING",+ "invalid generation request_id".to_string(),+ ))+ } else if active.contains(&request_id) {+ Err((+ "DUPLICATE_REQUEST",+ format!("generation request {request_id:?} is already active"),+ ))+ } else if active.len() >= MAX_GENERATE_STREAMS_PER_CONNECTION {+ Err((+ "CAPACITY_EXHAUSTED",+ format!(+ "connection already has {MAX_GENERATE_STREAMS_PER_CONNECTION} active generation streams"+ ),+ ))+ } else {+ match ActiveGenerateClaim::claim(+ request_id.clone(),+ Arc::clone(&shared.active_generate_request_ids),+ ) {+ Some(claim) => {+ active.insert(request_id.clone());+ Ok(claim)+ }+ None => Err((+ "DUPLICATE_REQUEST",+ format!("generation request {request_id:?} is already active"),+ )),+ }+ };+ drop(active);+ let generate_claim = match claim {+ Ok(claim) => claim,+ Err((code, message)) => {+ let error = crate::dispatcher::GenerateDispatchError {+ code: code.to_string(),+ message,+ };+ let frame = encode_generate_error(request.id, &error);+ write_response(&writer, frame).await;+ continue;+ }+ };++ let shared_op = Arc::clone(&shared);+ let writer_op = writer.clone();+ let lifecycle_op = Arc::clone(&lifecycle);+ let active_op = Arc::clone(&active_generate);+ tokio::spawn(async move {+ let _operation_permit = operation_permit;+ let _retained_data_permit = retained_data_permit;+ let _inbound_permit = inbound_permit;+ let _operation_id_guard = operation_id_guard;+ let _generate_claim = generate_claim;+ let operation_id = request.id;+ let stream_writer = GenerateStreamWriter::new(operation_id, writer_op);+ let result = publish_generate_stream(+ request.body,+ &shared_op,+ stream_writer.clone(),+ Arc::clone(&lifecycle_op),+ )+ .await;+ active_op.lock().await.remove(&request_id);+ if !lifecycle_op.is_closed() {+ let write_result = match result {+ Ok(()) => stream_writer.finish_success().await,+ Err(error) => stream_writer.finish_error(&error).await,+ };+ if let Err(error) = write_result {+ debug!(+ request_id,+ error, "local-ingest: generation terminal write failed"+ );+ }+ }+ });+ continue;+ }+ if request.op == OP_CANCEL {+ let shared_op = Arc::clone(&shared);+ let writer_op = writer.clone();+ let active_op = Arc::clone(&active_generate);+ tokio::spawn(async move {+ let _operation_permit = operation_permit;+ let _retained_data_permit = retained_data_permit;+ let _inbound_permit = inbound_permit;+ let _operation_id_guard = operation_id_guard;+ let request_id = request.body.request_id;+ let response = if !valid_request_id(&request_id) {+ encode_response(+ request.id,+ false,+ Some("InvalidTransportBinding: invalid request_id"),+ empty_body(),+ )+ } else {+ let owns_request = active_op.lock().await.contains(&request_id);+ if !owns_request {+ encode_response(request.id, true, None, empty_body())+ } else {+ match tokio::time::timeout(+ LOCAL_GENERATE_CANCEL_DRAIN_TIMEOUT,+ shared_op+ .dispatcher+ .signal_local_generate_cancel(&request_id),+ )+ .await+ {+ Ok(Ok(_)) => encode_response(request.id, true, None, empty_body()),+ Ok(Err(error)) => encode_response(+ request.id,+ false,+ Some(&error.to_string()),+ empty_body(),+ ),+ Err(_) => encode_response(+ request.id,+ false,+ Some("TimeoutError: cancellation RPC timed out"),+ empty_body(),+ ),+ }+ }+ };+ write_response(&writer_op, response).await;+ });+ continue;+ }// Each op runs as its own task; responses may interleave and are// correlated by `id` (same shape as the Python dispatcher server).let shared_op = Arc::clone(&shared);- let writer_op = Arc::clone(&writer);+ let writer_op = writer.clone();tokio::spawn(async move {+ let _operation_permit = operation_permit;+ let _retained_data_permit = retained_data_permit;+ let _inbound_permit = inbound_permit;+ let _operation_id_guard = operation_id_guard;let frame = run_op(request, &shared_op).await;- let mut w = writer_op.lock().await;- if let Err(e) = w.write_all(&frame).await {- debug!(error = %e, "local-ingest: response write failed (caller gone)");- }+ write_response(&writer_op, frame).await;});}++ lifecycle.close();+ let request_ids: Vec<String> = active_generate.lock().await.drain().collect();+ for request_id in request_ids {+ match tokio::time::timeout(+ LOCAL_GENERATE_CANCEL_DRAIN_TIMEOUT,+ shared.dispatcher.signal_local_generate_cancel(&request_id),+ )+ .await+ {+ Ok(Ok(_)) => {}+ Ok(Err(error)) => {+ debug!(+ request_id,+ error = %error,+ "local-ingest: disconnect cancellation failed"+ );+ }+ Err(_) => {+ debug!(+ request_id,+ "local-ingest: disconnect cancellation timed out"+ );+ }+ }+ }}async fn run_op(request: RequestEnvelope, shared: &IngestShared) -> Vec<u8> {match request.op.as_str() {OP_PING => encode_response(request.id, true, None, empty_body()),- OP_CANCEL => encode_response(request.id, true, None, empty_body()),OP_PUBLISH_WORK => match publish_work(request.body, shared).await {Ok(results_bytes) => {encode_response(request.id, true, None, results_body(results_bytes))@@ -383,6 +1043,190 @@ async fn run_op(request: RequestEnvelope, shared: &IngestShared) -> Vec<u8> {}}+fn valid_request_id(request_id: &str) -> bool {+ !request_id.is_empty()+ && request_id.len() <= MAX_REQUEST_ID_BYTES+ && !request_id.chars().any(char::is_whitespace)+}++async fn write_response(writer: &ConnectionWriter, frame: Vec<u8>) {+ if let Err(error) = writer.send(frame).await {+ debug!(error = %error, "local-ingest: response write failed (caller gone)");+ }+}++fn generate_chunk_body(seq: u64, payload: Vec<u8>) -> rmpv::Value {+ rmpv::Value::Map(vec![+ (rmpv::Value::from("chunk"), rmpv::Value::Binary(payload)),+ (rmpv::Value::from("seq"), rmpv::Value::from(seq)),+ ])+}++fn encode_generate_chunk_with_limit(+ id: u64,+ seq: u64,+ payload: Vec<u8>,+ max_frame_bytes: usize,+) -> Result<Vec<u8>, String> {+ let payload = encode_response_payload(id, true, None, generate_chunk_body(seq, payload));+ if payload.len() > max_frame_bytes {+ return Err(format!(+ "ResultTooLarge: generation chunk response frame is {} bytes; maximum is {max_frame_bytes}",+ payload.len()+ ));+ }+ Ok(frame_payload(payload))+}++fn encode_generate_chunk(id: u64, seq: u64, payload: Vec<u8>) -> Result<Vec<u8>, String> {+ encode_generate_chunk_with_limit(id, seq, payload, MAX_LOCAL_INGEST_FRAME_BYTES)+}++fn encode_generate_final(id: u64, chunks: u64) -> Vec<u8> {+ let outcome = rmpv::Value::Map(vec![+ (rmpv::Value::from("status"), rmpv::Value::from("complete")),+ (rmpv::Value::from("chunks"), rmpv::Value::from(chunks)),+ ]);+ let body = rmpv::Value::Map(vec![+ (rmpv::Value::from("final"), rmpv::Value::from(true)),+ (rmpv::Value::from("outcome"), outcome),+ ]);+ encode_response(id, true, None, body)+}++fn encode_generate_error(id: u64, error: &crate::dispatcher::GenerateDispatchError) -> Vec<u8> {+ let rendered = format!("{}: {}", error.code, error.message);+ encode_response(id, false, Some(&rendered), empty_body())+}++async fn publish_generate_stream(+ body: RequestBody,+ shared: &IngestShared,+ stream_writer: GenerateStreamWriter,+ lifecycle: Arc<ConnectionLifecycle>,+) -> Result<(), crate::dispatcher::GenerateDispatchError> {+ let semantic_deadline = generate_timeout_deadline(body.timeout_ms).map_err(|message| {+ crate::dispatcher::GenerateDispatchError {+ code: "INVALID_TRANSPORT_BINDING".to_string(),+ message,+ }+ })?;+ let timeout_ms = (body.timeout_ms > 0).then_some(body.timeout_ms as u64);+ validate_payload_digest(&body).map_err(|message| crate::dispatcher::GenerateDispatchError {+ code: "INVALID_TRANSPORT_BINDING".to_string(),+ message,+ })?;+ let mut items: Vec<WorkItem> = rmp_serde::from_slice(&body.items).map_err(|error| {+ crate::dispatcher::GenerateDispatchError {+ code: "DECODE_ERROR".to_string(),+ message: format!("items is not a msgpack WorkItem array: {error}"),+ }+ })?;+ validate_work_items_with_limit(&body, &items, 1).map_err(|message| {+ crate::dispatcher::GenerateDispatchError {+ code: "INVALID_TRANSPORT_BINDING".to_string(),+ message,+ }+ })?;+ if body.endpoint != "generate" {+ return Err(crate::dispatcher::GenerateDispatchError {+ code: "BAD_OPERATION".to_string(),+ message: "publish_generate_stream requires endpoint generate".to_string(),+ });+ }+ let mut work_item = items.pop().expect("validated exactly one generate item");+ let meta_pool = normalize_pool(&body.admission_pool);+ let item_pool = normalize_pool(&work_item.admission_pool);+ if let Some(message) = admission_error(&shared.lane_pool, &meta_pool, &item_pool) {+ return Err(crate::dispatcher::GenerateDispatchError {+ code: "POOL_ADMISSION_REJECTED".to_string(),+ message,+ });+ }+ if lifecycle.is_closed() {+ return Err(crate::dispatcher::GenerateDispatchError {+ code: "DISCONNECTED".to_string(),+ message: "local-ingest caller disconnected before generation dispatch".to_string(),+ });+ }+ work_item.reply_subject = format!("_LOCAL.{}", work_item.request_id);+ let request_id = body.request_id;+ let callback_writer = stream_writer.clone();+ let generation = shared+ .dispatcher+ .process_local_generate(work_item, move |payload| {+ let writer = callback_writer.clone();+ async move { writer.send_chunk(payload).await }+ });+ tokio::pin!(generation);+ let semantic_timeout = async move {+ match semantic_deadline {+ Some(deadline) => tokio::time::sleep_until(deadline).await,+ None => std::future::pending::<()>().await,+ }+ };+ tokio::pin!(semantic_timeout);++ enum WaitOutcome {+ Complete(Result<(), crate::dispatcher::GenerateDispatchError>),+ Timeout(u64),+ Disconnected,+ }++ let outcome = tokio::select! {+ biased;+ _ = lifecycle.wait_closed() => WaitOutcome::Disconnected,+ result = &mut generation => WaitOutcome::Complete(result),+ _ = &mut semantic_timeout => WaitOutcome::Timeout(+ timeout_ms.expect("semantic timeout future only settles for a positive timeout")+ ),+ };+ let (code, message) = match outcome {+ WaitOutcome::Complete(result) => return result,+ WaitOutcome::Timeout(timeout_ms) => (+ "TIMEOUT",+ format!("generation timed out after {timeout_ms}ms"),+ ),+ WaitOutcome::Disconnected => (+ "DISCONNECTED",+ "local-ingest caller disconnected during generation".to_string(),+ ),+ };++ stream_writer.stop_chunks();+ let cancel_deadline = tokio::time::Instant::now() + LOCAL_GENERATE_CANCEL_DRAIN_TIMEOUT;+ let cancel_error = match tokio::time::timeout_at(+ cancel_deadline,+ shared.dispatcher.signal_local_generate_cancel(&request_id),+ )+ .await+ {+ Ok(Ok(_)) => None,+ Ok(Err(error)) => Some(error.to_string()),+ Err(_) => Some("cancellation RPC timed out".to_string()),+ };+ let drain_deadline = tokio::time::Instant::now() + LOCAL_GENERATE_CANCEL_DRAIN_TIMEOUT;+ let drain_timed_out = tokio::time::timeout_at(drain_deadline, &mut generation)+ .await+ .is_err();+ let mut suffixes = Vec::new();+ if let Some(error) = cancel_error {+ suffixes.push(format!("cancellation failed: {error}"));+ }+ if drain_timed_out {+ suffixes.push("backend cancellation drain timed out".to_string());+ }+ let suffix = if suffixes.is_empty() {+ String::new()+ } else {+ format!("; {}", suffixes.join("; "))+ };+ Err(crate::dispatcher::GenerateDispatchError {+ code: code.to_string(),+ message: format!("{message}{suffix}"),+ })+}+// ---------------------------------------------------------------------------// publish_work// ---------------------------------------------------------------------------@@ -429,7 +1273,7 @@ fn validate_payload_digest(body: &RequestBody) -> Result<(), String> {Ok(())}-fn validate_publish_timeout(timeout_ms: i64) -> Result<(), String> {+fn validate_publish_work_timeout(timeout_ms: i64) -> Result<(), String> {if !(0..=MAX_PUBLISH_WORK_TIMEOUT_MS).contains(&timeout_ms) {return Err(format!("InvalidTransportBinding: timeout_ms {timeout_ms} must be between 0 and {MAX_PUBLISH_WORK_TIMEOUT_MS}"@@ -438,6 +1282,25 @@ fn validate_publish_timeout(timeout_ms: i64) -> Result<(), String> {Ok(())}+fn generate_timeout_deadline(timeout_ms: i64) -> Result<Option<tokio::time::Instant>, String> {+ if timeout_ms < 0 {+ return Err(format!(+ "InvalidTransportBinding: generation timeout_ms {timeout_ms} must be non-negative"+ ));+ }+ if timeout_ms == 0 {+ return Ok(None);+ }+ tokio::time::Instant::now()+ .checked_add(Duration::from_millis(timeout_ms as u64))+ .map(Some)+ .ok_or_else(|| {+ format!(+ "InvalidTransportBinding: generation timeout_ms {timeout_ms} is not representable"+ )+ })+}+#[derive(Clone, Copy)]enum MediaKind {ImageOrDocument,@@ -654,7 +1517,7 @@ fn error_result(wi: &WorkItem, worker_id: &str, code: &str, message: &str) -> Wo}async fn publish_work(body: RequestBody, shared: &IngestShared) -> Result<Vec<u8>, String> {- validate_publish_timeout(body.timeout_ms)?;+ validate_publish_work_timeout(body.timeout_ms)?;validate_payload_digest(&body)?;let items: Vec<WorkItem> = rmp_serde::from_slice(&body.items).map_err(|e| format!("DecodeError: items is not a msgpack WorkItem array: {e}"))?;@@ -934,18 +1797,25 @@ mod tests {}#[test]- fn publish_timeout_is_bounded() {- assert_eq!(validate_publish_timeout(0), Ok(()));+ fn unary_timeout_is_bounded_but_generation_zero_is_unlimited() {+ assert_eq!(validate_publish_work_timeout(0), Ok(()));assert_eq!(- validate_publish_timeout(MAX_PUBLISH_WORK_TIMEOUT_MS),+ validate_publish_work_timeout(MAX_PUBLISH_WORK_TIMEOUT_MS),Ok(()));- assert!(validate_publish_timeout(MAX_PUBLISH_WORK_TIMEOUT_MS + 1)- .unwrap_err()- .contains("must be between"));- assert!(validate_publish_timeout(-1).is_err());- assert!(validate_publish_timeout(i64::MIN).is_err());- assert!(validate_publish_timeout(i64::MAX).is_err());+ assert!(+ validate_publish_work_timeout(MAX_PUBLISH_WORK_TIMEOUT_MS + 1)+ .unwrap_err()+ .contains("must be between")+ );+ assert!(validate_publish_work_timeout(-1).is_err());+ assert!(validate_publish_work_timeout(i64::MIN).is_err());+ assert!(validate_publish_work_timeout(i64::MAX).is_err());++ assert!(generate_timeout_deadline(0).unwrap().is_none());+ assert!(generate_timeout_deadline(600_001).unwrap().is_some());+ assert!(generate_timeout_deadline(i64::MAX).unwrap().is_some());+ assert!(generate_timeout_deadline(-1).is_err());}#[test]@@ -1004,6 +1874,237 @@ mod tests {);}+ fn response_field<'a>(value: &'a rmpv::Value, key: &str) -> &'a rmpv::Value {+ let rmpv::Value::Map(fields) = value else {+ panic!("response map")+ };+ fields+ .iter()+ .find(|(field, _)| field.as_str() == Some(key))+ .map(|(_, value)| value)+ .expect("response field")+ }++ #[test]+ fn generation_frames_match_canonical_v02_contract() {+ let frame = encode_generate_chunk(17, 3, b"chunk".to_vec()).unwrap();+ let response: rmpv::Value = rmp_serde::from_slice(&frame[4..]).unwrap();+ assert_eq!(response_field(&response, "id").as_u64(), Some(17));+ assert_eq!(response_field(&response, "ok").as_bool(), Some(true));+ let body = response_field(&response, "body");+ assert_eq!(response_field(body, "seq").as_u64(), Some(3));+ assert_eq!(+ response_field(body, "chunk"),+ &rmpv::Value::Binary(b"chunk".to_vec())+ );++ let error = crate::dispatcher::GenerateDispatchError {+ code: "INVALID_INPUT".to_string(),+ message: "bad image".to_string(),+ };+ let frame = encode_generate_error(18, &error);+ let response: rmpv::Value = rmp_serde::from_slice(&frame[4..]).unwrap();+ assert_eq!(response_field(&response, "id").as_u64(), Some(18));+ assert_eq!(response_field(&response, "ok").as_bool(), Some(false));+ assert_eq!(+ response_field(&response, "error").as_str(),+ Some("INVALID_INPUT: bad image")+ );+ let body = response_field(&response, "body");+ assert_eq!(body, &empty_body());++ let frame = encode_generate_final(19, 4);+ let response: rmpv::Value = rmp_serde::from_slice(&frame[4..]).unwrap();+ let body = response_field(&response, "body");+ assert_eq!(response_field(body, "final").as_bool(), Some(true));+ let outcome = response_field(body, "outcome");+ assert_eq!(response_field(outcome, "status").as_str(), Some("complete"));+ assert_eq!(response_field(outcome, "chunks").as_u64(), Some(4));+ }++ #[test]+ fn oversized_generation_chunk_is_rejected_before_any_terminal_is_encoded() {+ let error = encode_generate_chunk_with_limit(17, 0, vec![0; 1_024], 256).unwrap_err();+ assert!(error.contains("ResultTooLarge"));+ }++ #[tokio::test]+ async fn generation_terminal_is_last_and_tombstones_late_chunks() {+ let (server, mut client) = UnixStream::pair().unwrap();+ let (_, write_half) = server.into_split();+ let lifecycle = Arc::new(ConnectionLifecycle::default());+ let writer = ConnectionWriter::spawn(write_half, Arc::clone(&lifecycle));+ let stream = GenerateStreamWriter::new(23, writer);++ stream.send_chunk(b"one".to_vec()).await.unwrap();+ let chunk = read_frame(&mut client).await.unwrap().unwrap();+ let chunk: rmpv::Value = rmp_serde::from_slice(&chunk).unwrap();+ let body = response_field(&chunk, "body");+ assert_eq!(response_field(body, "seq").as_u64(), Some(0));++ stream.finish_success().await.unwrap();+ let terminal = read_frame(&mut client).await.unwrap().unwrap();+ let terminal: rmpv::Value = rmp_serde::from_slice(&terminal).unwrap();+ let body = response_field(&terminal, "body");+ assert_eq!(response_field(body, "final").as_bool(), Some(true));+ assert_eq!(+ response_field(response_field(body, "outcome"), "chunks").as_u64(),+ Some(1)+ );++ let error = stream.send_chunk(b"late".to_vec()).await.unwrap_err();+ assert!(error.contains("after its transport terminal"));+ assert!(stream.finish_success().await.is_err());+ lifecycle.close();+ }++ #[tokio::test]+ async fn connection_operation_budget_blocks_until_capacity_returns() {+ let budget = Arc::new(Semaphore::new(1));+ let lifecycle = ConnectionLifecycle::default();+ let shutdown = Shutdown::new();+ let held = acquire_connection_operation(&budget, &lifecycle, &shutdown)+ .await+ .expect("initial operation admitted");++ assert!(+ tokio::time::timeout(+ Duration::from_millis(10),+ acquire_connection_operation(&budget, &lifecycle, &shutdown),+ )+ .await+ .is_err(),+ "a saturated connection must stop admitting work"+ );++ drop(held);+ assert!(+ acquire_connection_operation(&budget, &lifecycle, &shutdown)+ .await+ .is_some(),+ "released capacity must admit the next operation"+ );+ }++ #[tokio::test]+ async fn reserved_cancel_admission_survives_saturated_data_capacity() {+ let data_budget = Arc::new(Semaphore::new(1));+ let control_budget = Arc::new(Semaphore::new(1));+ let lifecycle = ConnectionLifecycle::default();+ let shutdown = Shutdown::new();+ let _held_data = Arc::clone(&data_budget)+ .acquire_owned()+ .await+ .expect("initial data operation admitted");++ assert!(matches!(+ admit_decoded_operation(+ OP_PUBLISH_WORK,+ &data_budget,+ &control_budget,+ &lifecycle,+ &shutdown,+ )+ .await,+ DecodedOperationAdmission::DataCapacityExhausted+ ));+ assert!(matches!(+ admit_decoded_operation(+ OP_CANCEL,+ &data_budget,+ &control_budget,+ &lifecycle,+ &shutdown,+ )+ .await,+ DecodedOperationAdmission::Admitted(_)+ ));+ }++ #[tokio::test]+ async fn reserved_cancel_bytes_survive_saturated_data_bytes() {+ let cancel_payload = rmp_serde::to_vec_named(&RequestEnvelope {+ id: 2,+ op: OP_CANCEL.to_string(),+ body: RequestBody {+ request_id: "x".repeat(MAX_REQUEST_ID_BYTES),+ ..RequestBody::default()+ },+ })+ .unwrap();+ assert!(cancel_payload.len() <= MAX_RESERVED_CONTROL_REQUEST_BYTES_PER_CONNECTION);++ let buffered = Arc::new(Semaphore::new(MAX_BUFFERED_REQUEST_BYTES_PER_CONNECTION));+ let retained_data = Arc::new(Semaphore::new(MAX_INFLIGHT_REQUEST_BYTES_PER_CONNECTION));+ let _buffered_data = Arc::clone(&buffered)+ .acquire_many_owned(MAX_INFLIGHT_REQUEST_BYTES_PER_CONNECTION as u32)+ .await+ .unwrap();+ let _retained_data = Arc::clone(&retained_data)+ .acquire_many_owned(MAX_INFLIGHT_REQUEST_BYTES_PER_CONNECTION as u32)+ .await+ .unwrap();++ assert!(retained_data.try_acquire().is_err());+ assert!(+ buffered+ .try_acquire_many(cancel_payload.len() as u32)+ .is_ok(),+ "a valid cancel frame must fit after the data byte budget is saturated"+ );+ }++ #[tokio::test]+ async fn retained_request_byte_budget_blocks_a_second_max_sized_frame() {+ let (mut writer, mut reader) = tokio::io::duplex(32);+ let frame = [4u32.to_le_bytes().as_slice(), b"full"].concat();+ writer.write_all(&frame).await.unwrap();+ writer.write_all(&frame).await.unwrap();++ let budget = Arc::new(Semaphore::new(4));+ let (first, first_permit) = read_frame_with_budget(&mut reader, &budget)+ .await+ .unwrap()+ .expect("first frame");+ assert_eq!(first, b"full");++ let second_budget = Arc::clone(&budget);+ let second =+ tokio::spawn(async move { read_frame_with_budget(&mut reader, &second_budget).await });+ tokio::task::yield_now().await;+ assert!(+ !second.is_finished(),+ "the next full-budget frame must wait without reading its body"+ );++ drop(first_permit);+ let (second, _second_permit) = tokio::time::timeout(Duration::from_millis(100), second)+ .await+ .expect("released byte capacity wakes the next frame")+ .unwrap()+ .unwrap()+ .expect("second frame");+ assert_eq!(second, b"full");+ }++ #[test]+ fn active_envelope_id_is_unique_until_its_terminal_guard_drops() {+ let active = Arc::new(StdMutex::new(HashSet::new()));+ let first = ActiveOperationIdGuard::claim(7, Arc::clone(&active)).expect("first claim");+ assert!(ActiveOperationIdGuard::claim(7, Arc::clone(&active)).is_none());++ drop(first);+ assert!(ActiveOperationIdGuard::claim(7, active).is_some());+ }++ #[test]+ fn generation_request_ids_are_bounded_and_token_safe() {+ assert!(valid_request_id("req-1"));+ assert!(!valid_request_id(""));+ assert!(!valid_request_id("req 1"));+ assert!(!valid_request_id(&"x".repeat(MAX_REQUEST_ID_BYTES + 1)));+ }+#[tokio::test]async fn oversized_declared_frame_is_rejected_before_body_allocation() {let (mut writer, mut reader) = tokio::io::duplex(4);diff --git a/packages/sie_server_sidecar/src/prep/media.rs b/packages/sie_server_sidecar/src/prep/media.rsindex b42be0cd8..df5ae9839 100644--- a/packages/sie_server_sidecar/src/prep/media.rs+++ b/packages/sie_server_sidecar/src/prep/media.rs@@ -6,6 +6,7 @@//! decode and document rendering remain adapter/engine-owned because the IPC//! contract has no reusable decoded-media representation.+use base64::Engine as _;use rmpv::Value;use thiserror::Error;@@ -58,6 +59,20 @@ pub enum MediaValidationError {"media payload is too large ({actual} bytes); maximum is {MAX_MEDIA_BYTES_PER_ITEM} bytes per item")]MediaTooLarge { actual: usize },+ #[error("generate must be a map")]+ GenerateNotMap,+ #[error("generate.messages must be an array")]+ GenerateMessagesNotArray,+ #[error("{path} must be a map")]+ GenerateObjectNotMap { path: String },+ #[error("{path} contains duplicate '{field}' fields")]+ DuplicateGenerateField { path: String, field: &'static str },+ #[error("{path} must be an array or null")]+ GenerateImagesNotArray { path: String },+ #[error("{path}.data must be non-empty bytes or a non-empty base64 string")]+ InvalidGenerateImageData { path: String },+ #[error("{path}.data is invalid base64: {message}")]+ InvalidGenerateImageBase64 { path: String, message: String },}/// Validate media carried by one native API item.@@ -97,6 +112,154 @@ pub fn validate_item_media(item: &Value) -> Result<(), MediaValidationError> {Ok(())}+/// Replace rolling-compatible generation image base64 strings with msgpack+/// binary after enforcing the public request's aggregate count and byte caps.+///+/// Compressed image decode and model-specific transforms remain adapter-owned.+pub fn normalize_generate_media(generate: &mut Value) -> Result<(), MediaValidationError> {+ let Value::Map(generate_fields) = generate else {+ return Err(MediaValidationError::GenerateNotMap);+ };+ let Some(messages) = unique_field_mut(generate_fields, "messages").map_err(|_| {+ MediaValidationError::DuplicateGenerateField {+ path: "generate".to_string(),+ field: "messages",+ }+ })?+ else {+ return Ok(());+ };+ let Value::Array(messages) = messages else {+ return Err(MediaValidationError::GenerateMessagesNotArray);+ };++ let mut image_count = 0usize;+ let mut total_bytes = 0usize;+ for (message_index, message) in messages.iter_mut().enumerate() {+ let message_path = format!("generate.messages[{message_index}]");+ let Value::Map(message_fields) = message else {+ return Err(MediaValidationError::GenerateObjectNotMap { path: message_path });+ };+ let Some(images) = unique_field_mut(message_fields, "images").map_err(|_| {+ MediaValidationError::DuplicateGenerateField {+ path: message_path.clone(),+ field: "images",+ }+ })?+ else {+ continue;+ };+ if matches!(images, Value::Nil) {+ continue;+ }+ let Value::Array(images) = images else {+ return Err(MediaValidationError::GenerateImagesNotArray { path: message_path });+ };++ image_count = image_count.saturating_add(images.len());+ if image_count > MAX_IMAGES_PER_ITEM {+ return Err(MediaValidationError::TooManyImages {+ actual: image_count,+ });+ }+ for (image_index, image) in images.iter_mut().enumerate() {+ let image_path = format!("{message_path}.images[{image_index}]");+ normalize_generate_image(image, &image_path, &mut total_bytes)?;+ }+ }+ Ok(())+}++fn normalize_generate_image(+ image: &mut Value,+ path: &str,+ total_bytes: &mut usize,+) -> Result<(), MediaValidationError> {+ let Value::Map(fields) = image else {+ return Err(MediaValidationError::GenerateObjectNotMap {+ path: path.to_string(),+ });+ };+ let format = unique_field(fields, "format").map_err(|_| {+ MediaValidationError::DuplicateGenerateField {+ path: path.to_string(),+ field: "format",+ }+ })?;+ if let Some(format) = format {+ if !matches!(format, Value::String(_) | Value::Nil) {+ return Err(MediaValidationError::InvalidMediaFormat {+ path: path.to_string(),+ });+ }+ }+ let data = unique_field_mut(fields, "data").map_err(|_| {+ MediaValidationError::DuplicateGenerateField {+ path: path.to_string(),+ field: "data",+ }+ })?;+ let Some(data) = data else {+ return Err(MediaValidationError::InvalidGenerateImageData {+ path: path.to_string(),+ });+ };++ let decoded = match data {+ Value::Binary(bytes) if !bytes.is_empty() => None,+ Value::String(encoded) => {+ let Some(encoded) = encoded.as_str() else {+ return Err(MediaValidationError::InvalidGenerateImageData {+ path: path.to_string(),+ });+ };+ let encoded = encoded.trim();+ if encoded.is_empty() {+ return Err(MediaValidationError::InvalidGenerateImageData {+ path: path.to_string(),+ });+ }+ let decoded_upper_bound = encoded.len().saturating_mul(3) / 4;+ if decoded_upper_bound > MAX_MEDIA_BYTES_PER_ITEM {+ return Err(MediaValidationError::MediaTooLarge {+ actual: decoded_upper_bound,+ });+ }+ Some(+ base64::engine::general_purpose::STANDARD+ .decode(encoded)+ .map_err(|error| MediaValidationError::InvalidGenerateImageBase64 {+ path: path.to_string(),+ message: error.to_string(),+ })?,+ )+ }+ _ => {+ return Err(MediaValidationError::InvalidGenerateImageData {+ path: path.to_string(),+ });+ }+ };+ if let Some(decoded) = decoded {+ if decoded.is_empty() {+ return Err(MediaValidationError::InvalidGenerateImageData {+ path: path.to_string(),+ });+ }+ *data = Value::Binary(decoded);+ }+ let Value::Binary(bytes) = data else {+ unreachable!("generation image normalized to msgpack binary");+ };+ *total_bytes = total_bytes.saturating_add(bytes.len());+ if *total_bytes > MAX_MEDIA_BYTES_PER_ITEM {+ return Err(MediaValidationError::MediaTooLarge {+ actual: *total_bytes,+ });+ }+ Ok(())+}+fn validate_media_object(value: &Value,path: &str,@@ -159,6 +322,22 @@ fn unique_field<'a>(fields: &'a [(Value, Value)], expected: &str) -> Result<OptiOk(found)}+fn unique_field_mut<'a>(+ fields: &'a mut [(Value, Value)],+ expected: &str,+) -> Result<Option<&'a mut Value>, ()> {+ let mut found = None;+ for (index, (key, _)) in fields.iter().enumerate() {+ if key_as_str(key) != Some(expected) {+ continue;+ }+ if found.replace(index).is_some() {+ return Err(());+ }+ }+ Ok(found.map(|index| &mut fields[index].1))+}+fn key_as_str(value: &Value) -> Option<&str> {match value {Value::String(value) => value.as_str(),@@ -189,6 +368,16 @@ mod tests {Value::Map(fields)}+ fn generate_with_images(images: Vec<Value>) -> Value {+ Value::Map(vec![(+ Value::from("messages"),+ Value::Array(vec![Value::Map(vec![(+ Value::from("images"),+ Value::Array(images),+ )])]),+ )])+ }+#[test]fn accepts_binary_images_and_document_without_mutation() {let value = item(@@ -277,6 +466,74 @@ mod tests {);}+ #[test]+ fn generation_base64_is_normalized_to_binary() {+ let mut generate =+ generate_with_images(vec![media(Value::from("aGVsbG8="), Value::from("png"))]);+ normalize_generate_media(&mut generate).unwrap();+ let Value::Map(root) = generate else {+ panic!("generate map")+ };+ let Value::Array(messages) = unique_field(&root, "messages").unwrap().unwrap() else {+ panic!("messages")+ };+ let Value::Map(message) = &messages[0] else {+ panic!("message")+ };+ let Value::Array(images) = unique_field(message, "images").unwrap().unwrap() else {+ panic!("images")+ };+ let Value::Map(image) = &images[0] else {+ panic!("image")+ };+ assert_eq!(+ unique_field(image, "data").unwrap(),+ Some(&Value::Binary(b"hello".to_vec()))+ );+ }++ #[test]+ fn generation_prepared_binary_is_rolling_compatible() {+ let mut generate = generate_with_images(vec![media(+ Value::Binary(b"already prepared".to_vec()),+ Value::Nil,+ )]);+ let before = generate.clone();+ normalize_generate_media(&mut generate).unwrap();+ assert_eq!(generate, before);+ }++ #[test]+ fn generation_media_rejects_invalid_empty_duplicate_and_excess_count() {+ for invalid in [+ Value::from("!!!"),+ Value::from(""),+ Value::Binary(Vec::new()),+ ] {+ let mut generate = generate_with_images(vec![media(invalid, Value::from("png"))]);+ assert!(normalize_generate_media(&mut generate).is_err());+ }++ let mut duplicate = generate_with_images(vec![Value::Map(vec![+ (Value::from("data"), Value::from("YQ==")),+ (Value::from("data"), Value::from("Yg==")),+ ])]);+ assert!(matches!(+ normalize_generate_media(&mut duplicate),+ Err(MediaValidationError::DuplicateGenerateField { .. })+ ));++ let mut too_many = generate_with_images(+ (0..=MAX_IMAGES_PER_ITEM)+ .map(|_| media(Value::Binary(vec![1]), Value::Nil))+ .collect(),+ );+ assert!(matches!(+ normalize_generate_media(&mut too_many),+ Err(MediaValidationError::TooManyImages { .. })+ ));+ }+#[test]fn rejects_image_count_above_existing_limit() {let images = (0..=MAX_IMAGES_PER_ITEM)diff --git a/packages/sie_server_sidecar/src/work_types.rs b/packages/sie_server_sidecar/src/work_types.rsindex 8c83a0a79..76eb46065 100644--- a/packages/sie_server_sidecar/src/work_types.rs+++ b/packages/sie_server_sidecar/src/work_types.rs@@ -61,7 +61,11 @@ pub struct WorkItem {#[serde(default)]pub output_schema: Option<serde_json::Value>,#[serde(default)]- pub generate: Option<serde_json::Value>,+ /// Generation parameters use the same msgpack-native value as media+ /// items. Legacy producers still serialize ordinary JSON maps, while+ /// sidecar-prepared vision requests can carry image data as msgpack+ /// binary without a second base64 allocation in Python.+ pub generate: Option<WireValue>,#[serde(default)]pub routing_key: Option<String>,#[serde(default)]diff --git a/packages/sie_server_sidecar/tests/integration_smoke.rs b/packages/sie_server_sidecar/tests/integration_smoke.rsindex c29e92183..64285ae98 100644--- a/packages/sie_server_sidecar/tests/integration_smoke.rs+++ b/packages/sie_server_sidecar/tests/integration_smoke.rs@@ -1102,12 +1102,12 @@ async fn work_cancel_is_namespaced_acks_before_ipc_and_excludes_generation() {score_items: None,labels: None,output_schema: None,- generate: Some(serde_json::json!({+ generate: Some(msg_value(serde_json::json!({"prompt": "generation is not request-cancelled","max_new_tokens": 4,"temperature": 0.0,"top_p": 1.0,- })),+ }))),routing_key: None,prompt_cache_key: None,bundle_config_hash: String::new(),@@ -1207,12 +1207,12 @@ async fn smoke_generate_direct_dispatch_round_trips_through_rust_worker() {score_items: None,labels: None,output_schema: None,- generate: Some(serde_json::json!({+ generate: Some(msg_value(serde_json::json!({"prompt": "hello","max_new_tokens": 4,"temperature": 0.0,"top_p": 1.0,- })),+ }))),routing_key: None,prompt_cache_key: None,bundle_config_hash: String::new(),@@ -1323,12 +1323,12 @@ async fn smoke_generation_direct_dispatch_is_active_before_capability_reconcile(score_items: None,labels: None,output_schema: None,- generate: Some(serde_json::json!({+ generate: Some(msg_value(serde_json::json!({"prompt": "hello after config","max_new_tokens": 4,"temperature": 0.0,"top_p": 1.0,- })),+ }))),routing_key: None,prompt_cache_key: None,bundle_config_hash: String::new(),diff --git a/packages/sie_server_sidecar/tests/local_ingest_loopback.rs b/packages/sie_server_sidecar/tests/local_ingest_loopback.rsindex 21b298122..9a1f3f727 100644--- a/packages/sie_server_sidecar/tests/local_ingest_loopback.rs+++ b/packages/sie_server_sidecar/tests/local_ingest_loopback.rs@@ -3,7 +3,7 @@//! What this proves://! * `sie-server-sidecar --ingest local` starts with **no NATS server**//! anywhere (the mode's whole point).-//! * The UDS listener speaks the wire protocol v0.1: u32-LE frame + msgpack+//! * The UDS listener speaks the wire protocol v0.2: u32-LE frame + msgpack//! `{id, op, body}` envelopes; `ping`, `publish_work`, unknown-op//! error envelope.//! * `publish_work` WorkItem bytes flow through the real dispatcher →@@ -141,6 +141,8 @@ impl PythonHarness {socket_path.to_str().unwrap(),"--worker-id","loopback-harness",+ "--fake-generate-model",+ "BAAI/bge-m3","--log-level","INFO",])@@ -499,7 +501,7 @@ async fn local_ingest_round_trips_publish_work_without_nats() {assert_eq!(r.error_code.as_deref(), Some("pool_admission_rejected"));}- // 4. generate op -> typed bad_operation error (streaming lands later).+ // 4. The legacy one-shot op still rejects generate instead of hanging.let gen = vec![work_item("li-req-3", 0, 1, "generate", "default")];send_request(&mut stream,@@ -534,7 +536,316 @@ async fn local_ingest_round_trips_publish_work_without_nats() {Some(true));- // 6. Concurrent publish_work calls on separate connections coalesce in+ // 6. Versioned generation streams one prepared binary-image chunk and one+ // transport final over the same Rust-sidecar/backend path.+ let mut generate = work_item("li-gen-1", 0, 1, "generate", "default");+ generate.item = None;+ generate.output_types = None;+ generate.generate = Some(rmpv::Value::Map(vec![+ (+ rmpv::Value::from("messages"),+ rmpv::Value::Array(vec![rmpv::Value::Map(vec![+ (rmpv::Value::from("role"), rmpv::Value::from("user")),+ (rmpv::Value::from("content"), rmpv::Value::from("inspect")),+ (+ rmpv::Value::from("images"),+ rmpv::Value::Array(vec![rmpv::Value::Map(vec![+ (rmpv::Value::from("data"), rmpv::Value::from("Y2F0Ynl0ZXM=")),+ (rmpv::Value::from("format"), rmpv::Value::from("png")),+ ])]),+ ),+ ])]),+ ),+ (rmpv::Value::from("max_new_tokens"), rmpv::Value::from(8)),+ ]));+ send_request(+ &mut stream,+ 7,+ "publish_generate_stream",+ publish_work_body(&[generate], "default", 600_001),+ )+ .await;+ let chunk = timeout(Duration::from_secs(30), read_response(&mut stream))+ .await+ .expect("generation chunk answered");+ assert_eq!(map_get(&chunk, "id").and_then(rmpv::Value::as_u64), Some(7));+ assert_eq!(+ map_get(&chunk, "ok").and_then(rmpv::Value::as_bool),+ Some(true)+ );+ let chunk_body = map_get(&chunk, "body").expect("chunk body");+ assert_eq!(+ map_get(chunk_body, "seq").and_then(rmpv::Value::as_u64),+ Some(0)+ );+ let rmpv::Value::Binary(payload) = map_get(chunk_body, "chunk").expect("chunk payload") else {+ panic!("generation payload must be msgpack binary");+ };+ let semantic: rmpv::Value = rmp_serde::from_slice(payload).expect("semantic chunk");+ assert_eq!(+ map_get(&semantic, "request_id").and_then(rmpv::Value::as_str),+ Some("li-gen-1")+ );+ assert_eq!(+ map_get(&semantic, "image_data_is_bytes").and_then(rmpv::Value::as_bool),+ Some(true)+ );+ assert_eq!(+ map_get(&semantic, "image_data"),+ Some(&rmpv::Value::Binary(b"catbytes".to_vec()))+ );+ let final_frame = read_response(&mut stream).await;+ let final_body = map_get(&final_frame, "body").expect("final body");+ assert_eq!(+ map_get(final_body, "final").and_then(rmpv::Value::as_bool),+ Some(true)+ );+ assert_eq!(+ map_get(final_body, "outcome")+ .and_then(|outcome| map_get(outcome, "chunks"))+ .and_then(rmpv::Value::as_u64),+ Some(1)+ );++ // 7. A control call can cancel an in-flight generation stream. Waiting+ // for its first chunk proves the Python processor registered the+ // request before cancel is sent, avoiding a test-only race.+ let mut cancellable = work_item("li-gen-cancel", 0, 1, "generate", "default");+ cancellable.item = None;+ cancellable.output_types = None;+ cancellable.generate = Some(rmpv::Value::Map(vec![+ (+ rmpv::Value::from("messages"),+ rmpv::Value::Array(vec![rmpv::Value::Map(vec![+ (rmpv::Value::from("role"), rmpv::Value::from("user")),+ (rmpv::Value::from("content"), rmpv::Value::from("wait")),+ ])]),+ ),+ (rmpv::Value::from("max_new_tokens"), rmpv::Value::from(8)),+ (+ rmpv::Value::from("wait_for_cancel"),+ rmpv::Value::from(true),+ ),+ ]));+ let duplicate = cancellable.clone();+ let mut deadline_generate = cancellable.clone();+ deadline_generate.work_item_id = "li-gen-timeout.0".to_string();+ deadline_generate.request_id = "li-gen-timeout".to_string();+ send_request(+ &mut stream,+ 8,+ "publish_generate_stream",+ publish_work_body(&[cancellable], "default", 30_000),+ )+ .await;+ let started = timeout(Duration::from_secs(30), read_response(&mut stream))+ .await+ .expect("generation start chunk answered");+ assert_eq!(+ map_get(&started, "id").and_then(rmpv::Value::as_u64),+ Some(8)+ );+ let started_body = map_get(&started, "body").expect("started body");+ let rmpv::Value::Binary(started_payload) =+ map_get(started_body, "chunk").expect("started payload")+ else {+ panic!("generation start payload must be msgpack binary");+ };+ let started_semantic: rmpv::Value =+ rmp_serde::from_slice(started_payload).expect("started semantic chunk");+ assert_eq!(+ map_get(&started_semantic, "done").and_then(rmpv::Value::as_bool),+ Some(false)+ );++ // A request id is process-wide while its backend generation is active.+ // A different connection cannot reuse it, even though envelope ids are+ // scoped to each connection.+ let mut foreign_stream = connect_with_retry(&ingest_sock.path, Duration::from_secs(30)).await;+ send_request(+ &mut foreign_stream,+ 1,+ "publish_generate_stream",+ publish_work_body(&[duplicate], "default", 30_000),+ )+ .await;+ let duplicate_response = timeout(Duration::from_secs(5), read_response(&mut foreign_stream))+ .await+ .expect("cross-connection duplicate answered");+ assert_eq!(+ map_get(&duplicate_response, "id").and_then(rmpv::Value::as_u64),+ Some(1)+ );+ assert_eq!(+ map_get(&duplicate_response, "ok").and_then(rmpv::Value::as_bool),+ Some(false)+ );+ assert!(map_get(&duplicate_response, "error")+ .and_then(rmpv::Value::as_str)+ .unwrap_or_default()+ .starts_with("DUPLICATE_REQUEST:"));++ // A different connection may know the request id but does not own the+ // stream. Its cancel is an idempotent no-op and must not reach the backend.+ send_request(+ &mut foreign_stream,+ 2,+ "cancel",+ rmpv::Value::Map(vec![(+ rmpv::Value::from("request_id"),+ rmpv::Value::from("li-gen-cancel"),+ )]),+ )+ .await;+ let foreign_cancel = timeout(Duration::from_secs(5), read_response(&mut foreign_stream))+ .await+ .expect("foreign cancel answered");+ assert_eq!(+ map_get(&foreign_cancel, "id").and_then(rmpv::Value::as_u64),+ Some(2)+ );+ assert_eq!(+ map_get(&foreign_cancel, "ok").and_then(rmpv::Value::as_bool),+ Some(true)+ );+ assert!(+ timeout(Duration::from_secs(1), read_response(&mut stream))+ .await+ .is_err(),+ "a foreign connection cancelled a generation stream it does not own"+ );++ send_request(+ &mut stream,+ 9,+ "cancel",+ rmpv::Value::Map(vec![(+ rmpv::Value::from("request_id"),+ rmpv::Value::from("li-gen-cancel"),+ )]),+ )+ .await;+ let mut saw_cancel = false;+ let mut saw_cancelled_chunk = false;+ let mut saw_final = false;+ for _ in 0..3 {+ let response = timeout(Duration::from_secs(30), read_response(&mut stream))+ .await+ .expect("cancel sequence answered");+ match map_get(&response, "id").and_then(rmpv::Value::as_u64) {+ Some(9) => {+ assert_eq!(+ map_get(&response, "body"),+ Some(&rmpv::Value::Map(Vec::new()))+ );+ saw_cancel = true;+ }+ Some(8) => {+ let body = map_get(&response, "body").expect("generation response body");+ if map_get(body, "final").and_then(rmpv::Value::as_bool) == Some(true) {+ saw_final = true;+ continue;+ }+ let rmpv::Value::Binary(payload) =+ map_get(body, "chunk").expect("cancelled chunk payload")+ else {+ panic!("cancelled payload must be msgpack binary");+ };+ let semantic: rmpv::Value =+ rmp_serde::from_slice(payload).expect("cancelled semantic chunk");+ assert_eq!(+ map_get(&semantic, "finish_reason").and_then(rmpv::Value::as_str),+ Some("cancelled")+ );+ saw_cancelled_chunk = true;+ }+ id => panic!("unexpected response id in cancel sequence: {id:?}"),+ }+ }+ assert!(saw_cancel && saw_cancelled_chunk && saw_final);++ // 8. The local total deadline signals backend cancellation, suppresses+ // chunks produced after the deadline, and emits one timeout terminal.+ send_request(+ &mut stream,+ 10,+ "publish_generate_stream",+ publish_work_body(&[deadline_generate], "default", 250),+ )+ .await;+ let started = timeout(Duration::from_secs(30), read_response(&mut stream))+ .await+ .expect("deadline generation start chunk answered");+ assert_eq!(+ map_get(&started, "id").and_then(rmpv::Value::as_u64),+ Some(10)+ );+ let started_body = map_get(&started, "body").expect("deadline start body");+ assert!(matches!(+ map_get(started_body, "chunk"),+ Some(rmpv::Value::Binary(_))+ ));+ let terminal = timeout(Duration::from_secs(5), read_response(&mut stream))+ .await+ .expect("generation timeout terminal answered");+ assert_eq!(+ map_get(&terminal, "id").and_then(rmpv::Value::as_u64),+ Some(10)+ );+ assert_eq!(+ map_get(&terminal, "ok").and_then(rmpv::Value::as_bool),+ Some(false)+ );+ let terminal_body = map_get(&terminal, "body").expect("timeout body");+ assert_eq!(terminal_body, &rmpv::Value::Map(Vec::new()));+ assert!(map_get(&terminal, "error")+ .and_then(rmpv::Value::as_str)+ .unwrap_or_default()+ .starts_with("TIMEOUT: generation timed out after 250ms"));++ // 9. A semantic NAK is intercepted by Rust and becomes one retryable+ // transport terminal; it is never misrouted as a malformed chunk.+ let mut retry = work_item("li-gen-retry", 0, 1, "generate", "default");+ retry.item = None;+ retry.output_types = None;+ retry.generate = Some(rmpv::Value::Map(vec![+ (+ rmpv::Value::from("messages"),+ rmpv::Value::Array(vec![rmpv::Value::Map(vec![+ (rmpv::Value::from("role"), rmpv::Value::from("user")),+ (rmpv::Value::from("content"), rmpv::Value::from("retry")),+ ])]),+ ),+ (rmpv::Value::from("max_new_tokens"), rmpv::Value::from(8)),+ (+ rmpv::Value::from("test_nak_reason"),+ rmpv::Value::from("kv_budget"),+ ),+ ]));+ send_request(+ &mut stream,+ 11,+ "publish_generate_stream",+ publish_work_body(&[retry], "default", 0),+ )+ .await;+ let retry_terminal = timeout(Duration::from_secs(30), read_response(&mut stream))+ .await+ .expect("semantic NAK terminal answered");+ assert_eq!(+ map_get(&retry_terminal, "ok").and_then(rmpv::Value::as_bool),+ Some(false)+ );+ assert!(map_get(&retry_terminal, "error")+ .and_then(rmpv::Value::as_str)+ .unwrap_or_default()+ .contains("RETRY_LATER: generation backend requested retry: kv_budget"));+ assert_eq!(+ map_get(&retry_terminal, "body"),+ Some(&rmpv::Value::Map(Vec::new()))+ );++ // 10. Concurrent publish_work calls on separate connections coalesce in// the same scheduler without cross-talk.let path_a = ingest_sock.path.clone();let path_b = ingest_sock.path.clone();diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex 9280e85da..c0f4afccc 100644--- a/packages/sie_ts_sdk/package.json+++ b/packages/sie_ts_sdk/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-sdk",- "version": "0.6.26",+ "version": "0.6.27","description": "Official TypeScript SDK for SIE (Search Inference Engine)","type": "module","main": "./dist/index.cjs",diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.tsindex 7aa52b0e9..dddf786f7 100644--- a/packages/sie_ts_sdk/src/client.ts+++ b/packages/sie_ts_sdk/src/client.ts@@ -92,10 +92,14 @@ import {buildJobBody,decodeChunkBytes,jobChunks,+ requireConnectionName,+ requireConnectionSchemaPolicy,+ requireConnectorIdempotencyKey,} from "./jobs.js";import { packMessage, unpackMessage } from "./msgpack.js";import { parseSseStream } from "./sse.js";import type {+ AddConnectionOptions,Batch,BatchList,CapacityInfo,@@ -135,14 +139,23 @@ import { SDK_VERSION } from "./version.js";/** The `client.jobs` batch namespace. */export interface JobsNamespace {- /** Submit a batch job (`POST /v1/jobs`); returns the created-job envelope. */- submit(options: SubmitJobOptions): Promise<JobSubmitResult>;+ /** Submit a batch job; exact connector replays may return current status. */+ submit(options: SubmitJobOptions): Promise<JobSubmitResult | JobStatus>;/** Fetch a job's public status doc (`GET /v1/jobs/{id}`). */get(jobId: string): Promise<JobStatus>;/** List the org's jobs (`GET /v1/jobs`; scoped to the key's org). */list(): Promise<JobStatus[]>;/** Cancel a job (`POST /v1/jobs/{id}/cancel`); the hold's remainder releases. */cancel(jobId: string): Promise<JobStatus>;+ /** Confirm one exact connector plan revision for execution. */+ execute(jobId: string, planRevision: number, idempotencyKey: string): Promise<JobStatus>;+ /** Repair one exact recovery-required connector attempt and cutoff. */+ repair(+ jobId: string,+ planRevision: number,+ recoveryAttemptOrdinal: number,+ idempotencyKey: string,+ ): Promise<JobStatus>;/** Retrieve a finished job's chunk refs and decode the per-item results. */results(jobId: string): Promise<JobResults>;/**@@ -156,7 +169,12 @@ export interface JobsNamespace {/** The `client.connections` namespace (org-scoped connector auth). */export interface ConnectionsNamespace {/** Create an org-scoped connection (connector auth by name). */- add(name: string, type: string, secret: string): Promise<ConnectionCreated>;+ add(+ name: string,+ type: string,+ secret: string,+ options?: AddConnectionOptions,+ ): Promise<ConnectionCreated>;/** List the org's active connections (secrets redacted). */list(): Promise<Connection[]>;/** Revoke (soft-delete) a connection; frees the name for reuse. */@@ -623,11 +641,15 @@ export class SIEClient {get: (jobId) => this.jobGet(jobId),list: () => this.jobList(),cancel: (jobId) => this.jobCancel(jobId),+ execute: (jobId, planRevision, idempotencyKey) =>+ this.jobExecute(jobId, planRevision, idempotencyKey),+ repair: (jobId, planRevision, recoveryAttemptOrdinal, idempotencyKey) =>+ this.jobRepair(jobId, planRevision, recoveryAttemptOrdinal, idempotencyKey),results: (jobId) => this.jobResults(jobId),wait: (jobId, options) => this.jobWait(jobId, options),};this.connections = {- add: (name, type, secret) => this.connectionAdd(name, type, secret),+ add: (name, type, secret, options) => this.connectionAdd(name, type, secret, options),list: () => this.connectionList(),revoke: (name) => this.connectionRevoke(name),};@@ -2432,12 +2454,14 @@ export class SIEClient {body?: unknown,timeoutMs: number = this.timeout,onError?: (response: Response) => Promise<void>,+ extraHeaders?: Record<string, string>,): Promise<T> {const url = target.startsWith("http") ? target : `${this.baseUrl}${target}`;const headers: Record<string, string> = {Accept: JSON_CONTENT_TYPE,[SDK_VERSION_HEADER]: SDK_VERSION,};+ if (extraHeaders) Object.assign(headers, extraHeaders);if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;const init: RequestInit = { method, headers };if (body !== undefined) {@@ -2470,12 +2494,25 @@ export class SIEClient {}}- private async jobSubmit(options: SubmitJobOptions): Promise<JobSubmitResult> {- return this.jsonRequest<JobSubmitResult>(+ private async jobSubmit(options: SubmitJobOptions): Promise<JobSubmitResult | JobStatus> {+ const body = buildJobBody(options);+ let extraHeaders: Record<string, string> | undefined;+ if ("src" in body) {+ extraHeaders = { "Idempotency-Key": requireConnectorIdempotencyKey(options.idempotencyKey) };+ } else if (options.idempotencyKey != null) {+ throw new RequestError(+ "idempotencyKey applies only to connector-src jobs; inline items must omit it",+ "invalid_request",+ 400,+ );+ }+ return this.jsonRequest<JobSubmitResult | JobStatus>("/v1/jobs","POST",- buildJobBody(options),+ body,Math.max(this.timeout, DEFAULT_LONG_RUNNING_TIMEOUT),+ undefined,+ extraHeaders,);}@@ -2492,6 +2529,40 @@ export class SIEClient {return this.jsonRequest<JobStatus>(`/v1/jobs/${encodeURIComponent(jobId)}/cancel`, "POST");}+ private async jobExecute(+ jobId: string,+ planRevision: number,+ idempotencyKey: string,+ ): Promise<JobStatus> {+ return this.jsonRequest<JobStatus>(+ `/v1/jobs/${encodeURIComponent(jobId)}/execute`,+ "POST",+ { plan_revision: planRevision },+ this.timeout,+ undefined,+ { "Idempotency-Key": requireConnectorIdempotencyKey(idempotencyKey) },+ );+ }++ private async jobRepair(+ jobId: string,+ planRevision: number,+ recoveryAttemptOrdinal: number,+ idempotencyKey: string,+ ): Promise<JobStatus> {+ return this.jsonRequest<JobStatus>(+ `/v1/jobs/${encodeURIComponent(jobId)}/repair`,+ "POST",+ {+ plan_revision: planRevision,+ recovery_attempt_ordinal: recoveryAttemptOrdinal,+ },+ this.timeout,+ undefined,+ { "Idempotency-Key": requireConnectorIdempotencyKey(idempotencyKey) },+ );+ }+private async jobResults(jobId: string): Promise<JobResults> {const job = await this.jobGet(jobId);const chunks = jobChunks(job);@@ -2523,7 +2594,7 @@ export class SIEClient {const deadline = Date.now() + timeoutMs;for (;;) {const job = await this.jobGet(jobId);- if (job.state && TERMINAL_JOB_STATES.has(job.state)) {+ if ((job.state && TERMINAL_JOB_STATES.has(job.state)) || job.phase === "planned") {return job;}if (Date.now() >= deadline) {@@ -2592,12 +2663,24 @@ export class SIEClient {name: string,type: string,secret: string,+ options: AddConnectionOptions = {},): Promise<ConnectionCreated> {- return this.jsonRequest<ConnectionCreated>(this.connectionsBase(), "POST", {+ requireConnectionName(name);+ const schemaPolicy = requireConnectionSchemaPolicy(+ type,+ options.sourceSchema,+ options.sinkSchema,+ );+ const body: Record<string, unknown> = {type,name,secret,- });+ };+ if (schemaPolicy) {+ body.source_schema = schemaPolicy.sourceSchema;+ body.sink_schema = schemaPolicy.sinkSchema;+ }+ return this.jsonRequest<ConnectionCreated>(this.connectionsBase(), "POST", body);}private async connectionList(): Promise<Connection[]> {@@ -2609,8 +2692,9 @@ export class SIEClient {}private async connectionRevoke(name: string): Promise<ConnectionRevoked> {+ const canonicalName = requireConnectionName(name);return this.jsonRequest<ConnectionRevoked>(- `${this.connectionsBase()}/${encodeURIComponent(name)}`,+ `${this.connectionsBase()}/${canonicalName}`,"DELETE",);}diff --git a/packages/sie_ts_sdk/src/index.ts b/packages/sie_ts_sdk/src/index.tsindex f326c5a06..81b98a029 100644--- a/packages/sie_ts_sdk/src/index.ts+++ b/packages/sie_ts_sdk/src/index.ts@@ -38,6 +38,15 @@ export type {JobFieldMap,SubmitJobOptions,JobPreflight,+ ConnectorJobValidation,+ ConnectorJobCapabilities,+ ConnectorPlanOutputShape,+ ConnectorJobPlan,+ ConnectorJobCheckpoint,+ ConnectorJobItemOutcomes,+ ConnectorJobPublication,+ ConnectorJobAttempt,+ ConnectorJobRecovery,JobChunk,JobSubmitResult,JobStatus,@@ -89,6 +98,7 @@ export type {PoolStatus,PoolInfo,// Connections (client.connections)+ AddConnectionOptions,Connection,ConnectionCreated,ConnectionRevoked,diff --git a/packages/sie_ts_sdk/src/jobs.ts b/packages/sie_ts_sdk/src/jobs.tsindex fc0841a70..d96567f1a 100644--- a/packages/sie_ts_sdk/src/jobs.ts+++ b/packages/sie_ts_sdk/src/jobs.ts@@ -62,24 +62,170 @@ export interface SubmitJobOptions {fieldMap?: JobFieldMap | null;/** Sink target (≈ `response.body`; aliases PG `column` / object-store `suffix`). */outputField?: string | null;- /** Trigger: "now" (default), "schedule:<cron>", or "watch:<source>". */+ /** Connector-only explicit consent: inspect a plan or run it. No implicit default. */+ execution?: "plan" | "run" | null;+ /** Required retry-stable key for a connector submission; inline jobs must omit it. */+ idempotencyKey?: string | null;+ /** Immediate trigger only: "now" (default); schedule/watch are unavailable. */when?: string | null;/** Encode output types (default: dense). */outputTypes?: string[];/**- * Per-item options plus the op inputs, forwarded as-is (operation- * matrix): score → `options.query`, extract → `options.labels` /+ * One job-level operation map, applied uniformly to every item and forwarded+ * as-is: score → `options.query`, extract → `options.labels` /* `options.output_schema`, generate → sampling (e.g. `max_new_tokens`).*/options?: Record<string, unknown> | null;}+/** Validate the gateway's connector-only `Idempotency-Key` header contract. */+export function requireConnectorIdempotencyKey(key: string | null | undefined): string {+ if (+ typeof key !== "string" ||+ key.length < 1 ||+ key.length > 256 ||+ [...key].some((character) => {+ const code = character.charCodeAt(0);+ return code < 0x20 || code > 0x7e;+ })+ ) {+ throw new RequestError(+ "connector idempotencyKey must contain 1-256 printable ASCII bytes",+ "invalid_request",+ 400,+ );+ }+ return key;+}+/** The preflight reservation echoed on submit / status. */export interface JobPreflight {estimated_credits?: number;estimate_basis?: string;}+/** Planner proofs safe to expose to a connector caller. */+export interface ConnectorJobValidation {+ source?: string;+ identity?: string;+ sink?: string;+}++/** The bounded behavior proven for one connector plan revision. */+export interface ConnectorJobCapabilities {+ incremental_inference?: boolean;+ incremental_source_scan?: boolean;+ source_scan?: string;+ source_proof?: string;+ checkpoint_profile?: string;+ incremental_selection?: boolean;+ inference?: string;+ sink_targets?: unknown;+ snapshot?: string;+ ordering?: string;+ deletion_handling?: string;+ publication?: string;+}++/** Redacted, canonical output shape for one connector plan. */+export interface ConnectorPlanOutputShape {+ result_kind: "vector";+ output_field: "embedding";+ output_types: ["dense"];+ dimensions: number | null;+}++/** A durable inspect-first plan. It contains metadata, never source rows. */+export interface ConnectorJobPlan {+ revision?: number;+ expires_at?: number;+ executable?: boolean;+ executor_available?: boolean | null;+ executor_availability?: string;+ blocking_code?: string | null;+ rows?: number;+ mapped_bytes?: number;+ input_bytes?: number;+ eligible_count?: number;+ eligible_count_quality?: string;+ eligible_input_byte_count?: number;+ matched_checkpoint_count?: number;+ skipped_unchanged_count?: number;+ deleted_preserved_count?: number;+ output_dimensions?: number | null;+ output: ConnectorPlanOutputShape;+ cost_basis?: string;+ max_reservation_credits?: number;+ validation?: ConnectorJobValidation;+ capabilities?: ConnectorJobCapabilities;+}++/** Public checkpoint/fence position for the connector profile. */+export interface ConnectorJobCheckpoint {+ profile?: string;+ profile_version?: number;+ region?: string;+ expected_generation?: number;+ generation?: number;+ published_revision?: number;+}++/** Bounded item counters for one connector attempt. */+export interface ConnectorJobItemOutcomes {+ claimed?: number;+ dispatched?: number;+ inferred?: number;+ staged?: number;+ published?: number;+ failed?: number;+ reexecution_required?: number;+ skipped_unchanged?: number;+}++/** Public evidence for one atomic sink publication. */+export interface ConnectorJobPublication {+ attempt_ordinal?: number;+ revision?: number;+ published?: number;+ skipped_unchanged?: number;+ deleted?: number;+ failed?: number;+ reexecuted?: number;+ committed_at?: number;+}++/** One public execute/repair attempt; private dispatch authority is omitted. */+export interface ConnectorJobAttempt {+ ordinal: number;+ action: "execute" | "repair";+ state: string;+ recovery_attempt_ordinal?: number;+ outcome?: string | null;+ error_code?: string | null;+ replayed?: boolean;+ billed_credits?: number | null;+ overlap_owner?: { job_id?: string; attempt_ordinal?: number } | null;+ item_outcomes?: ConnectorJobItemOutcomes;+ publication?: ConnectorJobPublication | null;+ created_at?: number;+ finished_at?: number | null;+}++/** Public crash-recovery posture; tokens and receipt MACs never appear. */+export interface ConnectorJobRecovery {+ required?: boolean;+ state?: string | null;+ outcome?: string | null;+ error_code?: string | null;+ reexecution_required?: boolean;+ repair?: {+ expires_at?: number | null;+ attempts_used?: number | null;+ attempts_remaining?: number | null;+ attempts_max?: number | null;+ };+}+/** One spawned chunk's settle metadata (`output.chunks[]`; results-as-refs). */export interface JobChunk {seq?: number;@@ -102,7 +248,7 @@ export interface JobChunk {error?: unknown;}-/** The `201` envelope from `POST /v1/jobs` (inline or connector job). */+/** The fresh `201` envelope from `POST /v1/jobs` (inline or connector job). */export interface JobSubmitResult {id: string;object: string;@@ -112,9 +258,17 @@ export interface JobSubmitResult {total_items?: number;chunks?: number;preflight?: JobPreflight;- input_source?: string;- source?: string;- sink?: string;+ // Connector source/sink URIs and SQL are deliberately absent from public responses.+ execution?: "plan" | "run";+ phase?: string;+ plan_revision?: number;+ plan_expires_at?: number;+ idempotency_expires_at?: number;+ plan?: ConnectorJobPlan | null;+ checkpoint?: ConnectorJobCheckpoint;+ attempt?: ConnectorJobAttempt;+ publication?: ConnectorJobPublication | null;+ recovery?: ConnectorJobRecovery;}/** A job's public status doc from `GET /v1/jobs/{id}` (refs, never payloads). */@@ -124,6 +278,19 @@ export interface JobStatus {operation: string;model: string;state: JobState;+ execution?: "plan" | "run";+ phase?: string;+ outcome?: string | null;+ error_code?: string | null;+ plan_revision?: number | null;+ plan_expires_at?: number | null;+ idempotency_expires_at?: number | null;+ plan?: ConnectorJobPlan | null;+ checkpoint?: ConnectorJobCheckpoint;+ attempt?: ConnectorJobAttempt;+ attempts?: ConnectorJobAttempt[];+ publication?: ConnectorJobPublication | null;+ recovery?: ConnectorJobRecovery;total_items?: number;completed_items?: number;preflight?: JobPreflight;@@ -164,6 +331,10 @@ const INTERNAL_SCHEMES = new Set(["upload"]);// Uniform source-mapping slots (the sink slot is `output_field`).const FIELD_MAP_KEYS = new Set(["id_field", "input_field", "carry", "input_type"]);const INPUT_TYPES = new Set(["text", "document"]);+const CONNECTION_NAME_START_PATTERN = /^[A-Za-z0-9]$/;+const CONNECTION_NAME_CHAR_PATTERN = /^[A-Za-z0-9._-]$/;+const POSTGRES_SCHEMA_START_PATTERN = /^[A-Za-z_]$/;+const POSTGRES_SCHEMA_CHAR_PATTERN = /^[A-Za-z0-9_$]$/;function isConnectorUri(value: string): boolean {return value.includes("://");@@ -190,7 +361,7 @@ export function connectionName(uri: string): string {// URL can't parse custom schemes reliably; take the authority manually.const afterScheme = uri.split("://", 2)[1] ?? "";const authority = afterScheme.split(/[/?#]/, 1)[0] ?? "";- const name = authority.trim();+ const name = authority;if (!name) {throw new RequestError(`connector URI ${JSON.stringify(uri)} names no connection (expected 'scheme://<connection>/…')`,@@ -198,9 +369,64 @@ export function connectionName(uri: string): string {400,);}+ return requireConnectionName(name);+}++/** Return a canonical named-connection path segment or fail before I/O. */+export function requireConnectionName(name: string): string {+ if (+ name.length === 0 ||+ name.length > 128 ||+ !CONNECTION_NAME_START_PATTERN.test(name[0] ?? "") ||+ Array.from(name).some((char) => !CONNECTION_NAME_CHAR_PATTERN.test(char))+ ) {+ throw new RequestError(+ "connection name must be 1-128 ASCII letters, digits, '.', '_', or '-', and start with a letter or digit",+ "invalid_request",+ 400,+ );+ }return name;}+/** Validate the optional Postgres source/sink namespace pair before I/O. */+export function requireConnectionSchemaPolicy(+ connectionType: string,+ sourceSchema: string | null | undefined,+ sinkSchema: string | null | undefined,+): { sourceSchema: string; sinkSchema: string } | undefined {+ const sourceMissing = sourceSchema == null;+ const sinkMissing = sinkSchema == null;+ if (sourceMissing !== sinkMissing) {+ throw new RequestError(+ "sourceSchema and sinkSchema must be supplied together",+ "invalid_request",+ 400,+ );+ }+ if (sourceMissing || sinkMissing) return undefined;+ if (connectionType !== "postgres") {+ throw new RequestError(+ "sourceSchema and sinkSchema apply only to postgres connections",+ "invalid_request",+ 400,+ );+ }+ const validSchema = (schema: string): boolean =>+ schema.length >= 1 &&+ schema.length <= 63 &&+ POSTGRES_SCHEMA_START_PATTERN.test(schema[0] ?? "") &&+ Array.from(schema.slice(1)).every((char) => POSTGRES_SCHEMA_CHAR_PATTERN.test(char));+ if (!validSchema(sourceSchema) || !validSchema(sinkSchema)) {+ throw new RequestError(+ "sourceSchema and sinkSchema must be canonical Postgres identifiers of at most 63 ASCII bytes",+ "invalid_request",+ 400,+ );+ }+ return { sourceSchema, sinkSchema };+}+function resolveSource(source: JobSource, connection?: string | null): Record<string, unknown> {if (Array.isArray(source)) {if (source.length === 0) {@@ -211,9 +437,14 @@ function resolveSource(source: JobSource, connection?: string | null): Record<stif (isConnectorUri(source)) {if (isInternalUri(source)) {// Internal scheme (upload:// = OUR Files store): no connection.- return connection ? { src: source, connection } : { src: source };+ return connection+ ? { src: source, connection: requireConnectionName(connection) }+ : { src: source };}- return { src: source, connection: connection ?? connectionName(source) };+ return {+ src: source,+ connection: connection == null ? connectionName(source) : requireConnectionName(connection),+ };}if (typeof source === "string" && source.trim()) {return { items: [{ text: source }] };@@ -240,10 +471,11 @@ function resolveSink(const body: Record<string, unknown> = { sink };if (isInternalUri(sink)) {// Internal scheme: OUR Files store, no connection to name.- if (sinkConnection != null) body.sink_connection = sinkConnection;+ if (sinkConnection != null) body.sink_connection = requireConnectionName(sinkConnection);return body;}- const resolved = sinkConnection ?? connectionName(sink);+ const resolved =+ sinkConnection == null ? connectionName(sink) : requireConnectionName(sinkConnection);// Thread the sink connection when explicitly overridden or distinct from// the source's (the common "index my own store" case reuses the source).if (sinkConnection != null || resolved !== sourceConnection) {@@ -317,27 +549,8 @@ function resolveWhen(when: string | null | undefined): Record<string, unknown> {if (when == null || when.trim() === "" || when.trim().toLowerCase() === "now") {return {};}- const text = when.trim();- // Slice off the prefix (not `split(":")`, which would drop a value's own colons).- if (text.toLowerCase().startsWith("schedule:")) {- return { when: "schedule", schedule: text.slice("schedule:".length).trim() };- }- if (text.toLowerCase().startsWith("watch:")) {- return { when: "watch", watch: text.slice("watch:".length).trim() };- }- if (text.toLowerCase() === "schedule") {- throw new RequestError(- "schedule trigger needs a cron expr: when='schedule:<cron>'",- "invalid_request",- 400,- );- }- // A bare cron expression (5 whitespace-separated fields) is a schedule.- if (text.split(/\s+/).length === 5) {- return { when: "schedule", schedule: text };- }throw new RequestError(- `unrecognized when ${JSON.stringify(when)}: use 'now', 'schedule:<cron>', or 'watch:<source>'`,+ `scheduled and watched jobs are not available; omit when or use "now" (got ${JSON.stringify(when)})`,"invalid_request",400,);@@ -356,14 +569,51 @@ export function buildJobBody(options: SubmitJobOptions): Record<string, unknown>const body: Record<string, unknown> = { operation, model: options.model };const sourceFields = resolveSource(options.source, options.connection);Object.assign(body, sourceFields);- Object.assign(- body,- resolveSink(- options.sink,- sourceFields.connection as string | undefined,- options.sinkConnection,- ),+ const sinkFields = resolveSink(+ options.sink,+ sourceFields.connection as string | undefined,+ options.sinkConnection,);+ if (+ "items" in sourceFields &&+ (options.connection != null ||+ Object.keys(sinkFields).length > 0 ||+ options.sinkConnection != null)+ ) {+ throw new RequestError(+ "connection/sink/sinkConnection apply only to connector-src jobs; inline items return results",+ "invalid_request",+ 400,+ );+ }+ Object.assign(body, sinkFields);+ if ("src" in body) {+ if (options.execution !== "plan" && options.execution !== "run") {+ throw new RequestError(+ "connector jobs require execution='plan' or execution='run'",+ "invalid_request",+ 400,+ );+ }+ if (+ options.execution !== "run" &&+ (isInternalUri(String(options.source)) ||+ (typeof options.sink === "string" && isInternalUri(options.sink)))+ ) {+ throw new RequestError(+ "upload:// connector jobs are run-only; set execution='run'",+ "invalid_request",+ 400,+ );+ }+ body.execution = options.execution;+ } else if (options.execution != null) {+ throw new RequestError(+ "execution applies only to connector-src jobs; inline items must omit it",+ "invalid_request",+ 400,+ );+ }const mappingFields = resolveFieldMap(options.fieldMap, options.outputField);if (Object.keys(mappingFields).length > 0 && !("src" in body)) {throw new RequestError(@@ -377,8 +627,8 @@ export function buildJobBody(options: SubmitJobOptions): Record<string, unknown>if (options.outputTypes && options.outputTypes.length > 0) {body.output_types = options.outputTypes;}- // Per-item options + op inputs (score query / extract labels / generate- // sampling), forwarded as-is; an empty map stays off the wire (additive).+ // One job-level operation map (score query / extract labels / generate+ // sampling), applied uniformly; an empty map stays off the wire (additive).if (options.options && Object.keys(options.options).length > 0) {body.options = options.options;}diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.tsindex 3a4ce05df..a6d1ff1d0 100644--- a/packages/sie_ts_sdk/src/types.ts+++ b/packages/sie_ts_sdk/src/types.ts@@ -623,6 +623,12 @@ export interface SIEClientOptions {org?: string;}+/** Optional immutable namespace policy for a PostgreSQL connection. */+export interface AddConnectionOptions {+ sourceSchema?: string | null;+ sinkSchema?: string | null;+}+/*** An org-scoped connection (connector auth by name). The secret is never* returned by the list endpoint (only the job-runner resolve path sees it).@@ -631,6 +637,9 @@ export interface Connection {id?: number;type?: string;name?: string;+ authorization_generation?: number;+ source_schema?: string | null;+ sink_schema?: string | null;created_at?: number;}diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.tsindex 86bdf8aba..c31563183 100644--- a/packages/sie_ts_sdk/src/version.ts+++ b/packages/sie_ts_sdk/src/version.ts@@ -1 +1 @@-export const SDK_VERSION = "0.6.26"; // x-release-please-version+export const SDK_VERSION = "0.6.27"; // x-release-please-versiondiff --git a/packages/sie_ts_sdk/tests/connections.test.ts b/packages/sie_ts_sdk/tests/connections.test.tsindex 1c0e200f7..1703d276b 100644--- a/packages/sie_ts_sdk/tests/connections.test.ts+++ b/packages/sie_ts_sdk/tests/connections.test.ts@@ -34,6 +34,52 @@ describe("client.connections", () => {});});+ it("add posts a validated PostgreSQL schema policy", async () => {+ mockFetch.mockResolvedValueOnce(+ jsonResponse(+ {+ org: "acme",+ account_id: 7,+ id: 1,+ type: "postgres",+ name: "wh",+ authorization_generation: 1,+ source_schema: "source_data",+ sink_schema: "sink_data",+ },+ 201,+ ),+ );+ const client = new SIEClient(GW, { apiKey: "sk-sie-x", controlPlaneUrl: CP, org: "acme" });+ const out = await client.connections.add("wh", "postgres", "postgres://u:p@h/db", {+ sourceSchema: "source_data",+ sinkSchema: "sink_data",+ });+ expect(out.source_schema).toBe("source_data");+ const [, init] = mockFetch.mock.calls[0];+ expect(JSON.parse(init.body)).toEqual({+ type: "postgres",+ name: "wh",+ secret: "postgres://u:p@h/db",+ source_schema: "source_data",+ sink_schema: "sink_data",+ });+ });++ it.each([+ ["postgres", { sourceSchema: "source" }],+ ["postgres", { sinkSchema: "sink" }],+ ["s3", { sourceSchema: "source", sinkSchema: "sink" }],+ ["postgres", { sourceSchema: "source.bad", sinkSchema: "sink" }],+ ["postgres", { sourceSchema: "source", sinkSchema: "sink-bad" }],+ ["postgres", { sourceSchema: "source", sinkSchema: "sink\n" }],+ ["postgres", { sourceSchema: "source", sinkSchema: "s".repeat(64) }],+ ])("rejects invalid schema policy for %s before I/O", async (type, options) => {+ const client = new SIEClient(GW, { apiKey: "sk-sie-x", controlPlaneUrl: CP, org: "acme" });+ await expect(client.connections.add("wh", type, "dsn", options)).rejects.toThrow(/Schema/);+ expect(mockFetch).not.toHaveBeenCalled();+ });+it("list returns the connections array", async () => {mockFetch.mockResolvedValueOnce(jsonResponse({@@ -58,6 +104,24 @@ describe("client.connections", () => {expect(init.method).toBe("DELETE");});+ it.each([+ "../other",+ "warehouse/name",+ "warehouse%2fname",+ "warehouse\n",+ "warehouse\r",+ "warehouse\u2028",+ "café",+ "a".repeat(129),+ ])("rejects non-canonical connection name %s before I/O", async (name) => {+ const client = new SIEClient(GW, { controlPlaneUrl: CP, org: "acme" });+ await expect(client.connections.add(name, "postgres", "dsn")).rejects.toThrow(+ /connection name/,+ );+ await expect(client.connections.revoke(name)).rejects.toThrow(/connection name/);+ expect(mockFetch).not.toHaveBeenCalled();+ });+it("throws when controlPlaneUrl is not configured", async () => {const client = new SIEClient(GW, { apiKey: "sk-sie-x" });await expect(client.connections.list()).rejects.toThrow(/controlPlaneUrl/);diff --git a/packages/sie_ts_sdk/tests/jobs.test.ts b/packages/sie_ts_sdk/tests/jobs.test.tsindex d31f0488a..ba17f61da 100644--- a/packages/sie_ts_sdk/tests/jobs.test.ts+++ b/packages/sie_ts_sdk/tests/jobs.test.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from "vitest";import { SIEClient } from "../src/client.js";import { buildJobBody, connectionName } from "../src/jobs.js";+import type { JobStatus } from "../src/jobs.js";import { packMessage } from "../src/msgpack.js";const mockFetch = vi.fn();@@ -24,7 +25,29 @@ const SUBMIT_RESP = {preflight: { estimated_credits: 64 },};+const CONNECTOR_STATUS_WITH_NUMERIC_REVISIONS: JobStatus = {+ id: "job-1",+ object: "job",+ operation: "encode",+ model: "BAAI/bge-m3",+ state: "succeeded",+ checkpoint: { published_revision: 3 },+ publication: { revision: 4 },+ attempt: {+ ordinal: 2,+ action: "repair",+ state: "published",+ recovery_attempt_ordinal: 1,+ },+};+describe("buildJobBody (pure slot mapping)", () => {+ it("types checkpoint and publication revisions as wire-format numbers", () => {+ expect(CONNECTOR_STATUS_WITH_NUMERIC_REVISIONS.checkpoint?.published_revision).toBe(3);+ expect(CONNECTOR_STATUS_WITH_NUMERIC_REVISIONS.publication?.revision).toBe(4);+ expect(CONNECTOR_STATUS_WITH_NUMERIC_REVISIONS.attempt?.recovery_attempt_ordinal).toBe(1);+ });+it("maps an inline list to items", () => {expect(buildJobBody({ source: ["a", "b"], model: "m" })).toEqual({operation: "encode",@@ -38,10 +61,12 @@ describe("buildJobBody (pure slot mapping)", () => {source: "postgres://warehouse?query=x",model: "m",sink: "postgres://warehouse?table=t",+ execution: "plan",});expect(body.src).toBe("postgres://warehouse?query=x");expect(body.connection).toBe("warehouse");expect(body.sink).toBe("postgres://warehouse?table=t");+ expect(body.execution).toBe("plan");expect(body.sink_connection).toBeUndefined();});@@ -50,21 +75,31 @@ describe("buildJobBody (pure slot mapping)", () => {source: "postgres://wh?query=x",model: "m",sink: "s3://out/vecs",+ execution: "run",});expect(body.sink_connection).toBe("out");});- it("maps schedule / watch triggers", () => {- expect(buildJobBody({ source: ["a"], model: "m", when: "schedule:*/5 * * * *" })).toMatchObject(- {- when: "schedule",- schedule: "*/5 * * * *",- },+ it("requires explicit connector execution and rejects it for inline jobs", () => {+ expect(() =>+ buildJobBody({+ source: "postgres://warehouse?query=x",+ model: "m",+ sink: "postgres://warehouse?table=t",+ }),+ ).toThrow(/require execution/);+ expect(() => buildJobBody({ source: ["a"], model: "m", execution: "plan" })).toThrow(+ /only to connector/,+ );+ });++ it("rejects unavailable schedule / watch triggers", () => {+ expect(() => buildJobBody({ source: ["a"], model: "m", when: "schedule:*/5 * * * *" })).toThrow(+ /not available/,+ );+ expect(() => buildJobBody({ source: ["a"], model: "m", when: "watch:s3://in" })).toThrow(+ /not available/,);- expect(buildJobBody({ source: ["a"], model: "m", when: "watch:s3://in" })).toMatchObject({- when: "watch",- watch: "s3://in",- });});it("derives connection names from URIs", () => {@@ -72,6 +107,37 @@ describe("buildJobBody (pure slot mapping)", () => {expect(connectionName("s3://customer-bucket/in/")).toBe("customer-bucket");});+ it.each([+ "../other",+ "warehouse/name",+ "warehouse%2fname",+ "warehouse\n",+ "warehouse\r",+ "warehouse\u2028",+ "café",+ "a".repeat(129),+ ])("rejects non-canonical connector name %s", (name) => {+ if (name !== "warehouse/name") {+ expect(() => connectionName(`postgres://${name}?query=x`)).toThrow(/connection name/);+ }+ expect(() =>+ buildJobBody({+ source: "postgres://warehouse?query=x",+ model: "m",+ sink: "postgres://warehouse?table=out",+ connection: name,+ }),+ ).toThrow(/connection name/);+ expect(() =>+ buildJobBody({+ source: "postgres://warehouse?query=x",+ model: "m",+ sink: "postgres://warehouse?table=out",+ sinkConnection: name,+ }),+ ).toThrow(/connection name/);+ });+// field_map / output_field + the internal upload:// schemeit("rides field_map + output_field on connector jobs", () => {@@ -86,6 +152,7 @@ describe("buildJobBody (pure slot mapping)", () => {input_type: "text",},outputField: "embedding",+ execution: "plan",});expect(body.field_map).toEqual({id_field: "id",@@ -105,6 +172,7 @@ describe("buildJobBody (pure slot mapping)", () => {source: "postgres://wh?query=x",model: "m",sink: "postgres://wh?table=t",+ execution: "plan",fieldMap: { id_column: "id" } as never,}),).toThrowError(/unknown field_map key/);@@ -113,17 +181,30 @@ describe("buildJobBody (pure slot mapping)", () => {source: "postgres://wh?query=x",model: "m",sink: "postgres://wh?table=t",+ execution: "plan",fieldMap: { input_type: "rows" } as never,}),).toThrowError(/input_type/);});+ it.each([+ { sink: "inplace" },+ { sink: "postgres://wh?table=vecs" },+ { sinkConnection: "wh" },+ { connection: "wh" },+ ])("rejects connector fields on inline items: %j", (connectorFields) => {+ expect(() => buildJobBody({ source: ["a"], model: "m", ...connectorFields })).toThrowError(+ /connector-src/,+ );+ });+it("derives no connection for the internal upload:// scheme", () => {const body = buildJobBody({source: "upload://file-abc?format=csv",model: "m",sink: "upload://file-out",fieldMap: { id_field: "doc_id", input_field: "text" },+ execution: "run",});expect(body.src).toBe("upload://file-abc?format=csv");expect(body.sink).toBe("upload://file-out");@@ -135,9 +216,18 @@ describe("buildJobBody (pure slot mapping)", () => {model: "m",sink: "postgres://wh?table=doc_vectors",sinkConnection: "wh",+ execution: "run",});expect(cross.connection).toBeUndefined();expect(cross.sink_connection).toBe("wh");+ expect(() =>+ buildJobBody({+ source: "upload://file-abc",+ model: "m",+ sink: "upload://file-out",+ execution: "plan",+ }),+ ).toThrow(/run-only/);});it("forwards op inputs via options as-is (op matrix)", () => {@@ -148,6 +238,7 @@ describe("buildJobBody (pure slot mapping)", () => {operation: "score",sink: "postgres://wh?table=scores",options: { query: "rank these documents" },+ execution: "run",});expect(score.options).toEqual({ query: "rank these documents" });@@ -195,11 +286,16 @@ describe("client.jobs", () => {source: "postgres://warehouse?query=x",model: "m",sink: "s3://out/vecs",+ execution: "plan",+ idempotencyKey: "plan-warehouse-1",});- const body = JSON.parse(mockFetch.mock.calls[0][1].body);+ const init = mockFetch.mock.calls[0][1];+ const body = JSON.parse(init.body);expect(body.src).toBe("postgres://warehouse?query=x");expect(body.connection).toBe("warehouse");expect(body.sink_connection).toBe("out");+ expect(body.execution).toBe("plan");+ expect(init.headers["Idempotency-Key"]).toBe("plan-warehouse-1");});it("submit forwards score query and extract labels via options", async () => {@@ -211,6 +307,8 @@ describe("client.jobs", () => {operation: "score",sink: "postgres://wh?table=scores",options: { query: "rank these documents" },+ execution: "run",+ idempotencyKey: "run-score-1",});const scoreBody = JSON.parse(mockFetch.mock.calls[0][1].body);expect(scoreBody.operation).toBe("score");@@ -228,6 +326,26 @@ describe("client.jobs", () => {expect(extractBody.options).toEqual({ labels: ["PERSON", "ORG"] });});+ it("requires a retry-stable idempotency key for connectors before fetch", async () => {+ const client = new SIEClient("http://gw:8080");+ await expect(+ client.jobs.submit({+ source: "postgres://warehouse?query=x",+ model: "m",+ sink: "postgres://warehouse?table=out",+ execution: "plan",+ }),+ ).rejects.toThrow(/idempotencyKey/);+ expect(mockFetch).not.toHaveBeenCalled();+ });++ it("keeps inline submissions free of connector idempotency headers", async () => {+ mockFetch.mockResolvedValueOnce(jsonResponse(SUBMIT_RESP, 201));+ const client = new SIEClient("http://gw:8080");+ await client.jobs.submit({ source: ["a"], model: "m" });+ expect(mockFetch.mock.calls[0][1].headers["Idempotency-Key"]).toBeUndefined();+ });+it("get and cancel hit the expected URLs", async () => {mockFetch.mockResolvedValueOnce(jsonResponse({ id: "job-1", state: "running" }));const client = new SIEClient("http://gw:8080");@@ -241,6 +359,47 @@ describe("client.jobs", () => {expect(mockFetch.mock.calls[1][1].method).toBe("POST");});+ it("execute posts the exact plan revision with one idempotency key", async () => {+ mockFetch.mockResolvedValueOnce(jsonResponse({ id: "job-1", state: "queued" }));+ const client = new SIEClient("http://gw:8080");++ await client.jobs.execute("job-1", 3, "execute-plan-3");++ const [url, init] = mockFetch.mock.calls[0];+ expect(url).toBe("http://gw:8080/v1/jobs/job-1/execute");+ expect(init.method).toBe("POST");+ expect(JSON.parse(init.body)).toEqual({ plan_revision: 3 });+ expect(init.headers["Idempotency-Key"]).toBe("execute-plan-3");+ });++ it("execute rejects an invalid idempotency key before fetch", async () => {+ const client = new SIEClient("http://gw:8080");+ await expect(client.jobs.execute("job-1", 3, "")).rejects.toThrow(/idempotencyKey/);+ expect(mockFetch).not.toHaveBeenCalled();+ });++ it("repair posts the exact plan revision and recovery predecessor", async () => {+ mockFetch.mockResolvedValueOnce(jsonResponse({ id: "job-1", state: "running" }, 202));+ const client = new SIEClient("http://gw:8080");++ await client.jobs.repair("job-1", 3, 2, "repair-plan-3-attempt-2");++ const [url, init] = mockFetch.mock.calls[0];+ expect(url).toBe("http://gw:8080/v1/jobs/job-1/repair");+ expect(init.method).toBe("POST");+ expect(JSON.parse(init.body)).toEqual({+ plan_revision: 3,+ recovery_attempt_ordinal: 2,+ });+ expect(init.headers["Idempotency-Key"]).toBe("repair-plan-3-attempt-2");+ });++ it("repair rejects an invalid idempotency key before fetch", async () => {+ const client = new SIEClient("http://gw:8080");+ await expect(client.jobs.repair("job-1", 3, 2, "")).rejects.toThrow(/idempotencyKey/);+ expect(mockFetch).not.toHaveBeenCalled();+ });+it("list returns the data array", async () => {mockFetch.mockResolvedValueOnce(jsonResponse({ object: "list", data: [{ id: "job-1" }, { id: "job-2" }] }),@@ -295,6 +454,16 @@ describe("client.jobs", () => {expect(mockFetch.mock.calls.length).toBe(2);});+ it("wait returns a stable planned connector phase without polling again", async () => {+ mockFetch.mockResolvedValueOnce(+ jsonResponse({ id: "job-plan-1", state: "queued", execution: "plan", phase: "planned" }),+ );+ const client = new SIEClient("http://gw:8080");+ const job = await client.jobs.wait("job-plan-1", { pollMs: 0 });+ expect(job.phase).toBe("planned");+ expect(mockFetch.mock.calls.length).toBe(1);+ });+it("wait throws a job_wait_timeout RequestError when the deadline passes", async () => {mockFetch.mockResolvedValue(jsonResponse({ id: "job-1", state: "running" }));const client = new SIEClient("http://gw:8080");diff --git a/uv.lock b/uv.lockindex 289cea19c..457cfaaf5 100644--- a/uv.lock+++ b/uv.lock@@ -4373,12 +4373,12 @@ dev = [[[package]]name = "sie-audio-prep"-version = "0.6.26"+version = "0.6.27"source = { editable = "packages/sie_audio_prep" }[[package]]name = "sie-chroma"-version = "0.6.26"+version = "0.6.27"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -4458,7 +4458,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.6.26"+version = "0.6.27"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -4483,7 +4483,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.6.26"+version = "0.6.27"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -4508,7 +4508,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.6.26"+version = "0.6.27"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -4535,7 +4535,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.6.26"+version = "0.6.27"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -4562,7 +4562,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.6.26"+version = "0.6.27"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -4589,7 +4589,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.6.26"+version = "0.6.27"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -4655,7 +4655,7 @@ dev = [[[package]]name = "sie-qdrant"-version = "0.6.26"+version = "0.6.27"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -4678,7 +4678,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.6.26"+version = "0.6.27"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -4731,7 +4731,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.6.26"+version = "0.6.27"source = { editable = "packages/sie_server" }dependencies = [{ name = "blake3" },@@ -4800,7 +4800,7 @@ xformers = [[package.metadata]requires-dist = [{ name = "blake3", specifier = ">=0.4,<1" },- { name = "docling", specifier = ">=2,<3" },+ { name = "docling", specifier = ">=2.99,<2.100" },{ name = "einops", specifier = ">=0.8,<1" },{ name = "fastapi", specifier = ">=0.115,<1" },{ name = "flagembedding", specifier = ">=1.3,<2" },@@ -4854,7 +4854,7 @@ dev = [][[package]]name = "sie-weaviate"-version = "0.6.26"+version = "0.6.27"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },