Skip to content

armgit / sie

Public Imported from GitHub
0

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

44.6 KB
Raw Blame
from __future__ import annotations

import json
from collections.abc import AsyncIterator

import pytest
from sie_server.adapters._generation_base import GenerationChunk
from sie_server.processors import tool_call_parser
from sie_server.processors.tool_call_parser import parse_tool_call_stream


async def _chunks(items: list[GenerationChunk]) -> AsyncIterator[GenerationChunk]:
    for item in items:
        yield item


@pytest.mark.asyncio
async def test_parse_tool_call_stream_emits_text_and_tool_delta() -> None:
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(
                        text_delta='Use this: <tool_call>{"name":"get_weather","arguments":{"city":"Paris"}}</tool_call>'
                    ),
                    GenerationChunk(
                        text_delta="", done=True, finish_reason="stop", prompt_tokens=5, completion_tokens=7
                    ),
                ]
            )
        )
    ]

    assert out[0].text_delta == "Use this: "
    assert out[1].tool_call_delta is not None
    assert out[1].tool_call_delta.index == 0
    assert out[1].tool_call_delta.id is not None
    assert out[1].tool_call_delta.function_name == "get_weather"
    assert out[2].tool_call_delta is not None
    assert out[2].tool_call_delta.arguments_delta == '{"city":"Paris"}'
    assert out[-1].done is True
    assert out[-1].finish_reason == "tool_calls"


@pytest.mark.asyncio
async def test_parse_tool_call_stream_handles_split_open_tag() -> None:
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(text_delta="<tool"),
                    GenerationChunk(text_delta='_call>{"name":"x","arguments":{}}</tool_call>'),
                    GenerationChunk(text_delta="", done=True, finish_reason="stop"),
                ]
            )
        )
    ]

    assert any(item.tool_call_delta is not None for item in out)
    assert out[-1].finish_reason == "tool_calls"


@pytest.mark.asyncio
async def test_parse_tool_call_stream_handles_split_close_tag() -> None:
    """BUG 1 regression: a ``</tool_call>`` split across a chunk boundary
    must still close the block and emit a tool_call_delta, not a parse error.
    """
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(text_delta='<tool_call>{"name":"f","arguments":{}}</tool_'),
                    GenerationChunk(text_delta="call>"),
                    GenerationChunk(text_delta="", done=True, finish_reason="stop"),
                ]
            )
        )
    ]

    deltas = [c.tool_call_delta for c in out if c.tool_call_delta is not None]
    assert deltas, "expected a tool_call_delta, got none"
    assert deltas[0].function_name == "f"
    # No parse error emitted.
    assert all(c.error_code is None for c in out)
    assert out[-1].done is True
    assert out[-1].finish_reason == "tool_calls"


@pytest.mark.asyncio
async def test_parse_tool_call_stream_handles_close_tag_split_mid_tag() -> None:
    """BUG 1 regression: close tag split in the MIDDLE of a longer split.

    Boundary lands several characters into ``</tool_call>`` so the retained
    tail must be re-scanned across more than one chunk.
    """
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(text_delta='<tool_call>{"name":"f","arguments":{}}</to'),
                    GenerationChunk(text_delta="ol_ca"),
                    GenerationChunk(text_delta="ll>"),
                    GenerationChunk(text_delta="", done=True, finish_reason="stop"),
                ]
            )
        )
    ]

    deltas = [c.tool_call_delta for c in out if c.tool_call_delta is not None]
    assert deltas, "expected a tool_call_delta, got none"
    assert deltas[0].function_name == "f"
    assert all(c.error_code is None for c in out)
    assert out[-1].finish_reason == "tool_calls"


@pytest.mark.asyncio
async def test_parse_tool_call_stream_args_value_with_literal_close_substring() -> None:
    """Contract pin: a tool args value containing a literal ``</tool_call>``
    substring inside a JSON string still parses; the FIRST real close tag
    terminates the block (the literal is JSON-escaped on the wire).
    """
    # The literal ``</tool_call>`` appears as escaped text inside a JSON
    # string value; the actual closing tag is the trailing one.
    raw = '<tool_call>{"name":"f","arguments":{"q":"a<\\/tool_call>b"}}</tool_call>'
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(text_delta=raw),
                    GenerationChunk(text_delta="", done=True, finish_reason="stop"),
                ]
            )
        )
    ]
    deltas = [c.tool_call_delta for c in out if c.tool_call_delta is not None]
    assert deltas, "expected a tool_call_delta, got none"
    assert deltas[0].function_name == "f"
    args = "".join(d.arguments_delta for d in deltas if d.arguments_delta)
    import json as _json

    assert _json.loads(args) == {"q": "a</tool_call>b"}
    assert all(c.error_code is None for c in out)
    assert out[-1].finish_reason == "tool_calls"


@pytest.mark.asyncio
async def test_parse_tool_call_stream_malformed_json_is_terminal_error() -> None:
    out = [
        item
        async for item in parse_tool_call_stream(_chunks([GenerationChunk(text_delta="<tool_call>{bad}</tool_call>")]))
    ]

    assert len(out) == 1
    assert out[0].done is True
    assert out[0].finish_reason == "error"
    assert out[0].error_code == "MODEL_OUTPUT_PARSE_ERROR"
    assert "malformed" in (out[0].error_message or "")


