Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

122 KB
Raw Blame
"""Contract tests for the direct OpenAI routes (/v1/chat/completions, /v1/rerank).

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 base64
import json
import threading
import time
from collections.abc import AsyncIterator, Callable, Iterator
from contextlib import contextmanager
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock

import cv2
import httpx
import numpy as np
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from openai.types.chat import ChatCompletion, ChatCompletionChunk
from sie_server.adapters.mlx import generation as mlx_generation
from sie_server.adapters.mlx.generation import MLXGenerationAdapter
from sie_server.adapters.sglang.generation import SGLangGenerationAdapter
from sie_server.api import anthropic_messages, openai_local, openai_responses
from sie_server.api.openai_local import _validate_mlx_seed, router
from sie_server.config.model import ModelConfig
from sie_server.core import video_frames
from sie_server.core.inference_output import ScoreOutput
from sie_server.core.loader import expand_profile_variants
from sie_server.core.timing import RequestTiming
from sie_server.core.worker import WorkerResult
from sie_server.types.inputs import MAX_ITEM_TEXT_BYTES
from tokenizers import Tokenizer, models, pre_tokenizers
from transformers import PreTrainedTokenizerFast

_GEMMA_OPEN = "<" + "|channel" + ">" + "thought\n"
_GEMMA_CLOSE = "<" + "channel|" + ">"


_UNKNOWN = "[UNK]"
_WORD_TEMPLATE = (
    "{% if tools %}{{ 'tools' }}{% for tool in tools %}{{ ' ' ~ tool.function.name }}{% endfor %}{{ ' ' }}{% endif %}"
    "{% for message in messages %}{{ message.role ~ ' ' ~ message.content }}"
    "{% for call in message.tool_calls or [] %}{{ ' ' ~ call.function.name }}"
    "{% for name, value in call.function.arguments.items() %}{{ ' ' ~ name ~ ' ' ~ value }}{% endfor %}"
    "{% endfor %}{{ ' ' }}{% endfor %}"
    "{% if enable_thinking %}{{ 'think ' }}{% endif %}{% if add_generation_prompt %}{{ 'assistant' }}{% endif %}"
)


def _word_tokenizer() -> PreTrainedTokenizerFast:
    """One token per word of a prompt naming each tool, each message's role, text and call arguments, and thinking."""
    backend = Tokenizer(models.WordLevel({_UNKNOWN: 0}, unk_token=_UNKNOWN))
    backend.pre_tokenizer = pre_tokenizers.WhitespaceSplit()
    tokenizer = PreTrainedTokenizerFast(tokenizer_object=backend, unk_token=_UNKNOWN)
    tokenizer.chat_template = _WORD_TEMPLATE
    return tokenizer


def _client() -> TestClient:
    app = FastAPI()
    app.include_router(router)
    # Registry is only reached AFTER input validation, so a stub is fine for 4xx paths.
    app.state.registry = MagicMock()
    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",
    video: bool = False,
    image: bool = False,
    tools: bool = True,
) -> 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 {},
        capabilities=SimpleNamespace(tools=tools),
    )
    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),
        inputs=SimpleNamespace(video=video, image=image),
        profiles={},
        routing=None,
        reasoning_effort_for=lambda _profile="default": None,
    )
    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,
    max_seq_length: int | None = 32768,
    image: bool = False,
    tools: bool = True,
) -> tuple[TestClient, MagicMock]:
    adapter = MLXGenerationAdapter(
        model_name_or_path="Qwen/Qwen3.5-4B",
        mlx_repo="mlx-community/Qwen3.5-4B-4bit",
        max_seq_length=max_seq_length,
    )
    adapter._server_url = "http://127.0.0.1:30401"
    monkeypatch.setattr(mlx_generation, "_chat_tokenizer", lambda _repo, _trust_remote_code: _word_tokenizer())
    generate_task = SimpleNamespace(
        max_output_tokens=max_output_tokens,
        chat_template_kwargs=chat_template_kwargs,
        capabilities=SimpleNamespace(tools=tools),
    )
    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),
        inputs=SimpleNamespace(video=False, image=image),
        profiles={},
        routing=None,
        reasoning_effort_for=lambda _profile="default": None,
    )
    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 -----------------------------------------


def test_chat_requires_object_body() -> None:
    r = _client().post("/v1/chat/completions", content=b"[]", headers={"content-type": "application/json"})
    assert r.status_code == 400


def test_chat_requires_model() -> None:
    r = _client().post("/v1/chat/completions", json={"messages": [{"role": "user", "content": "hi"}]})
    assert r.status_code == 400
    assert r.json()["error"]["param"] == "model"


def test_chat_requires_nonempty_messages() -> None:
    r = _client().post("/v1/chat/completions", json={"model": "m", "messages": []})
    assert r.status_code == 400
    assert r.json()["error"]["param"] == "messages"


@pytest.mark.parametrize(
    ("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()["error"]["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.
    client = _client()
    client.app.state.registry.get_config.return_value.tasks.generate = None
    r = client.post(
        "/v1/chat/completions", json={"model": "embed-model", "messages": [{"role": "user", "content": "hi"}]}
    )
    assert r.status_code == 400
    assert "generation" in r.json()["error"]["message"].lower()


def test_chat_rejects_non_bool_stream() -> None:
    msgs = [{"role": "user", "content": "hi"}]
    r = _client().post("/v1/chat/completions", json={"model": "m", "messages": msgs, "stream": "false"})
    assert r.status_code == 400
    assert r.json()["error"]["param"] == "stream"


def test_chat_rejects_unsupported_streaming_before_load(monkeypatch: pytest.MonkeyPatch) -> None:
    client, registry = _cuda_chat_client(
        monkeypatch,
        lambda _request: pytest.fail("unsupported streaming must not reach the child"),
    )
    generate_task = registry.get_config.return_value.tasks.generate
    generate_task.capabilities = SimpleNamespace(streaming=False)
    registry.is_loaded.return_value = False

    response = client.post(
        "/v1/chat/completions",
        json={
            "model": "Qwen/Qwen3.5-4B",
            "messages": [{"role": "user", "content": "hi"}],
            "stream": True,
        },
    )

    assert response.status_code == 400
    assert response.json()["error"]["code"] == "unsupported_field"
    assert response.json()["error"]["param"] == "stream"
    registry.start_load_async.assert_not_called()
    registry.get.assert_not_called()


def test_chat_rejects_invalid_max_tokens() -> None:
    msgs = [{"role": "user", "content": "hi"}]
    for bad in (0, -5, "100", True):
        r = _client().post("/v1/chat/completions", json={"model": "m", "messages": msgs, "max_tokens": bad})
        assert r.status_code == 400, bad
        assert r.json()["error"]["param"] == "max_tokens"


@pytest.mark.parametrize(
    ("bad", "message"),
    [
        (True, "'seed' must be an integer"),
        ("1", "'seed' must be an integer"),
        (1.5, "'seed' must be an integer"),
        (-(1 << 63) - 1, "'seed' is outside the supported integer range"),
        (1 << 63, "'seed' is outside the supported integer range"),
    ],
)
def test_chat_rejects_invalid_seed(bad: object, message: str) -> None:
    msgs = [{"role": "user", "content": "hi"}]
    r = _client().post("/v1/chat/completions", json={"model": "m", "messages": msgs, "seed": bad})
    assert r.status_code == 400, bad
    assert r.json()["error"] == {
        "code": "INVALID_INPUT",
        "message": message,
        "param": "seed",
        "type": "invalid_request_error",
    }


@pytest.mark.parametrize(
    ("seed", "expected"),
    [
        (-(1 << 63), 1 << 63),
        (-1, (1 << 64) - 1),
        (0, 0),
        ((1 << 63) - 1, (1 << 63) - 1),
    ],
)
def test_validate_mlx_seed_preserves_signed_bit_pattern(seed: int, expected: int) -> None:
    assert _validate_mlx_seed(seed) == expected


def test_validate_mlx_seed_preserves_absent_value() -> None:
    assert _validate_mlx_seed(None) is None


@pytest.mark.parametrize(
    ("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()["error"] == {
        "code": "unsupported_field",
        "message": "field 'draft_model' is not supported",
        "param": "draft_model",
        "type": "invalid_request_error",
    }
    registry.is_loaded.assert_not_called()
    registry.get.assert_not_called()


_WEATHER_TOOL = {
    "type": "function",
    "function": {
        "name": "get_weather",
        "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
    },
}
_PARIS_CALL = {
    "id": "call_paris",
    "type": "function",
    "function": {"name": "get_weather", "arguments": '{"city": "Paris"}'},
}
_TOKYO_CALL = {
    "id": "call_tokyo",
    "type": "function",
    "function": {"name": "get_weather", "arguments": '{"city": "Tokyo"}'},
}
_AFTER_A_TOOL_TURN = [
    {"role": "user", "content": "Weather in Paris?"},
    {"role": "assistant", "content": None, "tool_calls": [_PARIS_CALL]},
    {"role": "tool", "tool_call_id": "call_paris", "content": "18C, clear"},
    {"role": "user", "content": "And in Tokyo?"},
]


def _mlx_tool_call_stream(*calls: dict[str, Any]) -> _ChunkedAsyncStream:
    """An mlx_lm.server chat stream: one delta per completed call, then the finish event."""
    events = [
        {
            "id": "chatcmpl-mlx",
            "object": "chat.completion.chunk",
            "created": 1,
            "model": "mlx-community/Qwen3.5-4B-4bit",
            "choices": [
                {
                    "index": 0,
                    "finish_reason": None,
                    "delta": {"role": "assistant", "tool_calls": [{**call, "index": i}]},
                }
            ],
        }
        for i, call in enumerate(calls)
    ]
    events.append(
        {
            "id": "chatcmpl-mlx",
            "object": "chat.completion.chunk",
            "created": 1,
            "model": "mlx-community/Qwen3.5-4B-4bit",
            "choices": [{"index": 0, "finish_reason": "tool_calls", "delta": {"role": "assistant"}}],
        }
    )
    return _ChunkedAsyncStream([f"data: {json.dumps(event)}\n\n".encode() for event in events] + [b"data: [DONE]\n\n"])


def _sse_events(response_text: str) -> list[dict[str, Any]]:
    lines = [line.removeprefix("data: ") for line in response_text.splitlines() if line.startswith("data: ")]
    assert lines[-1] == "[DONE]"
    return [json.loads(line) for line in lines[:-1]]


@pytest.mark.parametrize(
    "tool_fields",
    [
        {"tool_choice": "auto"},
        {"tool_choice": "auto", "parallel_tool_calls": True},
        {"parallel_tool_calls": True},
    ],
)
def test_mlx_chat_accepts_auto_tool_choice_and_returns_every_call(
    monkeypatch: pytest.MonkeyPatch,
    tool_fields: dict[str, Any],
) -> None:
    seen: dict[str, Any] = {}

    def _handler(request: httpx.Request) -> httpx.Response:
        seen["body"] = json.loads(request.content)
        return httpx.Response(
            200, json=_chat_completion(None, finish_reason="tool_calls", tool_calls=[_PARIS_CALL, _TOKYO_CALL])
        )

    client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={"enable_thinking": False})
    response = client.post(
        "/v1/chat/completions",
        json={
            "model": "Qwen/Qwen3.5-4B",
            "messages": [{"role": "user", "content": "Weather in Paris and Tokyo?"}],
            "tools": [_WEATHER_TOOL],
            **tool_fields,
        },
    )

    assert response.status_code == 200
    assert seen["body"]["tools"] == [_WEATHER_TOOL]
    assert "tool_choice" not in seen["body"]
    assert "parallel_tool_calls" not in seen["body"]
    completion = ChatCompletion.model_validate(response.json())
    assert completion.choices[0].finish_reason == "tool_calls"
    assert [call.id for call in completion.choices[0].message.tool_calls or []] == ["call_paris", "call_tokyo"]


def test_mlx_chat_streams_every_tool_call_under_auto(monkeypatch: pytest.MonkeyPatch) -> None:
    seen: dict[str, Any] = {}
    upstream_stream = _mlx_tool_call_stream(_PARIS_CALL, _TOKYO_CALL)

    def _handler(request: httpx.Request) -> httpx.Response:
        seen["body"] = json.loads(request.content)
        return httpx.Response(200, stream=upstream_stream, headers={"content-type": "text/event-stream"})

    client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={"enable_thinking": False})
    response = client.post(
        "/v1/chat/completions",
        json={
            "model": "Qwen/Qwen3.5-4B",
            "messages": [{"role": "user", "content": "Weather in Paris and Tokyo?"}],
            "tools": [_WEATHER_TOOL],
            "tool_choice": "auto",
            "stream": True,
        },
    )

    assert response.status_code == 200
    assert seen["body"]["tools"] == [_WEATHER_TOOL]
    assert "tool_choice" not in seen["body"]
    chunks = [ChatCompletionChunk.model_validate(event) for event in _sse_events(response.text)]
    streamed = [call for chunk in chunks for call in chunk.choices[0].delta.tool_calls or []]
    assert [(call.index, call.id) for call in streamed] == [(0, "call_paris"), (1, "call_tokyo")]
    assert chunks[-1].choices[0].finish_reason == "tool_calls"
    assert upstream_stream.closed is True


@pytest.mark.parametrize("stream", [False, True])
def test_mlx_chat_parallel_tool_calls_false_returns_a_single_call(
    monkeypatch: pytest.MonkeyPatch, stream: bool
) -> None:
    seen: dict[str, Any] = {}

    def _handler(request: httpx.Request) -> httpx.Response:
        seen["body"] = json.loads(request.content)
        if stream:
            return httpx.Response(
                200, stream=_mlx_tool_call_stream(_PARIS_CALL), headers={"content-type": "text/event-stream"}
            )
        return httpx.Response(200, json=_chat_completion(None, finish_reason="tool_calls", tool_calls=[_PARIS_CALL]))

    client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={"enable_thinking": False})
    response = client.post(
        "/v1/chat/completions",
        json={
            "model": "Qwen/Qwen3.5-4B",
            "messages": [{"role": "user", "content": "Weather in Paris?"}],
            "tools": [_WEATHER_TOOL],
            "tool_choice": "auto",
            "parallel_tool_calls": False,
            "stream": stream,
        },
    )

    assert response.status_code == 200
    assert seen["body"]["tools"] == [_WEATHER_TOOL]
    assert "parallel_tool_calls" not in seen["body"]
    if stream:
        events = _sse_events(response.text)
        assert [call["id"] for event in events for call in event["choices"][0]["delta"].get("tool_calls", [])] == [
            "call_paris"
        ]
        assert events[-1]["choices"][0]["finish_reason"] == "tool_calls"
    else:
        assert [call["id"] for call in response.json()["choices"][0]["message"]["tool_calls"]] == ["call_paris"]


