Skip to content

armgit / sie

Public Imported from GitHub
0

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

fix: keep chat streams alive through long tool calls (#746)

Krisztian Gajdar00d7d732f0ac
diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rs
index a5b71bc1f..d3b7add82 100644
--- a/packages/sie_gateway/src/handlers/sse.rs
+++ b/packages/sie_gateway/src/handlers/sse.rs
@@ -684,6 +684,7 @@ async fn run_sse_driver_with_lifecycle(
let overall_deadline = publish_instant + overall_timeout;
let mut last_chunk_at: Option<tokio::time::Instant> = None;
let mut first_seen = false;
+ let mut output_seen = false;
// Per-``choice_index`` ``role_emitted`` set (H4). For n=1 (the default)
// this only ever contains 0; for streaming n>1 each candidate's first
// delta gets an ``assistant`` role emitted independently, matching
@@ -744,7 +745,7 @@ async fn run_sse_driver_with_lifecycle(
if now >= overall_deadline {
send_error_chunk_before_output(
&mut first_output,
- !first_seen,
+ !output_seen,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -1075,12 +1076,12 @@ async fn run_sse_driver_with_lifecycle(
Err(broadcast::error::RecvError::Closed) => {
// The collector was removed (terminal chunk applied
// and outcome fired, or drop_pending_stream raced).
- // If we never saw a chunk, surface a generic
+ // If no output was forwarded, surface a generic
// result-channel-closed; otherwise the terminator
// was already sent below on the terminal chunk
// arm — guard against a double `[DONE]` by checking
- // `first_seen`.
- if !first_seen {
+ // `output_seen`.
+ if !output_seen {
send_error_chunk_before_output(
&mut first_output,
false,
@@ -1114,6 +1115,17 @@ async fn run_sse_driver_with_lifecycle(
}
first_seen = true;
last_chunk_at = Some(tokio::time::Instant::now());
+ let progress_only = !chunk.carries_output()
+ && !chunk.done
+ && chunk.finish_reason.is_none()
+ && chunk.error.is_none()
+ && chunk.logprobs.is_none();
+ // A bridge keeps its HTTP refusal until real output; progress only
+ // feeds the deadlines above.
+ if progress_only && first_output.is_some() {
+ continue;
+ }
+ output_seen |= !progress_only;
// Forward as an SSE event, then handle terminal/error/usage.
let is_terminal = chunk.done;
@@ -1328,6 +1340,7 @@ async fn run_sse_driver_with_lifecycle(
return;
}
if chunk.error.is_none()
+ && (chunk.carries_output() || chunk.done)
&& !(chunk.done
&& matches!(chunk.finish_reason.as_deref(), Some("cancelled" | "error")))
{
@@ -4192,6 +4205,314 @@ mod tests {
assert_eq!(got.finish_reason.as_deref(), Some("stop"));
}
+ // ── Long tool calls ────────────────────────────────────────────
+
+ struct DrivenStream {
+ payloads: Vec<String>,
+ local_successes: usize,
+ bridge: Option<Result<(), PreOutputFailure>>,
+ }
+
+ /// Feed the real stream collector and SSE driver a worker's chunk
+ /// timeline: each chunk is applied after its delay and numbered in order.
+ /// A terminal resolves the outcome; a timeline without one drops the
+ /// collector. With `bridge`, the driver holds a first-output gate the way
+ /// a remote bridge does.
+ async fn drive_worker_timeline(
+ timeline: Vec<(Duration, ChunkEnvelope)>,
+ bridge: bool,
+ ) -> DrivenStream {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ use crate::queue::streaming::StreamCollector;
+ use crate::state::demand_tracker::PhysicalLaneCatalog;
+
+ let recorder = Arc::new(client_disconnect_grace::TeardownRecorder::default());
+ let publisher: Arc<dyn WorkDispatcher> = recorder as Arc<dyn WorkDispatcher>;
+ let catalog = PhysicalLaneCatalog::try_from_raw([(
+ "default".to_string(),
+ "default".to_string(),
+ "default".to_string(),
+ )])
+ .expect("catalog");
+ let demand_tracker = Arc::new(DemandTracker::new(catalog));
+ let physical_lane = demand_tracker
+ .resolve_lane("default", "default", "default")
+ .expect("lane");
+ let (collector_tx, _collector_rx) = tokio::sync::oneshot::channel();
+ let mut collector = StreamCollector::new(
+ collector_tx,
+ "test/model".to_string(),
+ "default".to_string(),
+ );
+ let chunk_rx = collector.install_chunk_tap();
+ let (outcome_tx, outcome_rx) = tokio::sync::oneshot::channel();
+ let (durability_tx, durability_completion) = tokio::sync::oneshot::channel();
+ durability_tx
+ .send(Ok::<(), String>(()))
+ .expect("durability receiver is live");
+ let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(8);
+ let (gate_tx, mut gate_rx) = tokio::sync::oneshot::channel();
+ let local_successes = Arc::new(AtomicUsize::new(0));
+ let recorded = Arc::clone(&local_successes);
+ let driver = tokio::spawn(run_sse_driver_with_lifecycle(
+ SseDriverArgs {
+ first_output: bridge.then_some(gate_tx),
+ local_serving_model: Some("test/model".to_string()),
+ event_tx,
+ chunk_rx,
+ outcome_rx,
+ durability_completion,
+ publisher,
+ demand_tracker,
+ physical_lane,
+ request_id: "req-test".to_string(),
+ model: "test/model".to_string(),
+ pool: "default".to_string(),
+ bundle: "default".to_string(),
+ gpu: "test".to_string(),
+ endpoint: SseEndpoint::Chat {
+ include_usage: false,
+ include_reasoning: false,
+ },
+ stream_chat_id: "chatcmpl-test".to_string(),
+ created: 1,
+ first_chunk_timeout: Duration::from_secs(90),
+ inter_chunk_timeout: Duration::from_secs(30),
+ overall_timeout: Duration::from_secs(600),
+ was_direct_dispatched: false,
+ pool_fallback_lane_worker_count: 1,
+ },
+ None,
+ move |_: &str| {
+ recorded.fetch_add(1, Ordering::SeqCst);
+ },
+ ));
+ let worker = tokio::spawn(async move {
+ for (seq, (delay, mut chunk)) in (0u32..).zip(timeline) {
+ tokio::time::sleep(delay).await;
+ chunk.seq = seq;
+ if chunk.done {
+ assert!(matches!(collector.apply(chunk), ChunkApplied::Terminal));
+ let _ = outcome_tx.send(collector.build_outcome().expect("terminal outcome"));
+ return;
+ }
+ assert!(matches!(collector.apply(chunk), ChunkApplied::Delta));
+ }
+ });
+
+ let mut payloads = Vec::new();
+ while let Some(event) = event_rx.recv().await {
+ payloads.push(_event_data(event.expect("infallible event")).await);
+ }
+ driver.await.expect("driver task");
+ worker.abort();
+ DrivenStream {
+ payloads,
+ local_successes: local_successes.load(Ordering::SeqCst),
+ bridge: bridge.then(|| gate_rx.try_recv().expect("bridge gate resolved")),
+ }
+ }
+
+ fn progress_beat(every: Duration) -> (Duration, ChunkEnvelope) {
+ (every, _delta_chunk(0, ""))
+ }
+
+ fn failed_terminal() -> ChunkEnvelope {
+ let mut failed = _terminal_chunk("error", None);
+ failed.error = Some(
+ serde_json::from_value(json!({
+ "code": "MODEL_OUTPUT_PARSE_ERROR",
+ "message": "unterminated <tool_call> block",
+ }))
+ .expect("chunk error"),
+ );
+ failed
+ }
+
+ /// An agent's long `write` call: a preamble, two minutes decoding inside
+ /// the call with a chunk every `progress` (or none), then the call.
+ fn long_tool_call_timeline(
+ progress: Option<Duration>,
+ arguments: &str,
+ ) -> Vec<(Duration, ChunkEnvelope)> {
+ let call_chunk = |name: Option<&str>, arguments: &str| {
+ let mut chunk = _delta_chunk(0, "");
+ chunk.tool_calls = Some(vec![ToolCallDeltaWire {
+ index: 0,
+ id: name.map(|_| "call_write".to_string()),
+ kind: "function".to_string(),
+ function: Some(ToolCallFunctionWire {
+ name: name.map(str::to_string),
+ arguments: arguments.to_string(),
+ }),
+ }]);
+ chunk
+ };
+ let decode = Duration::from_secs(120);
+ let mut timeline = vec![(Duration::ZERO, _delta_chunk(0, "Writing the file now.\n"))];
+ let call_after = match progress {
+ Some(every) => {
+ let beats = (decode.as_secs() / every.as_secs()) as usize;
+ timeline.extend((0..beats).map(|_| progress_beat(every)));
+ Duration::ZERO
+ }
+ None => decode,
+ };
+ timeline.push((call_after, call_chunk(Some("write"), "")));
+ timeline.push((Duration::ZERO, call_chunk(None, arguments)));
+ timeline.push((Duration::ZERO, _terminal_chunk("tool_calls", None)));
+ timeline
+ }
+
+ fn chat_events(payloads: &[String]) -> Vec<Value> {
+ assert_eq!(payloads.last().map(String::as_str), Some("[DONE]"));
+ payloads[..payloads.len() - 1]
+ .iter()
+ .map(|payload| serde_json::from_str(payload).expect("chat chunk JSON"))
+ .collect()
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_worker_silent_through_a_long_tool_call_ends_at_the_inter_chunk_deadline() {
+ let driven = drive_worker_timeline(long_tool_call_timeline(None, "{}"), false).await;
+ let events = chat_events(&driven.payloads);
+
+ assert_eq!(events.len(), 2);
+ assert_eq!(
+ events[0]["choices"][0]["delta"]["content"],
+ "Writing the file now.\n"
+ );
+ assert_eq!(events[1]["error"]["code"], "inter_chunk_timeout");
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn progress_chunks_carry_a_long_tool_call_past_the_inter_chunk_deadline() {
+ let arguments = json!({
+ "filePath": "src/handlers.py",
+ "content": " return {\"ok\": True}\n".repeat(4096),
+ })
+ .to_string();
+ assert!(arguments.len() > 64 * 1024);
+
+ let driven = drive_worker_timeline(
+ long_tool_call_timeline(Some(Duration::from_secs(1)), &arguments),
+ false,
+ )
+ .await;
+ let events = chat_events(&driven.payloads);
+
+ assert!(events.iter().all(|event| event.get("error").is_none()));
+ let progress: Vec<&Value> = events
+ .iter()
+ .filter(|event| {
+ event["choices"][0]["delta"] == json!({})
+ && event["choices"][0]["finish_reason"].is_null()
+ })
+ .collect();
+ assert_eq!(progress.len(), 120);
+ assert!(progress
+ .iter()
+ .all(|event| event["object"] == "chat.completion.chunk"));
+ let streamed: String = events
+ .iter()
+ .filter_map(|event| event["choices"][0]["delta"]["tool_calls"].as_array())
+ .flatten()
+ .map(|call| call["function"]["arguments"].as_str().unwrap_or_default())
+ .collect();
+ assert_eq!(streamed, arguments);
+ assert_eq!(
+ events.last().expect("terminal")["choices"][0]["finish_reason"],
+ "tool_calls"
+ );
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn progress_alone_is_not_local_serving_output() {
+ let second = Duration::from_secs(1);
+ let failed = drive_worker_timeline(
+ vec![
+ progress_beat(second),
+ progress_beat(second),
+ (Duration::ZERO, failed_terminal()),
+ ],
+ false,
+ )
+ .await;
+ assert!(chat_events(&failed.payloads)
+ .iter()
+ .any(|event| event["error"]["code"] == "MODEL_OUTPUT_PARSE_ERROR"));
+ assert_eq!(failed.local_successes, 0);
+
+ let empty = drive_worker_timeline(
+ vec![
+ progress_beat(second),
+ (Duration::ZERO, _terminal_chunk("stop", None)),
+ ],
+ false,
+ )
+ .await;
+ assert_eq!(empty.local_successes, 1);
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_closed_tap_after_progress_alone_still_ends_the_stream() {
+ let second = Duration::from_secs(1);
+ let driven =
+ drive_worker_timeline(vec![progress_beat(second), progress_beat(second)], false).await;
+ let events = chat_events(&driven.payloads);
+
+ assert_eq!(events.len(), 3);
+ assert_eq!(events[2]["error"]["code"], "transport_failure");
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn a_bridge_keeps_its_refusal_through_progress() {
+ let second = Duration::from_secs(1);
+ let failed = drive_worker_timeline(
+ vec![
+ progress_beat(second),
+ progress_beat(second),
+ (Duration::ZERO, failed_terminal()),
+ ],
+ true,
+ )
+ .await;
+ let refusal = failed.bridge.expect("bridge").expect_err("refusal kept");
+ assert_eq!(refusal.code.as_deref(), Some("MODEL_OUTPUT_PARSE_ERROR"));
+ assert!(!failed
+ .payloads
+ .iter()
+ .any(|payload| payload.contains("\"delta\":{}")));
+
+ let stalled = drive_worker_timeline(
+ (0..70)
+ .map(|_| progress_beat(Duration::from_secs(10)))
+ .collect(),
+ true,
+ )
+ .await;
+ let refusal = stalled.bridge.expect("bridge").expect_err("refusal kept");
+ assert_eq!(refusal.code.as_deref(), Some("overall_timeout"));
+ assert!(refusal.unanswered);
+
+ let answered = drive_worker_timeline(
+ vec![
+ progress_beat(second),
+ (Duration::ZERO, _delta_chunk(0, "answer")),
+ progress_beat(second),
+ (Duration::ZERO, _terminal_chunk("stop", None)),
+ ],
+ true,
+ )
+ .await;
+ assert!(answered.bridge.expect("bridge").is_ok());
+ let events = chat_events(&answered.payloads);
+ assert_eq!(events.len(), 3);
+ assert_eq!(events[0]["choices"][0]["delta"]["content"], "answer");
+ assert_eq!(events[1]["choices"][0]["delta"], json!({}));
+ }
+
// ── Helpers ────────────────────────────────────────────────────
/// Extract the `data:` payload from an `axum::response::sse::Event`
@@ -4209,7 +4530,7 @@ mod tests {
use axum::body::to_bytes;
let stream = futures_util::stream::once(async move { Ok::<_, Infallible>(ev) });
let resp = Sse::new(stream).into_response();
- let bytes = to_bytes(resp.into_body(), 64 * 1024)
+ let bytes = to_bytes(resp.into_body(), 1024 * 1024)
.await
.expect("collect");
let s = std::str::from_utf8(&bytes).expect("utf8");
diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.py
index 28b7b263d..822092645 100644
--- a/packages/sie_server/src/sie_server/api/openai_local.py
+++ b/packages/sie_server/src/sie_server/api/openai_local.py
@@ -89,7 +89,11 @@ from sie_server.config.upstreams import RemoteServingDisabledError
from sie_server.core.grammar_routing import resolve_grammar_serving_model
from sie_server.core.inference_output import ScoreOutput
from sie_server.core.loader import serves_remotely
-from sie_server.core.runtime_options import GenerationTimeoutError, grammar_default_sampling
+from sie_server.core.runtime_options import (
+ GenerationTimeoutError,
+ grammar_default_sampling,
+ resolve_generation_timeouts,
+)
from sie_server.core.score_cost import MAX_SCORE_ITEMS, build_score_prepared_items
from sie_server.core.timing import RequestTiming
from sie_server.core.video_frames import (
@@ -130,6 +134,9 @@ router = APIRouter(prefix="/v1", tags=["openai-compat"], dependencies=[Depends(r
# it applies to either managed generation child on this route.
_PROXY_READ_TIMEOUT_S = float(os.environ.get("SIE_MLX_READ_TIMEOUT_S", "300"))
_PROXY_TIMEOUT = httpx.Timeout(connect=10.0, read=_PROXY_READ_TIMEOUT_S, write=10.0, pool=10.0)
+# Same cadence as the gateway's SSE keep-alive, so client idle limits see bytes
+# while the child is silent.
+_SSE_KEEPALIVE_S = 15.0
# Cap the request body so a huge messages/documents array can't be buffered/forwarded
# unbounded (the gateway caps prod ingress; these local routes must cap themselves).
_MAX_BODY_BYTES = int(os.environ.get("SIE_CHAT_MAX_BODY_BYTES", str(8 * 1024 * 1024)))
@@ -1109,6 +1116,33 @@ async def _read_upstream_body(response: httpx.Response) -> bytes:
return bytes(body)
+def _child_budget(config: Any, proxied: dict[str, Any], *, stream: bool) -> float | None:
+ """Return the overall budget for one request to the generation child, if it has one.
+
+ The child writes nothing while it generates a non-streaming answer, or
+ while its own tool parser holds a streamed call's argument until that
+ argument closes. Those requests are bounded by the generation's overall
+ budget, as the other generation routes are; ``None`` keeps any other
+ stream on the byte-gap bound that catches a wedged child.
+ """
+ holds_output = not stream or (bool(proxied.get("tools")) and proxied.get("tool_choice") != "none")
+ overall = resolve_generation_timeouts(config, None).overall_s if holds_output else None
+ return overall if overall is not None and overall > _PROXY_READ_TIMEOUT_S else None
+
+
+def _child_timeout(budget: float | None) -> httpx.Timeout:
+ if budget is None:
+ return _PROXY_TIMEOUT
+ return httpx.Timeout(connect=10.0, read=budget, write=10.0, pool=10.0)
+
+
+def _generation_timeout_exception() -> HTTPException:
+ return HTTPException(
+ status_code=status.HTTP_504_GATEWAY_TIMEOUT,
+ detail={"code": "generation_timeout", "message": "generation timed out"},
+ )
+
+
def _new_proxy_client() -> httpx.AsyncClient:
# Ignore HTTP(S)_PROXY: even a loopback URL must connect directly to the
# adapter-managed child rather than an operator-shell proxy.
@@ -1127,6 +1161,7 @@ async def _sanitize_sse_stream(
tool_call_limit: int | None = None,
strict_grammar: GrammarSpec | None = None,
include_reasoning: bool = False,
+ deadline: float | None = None,
) -> AsyncIterator[bytes]:
states: dict[int, ThinkingBlockStripper] = {}
held_contents: dict[int, list[str]] = {}
@@ -1137,8 +1172,26 @@ async def _sanitize_sse_stream(
received = 0
saw_done = False
terminal_outcome_selected = False
+ chunks = response.aiter_bytes()
+ next_chunk: asyncio.Future[bytes | None] | None = None
+ loop = asyncio.get_running_loop()
try:
- async for chunk in response.aiter_bytes():
+ while True:
+ if deadline is not None and loop.time() >= deadline:
+ logger.warning("generation child chat stream exceeded its generation budget")
+ terminal_outcome_selected = True
+ yield _upstream_error_event("generation timed out", code="generation_timeout")
+ return
+ next_chunk = next_chunk or asyncio.ensure_future(anext(chunks, None))
+ wait_s = _SSE_KEEPALIVE_S if deadline is None else min(_SSE_KEEPALIVE_S, deadline - loop.time())
+ done, _ = await asyncio.wait({next_chunk}, timeout=wait_s)
+ if not done:
+ yield b": keepalive\n\n"
+ continue
+ chunk = next_chunk.result()
+ next_chunk = None
+ if chunk is None:
+ break
received += len(chunk)
if received > _MAX_CHAT_RESPONSE_BYTES:
logger.error("generation child SSE exceeded %d bytes", _MAX_CHAT_RESPONSE_BYTES)
@@ -1218,6 +1271,11 @@ async def _sanitize_sse_stream(
terminal_outcome_selected = True
yield _upstream_error_event()
finally:
+ if next_chunk is not None:
+ next_chunk.cancel()
+ await asyncio.wait({next_chunk})
+ if not next_chunk.cancelled():
+ next_chunk.exception()
try:
await aclose_with_error_precedence(
response,
@@ -1686,8 +1744,10 @@ async def _chat_completions(
if slot is not None:
await slot.acquire()
client = _new_proxy_client()
+ budget = _child_budget(config, proxied, stream=True)
+ deadline = None if budget is None else asyncio.get_running_loop().time() + budget
try:
- upstream_request = client.build_request("POST", url, json=proxied)
+ upstream_request = client.build_request("POST", url, json=proxied, timeout=_child_timeout(budget))
upstream = await client.send(upstream_request, stream=True)
except asyncio.CancelledError:
await client.aclose()
@@ -1743,6 +1803,7 @@ async def _chat_completions(
tool_call_limit=tool_call_limit,
strict_grammar=strict_grammar,
include_reasoning=include_reasoning,
+ deadline=deadline,
),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no", **route.headers()},
@@ -1750,15 +1811,22 @@ async def _chat_completions(
if slot is not None:
await slot.acquire()
+ budget = _child_budget(config, proxied, stream=False)
try:
async with _new_proxy_client() as client:
try:
- async with client.stream("POST", url, json=proxied) as upstream:
+ async with (
+ asyncio.timeout(budget),
+ client.stream("POST", url, json=proxied, timeout=_child_timeout(budget)) as upstream,
+ ):
raw = await _read_upstream_body(upstream)
upstream_status = upstream.status_code
except httpx.HTTPError:
logger.warning("generation child chat request failed", exc_info=True)
return _upstream_error_response("generation child is unavailable")
+ except TimeoutError:
+ logger.warning("generation child chat request exceeded its generation budget")
+ raise _generation_timeout_exception() from None
except ValueError:
logger.error("generation child chat response exceeded its byte limit")
return _upstream_error_response("upstream response exceeded the byte limit")
diff --git a/packages/sie_server/src/sie_server/processors/hybrid_usage.py b/packages/sie_server/src/sie_server/processors/hybrid_usage.py
index 757cafd18..8ab86fce7 100644
--- a/packages/sie_server/src/sie_server/processors/hybrid_usage.py
+++ b/packages/sie_server/src/sie_server/processors/hybrid_usage.py
@@ -30,18 +30,6 @@ class HybridCount:
count_tokens: Callable[[str], Awaitable[int]]
-def _only_reasoning(chunk: GenerationChunk) -> bool:
- return (
- not chunk.text_delta
- and not chunk.done
- and chunk.finish_reason is None
- and chunk.tool_call_delta is None
- and chunk.logprobs is None
- and chunk.candidates is None
- and chunk.error_code is None
- )
-
-
def _candidate_texts(candidate: dict[str, Any]) -> list[str]:
texts = [candidate.get("text") or ""]
for call in candidate.get("tool_calls") or ():
@@ -60,7 +48,8 @@ async def count_hybrid_usage(
upstream's counts in ``upstream_usage``. A completion the upstream counted
but that returned no text counts as one token, and no completion counts
above ``count.completion_limit``. Any other terminal passes through.
- ``keep_reasoning`` leaves the counted reasoning on the chunks.
+ ``keep_reasoning`` leaves the counted reasoning on the chunks; otherwise a
+ chunk that carried only reasoning stays in the stream, empty, as progress.
"""
texts: dict[int, list[str]] = {}
outcome_selected = False
@@ -73,8 +62,6 @@ async def count_hybrid_usage(
for index, candidate in enumerate(chunk.candidates or ()):
texts.setdefault(index, []).extend(_candidate_texts(candidate))
if chunk.reasoning_delta and not keep_reasoning:
- if _only_reasoning(chunk):
- continue
chunk = replace(chunk, reasoning_delta="")
if chunk.done and chunk.prompt_tokens is not None and chunk.completion_tokens is not None:
completion = 0
diff --git a/packages/sie_server/src/sie_server/processors/tool_call_parser.py b/packages/sie_server/src/sie_server/processors/tool_call_parser.py
index b7fe6e8a6..c91b63bc4 100644
--- a/packages/sie_server/src/sie_server/processors/tool_call_parser.py
+++ b/packages/sie_server/src/sie_server/processors/tool_call_parser.py
@@ -6,8 +6,10 @@ stream. This module converts those tagged regions into the worker/gateway
``tool_call_delta`` shape while preserving surrounding prose as normal text.
This first implementation emits arguments atomically when the closing tag arrives.
-It is intentionally strict: malformed JSON or missing ``name``/``arguments``
-turns into a terminal ``MODEL_OUTPUT_PARSE_ERROR`` chunk.
+While a block is open, each text delta it absorbs is passed on as an empty
+progress chunk, so a consumer that bounds the gap between chunks sees a call that
+is still being generated. It is intentionally strict: malformed JSON or missing
+``name``/``arguments`` turns into a terminal ``MODEL_OUTPUT_PARSE_ERROR`` chunk.
The XML forms carry every argument value as text. Each value is converted by
the JSON-schema type its parameter declares in the request's ``tools``: a
@@ -72,11 +74,10 @@ ToolCallFormat = Literal["auto", "qwen_xml", "hermes_json", "glm_xml"]
# stream as a parse error instead of an OOM.
_MAX_TOOL_BUFFER_CHARS = 256 * 1024
_MAX_TEXT_BUFFER_CHARS = 256 * 1024
-# Cap on the deserialised ``arguments`` blob's re-serialised length.
-# Defends against pathological deeply-nested JSON that survives
-# ``json.loads`` (Python's default recursion limit) but takes seconds
-# to ``json.dumps`` back out.
-_MAX_TOOL_ARGUMENTS_CHARS = 64 * 1024
+# A call's serialised ``arguments`` cross the queue as one chunk, and one queue
+# message carries at most 1 MiB by default. JSON escaping at most doubles
+# printable ASCII, so any such block that fits the tool buffer fits this bound.
+_MAX_TOOL_ARGUMENTS_BYTES = 2 * _MAX_TOOL_BUFFER_CHARS
ToolSchemas = Mapping[str, Mapping[str, Any]]
@@ -586,6 +587,8 @@ async def _parse_tool_call_stream_impl(
yield ev
if terminal:
return
+ if not (emitted or chunk.reasoning_delta or chunk.logprobs or chunk.finish_reason or chunk.done):
+ yield GenerationChunk(text_delta="", choice_index=idx)
# Forward the chunk's logprobs slice (already tagged with
# choice_index) as its own chunk so streaming logprobs survive
# the parser wrap. Tool-call deltas from the model surface via
@@ -826,12 +829,11 @@ def _tool_call_deltas(
arguments = {}
try:
arguments_json = json.dumps(arguments, separators=(",", ":"), ensure_ascii=False)
+ size = len(arguments_json.encode())
except (TypeError, ValueError) as exc:
raise ValueError(f"tool-call 'arguments' is not JSON-serialisable: {exc}") from exc
- if len(arguments_json) > _MAX_TOOL_ARGUMENTS_CHARS:
- raise ValueError(
- f"tool-call 'arguments' serialised to {len(arguments_json)} chars, exceeds {_MAX_TOOL_ARGUMENTS_CHARS}"
- )
+ if size > _MAX_TOOL_ARGUMENTS_BYTES:
+ raise ValueError(f"tool-call 'arguments' serialised to {size} bytes, exceeds {_MAX_TOOL_ARGUMENTS_BYTES}")
call_id = f"call_{uuid.uuid4().hex[:24]}"
return [
ToolCallDelta(index=index, id=call_id, function_name=name, arguments_delta=""),
diff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.py
index 035d756a9..bc9b5ed1d 100644
--- a/packages/sie_server/tests/api/test_openai_local.py
+++ b/packages/sie_server/tests/api/test_openai_local.py
@@ -9,7 +9,11 @@ from __future__ import annotations
import base64
import json
-from collections.abc import AsyncIterator, Callable
+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
@@ -2658,3 +2662,208 @@ def test_mlx_thinking_chat_stream_keeps_the_answer_beside_split_reasoning(
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
diff --git a/packages/sie_server/tests/processors/test_hybrid_usage.py b/packages/sie_server/tests/processors/test_hybrid_usage.py
index 5ee64a085..56e9da672 100644
--- a/packages/sie_server/tests/processors/test_hybrid_usage.py
+++ b/packages/sie_server/tests/processors/test_hybrid_usage.py
@@ -78,7 +78,7 @@ async def test_terminal_reports_the_worker_count_and_keeps_the_upstream_figure_b
],
_count(),
)
- assert [chunk.text_delta for chunk in out] == ["answer here", ""]
+ assert [chunk.text_delta for chunk in out] == ["", "answer here", ""]
assert all(not chunk.reasoning_delta for chunk in out)
terminal = out[-1]
assert (terminal.prompt_tokens, terminal.completion_tokens, terminal.cached_tokens) == (2, 5, None)
@@ -302,6 +302,23 @@ async def test_queued_upstream_chat_reports_the_worker_count(hybrid: tuple, stre
assert sent["messages"] == [{"role": "user", "content": "question"}]
+async def test_private_upstream_reasoning_keeps_the_queued_stream_publishing(
+ hybrid: tuple, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr("sie_server.processors.streaming._FLUSH_INTERVAL_S", 0)
+ reasoning = [
+ {"choices": [{"index": 0, "delta": {"reasoning_content": f"step {step} "}, "finish_reason": None}]}
+ for step in range(3)
+ ]
+ respond(hybrid, frames=[*reasoning, *_frames()[1:]])
+ chunks = await run(hybrid)
+ answer = next(index for index, chunk in enumerate(chunks) if chunk.get("text_delta"))
+ assert answer >= len(reasoning)
+ assert all(chunk["text_delta"] == "" and not chunk["done"] for chunk in chunks[:answer])
+ assert chunks[answer]["text_delta"] == "answer here"
+ assert "step" not in json.dumps(chunks)
+
+
async def test_a_platform_upstream_reports_its_own_count() -> None:
setup = _processor("sie", [])
setup[1]._get_tokenizer.side_effect = AssertionError("a platform upstream counts with its own tokenizer")
diff --git a/packages/sie_server/tests/processors/test_streaming_integration.py b/packages/sie_server/tests/processors/test_streaming_integration.py
index 8b7871352..c594fc298 100644
--- a/packages/sie_server/tests/processors/test_streaming_integration.py
+++ b/packages/sie_server/tests/processors/test_streaming_integration.py
@@ -24,6 +24,7 @@ Two scenarios:
from __future__ import annotations
import asyncio
+import json
import time
from collections.abc import AsyncIterator
from typing import Any
@@ -34,6 +35,7 @@ import pytest
from sie_server.adapters._generation_base import GenerationAdapter, GenerationChunk
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters.base import ModelCapabilities, ModelDims
+from sie_server.processors import tool_call_parser
from sie_server.processors.streaming import StreamingProcessor
@@ -93,6 +95,7 @@ class _PacedAdapter(GenerationAdapter):
temperature: float = 1.0,
top_p: float = 1.0,
stop: list[str] | None = None,
+ **_: Any,
) -> AsyncIterator[GenerationChunk]:
_ = (prompt, max_new_tokens, temperature, top_p, stop)
for i, delta in enumerate(self._deltas):
@@ -108,11 +111,13 @@ class _PacedAdapter(GenerationAdapter):
)
-def _make_registry(adapter: GenerationAdapter) -> MagicMock:
+def _make_registry(adapter: GenerationAdapter, *, tool_parser: str | None = None) -> MagicMock:
registry = MagicMock()
registry.is_loaded.return_value = True
registry.get.return_value = adapter
registry.device = "cpu"
+ if tool_parser is not None:
+ registry.get_config.return_value.resolve_profile.return_value.loadtime = {"tool_call_parser": tool_parser}
return registry
@@ -271,3 +276,144 @@ async def test_streaming_cancel_mid_stream_produces_cancelled_terminal() -> None
assert body # something was produced
assert body != "abcdef" # but not the full scripted output
msg.ack.assert_awaited()
+
+
+_WRITE_TOOL = {
+ "type": "function",
+ "function": {
+ "name": "write",
+ "description": "Write a file",
+ "parameters": {
+ "type": "object",
+ "properties": {"filePath": {"type": "string"}, "content": {"type": "string"}},
+ "required": ["filePath", "content"],
+ },
+ },
+}
+
+
+def _source_file(functions: int) -> str:
+ return "".join(f'def handler_{i}(request):\n return {{"id": {i}, "ok": True}}\n\n' for i in range(functions))
+
+
+def _write_call(parser_name: str, file_path: str, content: str) -> str:
+ if parser_name == "glm47":
+ return (
+ f"<tool_call>write<arg_key>filePath</arg_key><arg_value>{file_path}</arg_value>"
+ f"<arg_key>content</arg_key><arg_value>{content}</arg_value></tool_call>"
+ )
+ return (
+ f"<tool_call>\n<function=write>\n<parameter=filePath>\n{file_path}\n</parameter>\n"
+ f"<parameter=content>\n{content}\n</parameter>\n</function>\n</tool_call>"
+ )
+
+
+def _tool_work_item() -> dict[str, Any]:
+ return _make_work_item(
+ generate={
+ "prompt": "Write the handlers.",
+ "max_new_tokens": 8192,
+ "tools": [_WRITE_TOOL],
+ "tool_choice": "auto",
+ }
+ )
+
+
+def _tool_arguments(chunks: list[dict[str, Any]]) -> tuple[str, dict[str, Any]]:
+ calls = [call for chunk in chunks for call in chunk.get("tool_calls") or ()]
+ name = "".join(call["function"].get("name") or "" for call in calls)
+ return name, json.loads("".join(call["function"]["arguments"] for call in calls))
+
+
+ ("parser_name", "preamble"),
+ [("qwen3_coder", "Writing the file now.\n"), ("qwen3_coder", ""), ("glm47", "Writing the file now.\n")],
+)
+async def test_long_tool_call_keeps_the_stream_publishing_while_the_block_decodes(
+ parser_name: str, preamble: str
+) -> None:
+ """A paced engine stream that spends most of its time inside one long
+ ``write`` call. The gateway ends a queued stream that publishes nothing
+ for its inter-chunk (or first-chunk) deadline, so the worker must keep
+ publishing while the parser holds the block; the call itself must still
+ arrive intact.
+ """
+ content = _source_file(100)
+ text = preamble + _write_call(parser_name, "src/handlers.py", content)
+ adapter = _PacedAdapter(deltas=text.splitlines(keepends=True), gap_s=0.004)
+ nc = AsyncMock()
+ proc = StreamingProcessor(nc=nc, registry=_make_registry(adapter, tool_parser=parser_name), worker_id="w1")
+ msg = _make_msg(_tool_work_item())
+ published_at: list[float] = []
+ started_at = time.monotonic()
+
+ async def _capture(*_args: Any, **_kwargs: Any) -> None:
+ published_at.append(time.monotonic() - started_at)
+
+ nc.publish.side_effect = _capture
+ await proc.process(msg, "test/model")
+
+ decoded = _decode_chunks(nc)
+ assert [chunk["seq"] for chunk in decoded] == list(range(len(decoded)))
+ gaps = [later - earlier for earlier, later in zip([0.0, *published_at], published_at, strict=False)]
+ assert max(gaps) < published_at[-1] / 4, f"worker went {max(gaps):.3f}s of {published_at[-1]:.3f}s silent"
+ first_call = next(index for index, chunk in enumerate(decoded) if chunk.get("tool_calls"))
+ texts = [index for index, chunk in enumerate(decoded[:first_call]) if chunk["text_delta"]]
+ progress = decoded[texts[-1] + 1 if texts else 0 : first_call]
+ assert len(progress) > 2
+ assert all(chunk["text_delta"] == "" and not chunk["done"] and not chunk.get("tool_calls") for chunk in progress)
+ assert "".join(chunk["text_delta"] for chunk in decoded) == preamble
+ assert _tool_arguments(decoded) == ("write", {"filePath": "src/handlers.py", "content": content})
+ assert decoded[-1]["done"] is True
+ assert decoded[-1]["finish_reason"] == "tool_calls"
+ msg.ack.assert_awaited()
+
+
+async def test_tool_call_arguments_over_64_kib_reach_the_wire_intact() -> None:
+ content = _source_file(2000)
+ assert len(content) > 96 * 1024
+ text = _write_call("qwen3_coder", "src/handlers.py", content)
+ deltas = [text[start : start + 4096] for start in range(0, len(text), 4096)]
+ nc = AsyncMock()
+ proc = StreamingProcessor(
+ nc=nc,
+ registry=_make_registry(_PacedAdapter(deltas=deltas, gap_s=0), tool_parser="qwen3_coder"),
+ worker_id="w1",
+ )
+ msg = _make_msg(_tool_work_item())
+ await proc.process(msg, "test/model")
+
+ decoded = _decode_chunks(nc)
+ assert all("error" not in chunk for chunk in decoded), decoded[-1]
+ assert _tool_arguments(decoded) == ("write", {"filePath": "src/handlers.py", "content": content})
+ assert decoded[-1]["finish_reason"] == "tool_calls"
+ msg.ack.assert_awaited()
+
+
+async def test_the_largest_admitted_tool_call_fits_one_queue_message() -> None:
+ """The worker publishes a call's arguments as one chunk, and one queue
+ message carries at most 1 MiB. A block of printable ASCII that fills the
+ parser's tool buffer and doubles under JSON escaping must still fit.
+ """
+ prefix = "<tool_call>\n<function=write>\n<parameter=content>\n"
+ suffix = "\n</parameter>\n</function>\n</tool_call>"
+ body_overhead = len(prefix) - len("<tool_call>") + len(suffix) - len("</tool_call>")
+ content = '"' * (tool_call_parser._MAX_TOOL_BUFFER_CHARS - body_overhead)
+ text = prefix + content + suffix
+ deltas = [text[start : start + 4096] for start in range(0, len(text), 4096)]
+ nc = AsyncMock()
+ proc = StreamingProcessor(
+ nc=nc,
+ registry=_make_registry(_PacedAdapter(deltas=deltas, gap_s=0), tool_parser="qwen3_coder"),
+ worker_id="w1",
+ )
+ msg = _make_msg(_tool_work_item())
+ await proc.process(msg, "test/model")
+
+ decoded = _decode_chunks(nc)
+ assert all("error" not in chunk for chunk in decoded), decoded[-1]
+ assert _tool_arguments(decoded) == ("write", {"content": content})
+ assert max(len(call.args[1]) for call in nc.publish.await_args_list) < 1024 * 1024
diff --git a/packages/sie_server/tests/processors/test_tool_call_parser.py b/packages/sie_server/tests/processors/test_tool_call_parser.py
index 50e7ede39..9ef849b72 100644
--- a/packages/sie_server/tests/processors/test_tool_call_parser.py
+++ b/packages/sie_server/tests/processors/test_tool_call_parser.py
@@ -1,9 +1,11 @@
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
@@ -1012,3 +1014,41 @@ async def test_parse_tool_call_stream_keeps_reasoning_ahead_of_the_text_it_rode_
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"
+
+
+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"}'
+
+
+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)