@pytest.mark.asyncio
async def test_parse_tool_call_stream_passthrough_when_no_tool_call() -> None:
    """Plain prose flows through untouched, finish_reason stays 'stop'."""
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(text_delta="Hello "),
                    GenerationChunk(text_delta="world!"),
                    GenerationChunk(text_delta="", done=True, finish_reason="stop"),
                ]
            )
        )
    ]
    # First two chunks may be coalesced by the parser's flush-on-lookahead,
    # but the concatenated text_delta across non-terminal chunks must
    # equal the input, and the terminal must keep finish_reason="stop"
    # (no tool calls observed).
    text = "".join(c.text_delta for c in out if not c.done)
    assert text == "Hello world!"
    assert out[-1].done is True
    assert out[-1].finish_reason == "stop"
    assert all(c.tool_call_delta is None for c in out)


@pytest.mark.asyncio
async def test_parse_tool_call_stream_parallel_calls_use_distinct_indices() -> None:
    """Two adjacent <tool_call> blocks produce ToolCallDeltas with index 0 and 1."""
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(
                        text_delta=(
                            '<tool_call>{"name":"a","arguments":{"x":1}}</tool_call>'
                            '<tool_call>{"name":"b","arguments":{"y":2}}</tool_call>'
                        )
                    ),
                    GenerationChunk(text_delta="", done=True, finish_reason="stop"),
                ]
            )
        )
    ]
    deltas = [c.tool_call_delta for c in out if c.tool_call_delta is not None]
    assert len(deltas) == 4  # 2 calls × (announcement + arguments)
    indices = sorted({d.index for d in deltas})
    assert indices == [0, 1]
    names = {d.function_name for d in deltas if d.function_name is not None}
    assert names == {"a", "b"}
    assert out[-1].finish_reason == "tool_calls"


@pytest.mark.asyncio
async def test_parse_tool_call_stream_terminal_propagates_usage_and_tool_calls_reason() -> None:
    """Terminal chunk after a tool call keeps usage and overrides finish_reason."""
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(text_delta='<tool_call>{"name":"f","arguments":{}}</tool_call>'),
                    GenerationChunk(
                        text_delta="",
                        done=True,
                        finish_reason="stop",
                        prompt_tokens=11,
                        completion_tokens=13,
                        cached_tokens=9,
                    ),
                ]
            )
        )
    ]
    terminal = out[-1]
    assert terminal.done is True
    assert terminal.finish_reason == "tool_calls"
    assert terminal.prompt_tokens == 11
    assert terminal.completion_tokens == 13
    assert terminal.cached_tokens == 9


@pytest.mark.asyncio
async def test_parse_tool_call_stream_preserves_terminal_error_metadata() -> None:
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(
                        text_delta="",
                        done=True,
                        finish_reason="error",
                        error_code="grammar_invalid",
                        error_message="invalid grammar",
                    )
                ]
            )
        )
    ]

    terminal = out[-1]
    assert terminal.done is True
    assert terminal.finish_reason == "error"
    assert terminal.error_code == "grammar_invalid"
    assert terminal.error_message == "invalid grammar"


@pytest.mark.asyncio
async def test_parse_tool_call_stream_candidate_rewrite_preserves_terminal_error_metadata() -> None:
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(
                        text_delta="",
                        done=True,
                        finish_reason="stop",
                        candidates=({"text": "plain answer", "finish_reason": "stop", "logprobs": None},),
                        error_code="empty_model_output",
                        error_message="model produced no visible output text",
                    )
                ]
            )
        )
    ]

    terminal = out[-1]
    assert terminal.done is True
    assert terminal.finish_reason == "stop"
    assert terminal.error_code == "empty_model_output"
    assert terminal.error_message == "model produced no visible output text"
    assert terminal.candidates is not None
    assert terminal.candidates[0]["text"] == "plain answer"


# ── Qwen XML format ────────────────────────────────────────────────


async def _collect(text: str, **kwargs: object) -> list[GenerationChunk]:
    return [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(text_delta=text),
                    GenerationChunk(text_delta="", done=True, finish_reason="stop"),
                ]
            ),
            **kwargs,  # type: ignore[arg-type]
        )
    ]


def _deltas(out: list[GenerationChunk]) -> list:
    return [c.tool_call_delta for c in out if c.tool_call_delta is not None]


def _tool(name: str, **properties: dict) -> dict:
    return {
        "type": "function",
        "function": {"name": name, "parameters": {"type": "object", "properties": properties}},
    }


def _args_for(out: list[GenerationChunk], index: int = 0) -> str:
    """Concatenate the arguments_delta for a given tool-call index."""
    return "".join(d.arguments_delta for d in _deltas(out) if d.index == index and d.arguments_delta)


@pytest.mark.asyncio
async def test_xml_format_autodetected() -> None:
    """Qwen XML form is parsed by the runtime heuristic (auto)."""
    out = await _collect(
        "<tool_call>\n<function=get_weather>\n<parameter=city>\nTokyo\n</parameter>\n</function>\n</tool_call>"
    )
    deltas = _deltas(out)
    assert deltas[0].function_name == "get_weather"
    import json

    assert json.loads(_args_for(out)) == {"city": "Tokyo"}
    assert out[-1].finish_reason == "tool_calls"


@pytest.mark.asyncio
async def test_explicit_qwen_xml_format() -> None:
    out = await _collect(
        "<tool_call><function=f><parameter=a>\n1\n</parameter></function></tool_call>",
        tool_call_format="qwen_xml",
        tools=[_tool("f", a={"type": "integer"})],
    )
    import json

    assert _deltas(out)[0].function_name == "f"
    assert json.loads(_args_for(out)) == {"a": 1}


@pytest.mark.asyncio
async def test_explicit_hermes_json_format() -> None:
    out = await _collect(
        '<tool_call>{"name":"g","arguments":{"k":"v"}}</tool_call>',
        tool_call_format="hermes_json",
    )
    assert _deltas(out)[0].function_name == "g"
    assert _args_for(out) == '{"k":"v"}'