def test_mlx_chat_tool_choice_none_withholds_tools_from_the_child(monkeypatch: pytest.MonkeyPatch) -> None:
    seen: dict[str, Any] = {}

    def _handler(request: httpx.Request) -> httpx.Response:
        seen["body"] = json.loads(request.content)
        return httpx.Response(200, json=_chat_completion("It is sunny."))

    client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={"enable_thinking": False})
    response = client.post(
        "/v1/chat/completions",
        json={
            "model": "Qwen/Qwen3.5-4B",
            "messages": [{"role": "user", "content": "Weather in Paris?"}],
            "tools": [_WEATHER_TOOL],
            "tool_choice": "none",
        },
    )

    assert response.status_code == 200
    assert "tools" not in seen["body"]
    assert "tool_choice" not in seen["body"]
    assert response.json()["choices"][0]["message"]["content"] == "It is sunny."


@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize(
    ("tool_fields", "calls", "delivered", "message"),
    [
        (
            {"tools": [_WEATHER_TOOL], "parallel_tool_calls": False},
            [_PARIS_CALL, _TOKYO_CALL],
            ["call_paris"],
            "generation child returned more than one tool call with parallel_tool_calls=false",
        ),
        (
            {"tools": [_WEATHER_TOOL], "tool_choice": "none"},
            [_TOKYO_CALL],
            [],
            "generation child returned a tool call the request did not offer",
        ),
        (
            {},
            [_TOKYO_CALL],
            [],
            "generation child returned a tool call the request did not offer",
        ),
    ],
    ids=["parallel_tool_calls_false", "tool_choice_none", "no_tools"],
)
def test_mlx_chat_fails_closed_on_tool_calls_the_request_ruled_out(
    monkeypatch: pytest.MonkeyPatch,
    stream: bool,
    tool_fields: dict[str, Any],
    calls: list[dict[str, Any]],
    delivered: list[str],
    message: str,
) -> None:
    upstream_stream = _mlx_tool_call_stream(*calls)

    def _handler(_request: httpx.Request) -> httpx.Response:
        if stream:
            return httpx.Response(200, stream=upstream_stream, headers={"content-type": "text/event-stream"})
        return httpx.Response(200, json=_chat_completion(None, finish_reason="tool_calls", tool_calls=calls))

    client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={"enable_thinking": False})
    response = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3.5-4B", "messages": _AFTER_A_TOOL_TURN, "stream": stream, **tool_fields},
    )

    error = {"error": {"message": message, "type": "upstream_error", "param": None, "code": "upstream_error"}}
    if not stream:
        assert response.status_code == 502
        assert response.json() == error
        return
    assert response.status_code == 200
    events = _sse_events(response.text)
    assert events[-1] == error
    streamed = [call["id"] for event in events[:-1] for call in event["choices"][0]["delta"].get("tool_calls", [])]
    assert streamed == delivered
    assert all(event["choices"][0]["finish_reason"] is None for event in events[:-1])
    assert upstream_stream.closed is True


@pytest.mark.parametrize("device", ["mps", "cpu"])
@pytest.mark.parametrize(
    "tool_choice",
    ["required", {"type": "function", "function": {"name": "get_weather"}}],
)
def test_mlx_chat_refuses_a_forced_tool_choice_before_model_load(
    monkeypatch: pytest.MonkeyPatch,
    device: str,
    tool_choice: Any,
) -> None:
    client, registry = _mlx_chat_client(
        monkeypatch,
        lambda _request: pytest.fail("refused request must not reach upstream"),
        chat_template_kwargs={"enable_thinking": False},
    )
    registry.device = device

    response = client.post(
        "/v1/chat/completions",
        json={
            "model": "Qwen/Qwen3.5-4B",
            "messages": [{"role": "user", "content": "Weather in Paris?"}],
            "tools": [_WEATHER_TOOL],
            "tool_choice": tool_choice,
        },
    )

    assert response.status_code == 400
    assert response.json()["error"] == {
        "code": "unsupported_field",
        "message": "'tool_choice' must be 'auto' or 'none' on this device, which cannot force a tool call",
        "param": "tool_choice",
        "type": "invalid_request_error",
    }
    registry.is_loaded.assert_not_called()
    registry.get.assert_not_called()


@pytest.mark.parametrize(
    ("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()["error"]["code"] == code
    assert response.json()["error"]["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 _sglang_body_config(default_sampling: dict[str, Any]) -> SimpleNamespace:
    profile = SimpleNamespace(runtime={"default_sampling": default_sampling}, loadtime={})
    return SimpleNamespace(
        tasks=SimpleNamespace(generate=SimpleNamespace(max_output_tokens=512, chat_template_kwargs={})),
        resolve_profile=MagicMock(return_value=profile),
    )


_CHAT_RECIPE = {"temperature": 0.7, "top_p": 0.8, "top_k": 20, "presence_penalty": 1.5}


def _prepare_body(body: dict[str, Any]) -> dict[str, Any]:
    adapter = SGLangGenerationAdapter(model_name_or_path="upstream/repo", served_model_name="served")
    return openai_local._prepare_sglang_body(
        body,
        config=_sglang_body_config(dict(_CHAT_RECIPE)),
        adapter=adapter,
        max_completion_tokens=body.get("max_completion_tokens"),
        max_tokens=None,
        seed=None,
    )


@pytest.mark.parametrize("format_type", ["json_schema", "json_object"])
def test_cuda_chat_response_format_defaults_to_greedy_without_penalties(format_type: str) -> None:
    response_format: dict[str, Any] = {"type": format_type}
    if format_type == "json_schema":
        response_format["json_schema"] = {"name": "record", "schema": {"type": "object"}}

    proxied = _prepare_body(
        {
            "messages": [{"role": "user", "content": "Extract"}],
            "max_completion_tokens": 64,
            "response_format": response_format,
        }
    )

    assert proxied["temperature"] == 0.0
    assert proxied["presence_penalty"] == 0.0
    assert proxied["frequency_penalty"] == 0.0
    assert proxied["top_p"] == 0.8
    assert proxied["top_k"] == 20


def test_cuda_chat_response_format_keeps_explicit_sampler_fields() -> None:
    proxied = _prepare_body(
        {
            "messages": [{"role": "user", "content": "Extract"}],
            "max_completion_tokens": 64,
            "temperature": 0.6,
            "presence_penalty": 0.5,
            "response_format": {"type": "json_schema", "json_schema": {"name": "r", "schema": {"type": "object"}}},
        }
    )

    assert proxied["temperature"] == 0.6
    assert proxied["presence_penalty"] == 0.5
    assert proxied["frequency_penalty"] == 0.0


@pytest.mark.parametrize("response_format", [None, {"type": "text"}])
def test_cuda_chat_without_grammar_keeps_profile_recipe(response_format: dict[str, Any] | None) -> None:
    body: dict[str, Any] = {"messages": [{"role": "user", "content": "Hi"}], "max_completion_tokens": 64}
    if response_format is not None:
        body["response_format"] = response_format

    proxied = _prepare_body(body)

    assert proxied["temperature"] == 0.7
    assert proxied["presence_penalty"] == 1.5
    assert "frequency_penalty" not in proxied


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"


@pytest.mark.parametrize("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


# SGLang's chat surface refusing a request whose input plus output cap does not fit its window.
_SGLANG_WINDOW_REFUSAL = {
    "object": "error",
    "message": (
        "Requested token count exceeds the model's maximum context length of 32768 tokens. You requested a total "
        "of 32898 tokens: 28802 tokens from the input messages and 4096 tokens for the completion. Please reduce "
        "the number of tokens in the input messages or the completion to fit within the limit."
    ),
    "type": "BadRequestError",
    "param": None,
    "code": 400,
}
_WINDOW_REFUSAL_ERROR = {
    "message": (
        "prompt_tokens (28802) + max_new_tokens (4096) = 32898 exceeds context_length (32768) "
        "for model 'Qwen/Qwen3.5-4B'"
    ),
    "type": "invalid_request_error",
    "param": "prompt",
    "code": "INPUT_TOO_LONG",
}


@pytest.mark.parametrize("stream", [False, True])
def test_cuda_chat_names_the_window_the_child_refused(
    monkeypatch: pytest.MonkeyPatch,
    caplog: pytest.LogCaptureFixture,
    stream: bool,
) -> None:
    client, _ = _cuda_chat_client(monkeypatch, lambda _request: httpx.Response(400, json=_SGLANG_WINDOW_REFUSAL))
    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": "Hello"}], "stream": stream},
        )

    assert response.status_code == 400, response.text
    assert response.json() == {"error": _WINDOW_REFUSAL_ERROR}
    assert "generation child chat error" not in caplog.text


@pytest.mark.parametrize(
    ("path", "body", "error"),
    [
        (
            "/v1/responses",
            {"model": "Qwen/Qwen3.5-4B", "input": "Hello"},
            {"error": _WINDOW_REFUSAL_ERROR},
        ),
        (
            "/v1/messages",
            {"model": "Qwen/Qwen3.5-4B", "max_tokens": 32, "messages": [{"role": "user", "content": "Hello"}]},
            {
                "type": "error",
                "error": {
                    "type": "invalid_request_error",
                    "message": "prompt is too long: 32898 tokens > 32768 maximum",
                },
            },
        ),
    ],
    ids=["responses", "messages"],
)
def test_cuda_chat_window_refusal_reaches_the_translated_routes(
    monkeypatch: pytest.MonkeyPatch, path: str, body: dict[str, Any], error: dict[str, Any]
) -> None:
    client, _ = _cuda_chat_client(monkeypatch, lambda _request: httpx.Response(400, json=_SGLANG_WINDOW_REFUSAL))
    client.app.include_router(openai_responses.router)
    client.app.include_router(anthropic_messages.router)

    response = client.post(path, json=body)

    assert response.status_code == 400, response.text
    assert {key: response.json()[key] for key in error} == error


@pytest.mark.parametrize(
    ("upstream_status", "body"),
    [
        (500, _SGLANG_WINDOW_REFUSAL),
        (400, {**_SGLANG_WINDOW_REFUSAL, "message": f"{_SGLANG_WINDOW_REFUSAL['message']} secret"}),
    ],
    ids=["engine failure status", "longer text"],
)
def test_cuda_chat_keeps_other_child_errors_opaque(
    monkeypatch: pytest.MonkeyPatch, upstream_status: int, body: dict[str, Any]
) -> None:
    client, _ = _cuda_chat_client(monkeypatch, lambda _request: httpx.Response(upstream_status, json=body))
    response = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3.5-4B", "messages": [{"role": "user", "content": "Hello"}]},
    )

    assert response.json()["error"]["code"] == "upstream_error"
    assert "secret" not in response.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()["error"] == {
        "code": "unsupported_field",
        "message": "field 'routed_dp_rank' is not supported",
        "param": "routed_dp_rank",
        "type": "invalid_request_error",
    }

    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()["error"]["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()["error"]["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()["error"]["param"] == "messages[0].content[1].image_url"
    registry.get.assert_not_called()


def _video_data_uri(tmp_path: Path, *, width: int = 64, height: int = 48, frames: int = 6) -> str:
    path = tmp_path / "clip.mp4"
    writer = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), 10.0, (width, height))
    for index in range(frames):
        writer.write(np.full((height, width, 3), index * 40, dtype=np.uint8))
    writer.release()
    return "data:video/mp4;base64," + base64.b64encode(path.read_bytes()).decode()


def _video_messages(video_url: Any, *, parts: int = 1) -> list[dict[str, Any]]:
    content: list[dict[str, Any]] = [{"type": "text", "text": "What happens first?"}]
    content += [{"type": "video_url", "video_url": video_url} for _ in range(parts)]
    return [{"role": "user", "content": content}]


def test_cuda_chat_forwards_inline_video_unchanged(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    seen: dict[str, Any] = {}

    def _handler(request: httpx.Request) -> httpx.Response:
        seen["body"] = json.loads(request.content)
        return httpx.Response(
            200,
            json={
                "id": "chatcmpl-video",
                "object": "chat.completion",
                "created": 1,
                "model": "upstream-served-model",
                "choices": [
                    {
                        "index": 0,
                        "message": {"role": "assistant", "content": "A ball rolls."},
                        "finish_reason": "stop",
                    }
                ],
            },
        )

    client, _ = _cuda_chat_client(monkeypatch, _handler, video=True)
    messages = _video_messages({"url": _video_data_uri(tmp_path)})
    response = client.post("/v1/chat/completions", json={"model": "Qwen/Qwen3.5-4B", "messages": messages})

    assert response.status_code == 200
    assert seen["body"]["messages"] == messages


def test_cuda_chat_rejects_video_for_model_without_video_input(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    client, registry = _cuda_chat_client(
        monkeypatch,
        lambda _request: pytest.fail("video request must not reach upstream"),
    )
    response = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3.5-4B", "messages": _video_messages({"url": _video_data_uri(tmp_path)})},
    )

    assert response.status_code == 400
    assert response.json()["error"]["code"] == "unsupported_field"
    assert response.json()["error"]["param"] == "messages"
    registry.get.assert_not_called()


def test_mlx_chat_rejects_video(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    client, registry = _mlx_chat_client(
        monkeypatch,
        lambda _request: pytest.fail("video request must not reach upstream"),
        chat_template_kwargs={"enable_thinking": False},
    )
    registry.get_config.return_value.inputs = SimpleNamespace(video=True)
    response = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3.5-4B", "messages": _video_messages({"url": _video_data_uri(tmp_path)})},
    )

    assert response.status_code == 400
    assert response.json()["error"]["code"] == "unsupported_field"
    registry.get.assert_not_called()


@pytest.mark.parametrize(
    "video_url",
    [
        {"url": "https://example.com/clip.mp4"},
        {"url": "http://169.254.169.254/latest/meta-data/"},
        "file:///etc/passwd",
        {"url": "data:image/png;base64,iVBORw0KGgo="},
        {"url": "data:video/mp4,AAAA"},
        {"url": "data:video/mp4;base64"},
        {"url": "data:video/mp4;base64,not base64!"},
        {"url": "data:video/mp4;base64,"},
        {"url": ""},
        {},
        "data:video/mp4;base64,AAAAGGZ0eXBpc29t",
        {"url": "data:video/mp4;base64,AAAAGGZ0eXBpc29t", "max_dynamic_patch": 64},
        {"url": "data:video/mp4;base64, AAAAGGZ0eXBpc29t"},
        {
            "url": "data:video/mp4;base64,"
            + base64.b64encode(b"#EXTM3U\n#EXTINF:10,\nhttp://169.254.169.254/a.ts\n").decode()
        },
        {"url": "data:video/mp4;base64,AAAA"},
        {"url": "data:video/;base64,AAAAGGZ0eXBpc29t"},
    ],
)
def test_cuda_chat_rejects_invalid_video_before_model_lookup(
    monkeypatch: pytest.MonkeyPatch,
    video_url: Any,
) -> None:
    client, registry = _cuda_chat_client(
        monkeypatch,
        lambda _request: pytest.fail("invalid video must not reach upstream"),
        video=True,
    )
    response = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3.5-4B", "messages": _video_messages(video_url)},
    )

    assert response.status_code == 400
    assert response.json()["error"]["param"] == "messages[0].content[1].video_url"
    registry.get_config.assert_not_called()
    registry.get.assert_not_called()


def test_cuda_chat_rejects_oversized_video_before_decoding(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    video = _video_data_uri(tmp_path)
    monkeypatch.setattr(openai_local, "MAX_VIDEO_BYTES", 8)
    client, registry = _cuda_chat_client(
        monkeypatch,
        lambda _request: pytest.fail("oversized video must not reach upstream"),
        video=True,
    )
    response = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3.5-4B", "messages": _video_messages({"url": video})},
    )

    assert response.status_code == 400
    assert "video too large" in response.json()["error"]["message"]
    registry.get.assert_not_called()


def test_cuda_chat_rejects_second_video_part(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
    client, registry = _cuda_chat_client(
        monkeypatch,
        lambda _request: pytest.fail("second video must not reach upstream"),
        video=True,
    )
    response = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3.5-4B", "messages": _video_messages({"url": _video_data_uri(tmp_path)}, parts=2)},
    )

    assert response.status_code == 400
    assert response.json()["error"]["param"] == "messages[0].content[2].video_url"
    registry.get_config.assert_not_called()


@pytest.mark.parametrize(
    ("limit", "value", "message"),
    [
        ("MAX_GENERATION_VIDEO_FRAME_PIXELS", 64 * 47, "exceeds the 3008-pixel frame limit"),
        ("MAX_VIDEO_DURATION_S", 0.1, "admission cap"),
        ("MAX_GENERATION_VIDEO_FRAMES", 5, "frame cap"),
        ("MAX_GENERATION_VIDEO_FPS", 5.0, "fps cap"),
    ],
)
def test_cuda_chat_rejects_video_over_decode_bounds_before_model_load(
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
    limit: str,
    value: float,
    message: str,
) -> None:
    monkeypatch.setattr(video_frames, limit, value)
    client, registry = _cuda_chat_client(
        monkeypatch,
        lambda _request: pytest.fail("unbounded video must not reach upstream"),
        video=True,
    )
    response = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3.5-4B", "messages": _video_messages({"url": _video_data_uri(tmp_path)})},
    )

    assert response.status_code == 400
    assert message in response.json()["error"]["message"]
    assert response.json()["error"]["param"] == "messages[0].content[1].video_url"
    registry.get.assert_not_called()


def test_cuda_chat_rejects_undecodable_video_container(monkeypatch: pytest.MonkeyPatch) -> None:
    client, registry = _cuda_chat_client(
        monkeypatch,
        lambda _request: pytest.fail("undecodable video must not reach upstream"),
        video=True,
    )
    garbage = base64.b64encode(b"\x00\x00\x00\x18ftypisom" + b"\x00" * 64).decode()
    response = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3.5-4B", "messages": _video_messages({"url": f"data:video/mp4;base64,{garbage}"})},
    )

    assert response.status_code == 400
    assert response.json()["error"]["param"] == "messages[0].content[1].video_url"
    registry.get.assert_not_called()


def test_cuda_chat_still_rejects_audio(monkeypatch: pytest.MonkeyPatch) -> None:
    client, registry = _cuda_chat_client(
        monkeypatch,
        lambda _request: pytest.fail("audio must not reach upstream"),
        video=True,
    )
    messages = [
        {
            "role": "user",
            "content": [{"type": "audio_url", "audio_url": {"url": "data:audio/wav;base64,UklGRg=="}}],
        }
    ]
    response = client.post("/v1/chat/completions", json={"model": "Qwen/Qwen3.5-4B", "messages": messages})

    assert response.status_code == 400
    registry.get.assert_not_called()


@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize("reasoning_field", ["reasoning_content", "reasoning"])
@pytest.mark.parametrize("enable_thinking", [None, False, True])
def test_cuda_chat_drops_private_reasoning_logprobs_without_relying_on_thinking_policy(
    monkeypatch: pytest.MonkeyPatch,
    stream: bool,
    reasoning_field: str,
    enable_thinking: bool | None,
) -> None:
    container_key = "delta" if stream else "message"
    body = {
        "id": "chatcmpl-private-logprobs",
        "object": "chat.completion.chunk" if stream else "chat.completion",
        "created": 1,
        "model": "upstream-served-model",
        "choices": [
            {
                "index": 0,
                container_key: {"role": "assistant", "content": "Visible answer", reasoning_field: "private chain"},
                "logprobs": {"content": [{"token": "PRIVATE_REASONING", "logprob": -0.1}]},
                "finish_reason": "stop",
            }
        ],
    }

    def _handler(_request: httpx.Request) -> httpx.Response:
        if stream:
            wire = f"data: {json.dumps(body)}\n\ndata: [DONE]\n\n".encode()
            return httpx.Response(
                200,
                stream=_ChunkedAsyncStream([wire[:41], wire[41:]]),
                headers={"content-type": "text/event-stream"},
            )
        return httpx.Response(200, json=body)

    client, _ = _cuda_chat_client(
        monkeypatch,
        _handler,
        reasoning_parser="qwen3",
        chat_template_kwargs=None if enable_thinking is None else {"enable_thinking": enable_thinking},
    )
    response = client.post(
        "/v1/chat/completions",
        json={
            "model": "Qwen/Qwen3.5-4B",
            "messages": [{"role": "user", "content": "Hello"}],
            "logprobs": True,
            "stream": stream,
        },
    )

    assert response.status_code == 200
    payload = json.loads(response.text.split("\n\n")[0].removeprefix("data: ")) if stream else response.json()
    choice = payload["choices"][0]
    assert choice[container_key] == {"role": "assistant", "content": "Visible answer"}
    assert choice["logprobs"] is None
    assert "PRIVATE_REASONING" not in response.text
    assert "private chain" not in response.text