@pytest.mark.asyncio
async def test_xml_argument_values_follow_declared_types() -> None:
    """XML parameter values convert by declared type; a value that does not convert stays a string."""
    import json

    raw = (
        "<tool_call><function=f>"
        "<parameter=num>\n5\n</parameter>"
        "<parameter=flag>\ntrue\n</parameter>"
        '<parameter=nested>\n{"a":[1,2]}\n</parameter>'
        "<parameter=jsonish>\nnot json {oops\n</parameter>"
        "<parameter=empty>\n\n</parameter>"
        "<parameter=unicode>\ncafé ☕\n</parameter>"
        "<parameter=multiline>\nline1\nline2\n</parameter>"
        "</function></tool_call>"
    )
    tool = _tool(
        "f",
        num={"type": "integer"},
        flag={"type": "boolean"},
        nested={"type": "object"},
        jsonish={"type": "object"},
        empty={"type": "string"},
        unicode={"type": "string"},
        multiline={"type": "string"},
    )
    out = await _collect(raw, tool_call_format="qwen_xml", tools=[tool])
    args = json.loads(_args_for(out))
    assert args["num"] == 5
    assert args["flag"] is True
    assert args["nested"] == {"a": [1, 2]}
    assert args["jsonish"] == "not json {oops"
    assert args["empty"] == ""
    assert args["unicode"] == "café ☕"
    assert args["multiline"] == "line1\nline2"


@pytest.mark.asyncio
async def test_multiple_xml_blocks_distinct_indices() -> None:
    out = await _collect(
        "<tool_call><function=a><parameter=x>\n1\n</parameter></function></tool_call>"
        "<tool_call><function=b><parameter=y>\n2\n</parameter></function></tool_call>",
        tool_call_format="qwen_xml",
    )
    deltas = _deltas(out)
    assert sorted({d.index for d in deltas}) == [0, 1]
    assert {d.function_name for d in deltas if d.function_name} == {"a", "b"}
    assert out[-1].finish_reason == "tool_calls"


@pytest.mark.asyncio
async def test_parallel_tool_calls_false_rejects_second_call() -> None:
    """With ``parallel_tool_calls=false`` a second ``<tool_call>`` block is
    rejected with a terminal error chunk rather than silently dropped.

    The first call's deltas are still flushed (it's a legal call); the
    second opener trips the enforcement and ends the stream as ``error``
    with ``parallel_tool_calls_violated``.
    """
    out = await _collect(
        '<tool_call>{"name":"a","arguments":{"x":1}}</tool_call>'
        '<tool_call>{"name":"b","arguments":{"y":2}}</tool_call>',
        parallel_tool_calls=False,
    )
    # First call's deltas (announce + arguments) are emitted before the
    # violation is detected on the second opener.
    deltas = _deltas(out)
    assert {d.index for d in deltas} == {0}
    assert {d.function_name for d in deltas if d.function_name} == {"a"}
    # The second call never reaches the parser — no index 1 deltas.
    assert all(d.index == 0 for d in deltas)
    # Terminal chunk carries the enforcement error.
    terminal = out[-1]
    assert terminal.done is True
    assert terminal.finish_reason == "error"
    assert terminal.error_code == "parallel_tool_calls_violated"
    assert "parallel_tool_calls" in (terminal.error_message or "")


@pytest.mark.asyncio
async def test_parallel_tool_calls_false_single_call_passthrough() -> None:
    """A single tool call under ``parallel_tool_calls=false`` is unaffected:
    deltas flow normally and the stream finishes as ``tool_calls``.
    """
    out = await _collect(
        '<tool_call>{"name":"a","arguments":{"x":1}}</tool_call>',
        parallel_tool_calls=False,
    )
    deltas = _deltas(out)
    assert {d.function_name for d in deltas if d.function_name} == {"a"}
    assert out[-1].done is True
    assert out[-1].finish_reason == "tool_calls"
    assert out[-1].error_code is None


@pytest.mark.asyncio
async def test_parallel_tool_calls_true_keeps_all_calls() -> None:
    out = await _collect(
        '<tool_call>{"name":"a","arguments":{}}</tool_call><tool_call>{"name":"b","arguments":{}}</tool_call>',
        parallel_tool_calls=True,
    )
    assert sorted({d.index for d in _deltas(out)}) == [0, 1]


# ── fix #6: linear (non-backtracking) XML parameter scan ───────────────


def test_xml_param_scan_matches_well_formed_input() -> None:
    """The linear ``str.find`` scan reproduces the old regex behavior for
    well-formed input — multiple params, each converted by its declared type.
    """
    from sie_server.processors.tool_call_parser import _parse_xml_tool_call

    raw = (
        "<function=f>"
        "<parameter=a>\n1\n</parameter>"
        "<parameter=b>\nhello\n</parameter>"
        '<parameter=c>\n{"k":[1,2]}\n</parameter>'
        "</function>"
    )
    schemas = {"f": {"properties": {"a": {"type": "integer"}, "b": {"type": "string"}, "c": {"type": "object"}}}}
    name, args = _parse_xml_tool_call(raw, schemas)
    assert name == "f"
    assert args == {"a": 1, "b": "hello", "c": {"k": [1, 2]}}


def test_xml_param_scan_stops_at_unterminated_parameter() -> None:
    """An opener with no closing ``</parameter>`` stops the scan instead of
    swallowing the rest of the buffer (and never backtracks).
    """
    from sie_server.processors.tool_call_parser import _parse_xml_tool_call

    raw = "<function=f><parameter=ok>\nv\n</parameter><parameter=dangling>\nno close here"
    name, args = _parse_xml_tool_call(raw)
    assert name == "f"
    assert args == {"ok": "v"}