@pytest.mark.parametrize("reasoning_field", ["reasoning_content", "reasoning"])
@pytest.mark.parametrize("reasoning_value", [None, ""])
def test_cuda_chat_preserves_visible_logprobs_when_reasoning_is_empty(
    monkeypatch: pytest.MonkeyPatch,
    reasoning_field: str,
    reasoning_value: str | None,
) -> 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_field: reasoning_value,
                        },
                        "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 ----------------------------------------------------


def test_rerank_requires_model() -> None:
    r = _client().post("/v1/rerank", json={"query": "q", "documents": ["a"]})
    assert r.status_code == 400
    assert r.json()["error"]["param"] == "model"


def test_rerank_requires_query() -> None:
    r = _client().post("/v1/rerank", json={"model": "m", "documents": ["a"]})
    assert r.status_code == 400
    assert r.json()["error"]["param"] == "query"


def test_rerank_rejects_blank_model_and_query() -> None:
    for body, param in [
        ({"model": "   ", "query": "q", "documents": ["a"]}, "model"),
        ({"model": "m", "query": "   ", "documents": ["a"]}, "query"),
    ]:
        r = _client().post("/v1/rerank", json=body)
        assert r.status_code == 400
        assert r.json()["error"]["param"] == param


def test_rerank_requires_nonempty_string_documents() -> None:
    for docs in ([], "not-a-list", [1, 2], ["ok", 3], ["   "]):
        r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": docs})
        assert r.status_code == 400, docs
        assert r.json()["error"]["param"] == "documents"


def test_rerank_top_n_must_be_positive_int() -> None:
    for bad in (0, -1, "3", True):
        r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": ["a"], "top_n": bad})
        assert r.status_code == 400, bad
        assert r.json()["error"]["param"] == "top_n"


def test_rerank_rejects_too_many_documents() -> None:
    docs = ["d"] * (openai_local._MAX_RERANK_DOCS + 1)
    r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": docs})
    assert r.status_code == 400
    assert r.json()["error"]["param"] == "documents"


def test_rerank_rejects_texts_over_the_item_text_cap() -> None:
    long_text = "x" * (MAX_ITEM_TEXT_BYTES + 1)
    for body, param, field in [
        ({"model": "m", "query": long_text, "documents": ["a"]}, "query", "query"),
        ({"model": "m", "query": "q", "documents": ["a", long_text]}, "documents", "documents[1]"),
    ]:
        r = _client().post("/v1/rerank", json=body)
        assert r.status_code == 400, field
        error = r.json()["error"]
        assert error["param"] == param
        assert error["code"] == "INVALID_INPUT"
        assert error["message"] == f"Field '{field}' must hold at most {MAX_ITEM_TEXT_BYTES} bytes of UTF-8 text"


def test_rerank_rejects_non_bool_return_documents() -> None:
    r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": ["a"], "return_documents": "true"})
    assert r.status_code == 400
    assert r.json()["error"]["param"] == "return_documents"


def test_rerank_rejects_unknown_fields() -> None:
    r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": ["a"], "priority": 1})
    assert r.status_code == 400
    assert r.json()["error"]["param"] == "priority"


# -- top-level OpenAI error envelope (no {"detail": ...} wrapper) -------------


def test_chat_unknown_model_returns_top_level_openai_error() -> None:
    client = _client()
    client.app.state.registry.has_model.return_value = False
    r = client.post(
        "/v1/chat/completions",
        json={"model": "missing-model", "messages": [{"role": "user", "content": "hi"}]},
    )
    assert r.status_code == 404
    body = r.json()
    assert "detail" not in body
    error = body["error"]
    assert error["code"] == "MODEL_NOT_FOUND"
    assert error["type"] == "invalid_request_error"
    assert "message" in error


def test_chat_invalid_input_returns_top_level_openai_error() -> None:
    r = _client().post("/v1/chat/completions", json={"model": "m", "messages": []})
    assert r.status_code == 400
    body = r.json()
    assert "detail" not in body
    error = body["error"]
    assert error["param"] == "messages"
    assert error["type"] == "invalid_request_error"
    assert error["code"] == "INVALID_INPUT"
    assert "message" in error


def test_chat_unloading_model_returns_top_level_openai_server_error(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    client, registry = _cuda_chat_client(
        monkeypatch,
        lambda _request: pytest.fail("unloading model must not reach upstream"),
    )
    registry.is_unloading.return_value = True
    r = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3.5-4B", "messages": [{"role": "user", "content": "hi"}]},
    )
    assert r.status_code == 503
    body = r.json()
    assert "detail" not in body
    error = body["error"]
    assert error["code"] == "MODEL_NOT_LOADED"
    assert error["type"] == "server_error"
    assert "message" in error


def _rerank_client() -> tuple[TestClient, MagicMock]:
    """Rerank client whose registry passes all model-state checks."""
    profile = SimpleNamespace(runtime={}, loadtime={})
    config = SimpleNamespace(
        tasks=SimpleNamespace(generate=None, score=SimpleNamespace()),
        resolve_profile=MagicMock(return_value=profile),
        profiles={},
        routing=None,
    )
    registry = MagicMock()
    registry.device = "cpu"
    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
    client = _client()
    client.app.state.registry = registry
    return client, registry


def test_rerank_unknown_model_returns_top_level_openai_error() -> None:
    client = _client()
    client.app.state.registry.has_model.return_value = False
    r = client.post("/v1/rerank", json={"model": "missing-model", "query": "q", "documents": ["a"]})
    assert r.status_code == 404
    body = r.json()
    assert "detail" not in body
    error = body["error"]
    assert error["code"] == "MODEL_NOT_FOUND"
    assert error["type"] == "invalid_request_error"
    assert "message" in error


def test_rerank_invalid_input_returns_top_level_openai_error() -> None:
    r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": []})
    assert r.status_code == 400
    body = r.json()
    assert "detail" not in body
    error = body["error"]
    assert error["param"] == "documents"
    assert error["type"] == "invalid_request_error"
    assert error["code"] == "INVALID_INPUT"
    assert "message" in error


def test_rerank_inference_error_returns_top_level_openai_500() -> None:
    client, registry = _rerank_client()

    async def _boom() -> None:
        raise RuntimeError("sensitive reranker detail")

    worker = MagicMock()
    worker.submit_score = AsyncMock(return_value=_boom())
    registry.start_worker = AsyncMock(return_value=worker)

    r = client.post("/v1/rerank", json={"model": "m", "query": "q", "documents": ["a"]})
    assert r.status_code == 500
    body = r.json()
    assert "detail" not in body
    error = body["error"]
    assert error["code"] == "inference_error"
    assert error["type"] == "server_error"
    assert error["message"] == "internal error during reranking"
    assert "sensitive reranker detail" not in r.text


@pytest.mark.parametrize("bad", [float("nan"), float("inf"), float("-inf")])
def test_rerank_non_finite_scores_return_top_level_openai_500(bad: float) -> None:
    """NaN/inf model scores fail closed as an enveloped 500 naming the model.

    Regression for pass-2 audit A2: on this JSON-only surface a NaN score
    crashed json.dumps ("Out of range float values are not JSON compliant")
    into a bare, un-enveloped 500 with no OpenAI error object.
    """
    client, registry = _rerank_client()

    async def _result() -> WorkerResult:
        return WorkerResult(
            output=ScoreOutput(scores=np.array([0.9, bad], dtype=np.float32)),
            timing=RequestTiming(),
        )

    worker = MagicMock()
    worker.submit_score = AsyncMock(return_value=_result())
    registry.start_worker = AsyncMock(return_value=worker)

    r = client.post("/v1/rerank", json={"model": "m", "query": "q", "documents": ["a", "b"]})
    assert r.status_code == 500
    body = r.json()
    assert "detail" not in body  # enveloped OpenAI error, not FastAPI's {"detail": ...}
    error = body["error"]
    assert error["code"] == "INFERENCE_ERROR"
    assert error["type"] == "server_error"
    assert "m" in error["message"]
    assert "non-finite" in error["message"]


_STRICT_RESPONSE_FORMAT = {
    "type": "json_schema",
    "json_schema": {
        "name": "answer",
        "strict": True,
        "schema": {
            "type": "object",
            "properties": {"answer": {"type": "string"}},
            "required": ["answer"],
            "additionalProperties": False,
        },
    },
}


def _chat_completion(
    content: str | None, *, finish_reason: str = "stop", tool_calls: list[Any] | None = None
) -> dict[str, Any]:
    message: dict[str, Any] = {"role": "assistant", "content": content}
    if tool_calls is not None:
        message["tool_calls"] = tool_calls
    return {
        "id": "chatcmpl-strict",
        "object": "chat.completion",
        "created": 1,
        "model": "upstream-served-model",
        "choices": [{"index": 0, "message": message, "logprobs": None, "finish_reason": finish_reason}],
        "usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7},
    }


def _chat_stream(*contents: str) -> bytes:
    events: list[dict[str, Any]] = [
        {
            "id": "chatcmpl-strict",
            "object": "chat.completion.chunk",
            "created": 1,
            "model": "upstream-served-model",
            "choices": [{"index": 0, "delta": {"content": content}, "finish_reason": None}],
        }
        for content in contents
    ]
    events.append(
        {
            "id": "chatcmpl-strict",
            "object": "chat.completion.chunk",
            "created": 1,
            "model": "upstream-served-model",
            "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
        }
    )
    return b"".join(f"data: {json.dumps(event)}\n\n".encode() for event in events) + b"data: [DONE]\n\n"


def _chat_request(response_format: dict[str, Any], *, stream: bool = False) -> dict[str, Any]:
    return {
        "model": "Qwen/Qwen3-0.6B",
        "messages": [{"role": "user", "content": "Answer in JSON"}],
        "max_tokens": 8,
        "stream": stream,
        "response_format": response_format,
    }


def test_cuda_chat_strict_schema_violation_returns_a_typed_error(monkeypatch: pytest.MonkeyPatch) -> None:
    client, _ = _cuda_chat_client(
        monkeypatch, lambda _request: httpx.Response(200, json=_chat_completion('{"answer": 3}'))
    )

    response = client.post("/v1/chat/completions", json=_chat_request(_STRICT_RESPONSE_FORMAT))

    assert response.status_code == 500
    assert response.json() == {
        "error": {
            "message": "generated output does not match the requested JSON schema at $.answer ('type' keyword)",
            "type": "server_error",
            "param": None,
            "code": "MODEL_OUTPUT_PARSE_ERROR",
        }
    }


def test_cuda_chat_strict_schema_violation_errors_the_stream(monkeypatch: pytest.MonkeyPatch) -> None:
    upstream_stream = _ChunkedAsyncStream([_chat_stream('{"answer"', ": 3}")])

    def _handler(_request: httpx.Request) -> httpx.Response:
        return httpx.Response(200, stream=upstream_stream, headers={"content-type": "text/event-stream"})

    client, _ = _cuda_chat_client(monkeypatch, _handler)

    response = client.post("/v1/chat/completions", json=_chat_request(_STRICT_RESPONSE_FORMAT, stream=True))

    assert response.status_code == 200
    data_lines = [line.removeprefix("data: ") for line in response.text.splitlines() if line.startswith("data: ")]
    assert data_lines[-1] == "[DONE]"
    events = [json.loads(line) for line in data_lines[:-1]]
    assert "".join(event["choices"][0]["delta"].get("content", "") for event in events[:-1]) == '{"answer": 3}'
    assert events[-1] == {
        "error": {
            "message": "generated output does not match the requested JSON schema at $.answer ('type' keyword)",
            "type": "server_error",
            "param": None,
            "code": "MODEL_OUTPUT_PARSE_ERROR",
        }
    }
    assert '"finish_reason": "stop"' not in response.text
    assert upstream_stream.closed is True