def test_xml_param_scan_bounds_param_count() -> None:
    """Adversarial buffer with a huge number of openers parses at most
    ``MAX_XML_PARAMS`` and returns in linear time (no O(n^2) backtracking).
    """
    import time

    from sie_server.processors.tool_call_parser import MAX_XML_PARAMS, _parse_xml_tool_call

    # Far more params than the cap, each well-formed.
    n = MAX_XML_PARAMS + 5_000
    body = "".join(f"<parameter=p{i}>\n{i}\n</parameter>" for i in range(n))
    raw = "<function=f>" + body + "</function>"
    t0 = time.monotonic()
    name, args = _parse_xml_tool_call(raw)
    elapsed = time.monotonic() - t0
    assert name == "f"
    assert len(args) == MAX_XML_PARAMS
    # Generous ceiling: linear parse of this buffer is milliseconds.
    assert elapsed < 2.0


def test_xml_param_scan_garbled_openers_no_close_is_fast() -> None:
    """A 256 KiB buffer of openers with NO closing tags is the worst case for
    the old ``(.*?)...</parameter>`` regex; the linear scan returns promptly
    with zero params.
    """
    import time

    from sie_server.processors.tool_call_parser import _parse_xml_tool_call

    garbage = "<parameter=x>" * (256 * 1024 // len("<parameter=x>"))
    raw = "<function=f>" + garbage
    t0 = time.monotonic()
    name, args = _parse_xml_tool_call(raw)
    elapsed = time.monotonic() - t0
    assert name == "f"
    assert args == {}  # no closer found for any opener
    assert elapsed < 2.0


@pytest.mark.parametrize(
    "garbage",
    [
        "<parameter=" * (256 * 1024 // len("<parameter=")),
        "<parameter=a b " * (256 * 1024 // len("<parameter=a b ")),
        "<parameter=" + " " * (256 * 1024),
    ],
    ids=["openers-only", "openers-with-spaces", "one-opener-then-spaces"],
)
def test_xml_param_scan_openers_that_never_end_are_fast(garbage: str) -> None:
    """An opener with no ``>`` must not rescan the buffer for every opener."""
    import time

    from sie_server.processors.tool_call_parser import _parse_xml_tool_call

    t0 = time.monotonic()
    parsed = _parse_xml_tool_call("<function=f>" + garbage)
    elapsed = time.monotonic() - t0
    assert parsed == ("f", {})
    assert elapsed < 2.0


def test_xml_param_name_may_contain_spaces() -> None:
    """JSON Schema allows such a name, and failing to read it loses the argument silently."""
    from sie_server.processors.tool_call_parser import _parse_xml_tool_call

    raw = "<function=f><parameter=first name>\nAda\n</parameter><parameter=city >\nParis\n</parameter></function>"
    assert _parse_xml_tool_call(raw) == ("f", {"first name": "Ada", "city": "Paris"})


def test_xml_param_opener_needs_a_visible_name() -> None:
    from sie_server.processors.tool_call_parser import _parse_xml_tool_call

    assert _parse_xml_tool_call("<function=f><parameter= >\nv\n</parameter></function>") == ("f", {})


# ── GLM argument tags ──────────────────────────────────────────────────


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "raw",
    [
        (
            "<tool_call>get_weather<arg_key>city</arg_key><arg_value>Tokyo</arg_value>"
            "<arg_key>days</arg_key><arg_value>3</arg_value></tool_call>"
        ),
        (
            "<tool_call>get_weather\n<arg_key>city</arg_key>\n<arg_value>Tokyo</arg_value>\n"
            "<arg_key>days</arg_key>\n<arg_value>3</arg_value>\n</tool_call>"
        ),
    ],
)
async def test_explicit_glm_xml_format(raw: str) -> None:
    import json

    out = await _collect(
        "Checking. " + raw,
        tool_call_format="glm_xml",
        tools=[_tool("get_weather", city={"type": "string"}, days={"type": "integer"})],
    )

    assert out[0].text_delta == "Checking. "
    assert _deltas(out)[0].function_name == "get_weather"
    assert json.loads(_args_for(out)) == {"city": "Tokyo", "days": 3}
    assert out[-1].finish_reason == "tool_calls"


@pytest.mark.asyncio
async def test_glm_xml_call_without_arguments() -> None:
    out = await _collect("<tool_call>get_time</tool_call>", tool_call_format="glm_xml")

    assert _deltas(out)[0].function_name == "get_time"
    assert _args_for(out) == "{}"


@pytest.mark.asyncio
async def test_glm_xml_argument_values_follow_declared_types() -> None:
    import json

    raw = (
        "<tool_call>f"
        "<arg_key>num</arg_key><arg_value>5</arg_value>"
        "<arg_key>flag</arg_key><arg_value>true</arg_value>"
        '<arg_key>nested</arg_key><arg_value>{"a": [1, 2]}</arg_value>'
        "<arg_key>text</arg_key><arg_value>café ☕</arg_value>"
        "<arg_key>multiline</arg_key><arg_value>line1\nline2</arg_value>"
        "</tool_call>"
    )
    tool = _tool(
        "f",
        num={"type": "integer"},
        flag={"type": "boolean"},
        nested={"type": "object"},
        text={"type": "string"},
        multiline={"type": "string"},
    )
    out = await _collect(raw, tool_call_format="glm_xml", tools=[tool])

    assert json.loads(_args_for(out)) == {
        "num": 5,
        "flag": True,
        "nested": {"a": [1, 2]},
        "text": "café ☕",
        "multiline": "line1\nline2",
    }


@pytest.mark.asyncio
async def test_glm_xml_unterminated_argument_is_terminal_parse_error() -> None:
    out = await _collect(
        "<tool_call>f<arg_key>a</arg_key><arg_value>1</tool_call>",
        tool_call_format="glm_xml",
    )

    assert out[-1].done is True
    assert out[-1].error_code == "MODEL_OUTPUT_PARSE_ERROR"
    assert "unterminated argument" in (out[-1].error_message or "")


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("raw", "reason"),
    [
        ("<tool_call>f<arg_value>1</arg_value></tool_call>", "invalid function name"),
        ("<tool_call>get weather</tool_call>", "invalid function name"),
        (
            "<tool_call>f<arg_key>a</arg_key><arg_value>1</arg_value><arg_value>2</arg_value></tool_call>",
            "expected <arg_key>",
        ),
        ("<tool_call>f<arg_key>a</arg_key>junk<arg_value>1</arg_value></tool_call>", "expected <arg_value>"),
        (
            "<tool_call>f<arg_key>a<arg_value>1</arg_value><arg_key>b</arg_key><arg_value>2</arg_value></tool_call>",
            "invalid argument key",
        ),
    ],
)
async def test_glm_xml_misplaced_tags_are_terminal_parse_errors(raw: str, reason: str) -> None:
    out = await _collect(raw, tool_call_format="glm_xml")

    assert _deltas(out) == []
    assert out[-1].error_code == "MODEL_OUTPUT_PARSE_ERROR"
    assert reason in (out[-1].error_message or "")


def test_glm_argument_scan_bounds_argument_count() -> None:
    import time

    from sie_server.processors.tool_call_parser import MAX_XML_PARAMS, _parse_glm_tool_call

    n = MAX_XML_PARAMS + 5_000
    raw = "f" + "".join(f"<arg_key>p{i}</arg_key><arg_value>{i}</arg_value>" for i in range(n))
    t0 = time.monotonic()
    with pytest.raises(ValueError, match=f"more than {MAX_XML_PARAMS} arguments"):
        _parse_glm_tool_call(raw)
    elapsed = time.monotonic() - t0
    assert elapsed < 2.0

    at_cap = "f" + "".join(f"<arg_key>p{i}</arg_key><arg_value>{i}</arg_value>" for i in range(MAX_XML_PARAMS))
    name, args = _parse_glm_tool_call(at_cap)
    assert name == "f"
    assert len(args) == MAX_XML_PARAMS


# ── Per-choice (n>1) streaming (H5) ──────────────────────────────────────


@pytest.mark.asyncio
async def test_parse_tool_call_stream_per_choice_state_isolated() -> None:
    """H5: streaming ``n>1`` runs each candidate through its own parser
    state. Two interleaved candidates each containing their own
    ``<tool_call>`` block must produce two independent tool-call deltas,
    each tagged with the right ``choice_index``.
    """
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(text_delta="A:", choice_index=0),
                    GenerationChunk(text_delta="B:", choice_index=1),
                    GenerationChunk(
                        text_delta='<tool_call>{"name":"fa","arguments":{}}</tool_call>',
                        choice_index=0,
                    ),
                    GenerationChunk(
                        text_delta='<tool_call>{"name":"fb","arguments":{}}</tool_call>',
                        choice_index=1,
                    ),
                    # Per-choice finishes (non-terminal with finish_reason).
                    GenerationChunk(text_delta="", choice_index=0, finish_reason="stop"),
                    GenerationChunk(text_delta="", choice_index=1, finish_reason="length"),
                    GenerationChunk(
                        text_delta="",
                        done=True,
                        finish_reason="stop",
                        prompt_tokens=3,
                        completion_tokens=8,
                    ),
                ]
            )
        )
    ]

    tool_calls_by_choice: dict[int, list] = {}
    for item in out:
        if item.tool_call_delta is not None:
            tool_calls_by_choice.setdefault(item.choice_index, []).append(item.tool_call_delta)

    # Each candidate produced its own tool-call announce+body pair.
    assert 0 in tool_calls_by_choice
    assert 1 in tool_calls_by_choice
    names_0 = {tcd.function_name for tcd in tool_calls_by_choice[0] if tcd.function_name}
    names_1 = {tcd.function_name for tcd in tool_calls_by_choice[1] if tcd.function_name}
    assert names_0 == {"fa"}
    assert names_1 == {"fb"}

    # Per-choice closures carry the right finish_reason — coerced to
    # ``tool_calls`` because each emitted a tool call.
    closures = [item for item in out if not item.done and item.finish_reason is not None and not item.tool_call_delta]
    closure_by_choice = {c.choice_index: c.finish_reason for c in closures}
    assert closure_by_choice.get(0) == "tool_calls"
    assert closure_by_choice.get(1) == "tool_calls"


@pytest.mark.asyncio
async def test_parse_tool_call_stream_per_choice_logprobs_pass_through() -> None:
    """H4: a chunk with ``logprobs`` set and an empty text_delta surfaces as
    its own logprobs-bearing chunk through the parser, preserving
    ``choice_index``. Required for streaming ``n>1`` + logprobs.
    """
    lp_entry = {"token": "t", "logprob": -0.5, "bytes": [116], "top_logprobs": []}
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(text_delta="t", choice_index=2, logprobs=(lp_entry,)),
                    GenerationChunk(text_delta="", done=True, finish_reason="stop"),
                ]
            )
        )
    ]
    lp_chunks = [c for c in out if c.logprobs]
    assert lp_chunks, "logprobs must survive the parser wrap"
    assert any(c.choice_index == 2 for c in lp_chunks)


@pytest.mark.asyncio
async def test_parse_tool_call_stream_non_streaming_per_candidate_tool_calls() -> None:
    """H5 non-streaming: the parser injects per-candidate ``tool_calls`` onto
    the terminal's ``candidates`` array by parsing each candidate's full
    text for ``<tool_call>`` blocks.
    """
    candidates = (
        {
            "text": 'Hi <tool_call>{"name":"get_weather","arguments":{"city":"Tokyo"}}</tool_call>',
            "finish_reason": "stop",
            "logprobs": None,
        },
        {
            "text": "plain answer",
            "finish_reason": "stop",
            "logprobs": None,
        },
    )
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(
                        text_delta="",
                        done=True,
                        finish_reason="stop",
                        prompt_tokens=4,
                        completion_tokens=10,
                        candidates=candidates,
                    ),
                ]
            )
        )
    ]
    terminal = out[-1]
    assert terminal.done is True
    assert terminal.candidates is not None
    cands = list(terminal.candidates)
    assert "tool_calls" in cands[0]
    assert cands[0]["tool_calls"][0]["function"]["name"] == "get_weather"
    # Per-candidate finish_reason coerced to ``tool_calls`` when a call was parsed.
    assert cands[0]["finish_reason"] == "tool_calls"
    assert "tool_calls" not in cands[1] or not cands[1].get("tool_calls")
    assert cands[1]["finish_reason"] == "stop"