@pytest.mark.parametrize("stream", [False, True])
def test_cuda_chat_conforming_strict_output_is_returned(monkeypatch: pytest.MonkeyPatch, stream: bool) -> None:
    def _handler(_request: httpx.Request) -> httpx.Response:
        if stream:
            return httpx.Response(
                200,
                stream=_ChunkedAsyncStream([_chat_stream('{"answer": ', '"yes"}')]),
                headers={"content-type": "text/event-stream"},
            )
        return httpx.Response(200, json=_chat_completion('{"answer": "yes"}'))

    client, _ = _cuda_chat_client(monkeypatch, _handler)

    response = client.post("/v1/chat/completions", json=_chat_request(_STRICT_RESPONSE_FORMAT, stream=stream))

    assert response.status_code == 200
    assert "MODEL_OUTPUT_PARSE_ERROR" not in response.text
    if not stream:
        assert response.json()["choices"][0]["message"]["content"] == '{"answer": "yes"}'


@pytest.mark.parametrize(
    "response_format",
    [
        {**_STRICT_RESPONSE_FORMAT, "json_schema": {**_STRICT_RESPONSE_FORMAT["json_schema"], "strict": False}},
        {"type": "json_schema", "json_schema": {"name": "answer", "schema": {"type": "object"}}},
        {"type": "json_object"},
    ],
)
def test_cuda_chat_non_strict_response_format_is_not_verified(
    monkeypatch: pytest.MonkeyPatch,
    response_format: dict[str, Any],
) -> None:
    client, _ = _cuda_chat_client(monkeypatch, lambda _request: httpx.Response(200, json=_chat_completion("[]")))

    response = client.post("/v1/chat/completions", json=_chat_request(response_format))

    assert response.status_code == 200
    assert response.json()["choices"][0]["message"]["content"] == "[]"


@pytest.mark.parametrize("finish_reason", ["length", "tool_calls"])
def test_cuda_chat_strict_output_skips_truncated_and_tool_call_turns(
    monkeypatch: pytest.MonkeyPatch,
    finish_reason: str,
) -> None:
    tool_calls = (
        [{"id": "call_1", "type": "function", "function": {"name": "lookup", "arguments": "{}"}}]
        if finish_reason == "tool_calls"
        else None
    )
    body = _chat_completion(
        '{"answer"' if finish_reason == "length" else None, finish_reason=finish_reason, tool_calls=tool_calls
    )
    client, _ = _cuda_chat_client(monkeypatch, lambda _request: httpx.Response(200, json=body))

    response = client.post("/v1/chat/completions", json=_chat_request(_STRICT_RESPONSE_FORMAT))

    assert response.status_code == 200
    assert response.json()["choices"][0]["finish_reason"] == finish_reason


def _serve_grammar_routed_configs(registry: MagicMock, *, without: tuple[str, ...] = ()) -> None:
    config = ModelConfig.model_validate(
        {
            "sie_id": "Qwen/Qwen3.5-4B",
            "hf_id": "Qwen/Qwen3.5-4B",
            "inputs": {"text": True},
            "tasks": {
                "generate": {
                    "context_length": 4096,
                    "max_output_tokens": 64,
                    "grammar_profile": "no-spec",
                    "capabilities": {"grammar": ["json_schema"]},
                }
            },
            "profiles": {
                "default": {
                    "max_batch_tokens": 4096,
                    "kv_budget_tokens": 2048,
                    "adapter_path": "sie_server.adapters.sglang.generation:SGLangGenerationAdapter",
                    "adapter_options": {"loadtime": {"speculative": {"algorithm": "NEXTN", "num_steps": 3}}},
                },
                "no-spec": {
                    "extends": "default",
                    "adapter_options": {"loadtime": {"speculative": {"enabled": False}}},
                },
            },
        }
    )
    configs = {name: value for name, value in expand_profile_variants([config]).items() if name not in without}
    registry.has_model.side_effect = configs.__contains__
    registry.get_config.side_effect = configs.__getitem__


def test_cuda_chat_refuses_strict_tools_before_the_child(monkeypatch: pytest.MonkeyPatch) -> None:
    """SGLang's own chat endpoint does not constrain tool arguments, so the direct route refuses strict tools."""

    def _handler(_request: httpx.Request) -> httpx.Response:
        raise AssertionError("a strict tool must not reach the child")

    client, _registry = _cuda_chat_client(monkeypatch, _handler)
    strict_tool = {**_WEATHER_TOOL, "function": {**_WEATHER_TOOL["function"], "strict": True}}
    response = client.post(
        "/v1/chat/completions",
        json={"model": "upstream/repo", "messages": [{"role": "user", "content": "hi"}], "tools": [strict_tool]},
    )

    assert response.status_code == 400
    error = response.json()["error"]
    assert error["code"] == "unsupported_field"
    assert error["param"] == "tools[0].function.strict"


def test_cuda_chat_strict_schema_with_unevaluated_properties_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:
    def _handler(_request: httpx.Request) -> httpx.Response:
        raise AssertionError("an unverifiable strict schema must not reach the child")

    client, registry = _cuda_chat_client(monkeypatch, _handler)
    response_format = {
        "type": "json_schema",
        "json_schema": {
            "name": "answer",
            "strict": True,
            "schema": {"type": "object", "unevaluatedProperties": False},
        },
    }

    response = client.post("/v1/chat/completions", json=_chat_request(response_format))

    assert response.status_code == 400
    error = response.json()["error"]
    assert error["code"] == "unsupported_field"
    assert error["param"] == "response_format"
    registry.get.assert_not_called()


def test_cuda_chat_response_format_runs_on_the_grammar_profile(monkeypatch: pytest.MonkeyPatch) -> None:
    seen: dict[str, Any] = {}

    def _handler(request: httpx.Request) -> httpx.Response:
        seen["body"] = json.loads(request.content)
        return httpx.Response(200, json=_chat_completion('{"answer": "yes"}'))

    client, registry = _cuda_chat_client(monkeypatch, _handler)
    _serve_grammar_routed_configs(registry)
    request = {**_chat_request(_STRICT_RESPONSE_FORMAT), "model": "Qwen/Qwen3.5-4B"}

    response = client.post("/v1/chat/completions", json=request)

    assert response.status_code == 200, response.text
    registry.get.assert_called_once_with("Qwen/Qwen3.5-4B:no-spec")
    assert response.json()["model"] == "Qwen/Qwen3.5-4B"
    assert seen["body"]["response_format"] == _STRICT_RESPONSE_FORMAT

    registry.get.reset_mock()
    plain = {key: value for key, value in request.items() if key != "response_format"}
    assert client.post("/v1/chat/completions", json=plain).status_code == 200
    registry.get.assert_called_once_with("Qwen/Qwen3.5-4B")


def test_cuda_chat_response_format_without_its_grammar_profile_is_rejected(monkeypatch: pytest.MonkeyPatch) -> None:
    def _handler(_request: httpx.Request) -> httpx.Response:
        raise AssertionError("a request without a grammar-safe profile must not reach the child")

    client, registry = _cuda_chat_client(monkeypatch, _handler)
    _serve_grammar_routed_configs(registry, without=("Qwen/Qwen3.5-4B:no-spec",))

    response = client.post(
        "/v1/chat/completions",
        json={**_chat_request(_STRICT_RESPONSE_FORMAT), "model": "Qwen/Qwen3.5-4B"},
    )

    assert response.status_code == 400
    error = response.json()["error"]
    assert error["code"] == "unsupported_field"
    assert error["param"] == "response_format"
    assert "'no-spec'" in error["message"]
    registry.get.assert_not_called()


# -- /v1/chat/completions include_reasoning ---------------------------------


def _reasoning_child_payload(content: str, *, reasoning_content: str | None = None) -> dict[str, Any]:
    message: dict[str, Any] = {"role": "assistant", "content": content}
    if reasoning_content is not None:
        message["reasoning_content"] = reasoning_content
    return {
        "id": "chatcmpl-test",
        "object": "chat.completion",
        "created": 1,
        "model": "upstream-served-model",
        "choices": [
            {
                "index": 0,
                "message": message,
                "logprobs": {"content": [{"token": "Visible", "logprob": -0.1, "bytes": None, "top_logprobs": []}]},
                "finish_reason": "stop",
            }
        ],
        "usage": {"prompt_tokens": 3, "completion_tokens": 4, "total_tokens": 7},
    }


def _stream_event(delta: dict[str, Any], *, finish_reason: str | None = None) -> dict[str, Any]:
    return {
        "id": "chatcmpl-stream",
        "object": "chat.completion.chunk",
        "created": 1,
        "model": "upstream-served-model",
        "choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}],
    }


@pytest.mark.parametrize(
    ("declares_reasoning", "include_reasoning", "expected"),
    [(True, True, "private chain"), (True, False, None), (False, True, None)],
)
def test_cuda_chat_blocking_publishes_parser_reasoning_only_when_asked(
    monkeypatch: pytest.MonkeyPatch, declares_reasoning: bool, include_reasoning: bool, expected: str | None
) -> None:
    seen: dict[str, Any] = {}

    def _handler(request: httpx.Request) -> httpx.Response:
        seen["body"] = json.loads(request.content)
        return httpx.Response(200, json=_reasoning_child_payload("Visible answer", reasoning_content="private chain"))

    client, _ = _cuda_chat_client(
        monkeypatch,
        _handler,
        reasoning_parser="qwen3",
        chat_template_kwargs={"enable_thinking": True} if declares_reasoning else {},
    )
    body: dict[str, Any] = {"model": "Qwen/Qwen3-0.6B", "messages": [{"role": "user", "content": "Hello"}]}
    if include_reasoning:
        body["include_reasoning"] = True

    response = client.post("/v1/chat/completions", json=body)

    assert response.status_code == 200
    assert "include_reasoning" not in seen["body"]
    payload = response.json()
    assert payload["choices"][0]["message"]["content"] == "Visible answer"
    assert payload["choices"][0]["message"].get("reasoning_content") == expected
    assert payload["choices"][0]["logprobs"] is None
    assert payload["usage"]["completion_tokens"] == 4