# ── schema-driven argument values ──────────────────────────────────


def _qwen_call(name: str, **values: str) -> str:
    body = "".join(f"<parameter={key}>\n{value}\n</parameter>\n" for key, value in values.items())
    return f"<tool_call>\n<function={name}>\n{body}</function>\n</tool_call>"


def _glm_call(name: str, **values: str) -> str:
    body = "".join(f"<arg_key>{key}</arg_key><arg_value>{value}</arg_value>" for key, value in values.items())
    return f"<tool_call>{name}{body}</tool_call>"


_EDIT_TOOL = _tool(
    "edit_file",
    path={"type": "string"},
    old_str={"type": "string"},
    new_str={"type": "string"},
    content={"type": "string"},
    version={"type": "string"},
    pattern={"type": "string"},
    query={"type": "string"},
)

_EXACT_STRINGS = {
    "old_str": "    return x",
    "new_str": "        return y",
    "content": '{"version": "1.10"}',
    "version": "1.10",
    "pattern": "true",
    "query": "null",
}


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("raw", "tool_call_format"),
    [
        (_qwen_call("edit_file", **_EXACT_STRINGS), "qwen_xml"),
        (_glm_call("edit_file", **_EXACT_STRINGS), "glm_xml"),
    ],
)
async def test_string_parameters_keep_their_exact_text(raw: str, tool_call_format: str) -> None:
    import json

    out = await _collect(raw, tool_call_format=tool_call_format, tools=[_EDIT_TOOL])

    assert json.loads(_args_for(out)) == _EXACT_STRINGS


@pytest.mark.asyncio
async def test_qwen_xml_removes_only_the_template_newlines() -> None:
    import json

    raw = "<tool_call><function=edit_file><parameter=content>\nline\n\n</parameter></function></tool_call>"
    out = await _collect(raw, tool_call_format="qwen_xml", tools=[_EDIT_TOOL])

    assert json.loads(_args_for(out)) == {"content": "line\n"}


@pytest.mark.asyncio
async def test_glm_xml_string_values_are_not_json_unquoted() -> None:
    import json

    out = await _collect(_glm_call("edit_file", new_str='"hello"'), tool_call_format="glm_xml", tools=[_EDIT_TOOL])

    assert json.loads(_args_for(out)) == {"new_str": '"hello"'}


@pytest.mark.asyncio
@pytest.mark.parametrize("tool_call_format", ["qwen_xml", "glm_xml"])
async def test_undeclared_tool_and_parameter_values_stay_strings(tool_call_format: str) -> None:
    import json

    values = {"count": "5", "flag": "true", "data": '{"a": 1}'}
    raw = (_qwen_call if tool_call_format == "qwen_xml" else _glm_call)("unknown_tool", **values)
    out = await _collect(raw, tool_call_format=tool_call_format, tools=[_EDIT_TOOL])
    assert _deltas(out)[0].function_name == "unknown_tool"
    assert json.loads(_args_for(out)) == values

    raw = (_qwen_call if tool_call_format == "qwen_xml" else _glm_call)("edit_file", path="a.py", extra="5")
    out = await _collect(raw, tool_call_format=tool_call_format, tools=[_EDIT_TOOL])
    assert json.loads(_args_for(out)) == {"path": "a.py", "extra": "5"}


@pytest.mark.asyncio
async def test_values_without_tools_stay_strings() -> None:
    import json

    out = await _collect(_qwen_call("f", n="5"), tool_call_format="qwen_xml")

    assert json.loads(_args_for(out)) == {"n": "5"}


@pytest.mark.parametrize(
    ("schema", "text", "expected"),
    [
        ({"type": "integer"}, "42", 42),
        ({"type": "integer"}, "forty", "forty"),
        ({"type": "integer"}, "null", None),
        ({"type": "number"}, "1.5", 1.5),
        ({"type": "number"}, "2", 2),
        ({"type": "number"}, "nan", "nan"),
        ({"type": "number"}, "1e400", "1e400"),
        ({"type": "boolean"}, "False", False),
        ({"type": "boolean"}, "yes", "yes"),
        ({"type": "array"}, "[1, 2]", [1, 2]),
        ({"type": "object"}, "{'a': 1}", {"a": 1}),
        ({"type": "object"}, "{'a': {1, 2}}", "{'a': {1, 2}}"),
        ({"type": "object"}, '{"a": NaN}', '{"a": NaN}'),
        ({"type": "string"}, "null", "null"),
        ({"type": ["string", "null"]}, "null", None),
        ({"type": "string", "nullable": True}, "null", None),
        ({"type": ["integer", "null"]}, "7", 7),
        ({"anyOf": [{"type": "integer"}, {"type": "null"}]}, "7", 7),
        ({"anyOf": [{"type": "integer"}, {"type": "string"}]}, "7", "7"),
        ({"oneOf": [{"type": "integer"}, {"type": "boolean"}]}, "7", 7),
        ({"enum": [1, 2, 3]}, "2", 2),
        ({"enum": ["1", "2"]}, "2", "2"),
        ({"enum": [1, "a"]}, "1", "1"),
        ({"allOf": [{"type": "integer"}, {"minimum": 0}]}, "3", 3),
        ({"properties": {"a": {"type": "integer"}}}, '{"a": 1}', {"a": 1}),
        ({"items": {"type": "integer"}}, "[1]", [1]),
        ({"$ref": "#/$defs/Count"}, "9", 9),
        ({"$ref": "#/$defs/Missing"}, "9", "9"),
        ({"$ref": "https://example.com/schema"}, "9", "9"),
        ({"description": "no type"}, "9", "9"),
    ],
)
def test_argument_conversion_follows_the_declared_schema(schema: dict, text: str, expected: object) -> None:
    from sie_server.processors.tool_call_parser import _parse_xml_tool_call

    schemas = {"f": {"$defs": {"Count": {"type": "integer"}}, "properties": {"v": schema}}}
    _, args = _parse_xml_tool_call(f"<function=f><parameter=v>\n{text}\n</parameter></function>", schemas)

    assert args == {"v": expected}
    assert type(args["v"]) is type(expected)


def test_self_referencing_schema_does_not_loop() -> None:
    from sie_server.processors.tool_call_parser import _parse_xml_tool_call

    schemas = {"f": {"$defs": {"A": {"$ref": "#/$defs/A"}}, "properties": {"v": {"$ref": "#/$defs/A"}}}}

    assert _parse_xml_tool_call("<function=f><parameter=v>\n1\n</parameter></function>", schemas) == ("f", {"v": "1"})


@pytest.mark.parametrize("combinator", ["anyOf", "allOf"])
def test_shared_definitions_under_combinators_are_inferred_once(combinator: str) -> None:
    """Each definition names the next twice, so a walk without memoization visits 2**25 paths."""
    definitions = {f"D{i}": {combinator: [{"$ref": f"#/$defs/D{i + 1}"}] * 2} for i in range(25)}
    definitions["D25"] = {"type": "integer"}
    schemas = {"f": {"$defs": definitions, "properties": {"v": {"$ref": "#/$defs/D0"}}}}

    call = "<function=f><parameter=v>\n7\n</parameter></function>"
    assert tool_call_parser._parse_xml_tool_call(call, schemas) == ("f", {"v": 7})


@pytest.mark.parametrize("combinator", ["anyOf", "allOf"])
def test_a_definition_first_reached_at_the_depth_limit_is_inferred_again_nearer_the_root(combinator: str) -> None:
    """The long chain reaches ``Shared`` at the depth limit, where its variants are cut off; the short path does not."""
    depth = tool_call_parser._MAX_SCHEMA_DEPTH
    definitions: dict[str, object] = {f"C{i}": {combinator: [{"$ref": f"#/$defs/C{i + 1}"}]} for i in range(depth - 2)}
    definitions[f"C{depth - 2}"] = {combinator: [{"$ref": "#/$defs/Shared"}]}
    definitions["Shared"] = {"anyOf": [{"$ref": "#/$defs/Leaf"}]}
    root = {"$defs": definitions}
    parameter = {combinator: [{"$ref": "#/$defs/C0"}, {"$ref": "#/$defs/Shared"}]}

    definitions["Leaf"] = {"type": "integer"}
    assert tool_call_parser.schema_conversion_type(parameter, root) == "integer"
    definitions["Leaf"] = {"type": "null"}
    assert tool_call_parser.schema_allows_null({"anyOf": parameter[combinator]}, root)


@pytest.mark.asyncio
async def test_non_streaming_candidates_keep_a_malformed_block_as_text() -> None:
    import json

    malformed = "<tool_call>{not json</tool_call>"
    candidates = (
        {"text": "Calling " + malformed, "finish_reason": "stop", "logprobs": None},
        {"text": _qwen_call("edit_file", old_str="    a"), "finish_reason": "stop", "logprobs": None},
    )
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks([GenerationChunk(text_delta="", done=True, finish_reason="stop", candidates=candidates)]),
            tool_call_format="hermes_json",
            tools=[_EDIT_TOOL],
        )
    ]
    first, second = out[-1].candidates

    assert first["text"] == "Calling " + malformed
    assert not first.get("tool_calls")
    assert first["finish_reason"] == "stop"
    assert second["finish_reason"] == "stop"

    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks([GenerationChunk(text_delta="", done=True, finish_reason="stop", candidates=candidates[1:])]),
            tool_call_format="qwen_xml",
            tools=[_EDIT_TOOL],
        )
    ]
    (parsed,) = out[-1].candidates
    assert json.loads(parsed["tool_calls"][0]["function"]["arguments"]) == {"old_str": "    a"}
    assert parsed["finish_reason"] == "tool_calls"