@pytest.mark.parametrize("parser", [False, True])
def test_cuda_chat_stream_publishes_split_reasoning_when_asked(monkeypatch: pytest.MonkeyPatch, parser: bool) -> None:
    reasoning_deltas = (
        [
            _stream_event({"reasoning_content": "private ", "content": ""}),
            _stream_event({"reasoning_content": "chain"}),
            _stream_event({"content": "Visible answer"}),
        ]
        if parser
        else [
            _stream_event({"content": "private chain</thi"}),
            _stream_event({"content": "nk>Visible answer"}),
        ]
    )
    events = [
        _stream_event({"role": "assistant", "content": ""}),
        *reasoning_deltas,
        _stream_event({}, 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[: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,
        reasoning_parser="qwen3" if parser else None,
        chat_template_kwargs={"enable_thinking": True},
    )
    response = client.post(
        "/v1/chat/completions",
        json={
            "model": "Qwen/Qwen3-0.6B:thinking",
            "messages": [{"role": "user", "content": "Hello"}],
            "max_tokens": 8,
            "stream": True,
            "include_reasoning": True,
        },
    )

    assert response.status_code == 200
    data_lines = [line.removeprefix("data: ") for line in response.text.splitlines() if line.startswith("data: ")]
    assert data_lines[-1] == "[DONE]"
    deltas = [json.loads(line)["choices"][0]["delta"] for line in data_lines[:-1]]
    assert "".join(delta.get("content", "") for delta in deltas) == "Visible answer"
    assert "".join(delta.get("reasoning_content", "") for delta in deltas) == "private chain"
    assert "</think>" not in response.text
    assert upstream_stream.closed is True


def test_mlx_chat_publishes_raw_tag_reasoning_when_asked(monkeypatch: pytest.MonkeyPatch) -> None:
    seen: dict[str, Any] = {}

    def _handler(request: httpx.Request) -> httpx.Response:
        seen["body"] = json.loads(request.content)
        return httpx.Response(
            200,
            json={
                "id": "chatcmpl-mlx",
                "object": "chat.completion",
                "created": 1,
                "model": "mlx-community/Qwen3.5-4B-4bit",
                "choices": [
                    {
                        "index": 0,
                        "message": {
                            "role": "assistant",
                            "content": "<think>private default reasoning</think>Visible answer",
                        },
                        "finish_reason": "stop",
                    }
                ],
                "usage": {"prompt_tokens": 3, "completion_tokens": 9, "total_tokens": 12},
            },
        )

    client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={"enable_thinking": False})
    response = client.post(
        "/v1/chat/completions",
        json={
            "model": "Qwen/Qwen3.5-4B",
            "messages": [{"role": "user", "content": "Hello"}],
            "include_reasoning": True,
        },
    )

    assert response.status_code == 200
    assert "include_reasoning" not in seen["body"]
    message = response.json()["choices"][0]["message"]
    assert message["content"] == "Visible answer"
    assert message["reasoning_content"] == "private default reasoning"


def test_chat_rejects_a_non_boolean_include_reasoning(monkeypatch: pytest.MonkeyPatch) -> None:
    client, registry = _cuda_chat_client(monkeypatch, lambda _request: httpx.Response(500))

    response = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3-0.6B", "messages": [{"role": "user", "content": "Hi"}], "include_reasoning": "yes"},
    )

    assert response.status_code == 400
    assert response.json()["error"]["param"] == "include_reasoning"
    registry.get.assert_not_called()


def _sse_wire(events: list[dict[str, Any]]) -> bytes:
    return b"".join(f"data: {json.dumps(event)}\n\n".encode() for event in events) + b"data: [DONE]\n\n"


def _sse_deltas(response_text: str) -> list[dict[str, Any]]:
    lines = [line.removeprefix("data: ") for line in response_text.splitlines() if line.startswith("data: ")]
    assert lines[-1] == "[DONE]"
    return [json.loads(line)["choices"][0]["delta"] for line in lines[:-1]]


@pytest.mark.parametrize(
    ("parsed", "content", "expected_reasoning", "expected_content"),
    [
        ("A", "x<think>B</think>y", "AB", "xy"),
        ("same", "<think>same</think>answer", "same", "answer"),
    ],
)
def test_cuda_chat_answers_parser_and_raw_tag_reasoning_without_losing_either(
    monkeypatch: pytest.MonkeyPatch, parsed: str, content: str, expected_reasoning: str, expected_content: str
) -> None:
    client, _ = _cuda_chat_client(
        monkeypatch,
        lambda _request: httpx.Response(200, json=_reasoning_child_payload(content, reasoning_content=parsed)),
        reasoning_parser="qwen3",
        chat_template_kwargs={"enable_thinking": True},
    )

    response = client.post(
        "/v1/chat/completions",
        json={
            "model": "Qwen/Qwen3-0.6B",
            "messages": [{"role": "user", "content": "Hello"}],
            "include_reasoning": True,
        },
    )

    assert response.status_code == 200
    message = response.json()["choices"][0]["message"]
    assert message["reasoning_content"] == expected_reasoning
    assert message["content"] == expected_content


@pytest.mark.parametrize("stream", [False, True])
def test_cuda_chat_with_tools_answers_reasoning_beside_the_calls(monkeypatch: pytest.MonkeyPatch, stream: bool) -> None:
    call = {"id": "call-1", "type": "function", "function": {"name": "lookup", "arguments": '{"q":"x"}'}}
    seen: dict[str, Any] = {}

    def _handler(request: httpx.Request) -> httpx.Response:
        seen["body"] = json.loads(request.content)
        if not stream:
            payload = _reasoning_child_payload("", reasoning_content="need a lookup")
            payload["choices"][0]["message"].update(content=None, tool_calls=[call])
            payload["choices"][0]["finish_reason"] = "tool_calls"
            return httpx.Response(200, json=payload)
        wire = _sse_wire(
            [
                _stream_event({"role": "assistant", "content": ""}),
                _stream_event({"reasoning_content": "need a lookup"}),
                _stream_event({"tool_calls": [{"index": 0, **call}]}),
                _stream_event({}, finish_reason="tool_calls"),
            ]
        )
        return httpx.Response(200, stream=_ChunkedAsyncStream([wire]), headers={"content-type": "text/event-stream"})

    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-0.6B",
            "messages": [{"role": "user", "content": "Look it up"}],
            "tools": [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}],
            "stream": stream,
            "include_reasoning": True,
        },
    )

    assert response.status_code == 200
    assert "include_reasoning" not in seen["body"]
    assert seen["body"]["tools"][0]["function"]["name"] == "lookup"
    if stream:
        deltas = _sse_deltas(response.text)
        assert "".join(delta.get("reasoning_content", "") for delta in deltas) == "need a lookup"
        assert [delta["tool_calls"][0]["function"]["name"] for delta in deltas if delta.get("tool_calls")] == ["lookup"]
    else:
        message = response.json()["choices"][0]["message"]
        assert message["reasoning_content"] == "need a lookup"
        assert message["tool_calls"][0]["function"] == call["function"]
        assert response.json()["choices"][0]["finish_reason"] == "tool_calls"


@pytest.mark.parametrize("include_reasoning", [False, True])
def test_mlx_chat_stream_publishes_raw_tag_reasoning_only_when_asked(
    monkeypatch: pytest.MonkeyPatch, include_reasoning: bool
) -> None:
    wire = _sse_wire(
        [
            _stream_event({"role": "assistant", "content": ""}),
            _stream_event({"content": "<think>private "}),
            _stream_event({"content": "default reasoning</th"}),
            _stream_event({"content": "ink>Visible answer"}),
            _stream_event({}, finish_reason="stop"),
        ]
    )
    seen: dict[str, Any] = {}

    def _handler(request: httpx.Request) -> httpx.Response:
        seen["body"] = json.loads(request.content)
        return httpx.Response(
            200, stream=_ChunkedAsyncStream([wire[:61], wire[61:]]), headers={"content-type": "text/event-stream"}
        )

    client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={"enable_thinking": False})
    response = client.post(
        "/v1/chat/completions",
        json={
            "model": "Qwen/Qwen3.5-4B",
            "messages": [{"role": "user", "content": "Hello"}],
            "stream": True,
            "include_reasoning": include_reasoning,
        },
    )

    assert response.status_code == 200
    assert "include_reasoning" not in seen["body"]
    deltas = _sse_deltas(response.text)
    assert "".join(delta.get("content", "") for delta in deltas) == "Visible answer"
    reasoning = "".join(delta.get("reasoning_content", "") for delta in deltas)
    assert reasoning == ("private default reasoning" if include_reasoning else "")
    assert "<think>" not in response.text


_MLX_REASONING = "The user wants one word.\n"
_MLX_ANSWER = "\n\nready"


@pytest.mark.parametrize("include_reasoning", [False, True])
@pytest.mark.parametrize(
    ("message", "finish_reason", "content", "reasoning", "hidden"),
    [
        (
            {"role": "assistant", "content": _MLX_ANSWER, "reasoning": _MLX_REASONING},
            "stop",
            _MLX_ANSWER,
            _MLX_REASONING,
            "one word",
        ),
        (
            {"role": "assistant", "content": _MLX_ANSWER, "reasoning_content": _MLX_REASONING},
            "stop",
            _MLX_ANSWER,
            _MLX_REASONING,
            "one word",
        ),
        (
            {"role": "assistant", "content": _MLX_REASONING + "</think>" + _MLX_ANSWER},
            "stop",
            _MLX_ANSWER,
            _MLX_REASONING,
            "one word",
        ),
        (
            {"role": "assistant", "content": "one word.\n</think>" + _MLX_ANSWER, "reasoning": "The user wants "},
            "stop",
            _MLX_ANSWER,
            _MLX_REASONING,
            "one word",
        ),
        (
            {"role": "assistant", "content": "ready<think>one word", "reasoning": _MLX_REASONING},
            "stop",
            "ready",
            _MLX_REASONING + "one word",
            "one word",
        ),
        (
            {"role": "assistant", "content": "still thinking", "reasoning": _MLX_REASONING},
            "length",
            "",
            _MLX_REASONING + "still thinking",
            "still thinking",
        ),
        ({"role": "assistant", "content": _MLX_ANSWER}, "stop", "", _MLX_ANSWER, "ready"),
    ],
    ids=[
        "reasoning",
        "reasoning_content",
        "raw_tags",
        "split_and_raw_close",
        "split_then_raw_open",
        "split_cut_off",
        "no_reasoning_field",
    ],
)
def test_mlx_thinking_chat_keeps_the_answer_beside_split_reasoning(
    monkeypatch: pytest.MonkeyPatch,
    message: dict[str, Any],
    finish_reason: str,
    content: str,
    reasoning: str,
    hidden: str,
    include_reasoning: bool,
) -> None:
    payload = {
        "id": "chatcmpl-mlx",
        "system_fingerprint": "0.32.0",
        "object": "chat.completion",
        "model": "mlx-community/Qwen3.5-4B-4bit",
        "created": 1,
        "choices": [{"index": 0, "finish_reason": finish_reason, "message": message}],
        "usage": {"prompt_tokens": 14, "completion_tokens": 12, "total_tokens": 26},
    }
    client, _ = _mlx_chat_client(
        monkeypatch, lambda _request: httpx.Response(200, json=payload), chat_template_kwargs={"enable_thinking": True}
    )

    response = client.post(
        "/v1/chat/completions",
        json={
            "model": "Qwen/Qwen3.5-4B:thinking",
            "messages": [{"role": "user", "content": "Reply with one word: ready"}],
            "include_reasoning": include_reasoning,
        },
    )

    assert response.status_code == 200
    returned = response.json()["choices"][0]["message"]
    assert returned["content"] == content
    assert "reasoning" not in returned
    assert returned.get("reasoning_content") == (reasoning if include_reasoning else None)
    assert include_reasoning or hidden not in response.text


@pytest.mark.parametrize("include_reasoning", [False, True])
@pytest.mark.parametrize(
    ("deltas", "finish_reason", "content", "reasoning", "hidden"),
    [
        (
            [
                {"role": "assistant", "reasoning": "The user wants "},
                {"role": "assistant", "reasoning": "one word.\n"},
                {"role": "assistant", "content": "\n\n"},
                {"role": "assistant", "content": "ready"},
            ],
            "stop",
            _MLX_ANSWER,
            _MLX_REASONING,
            "one word",
        ),
        (
            [
                {"role": "assistant", "content": ""},
                {"reasoning_content": "The user wants "},
                {"reasoning_content": "one word.\n"},
                {"content": "\n\nready"},
            ],
            "stop",
            _MLX_ANSWER,
            _MLX_REASONING,
            "one word",
        ),
        (
            [
                {"role": "assistant", "content": "The user wants "},
                {"role": "assistant", "content": "one word.\n</th"},
                {"role": "assistant", "content": "ink>\n\nready"},
            ],
            "stop",
            _MLX_ANSWER,
            _MLX_REASONING,
            "one word",
        ),
        (
            [
                {"role": "assistant", "content": ""},
                {"reasoning_content": "The user wants "},
                {"content": "one word.\n</think>\n\nready"},
            ],
            "stop",
            _MLX_ANSWER,
            _MLX_REASONING,
            "one word",
        ),
        (
            [
                {"role": "assistant", "reasoning": "The user wants "},
                {"role": "assistant", "content": "one word.\n</th"},
                {"role": "assistant", "content": "ink>\n\nready"},
            ],
            "stop",
            _MLX_ANSWER,
            _MLX_REASONING,
            "one word",
        ),
        (
            [{"role": "assistant", "reasoning": _MLX_REASONING, "content": _MLX_ANSWER}],
            "stop",
            _MLX_ANSWER,
            _MLX_REASONING,
            "one word",
        ),
        (
            [
                {"role": "assistant", "reasoning": _MLX_REASONING},
                {"role": "assistant", "content": "Checking."},
                {"role": "assistant", "tool_calls": [{"index": 0, **_PARIS_CALL}]},
            ],
            "tool_calls",
            "Checking.",
            _MLX_REASONING,
            "one word",
        ),
        (
            [{"role": "assistant", "reasoning": _MLX_REASONING}, {"role": "assistant", "content": "still thinking"}],
            "length",
            "",
            _MLX_REASONING + "still thinking",
            "still thinking",
        ),
        ([{"role": "assistant", "content": _MLX_ANSWER}], "stop", "", _MLX_ANSWER, "ready"),
    ],
    ids=[
        "reasoning",
        "reasoning_content_after_role",
        "raw_tags",
        "split_then_raw_close",
        "split_then_raw_close_across_deltas",
        "split_and_answer_in_one_delta",
        "answer_before_tool_call",
        "split_cut_off",
        "no_reasoning_field",
    ],
)
def test_mlx_thinking_chat_stream_keeps_the_answer_beside_split_reasoning(
    monkeypatch: pytest.MonkeyPatch,
    deltas: list[dict[str, Any]],
    finish_reason: str,
    content: str,
    reasoning: str,
    hidden: str,
    include_reasoning: bool,
) -> None:
    wire = _sse_wire(
        [*(_stream_event(delta) for delta in deltas), _stream_event({"role": "assistant"}, finish_reason=finish_reason)]
    )
    client, _ = _mlx_chat_client(
        monkeypatch,
        lambda _request: httpx.Response(
            200, stream=_ChunkedAsyncStream([wire[:83], wire[83:]]), headers={"content-type": "text/event-stream"}
        ),
        chat_template_kwargs={"enable_thinking": True},
    )

    response = client.post(
        "/v1/chat/completions",
        json={
            "model": "Qwen/Qwen3.5-4B:thinking",
            "messages": [{"role": "user", "content": "Reply with one word: ready"}],
            "tools": [_WEATHER_TOOL],
            "stream": True,
            "include_reasoning": include_reasoning,
        },
    )

    assert response.status_code == 200
    returned = _sse_deltas(response.text)
    assert "".join(delta.get("content") or "" for delta in returned) == content
    assert not any("reasoning" in delta for delta in returned)
    assert "".join(delta.get("reasoning_content", "") for delta in returned) == (reasoning if include_reasoning else "")
    assert include_reasoning or hidden not in response.text


# -- engine child silence --------------------------------------------------------

_BYTE_GAP_S = 0.3
_SILENCE_S = 3 * _BYTE_GAP_S


@contextmanager
def _loopback_child(*, before_headers_s: float, content_type: str, parts: list[tuple[float, bytes]]) -> Iterator[str]:
    """Serve one scripted chat answer over real loopback HTTP, with real pauses."""

    class _Handler(BaseHTTPRequestHandler):
        def do_POST(self) -> None:
            self.rfile.read(int(self.headers["Content-Length"]))
            try:
                time.sleep(before_headers_s)
                self.send_response(200)
                self.send_header("Content-Type", content_type)
                if content_type == "application/json":
                    self.send_header("Content-Length", str(sum(len(part) for _, part in parts)))
                self.end_headers()
                for pause, part in parts:
                    time.sleep(pause)
                    self.wfile.write(part)
                    self.wfile.flush()
            except (BrokenPipeError, ConnectionResetError):
                return

        def log_message(self, *_args: object) -> None:
            return

    server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    try:
        yield f"http://127.0.0.1:{server.server_address[1]}"
    finally:
        server.shutdown()
        server.server_close()
        thread.join()


def _child_chat_client(
    monkeypatch: pytest.MonkeyPatch, server_url: str, *, overall_s: float = 10 * _SILENCE_S
) -> TestClient:
    proxy_client = openai_local._new_proxy_client
    client, registry = _cuda_chat_client(
        monkeypatch, lambda _request: pytest.fail("the child is real"), server_url=server_url
    )
    monkeypatch.setattr(openai_local, "_new_proxy_client", proxy_client)
    monkeypatch.setattr(openai_local, "_PROXY_READ_TIMEOUT_S", _BYTE_GAP_S)
    monkeypatch.setattr(
        openai_local, "_PROXY_TIMEOUT", httpx.Timeout(connect=10.0, read=_BYTE_GAP_S, write=10.0, pool=10.0)
    )
    monkeypatch.setattr(openai_local, "_SSE_KEEPALIVE_S", _BYTE_GAP_S / 6, raising=False)
    registry.get_config.return_value.resolve_profile.return_value.runtime["overall_timeout_s"] = overall_s
    return client


_WRITE_FILE_TOOL = {
    "type": "function",
    "function": {
        "name": "write_file",
        "parameters": {
            "type": "object",
            "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
        },
    },
}


def test_cuda_chat_stream_outlasts_the_engine_holding_a_long_tool_argument(monkeypatch: pytest.MonkeyPatch) -> None:
    """The engine's own tool parser streams a call's head and short arguments,
    then sends nothing until a long argument closes. The proxy must wait the
    generation out and keep the client's connection busy meanwhile.
    """
    content = "print('hello')\n" * (64 * 1024 // 15 + 1)
    call = {"id": "call_write", "type": "function", "function": {"name": "write_file", "arguments": ""}}

    def _arguments(text: str) -> dict[str, Any]:
        return {"tool_calls": [{"index": 0, "function": {"arguments": text}}]}

    head = b"".join(
        f"data: {json.dumps(event)}\n\n".encode()
        for event in [
            _stream_event({"role": "assistant", "content": ""}),
            _stream_event({"tool_calls": [{"index": 0, **call}]}),
            _stream_event(_arguments("{")),
            _stream_event(_arguments('"path": "src/app.py"')),
        ]
    )
    tail = _sse_wire(
        [
            _stream_event(_arguments(', "content": ' + json.dumps(content))),
            _stream_event(_arguments("}")),
            _stream_event({}, finish_reason="tool_calls"),
        ]
    )
    with _loopback_child(
        before_headers_s=0, content_type="text/event-stream", parts=[(0, head), (_SILENCE_S, tail)]
    ) as url:
        client = _child_chat_client(monkeypatch, url)
        response = client.post(
            "/v1/chat/completions",
            json={
                "model": "Qwen/Qwen3-0.6B",
                "messages": [{"role": "user", "content": "Write the file"}],
                "tools": [_WRITE_FILE_TOOL],
                "stream": True,
            },
        )

    assert response.status_code == 200
    assert "error" not in response.text
    deltas = _sse_deltas(response.text)
    arguments = "".join(
        call["function"].get("arguments") or "" for delta in deltas for call in delta.get("tool_calls") or ()
    )
    assert json.loads(arguments) == {"path": "src/app.py", "content": content}
    assert response.text.splitlines().count(": keepalive") >= 2


def test_cuda_chat_stream_without_tools_still_ends_at_the_byte_gap(monkeypatch: pytest.MonkeyPatch) -> None:
    head = f"data: {json.dumps(_stream_event({'role': 'assistant', 'content': 'Hel'}))}\n\n".encode()
    tail = _sse_wire([_stream_event({"content": "lo"}, finish_reason="stop")])
    with _loopback_child(
        before_headers_s=0, content_type="text/event-stream", parts=[(0, head), (_SILENCE_S, tail)]
    ) as url:
        client = _child_chat_client(monkeypatch, url)
        response = client.post(
            "/v1/chat/completions",
            json={"model": "Qwen/Qwen3-0.6B", "messages": [{"role": "user", "content": "hi"}], "stream": True},
        )

    assert response.status_code == 200
    data = [line.removeprefix("data: ") for line in response.text.splitlines() if line.startswith("data: ")]
    assert data[-1] == "[DONE]"
    assert json.loads(data[-2])["error"]["code"] == "upstream_error"
    assert '"lo"' not in response.text


def test_cuda_chat_blocking_waits_out_a_silent_generation(monkeypatch: pytest.MonkeyPatch) -> None:
    payload = _reasoning_child_payload("a long answer")
    with _loopback_child(
        before_headers_s=_SILENCE_S, content_type="application/json", parts=[(0, json.dumps(payload).encode())]
    ) as url:
        client = _child_chat_client(monkeypatch, url)
        response = client.post(
            "/v1/chat/completions",
            json={"model": "Qwen/Qwen3-0.6B", "messages": [{"role": "user", "content": "hi"}]},
        )

    assert response.status_code == 200
    assert response.json()["choices"][0]["message"]["content"] == "a long answer"


def test_cuda_chat_stream_with_tools_ends_at_the_generation_budget(monkeypatch: pytest.MonkeyPatch) -> None:
    budget_s = 4 * _BYTE_GAP_S
    trickle = f"data: {json.dumps(_stream_event({'content': '.'}))}\n\n".encode()
    head = f"data: {json.dumps(_stream_event({'role': 'assistant', 'content': ''}))}\n\n".encode()
    beats = int(3 * budget_s / (_BYTE_GAP_S / 3))
    with _loopback_child(
        before_headers_s=0,
        content_type="text/event-stream",
        parts=[(0, head), *[(_BYTE_GAP_S / 3, trickle)] * beats, (0, b"data: [DONE]\n\n")],
    ) as url:
        client = _child_chat_client(monkeypatch, url, overall_s=budget_s)
        started = time.monotonic()
        response = client.post(
            "/v1/chat/completions",
            json={
                "model": "Qwen/Qwen3-0.6B",
                "messages": [{"role": "user", "content": "Write the file"}],
                "tools": [_WRITE_FILE_TOOL],
                "stream": True,
            },
        )
        elapsed = time.monotonic() - started

    data = [line.removeprefix("data: ") for line in response.text.splitlines() if line.startswith("data: ")]
    assert data[-1] == "[DONE]"
    assert json.loads(data[-2])["error"]["code"] == "generation_timeout"
    assert elapsed < 2 * budget_s


def test_cuda_chat_blocking_ends_at_the_generation_budget(monkeypatch: pytest.MonkeyPatch) -> None:
    budget_s = 4 * _BYTE_GAP_S
    body = json.dumps(_reasoning_child_payload("a long answer")).encode()
    beats = int(3 * budget_s / (_BYTE_GAP_S / 3))
    step = len(body) // beats + 1
    pieces = [body[start : start + step] for start in range(0, len(body), step)]
    with _loopback_child(
        before_headers_s=0,
        content_type="application/json",
        parts=[(_BYTE_GAP_S / 3, piece) for piece in pieces],
    ) as url:
        client = _child_chat_client(monkeypatch, url, overall_s=budget_s)
        response = client.post(
            "/v1/chat/completions",
            json={"model": "Qwen/Qwen3-0.6B", "messages": [{"role": "user", "content": "hi"}]},
        )

    assert response.status_code == 504
    assert "generation_timeout" in response.text


_PIXEL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
_IMAGE_TURN = [
    {"role": "user", "content": [{"type": "text", "text": "Describe it."}, {"type": "image_url", "image_url": _PIXEL}]}
]


@pytest.mark.parametrize("backend", ["cuda", "mlx"])
def test_chat_refuses_tools_on_a_model_without_tool_calling_before_the_child(
    monkeypatch: pytest.MonkeyPatch, backend: str
) -> None:
    def _handler(_request: httpx.Request) -> httpx.Response:
        pytest.fail("a refused request must not reach the child")

    if backend == "cuda":
        client, registry = _cuda_chat_client(monkeypatch, _handler, tools=False)
    else:
        client, registry = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={}, tools=False)
    response = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3.5-4B", "messages": [{"role": "user", "content": "hi"}], "tools": [_WEATHER_TOOL]},
    )

    assert response.status_code == 400, response.text
    assert response.json()["error"] == {
        "message": "Model 'Qwen/Qwen3.5-4B' does not support tool calling",
        "type": "invalid_request_error",
        "param": "tools",
        "code": "unsupported_field",
    }
    registry.get.assert_not_called()