@pytest.mark.asyncio
async def test_parse_tool_call_stream_keeps_reasoning_ahead_of_the_text_it_rode_on() -> None:
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    GenerationChunk(text_delta="", reasoning_delta="think "),
                    GenerationChunk(
                        text_delta='<tool_call>{"name":"get_weather","arguments":{"city":"Paris"}}</tool_call>',
                        reasoning_delta="more",
                    ),
                    GenerationChunk(text_delta="", done=True, finish_reason="stop"),
                ]
            )
        )
    ]

    assert [item.reasoning_delta for item in out if item.reasoning_delta] == ["think ", "more"]
    first_tool = next(index for index, item in enumerate(out) if item.tool_call_delta is not None)
    assert all(not item.reasoning_delta for item in out[first_tool:])
    assert out[-1].finish_reason == "tool_calls"


@pytest.mark.asyncio
async def test_text_held_inside_a_block_passes_on_as_progress() -> None:
    block = ["<tool_call>\n<function=write>\n", "<parameter=content>\n", "a\n", "b\n", "</parameter>\n</function>\n"]
    out = [
        item
        async for item in parse_tool_call_stream(
            _chunks(
                [
                    *(GenerationChunk(text_delta=text, choice_index=1) for text in block),
                    GenerationChunk(text_delta="</tool_call>", choice_index=1),
                    GenerationChunk(text_delta="", done=True, finish_reason="stop"),
                ]
            ),
            tool_call_format="qwen_xml",
        )
    ]

    first_call = next(index for index, item in enumerate(out) if item.tool_call_delta is not None)
    assert out[:first_call] == [GenerationChunk(text_delta="", choice_index=1)] * len(block)
    assert _args_for(out) == '{"content":"a\\nb"}'


@pytest.mark.asyncio
async def test_arguments_too_large_for_one_queue_message_end_with_a_parse_error() -> None:
    content = "\x01" * 200_000
    assert len(content) < tool_call_parser._MAX_TOOL_BUFFER_CHARS
    assert len(json.dumps({"content": content}).encode()) > 1024 * 1024
    out = await _collect(
        f"<tool_call>\n<function=write>\n<parameter=content>\n{content}\n</parameter>\n</function>\n</tool_call>",
        tool_call_format="qwen_xml",
    )

    assert out[-1].done is True
    assert out[-1].error_code == "MODEL_OUTPUT_PARSE_ERROR"
    assert "bytes, exceeds" in (out[-1].error_message or "")
    assert not _deltas(out)


def _hermes_call(name: str, **values: str) -> str:
    return "<tool_call>" + json.dumps({"name": name, "arguments": values}) + "</tool_call>"


_CANDIDATE_FORMATS = [
    pytest.param("hermes_json", _hermes_call, id="hermes_json"),
    pytest.param("qwen_xml", _qwen_call, id="qwen_xml"),
]


async def _parse_candidates(
    texts: list[str], tool_call_format: str, *, parallel_tool_calls: bool
) -> list[GenerationChunk]:
    candidates = tuple({"text": text, "finish_reason": "stop", "logprobs": None} for text in texts)
    return [
        item
        async for item in parse_tool_call_stream(
            _chunks([GenerationChunk(text_delta="", done=True, finish_reason="stop", candidates=candidates)]),
            tool_call_format=tool_call_format,
            parallel_tool_calls=parallel_tool_calls,
            tools=[_EDIT_TOOL],
        )
    ]


@pytest.mark.asyncio
@pytest.mark.parametrize(("tool_call_format", "call"), _CANDIDATE_FORMATS)
async def test_non_streaming_candidate_with_a_second_call_violates_parallel_tool_calls(
    tool_call_format: str, call
) -> None:
    out = await _parse_candidates(
        [call("edit_file", path="a"), call("edit_file", path="b") + call("edit_file", path="c")],
        tool_call_format,
        parallel_tool_calls=False,
    )

    terminal = out[-1]
    assert terminal.done is True
    assert terminal.finish_reason == "error"
    assert terminal.error_code == "parallel_tool_calls_violated"
    assert not terminal.candidates


@pytest.mark.asyncio
@pytest.mark.parametrize(("tool_call_format", "call"), _CANDIDATE_FORMATS)
async def test_non_streaming_candidates_with_one_call_each_pass_parallel_tool_calls_false(
    tool_call_format: str, call
) -> None:
    out = await _parse_candidates(
        [call("edit_file", path="a"), "Calling " + call("edit_file", path="b") + " done"],
        tool_call_format,
        parallel_tool_calls=False,
    )

    terminal = out[-1]
    assert terminal.error_code is None
    assert terminal.finish_reason == "tool_calls"
    assert [len(candidate["tool_calls"]) for candidate in terminal.candidates] == [1, 1]


@pytest.mark.asyncio
@pytest.mark.parametrize(("tool_call_format", "call"), _CANDIDATE_FORMATS)
async def test_non_streaming_candidate_keeps_every_call_when_parallel_tool_calls_is_true(
    tool_call_format: str, call
) -> None:
    out = await _parse_candidates(
        [call("edit_file", path="a") + call("edit_file", path="b")],
        tool_call_format,
        parallel_tool_calls=True,
    )

    (candidate,) = out[-1].candidates
    assert [json.loads(tc["function"]["arguments"])["path"] for tc in candidate["tool_calls"]] == ["a", "b"]


@pytest.mark.asyncio
async def test_non_streaming_candidate_with_a_malformed_first_block_keeps_one_call_under_parallel_false() -> None:
    malformed = "<tool_call>{not json</tool_call>"
    out = await _parse_candidates(
        [malformed + _hermes_call("edit_file", path="a")],
        "hermes_json",
        parallel_tool_calls=False,
    )

    (candidate,) = out[-1].candidates
    assert out[-1].error_code is None
    assert candidate["text"] == malformed
    assert [tc["function"]["name"] for tc in candidate["tool_calls"]] == ["edit_file"]