@pytest.mark.parametrize(
    ("backend", "image"),
    [("cuda", False), ("mlx", False), ("mlx", True)],
    ids=["cuda text-only model", "mlx text-only model", "mlx child without image input"],
)
def test_chat_refuses_an_image_the_backend_cannot_read_before_the_child(
    monkeypatch: pytest.MonkeyPatch, backend: str, image: bool
) -> None:
    def _handler(_request: httpx.Request) -> httpx.Response:
        pytest.fail("a refused request must not reach the child")

    if backend == "cuda":
        client, registry = _cuda_chat_client(monkeypatch, _handler, image=image)
    else:
        client, registry = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={}, image=image)
    response = client.post("/v1/chat/completions", json={"model": "Qwen/Qwen3.5-4B", "messages": _IMAGE_TURN})

    assert response.status_code == 400, response.text
    assert response.json()["error"] == {
        "message": "Model 'Qwen/Qwen3.5-4B' does not support image input",
        "type": "invalid_request_error",
        "param": "messages",
        "code": "unsupported_field",
    }
    registry.get.assert_not_called()


def test_an_input_image_part_is_an_image(monkeypatch: pytest.MonkeyPatch) -> None:
    client, registry = _cuda_chat_client(
        monkeypatch, lambda _request: pytest.fail("a refused request must not reach the child")
    )
    response = client.post(
        "/v1/chat/completions",
        json={
            "model": "Qwen/Qwen3.5-4B",
            "messages": [{"role": "user", "content": [{"type": "input_image", "image_url": _PIXEL}]}],
        },
    )

    assert response.status_code == 400, response.text
    assert response.json()["error"]["message"] == "Model 'Qwen/Qwen3.5-4B' does not support image input"
    registry.get.assert_not_called()


def test_cuda_chat_sends_an_image_to_a_vision_model(monkeypatch: pytest.MonkeyPatch) -> None:
    seen: list[dict[str, Any]] = []

    def _handler(request: httpx.Request) -> httpx.Response:
        seen.append(json.loads(request.content))
        return httpx.Response(200, json=_chat_completion("a pixel"))

    client, _ = _cuda_chat_client(monkeypatch, _handler, image=True)
    response = client.post("/v1/chat/completions", json={"model": "Qwen/Qwen3.5-4B", "messages": _IMAGE_TURN})

    assert response.status_code == 200, response.text
    assert seen[0]["messages"][0]["content"][1] == {"type": "image_url", "image_url": _PIXEL}


_WINDOW = 64


def _tool_turns(words: int) -> list[dict[str, Any]]:
    return [
        {"role": "user", "content": " ".join(["w"] * words)},
        {"role": "assistant", "content": None, "tool_calls": [_PARIS_CALL]},
        {"role": "tool", "tool_call_id": "call_paris", "content": "18"},
    ]


@pytest.mark.parametrize(
    ("fields", "template_kwargs", "prompt_tokens"),
    [
        ({"messages": [{"role": "user", "content": "w " * 30}]}, {}, 32),
        (
            {
                "messages": [
                    {"role": "user", "content": [{"type": "text", "text": "w w"}, {"type": "text", "text": " w"}]}
                ]
            },
            {},
            5,
        ),
        ({"messages": [{"role": "user", "content": "w " * 30}], "tools": [_WEATHER_TOOL]}, {}, 34),
        ({"messages": [{"role": "user", "content": "w " * 30}]}, {"enable_thinking": True}, 33),
        ({"messages": _tool_turns(10), "tools": [_WEATHER_TOOL]}, {}, 20),
    ],
    ids=["text", "text parts", "tools", "template kwargs", "tool call and result"],
)
def test_mlx_chat_enforces_the_declared_window_on_the_rendered_prompt(
    monkeypatch: pytest.MonkeyPatch, fields: dict[str, Any], template_kwargs: dict[str, Any], prompt_tokens: int
) -> None:
    seen: list[dict[str, Any]] = []

    def _handler(request: httpx.Request) -> httpx.Response:
        seen.append(json.loads(request.content))
        return httpx.Response(200, json=_chat_completion("ok"))

    client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs=template_kwargs, max_seq_length=_WINDOW)
    fits = client.post(
        "/v1/chat/completions", json={"model": "Qwen/Qwen3.5-4B", "max_tokens": _WINDOW - prompt_tokens, **fields}
    )
    over = client.post(
        "/v1/chat/completions", json={"model": "Qwen/Qwen3.5-4B", "max_tokens": _WINDOW + 1 - prompt_tokens, **fields}
    )

    assert fits.status_code == 200, fits.text
    assert len(seen) == 1
    assert over.status_code == 400, over.text
    assert over.json()["error"] == {
        "message": (
            f"prompt_tokens ({prompt_tokens}) + max_new_tokens ({_WINDOW + 1 - prompt_tokens}) = {_WINDOW + 1} "
            f"exceeds context_length ({_WINDOW}) for model 'Qwen/Qwen3.5-4B'"
        ),
        "type": "invalid_request_error",
        "param": "prompt",
        "code": "INPUT_TOO_LONG",
    }


_UNPARSED_CALL = {**_PARIS_CALL, "function": {"name": "get_weather", "arguments": "{"}}


@pytest.mark.parametrize(
    ("max_seq_length", "messages"),
    [
        (None, [{"role": "user", "content": "w " * 100}]),
        (_WINDOW, [*_tool_turns(100)[:1], {"role": "assistant", "content": None, "tool_calls": [_UNPARSED_CALL]}]),
    ],
    ids=["no declared window", "arguments the template cannot read"],
)
def test_mlx_chat_leaves_a_prompt_it_cannot_count_to_the_child(
    monkeypatch: pytest.MonkeyPatch, max_seq_length: int | None, messages: list[dict[str, Any]]
) -> None:
    seen: list[dict[str, Any]] = []

    def _handler(request: httpx.Request) -> httpx.Response:
        seen.append(json.loads(request.content))
        return httpx.Response(200, json=_chat_completion("ok"))

    client, _ = _mlx_chat_client(monkeypatch, _handler, chat_template_kwargs={}, max_seq_length=max_seq_length)
    response = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3.5-4B", "max_tokens": 8, "messages": messages, "tools": [_WEATHER_TOOL]},
    )

    assert response.status_code == 200, response.text
    assert len(seen) == 1


def test_mlx_messages_refuse_a_prompt_over_the_window_with_the_compaction_wording(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    client, _ = _mlx_chat_client(
        monkeypatch,
        lambda _request: pytest.fail("a refused request must not reach the child"),
        chat_template_kwargs={},
        max_seq_length=_WINDOW,
    )
    client.app.include_router(anthropic_messages.router)
    response = client.post(
        "/v1/messages",
        json={"model": "Qwen/Qwen3.5-4B", "max_tokens": 32, "messages": [{"role": "user", "content": "w " * 40}]},
    )

    assert response.status_code == 400, response.text
    assert response.json()["error"] == {
        "type": "invalid_request_error",
        "message": f"prompt is too long: {42 + 32} tokens > {_WINDOW} maximum",
    }


_IGNORED_OPENAI_FIELDS = {
    "metadata": {"run": "eval-7"},
    "store": True,
    "service_tier": "auto",
    "prompt_cache_key": "session-1",
}


def _chat_client_for(
    engine: str, monkeypatch: pytest.MonkeyPatch, handler: Callable[[httpx.Request], httpx.Response]
) -> TestClient:
    if engine == "cuda":
        return _cuda_chat_client(monkeypatch, handler)[0]
    return _mlx_chat_client(monkeypatch, handler, chat_template_kwargs={"enable_thinking": False})[0]


@pytest.mark.parametrize("engine", ["cuda", "mlx"])
@pytest.mark.parametrize("extra", [_IGNORED_OPENAI_FIELDS, dict.fromkeys(_IGNORED_OPENAI_FIELDS)])
def test_chat_accepts_and_drops_the_ignored_openai_fields(
    monkeypatch: pytest.MonkeyPatch, engine: str, extra: dict[str, Any]
) -> None:
    forwarded: list[dict[str, Any]] = []

    def _handler(request: httpx.Request) -> httpx.Response:
        forwarded.append(json.loads(request.content))
        return httpx.Response(
            200,
            json={
                "id": "chatcmpl-test",
                "object": "chat.completion",
                "created": 1,
                "model": "served",
                "choices": [
                    {"index": 0, "message": {"role": "assistant", "content": "Hello"}, "finish_reason": "stop"}
                ],
                "usage": {"prompt_tokens": 3, "completion_tokens": 1, "total_tokens": 4},
            },
        )

    client = _chat_client_for(engine, monkeypatch, _handler)
    body = {"model": "Qwen/Qwen3.5-4B", "messages": [{"role": "user", "content": "Hello"}], "max_tokens": 8}

    plain = client.post("/v1/chat/completions", json=body)
    with_fields = client.post("/v1/chat/completions", json={**body, **extra})

    assert plain.status_code == 200
    assert with_fields.status_code == 200
    # The engine sees the same request either way: the fields are not forwarded.
    assert forwarded[1] == forwarded[0]
    assert not forwarded[1].keys() & _IGNORED_OPENAI_FIELDS.keys()
    assert with_fields.json()["choices"] == plain.json()["choices"]


@pytest.mark.parametrize("engine", ["cuda", "mlx"])
@pytest.mark.parametrize(
    ("field", "value", "expected"),
    [
        ("metadata", "run", "an object"),
        ("store", "yes", "a boolean"),
        ("service_tier", 1, "a string"),
        ("prompt_cache_key", 1, "a string"),
    ],
)
def test_chat_rejects_wrongly_typed_ignored_openai_fields(
    monkeypatch: pytest.MonkeyPatch, engine: str, field: str, value: Any, expected: str
) -> None:
    client = _chat_client_for(
        engine, monkeypatch, lambda _request: pytest.fail("rejected request must not reach the engine")
    )

    response = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3.5-4B", "messages": [{"role": "user", "content": "Hello"}], field: value},
    )

    assert response.status_code == 400
    assert response.json()["error"]["param"] == field
    assert response.json()["error"]["message"] == f"'{field}' must be {expected}"
    assert response.json()["error"]["code"] != "unsupported_field"


@pytest.mark.parametrize("engine", ["cuda", "mlx"])
@pytest.mark.parametrize("field", ["functions", "function_call", "modalities", "audio", "prediction", "verbosity"])
def test_chat_still_rejects_out_of_scope_openai_fields(
    monkeypatch: pytest.MonkeyPatch, engine: str, field: str
) -> None:
    client = _chat_client_for(
        engine, monkeypatch, lambda _request: pytest.fail("rejected request must not reach the engine")
    )

    response = client.post(
        "/v1/chat/completions",
        json={"model": "Qwen/Qwen3.5-4B", "messages": [{"role": "user", "content": "Hello"}], field: {}},
    )

    assert response.status_code == 400
    assert response.json()["error"]["code"] == "unsupported_field"
    assert response.json()["error"]["param"] == field