Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Keep a passthrough SSE stream alive while llama-server prefills (#10911)
Daniel Han91b5adb0283a
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex f1b902090da..632b64d1743 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -620,6 +620,8 @@ def _byte_fallback_prompt_tokens(prompt: str) -> int:_OPENAI_COMPAT_STREAM_STALL_TIMEOUT_ENV = "UNSLOTH_OPENAI_COMPAT_STREAM_STALL_TIMEOUT"+_OPENAI_COMPAT_STREAM_KEEPALIVE_ENV = "UNSLOTH_OPENAI_COMPAT_STREAM_KEEPALIVE_INTERVAL"+_OPENAI_COMPAT_FIRST_TOKEN_TIMEOUT_ENV = "UNSLOTH_OPENAI_COMPAT_FIRST_TOKEN_TIMEOUT"def _positive_float_env(env_name: str, default):@@ -1711,11 +1713,11 @@ except ImportError:def _llama_non_streaming_generation_timeout() -> httpx.Timeout:- return httpx.Timeout(_DEFAULT_FIRST_TOKEN_TIMEOUT_S)+ return httpx.Timeout(_first_token_timeout_s())def _llama_streaming_generation_timeout() -> httpx.Timeout:- return httpx.Timeout(_DEFAULT_FIRST_TOKEN_TIMEOUT_S)+ return httpx.Timeout(_first_token_timeout_s())def _set_stream_response_read_timeout(@@ -1736,6 +1738,30 @@ _STREAM_DISCONNECT_POLL_TIMEOUT_S = 0.25_OPENAI_PASSTHROUGH_PREHEADER_STATUS_WINDOW_S = 0.1_OPENAI_PASSTHROUGH_PENDING_RESPONSE_KEEPALIVE_S = 5.0_OPENAI_PASSTHROUGH_SSE_KEEPALIVE = ": keep-alive\n\n"+# Deliberately a whole SSE comment FRAME, blank line included, not a bare comment+# line. A bare line would ride at the head of the next frame, and a client that+# classifies a frame by its first character -- `startswith(":")` is a comment,+# else `startswith("data:")` -- then files the whole frame as a comment and drops+# the chunk. Measured: raw curl and Node undici readers lose the token that way.+# The cost of the blank line is that openai's and anthropic's Python decoders+# dispatch one empty event per tick IF the upstream has sent an SSE `id:`, since+# a retained last-event-id satisfies their "anything to dispatch" test; that is a+# decoder conformance bug, it costs an ignorable event rather than data, and+# llama-server does not send `id:`. Losing a token is the worse failure.+++class _LlamaStreamKeepalive:+ """Pump wake-up, translated per call site and never treated as an upstream+ item (no stream state, healer or monitor). An object, not the comment+ string: every site filters relayed lines on ``startswith("data:")``."""++ __slots__ = ()++ def __repr__(self) -> str:+ return "<llama-stream-keepalive>"+++_LLAMA_STREAM_KEEPALIVE = _LlamaStreamKeepalive()# Lets a client tell "queued" from "backend silent"; SSE comments, so readers ignore both._OPENAI_ADMISSION_SSE_WAIT = ": admission-wait\n\n"# Paired with the above: the slot is ours, so a suspended client clock starts now.@@ -2562,6 +2588,47 @@ def _openai_compat_stream_stall_timeout():)+def _finite_positive_float_env(env_name: str, default):+ """``_positive_float_env`` with infinities rejected.++ ``float("inf")`` is positive, so the plain parser accepts it and the caller+ ends up with a deadline that never fires; ``1e309`` parses to it too, which+ a human writing a large number will not expect. Both fall back to the+ default here. NaN already does, since no comparison with it is true.+ """+ value = _positive_float_env(env_name, default)+ if isinstance(value, float) and not math.isfinite(value):+ return default+ return value+++def _first_token_timeout_s() -> float:+ """How long a passthrough waits for llama-server's first token.++ Unlike the stall guard, 0 does NOT disable it: the deadline is unconditional+ downstream, so a non-positive value keeps the default. Raise it, do not lower+ it: the same value builds the non-streaming timeout, where httpx.Timeout's+ positional form also covers connect/read/write/pool.+ """+ value = _finite_positive_float_env(+ _OPENAI_COMPAT_FIRST_TOKEN_TIMEOUT_ENV,+ _DEFAULT_FIRST_TOKEN_TIMEOUT_S,+ )+ return _DEFAULT_FIRST_TOKEN_TIMEOUT_S if value is None else value+++def _openai_passthrough_stream_keepalive_interval():+ """Idle gap before a passthrough relay emits an SSE keepalive comment.++ llama-server is silent for the whole prefill and undici aborts a response+ after 300s with no bytes. 0 relays in silence like before.+ """+ return _finite_positive_float_env(+ _OPENAI_COMPAT_STREAM_KEEPALIVE_ENV,+ _OPENAI_PASSTHROUGH_PENDING_RESPONSE_KEEPALIVE_S,+ )++def _openai_passthrough_upstream_headers(*, llama_backend = None) -> dict:headers = {}auth_headers = getattr(llama_backend, "_auth_headers", None)@@ -2571,50 +2638,6 @@ def _openai_passthrough_upstream_headers(*, llama_backend = None) -> dict:return headers-class _CompatSameTaskTimeout:- """Same-task timeout fallback for Python versions before asyncio.timeout."""-- def __init__(self, timeout_s: float):- self.timeout_s = timeout_s- self._task = None- self._handle = None- self._timed_out = False- self._cancelling = 0-- async def __aenter__(self):- self._task = asyncio.current_task()- if self._task is None:- return self- if hasattr(self._task, "cancelling"):- self._cancelling = self._task.cancelling()- loop = asyncio.get_running_loop()- self._handle = loop.call_later(max(self.timeout_s, 0), self._cancel_task)- return self-- async def __aexit__(self, exc_type, exc, tb):- if self._handle is not None:- self._handle.cancel()- if exc_type is not None and issubclass(exc_type, asyncio.CancelledError):- if self._timed_out:- if self._task is not None and hasattr(self._task, "uncancel"):- if self._task.uncancel() > self._cancelling:- return None- raise asyncio.TimeoutError from exc- return None-- def _cancel_task(self) -> None:- self._timed_out = True- if self._task is not None:- self._task.cancel()---def _same_task_timeout(timeout_s: float):- timeout_ctx = getattr(asyncio, "timeout", None)- if timeout_ctx is not None:- return timeout_ctx(timeout_s)- return _CompatSameTaskTimeout(timeout_s)--class _SameTaskStreamingResponse(StreamingResponse):"""StreamingResponse without Starlette's legacy AnyIO task-group wrapper."""@@ -2775,15 +2798,17 @@ async def _tunnel_safe_json(coro, *, label: str):async def _aclose_stream_resources(*,watchers = (),+ items = None,iterator = None,resp = None,client = None,) -> None:"""Tear down an httpx streaming generator's resources in the required order:- cancel + bounded-wait each watcher task, then aclose() the byte/line iterator,- the response, and the client. Each step swallows its own exceptions so teardown- always completes; a close-time CancelledError is re-raised only after every- step has run. See _anthropic_passthrough_stream for the ordering rationale."""+ cancel + bounded-wait each watcher task, then aclose() the relay pump, the+ byte/line iterator, the response, and the client. Each step swallows its own+ exceptions so teardown always completes; a close-time CancelledError is+ re-raised only after every step has run. See _anthropic_passthrough_stream+ for the ordering rationale."""# Bounded: a watcher parked in Request.is_disconnected() can swallow cancel(), so an# unbounded await holds the response open. Stopped together, so N watchers cost one# bound before the closes, which are what stop llama-server decoding. #7617@@ -2801,6 +2826,15 @@ async def _aclose_stream_resources(except (asyncio.CancelledError, Exception):passclose_cancelled = False+ # Before `iterator`, awaited out: cancelling the pump's read is not enough,+ # the iterator stays ag_running until the pump's finally returns. #7617+ if items is not None:+ try:+ await items.aclose()+ except asyncio.CancelledError:+ close_cancelled = True+ except Exception:+ passif iterator is not None:try:await iterator.aclose()@@ -2967,6 +3001,19 @@ async def _send_stream_with_preheader_cancel(pass+def _ceiling_for_first_read(+ first_token_deadline: float, post_first_item_read_timeout_s: Optional[float]+) -> Optional[float]:+ """The latched socket read timeout for a fixed post-token bound.++ None means the operator disabled the stall guard, so nothing bounds the+ socket either.+ """+ if post_first_item_read_timeout_s is None:+ return None+ return max(first_token_deadline - time.monotonic(), post_first_item_read_timeout_s)++async def _aiter_llama_stream_items(async_iter,*,@@ -2977,72 +3024,127 @@ async def _aiter_llama_stream_items(post_first_item_read_timeout_s: Optional[Union[float, Callable[[], Optional[float]]]] = _DEFAULT_STREAM_STALL_TIMEOUT_S,+ keepalive_interval_s: Optional[float] = None,):+ """Relay upstream items, waking every ``keepalive_interval_s`` to yield+ ``_LLAMA_STREAM_KEEPALIVE`` while the socket is silent.++ One ``__anext__`` per item, awaited across as many ticks as it takes.+ ``asyncio.wait`` is used because it does not cancel on timeout, and the read+ must be neither cancelled nor restarted to tick: httpcore closes the body+ stream on any streaming exception, so a ReadTimeout here is terminal.+ """if first_token_deadline is None:- first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S+ first_token_deadline = time.monotonic() + _first_token_timeout_s()last_item_at: Optional[float] = None+ item_task: Optional[asyncio.Future] = Nonedef _post_first_timeout_s() -> Optional[float]:if callable(post_first_item_read_timeout_s):return post_first_item_read_timeout_s()return post_first_item_read_timeout_s- while True:- if cancel_event is not None and cancel_event.is_set():- return- if request is not None and await request.is_disconnected():- if cancel_event is not None:- cancel_event.set()- return- waiting_first_item = last_item_at is None- try:- if waiting_first_item:- remaining_s = first_token_deadline - time.monotonic()- if remaining_s <= 0:- raise httpx.ReadTimeout("The model did not produce a first token in time.")+ try:+ while True:+ if cancel_event is not None and cancel_event.is_set():+ return+ if request is not None and await request.is_disconnected():+ if cancel_event is not None:+ cancel_event.set()+ return+ waiting_first_item = last_item_at is None+ if item_task is None:if response is not None:- _set_stream_response_read_timeout(response, remaining_s)- # Keep httpx/httpcore's AnyIO cancel scope in this task.- # asyncio.wait_for would drive __anext__ in a child task.- async with _same_task_timeout(remaining_s):- item = await async_iter.__anext__()- else:- timeout_s = _post_first_timeout_s()- if (- request is not None- and response is not None- and timeout_s is not None- and last_item_at is not None- ):- stall_remaining_s = timeout_s - (time.monotonic() - last_item_at)- if stall_remaining_s <= 0:- raise httpx.ReadTimeout("The model stopped producing tokens mid-response.")- _set_stream_response_read_timeout(response, stall_remaining_s)- item = await async_iter.__anext__()- except asyncio.TimeoutError as exc:+ # httpcore latches this once per body, so the first arm is the+ # ceiling for every later read and must not undercut a deadline+ # this pump will later enforce. A callable bound can RISE (the+ # passthrough switches to the terminal grace on a finish chunk)+ # and its range is unknowable here, so it latches nothing and+ # leaves the wall clock, authoritative anyway, to enforce.+ if waiting_first_item:+ ceiling = (+ None+ if callable(post_first_item_read_timeout_s)+ else _ceiling_for_first_read(+ first_token_deadline, post_first_item_read_timeout_s+ )+ )+ else:+ ceiling = _post_first_timeout_s()+ _set_stream_response_read_timeout(response, ceiling)+ item_task = asyncio.ensure_future(async_iter.__anext__())+if waiting_first_item:- raise httpx.ReadTimeout("The model did not produce a first token in time.") from exc- raise- except StopAsyncIteration:- return- except httpx.ReadTimeout:- now = time.monotonic()- if last_item_at is None:- if now >= first_token_deadline:- raise- continue- timeout_s = _post_first_timeout_s()- if request is not None and timeout_s is not None and now - last_item_at < timeout_s:- continue- raise httpx.ReadTimeout("The model stopped producing tokens mid-response.")- if last_item_at is None and response is not None:- # The first-token read deadline no longer applies once a chunk has- # arrived: switch to the stall timeout, or clear the read timeout- # entirely when the stall guard is disabled (callable returns None)- # so a long gap can't trip the stale first-token deadline.- _set_stream_response_read_timeout(response, _post_first_timeout_s())- last_item_at = time.monotonic()- yield item+ hard_deadline = first_token_deadline+ else:+ stall_timeout_s = _post_first_timeout_s()+ hard_deadline = None if stall_timeout_s is None else last_item_at + stall_timeout_s+ timed_out_message = (+ "The model did not produce a first token in time."+ if waiting_first_item+ else "The model stopped producing tokens mid-response."+ )++ remaining_s = (+ None if hard_deadline is None else max(hard_deadline - time.monotonic(), 0.0)+ )+ if keepalive_interval_s:+ wait_s = (+ keepalive_interval_s+ if remaining_s is None+ else min(keepalive_interval_s, remaining_s)+ )+ else:+ wait_s = remaining_s++ if not item_task.done():+ # One turn of the loop before paying for a wait. A read whose+ # bytes are already buffered finishes here, which skips a timer,+ # a waiter future and two callbacks: 11.7us -> 4.1us per item,+ # and llama-server at speed lands in this branch every time.+ await asyncio.sleep(0)+ if not item_task.done():+ done, _pending = await asyncio.wait({item_task}, timeout = wait_s)+ if not done:+ # Only ever enforced on an EMPTY `done`: a read that landed+ # while the pump was suspended outranks an expired clock.+ if hard_deadline is not None and time.monotonic() >= hard_deadline:+ raise httpx.ReadTimeout(timed_out_message)+ # Must not advance last_item_at, or the stall guard never fires.+ if keepalive_interval_s:+ yield _LLAMA_STREAM_KEEPALIVE+ continue+ try:+ item = item_task.result()+ except StopAsyncIteration:+ return+ except (httpx.ReadTimeout, asyncio.TimeoutError) as exc:+ raise httpx.ReadTimeout(timed_out_message) from exc+ finally:+ item_task = None+ if last_item_at is None and response is not None:+ # Before yielding, not before the next read: the consumer may sit+ # on this item while the first-token deadline is still armed.+ _set_stream_response_read_timeout(response, _post_first_timeout_s())+ last_item_at = time.monotonic()+ yield item+ finally:+ if item_task is not None:+ # Bounded, then abandoned; the callback drains it. Cf _aclose_send_task. #7617+ if not item_task.done():+ item_task.cancel()+ item_task.add_done_callback(_discard_task_outcome)+ stop_cancelled = False+ try:+ await asyncio.wait({item_task}, timeout = _TEARDOWN_TASK_STOP_TIMEOUT_S)+ except asyncio.CancelledError:+ # Recorded, not swallowed: _aclose_stream_resources reads a+ # cancellation out of this aclose() to re-raise once every+ # resource is shut, and absorbing it here would return the pump+ # normally and let a cancelled stream run on to emit a finish.+ stop_cancelled = True+ if stop_cancelled:+ raise asyncio.CancelledError()from models.inference import (@@ -27804,6 +27906,7 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge)resp = Nonebytes_iter = None+ items_iter = Nonedisconnect_event = threading.Event()disconnect_watcher = None# This proxy relays straight from llama-server, so the swap gate has to see it: without an@@ -27820,7 +27923,7 @@ async def openai_completions(request: Request, current_subject: str = Depends(gereq = client.build_request("POST", target_url, json = upstream_body, headers = {"Connection": "close"})- first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S+ first_token_deadline = time.monotonic() + _first_token_timeout_s()# Same event the relay loop polls, so a forced swap ends the request during prefill# instead of only once headers arrive.resp = await _send_stream_with_preheader_cancel(@@ -27839,13 +27942,20 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge)bytes_iter = resp.aiter_bytes()buffer = b""- async for chunk in _aiter_llama_stream_items(+ # Bound, not inlined: teardown must aclose() this before bytes_iter.+ items_iter = _aiter_llama_stream_items(bytes_iter,cancel_event = disconnect_event,request = request,first_token_deadline = first_token_deadline,response = resp,- ):+ keepalive_interval_s = _openai_passthrough_stream_keepalive_interval(),+ )+ async for chunk in items_iter:+ # Out of `buffer`: the split below would hand it to the monitor.+ if chunk is _LLAMA_STREAM_KEEPALIVE:+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE.encode()+ continuebuffer += chunkwhile b"\n\n" in buffer:event, buffer = buffer.split(b"\n\n", 1)@@ -27914,6 +28024,7 @@ async def openai_completions(request: Request, current_subject: str = Depends(getry:await _aclose_stream_resources(watchers = (disconnect_watcher,),+ items = items_iter,iterator = bytes_iter,resp = resp,client = client,@@ -30121,6 +30232,7 @@ async def _responses_stream()resp = Nonelines_iter = None+ items_iter = Nonedisconnect_watcher = None# Tracked per-run event: a client disconnect and a forced reload both land here.disconnect_event = cancel_event@@ -30128,7 +30240,7 @@ async def _responses_stream(req = client.build_request("POST", target_url, json = body, headers = {"Connection": "close"})- first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S+ first_token_deadline = time.monotonic() + _first_token_timeout_s()try:# Same event the loop below polls: prefill can run for the whole first-token window,# and only the send watcher can end it early.@@ -30197,13 +30309,18 @@ async def _responses_stream(disconnect_watcher = asyncio.create_task(_await_disconnect_then_close(request, resp, disconnect_event))- async for raw_line in _aiter_llama_stream_items(+ items_iter = _aiter_llama_stream_items(lines_iter,cancel_event = disconnect_event,request = request,first_token_deadline = first_token_deadline,response = resp,- ):+ keepalive_interval_s = _openai_passthrough_stream_keepalive_interval(),+ )+ async for raw_line in items_iter:+ if raw_line is _LLAMA_STREAM_KEEPALIVE:+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE+ continueif not raw_line:continueif not raw_line.startswith("data: "):@@ -30346,6 +30463,7 @@ async def _responses_stream(finally:await _aclose_stream_resources(watchers = (disconnect_watcher,),+ items = items_iter,iterator = lines_iter,resp = resp,client = client,@@ -33768,13 +33886,14 @@ async def _anthropic_passthrough_stream()resp = Nonelines_iter = None+ items_iter = Nonecancel_watcher = Nonedisconnect_watcher = Nonetry:url = target_urltry:req = client.build_request("POST", url, json = body, headers = {"Connection": "close"})- first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S+ first_token_deadline = time.monotonic() + _first_token_timeout_s()resp = await _send_stream_with_preheader_cancel(client, req, cancel_event, request = request)@@ -33785,7 +33904,7 @@ async def _anthropic_passthrough_stream(if url is None:raisereq = client.build_request("POST", url, json = body, headers = {"Connection": "close"})- first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S+ first_token_deadline = time.monotonic() + _first_token_timeout_s()resp = await _send_stream_with_preheader_cancel(client, req, cancel_event, request = request)@@ -33827,13 +33946,18 @@ async def _anthropic_passthrough_stream(_await_disconnect_then_close(request, resp, cancel_event))lines_iter = resp.aiter_lines()- async for raw_line in _aiter_llama_stream_items(+ items_iter = _aiter_llama_stream_items(lines_iter,cancel_event = cancel_event,request = request,first_token_deadline = first_token_deadline,response = resp,- ):+ keepalive_interval_s = _openai_passthrough_stream_keepalive_interval(),+ )+ async for raw_line in items_iter:+ if raw_line is _LLAMA_STREAM_KEEPALIVE:+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE+ continueif not raw_line or not raw_line.startswith("data: "):continuedata_str = raw_line[6:]@@ -33892,6 +34016,7 @@ async def _anthropic_passthrough_stream(try:await _aclose_stream_resources(watchers = (cancel_watcher, disconnect_watcher),+ items = items_iter,iterator = lines_iter,resp = resp,client = client,@@ -34995,7 +35120,7 @@ async def _openai_passthrough_stream_admitted(while True:try:req = client.build_request("POST", target_url, json = body, headers = upstream_headers)- first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S+ first_token_deadline = time.monotonic() + _first_token_timeout_s()send_task = asyncio.create_task(_send_stream_with_preheader_cancel(client,@@ -35117,6 +35242,7 @@ async def _openai_passthrough_stream_admitted(# save resp.aiter_lines() so the finally block can aclose() it on# our task. See that function for full rationale.lines_iter = None+ items_iter = None# Watchers unblock aiter_lines() during prefill, before in-loop# cancel/disconnect checks can run.cancel_watcher = None@@ -35373,7 +35499,7 @@ async def _openai_passthrough_stream_admitted())first_token_deadline = (- time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S+ time.monotonic() + _first_token_timeout_s())continuelogger.error(@@ -35412,7 +35538,7 @@ async def _openai_passthrough_stream_admitted(req = client.build_request("POST", target_url, json = body, headers = upstream_headers)- first_token_deadline = time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S+ first_token_deadline = time.monotonic() + _first_token_timeout_s()send_task = asyncio.create_task(_send_stream_with_preheader_cancel(client,@@ -35451,14 +35577,19 @@ async def _openai_passthrough_stream_admitted(_await_disconnect_then_close(request, resp, cancel_event))lines_iter = resp.aiter_lines()- async for raw_line in _aiter_llama_stream_items(+ items_iter = _aiter_llama_stream_items(lines_iter,cancel_event = cancel_event,request = request,first_token_deadline = first_token_deadline,response = resp,post_first_item_read_timeout_s = _terminal_read_timeout_s,- ):+ keepalive_interval_s = _openai_passthrough_stream_keepalive_interval(),+ )+ async for raw_line in items_iter:+ if raw_line is _LLAMA_STREAM_KEEPALIVE:+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE+ continueif not raw_line:continueif not raw_line.startswith("data:"):@@ -35707,6 +35838,7 @@ async def _openai_passthrough_stream_admitted(try:await _aclose_stream_resources(watchers = (cancel_watcher, disconnect_watcher),+ items = items_iter,iterator = lines_iter,resp = resp,client = client,diff --git a/studio/backend/tests/test_llama_route_timeouts.py b/studio/backend/tests/test_llama_route_timeouts.pyindex 10da8248278..b71138ef613 100644--- a/studio/backend/tests/test_llama_route_timeouts.py+++ b/studio/backend/tests/test_llama_route_timeouts.py@@ -2,6 +2,7 @@# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.import asyncio+import mathimport osimport sysimport time@@ -24,6 +25,38 @@ def test_non_streaming_generation_timeout_has_read_deadline():assert timeout.read == inf_mod._DEFAULT_FIRST_TOKEN_TIMEOUT_S+def test_an_infinite_env_value_does_not_remove_the_deadline(monkeypatch):+ """`inf` is positive, so a `value > 0` parser lets it through.++ Both of this branch's knobs feed deadlines, and the first-token one also+ builds `httpx.Timeout` for the non-streaming path, where the positional+ form covers connect, read, write and pool. An operator writing `inf`, or+ `1e309` which parses to it, would otherwise get a request that can never+ time out anywhere. The default is restored instead.+ """+ for raw in ("inf", "Infinity", "1e309", "-inf"):+ monkeypatch.setenv(inf_mod._OPENAI_COMPAT_FIRST_TOKEN_TIMEOUT_ENV, raw)+ monkeypatch.setenv(inf_mod._OPENAI_COMPAT_STREAM_KEEPALIVE_ENV, raw)++ first = inf_mod._first_token_timeout_s()+ assert math.isfinite(first), (raw, first)+ assert first == inf_mod._DEFAULT_FIRST_TOKEN_TIMEOUT_S, (raw, first)++ keepalive = inf_mod._openai_passthrough_stream_keepalive_interval()+ assert keepalive is None or math.isfinite(keepalive), (raw, keepalive)++ # The non-streaming timeout is built from the same value, and every+ # field of it has to stay finite.+ timeout = inf_mod._llama_non_streaming_generation_timeout()+ for field in ("connect", "read", "write", "pool"):+ value = getattr(timeout, field)+ assert value is None or math.isfinite(value), (raw, field, value)++ # A finite override is still honoured; this must not become a blanket veto.+ monkeypatch.setenv(inf_mod._OPENAI_COMPAT_FIRST_TOKEN_TIMEOUT_ENV, "37.5")+ assert inf_mod._first_token_timeout_s() == 37.5++def test_stream_first_item_deadline_after_headers():async def _run():class _Never:@@ -46,48 +79,65 @@ def test_stream_first_item_deadline_after_headers():asyncio.run(_run())-def test_stream_first_item_deadline_does_not_hop_tasks():+def test_stream_read_is_never_cancelled_to_implement_a_deadline():+ """Replaces a pair that asserted `__anext__` ran in the request task.++ That targeted `asyncio.wait_for`, which times out by CANCELLING the read --+ and httpcore closes the body on any streaming exception, so a cancelled read+ is a dead stream that surfaces as a truncated 200. Cancellation was the+ hazard, task identity only its proxy; emitting while a read is outstanding+ needs a task, so pin the hazard itself.+ """+async def _run():- outer_task = asyncio.current_task()- seen_tasks = []+ cancels = []+ reads = []- class _One:+ class _Items:def __init__(self):- self.done = False+ self.count = 0async def __anext__(self):- seen_tasks.append(asyncio.current_task())- if self.done:+ reads.append(1)+ try:+ await asyncio.sleep(0.05)+ except asyncio.CancelledError:+ cancels.append(1)+ raise+ self.count += 1+ if self.count > 2:raise StopAsyncIteration- self.done = Truereturn "data: {}"out = []async for item in inf_mod._aiter_llama_stream_items(- _One(),- first_token_deadline = time.monotonic() + 1,+ _Items(),+ first_token_deadline = time.monotonic() + 5,+ keepalive_interval_s = 0.01,):+ if item is inf_mod._LLAMA_STREAM_KEEPALIVE:+ continueout.append(item)- assert out == ["data: {}"]- assert seen_tasks == [outer_task, outer_task]+ assert out == ["data: {}", "data: {}"]+ assert cancels == [], "a keepalive tick must never cancel the in-flight read"+ # One per item plus the StopAsyncIteration: same read, never restarted.+ assert len(reads) == 3, readsasyncio.run(_run())-def test_stream_first_item_deadline_uses_compat_timeout_without_task_hop(monkeypatch):+def test_stream_pump_does_not_require_asyncio_timeout(monkeypatch):+ """The repo floor is 3.9, which has no `asyncio.timeout`. The rewrite needs+ only `ensure_future` + `wait`, so removing it must change nothing."""monkeypatch.setattr(inf_mod.asyncio, "timeout", None, raising = False)async def _run():- outer_task = asyncio.current_task()- seen_tasks = []-class _One:def __init__(self):self.done = Falseasync def __anext__(self):- seen_tasks.append(asyncio.current_task())if self.done:raise StopAsyncIterationself.done = True@@ -101,7 +151,8 @@ def test_stream_first_item_deadline_uses_compat_timeout_without_task_hop(monkeypout.append(item)assert out == ["data: {}"]- assert seen_tasks == [outer_task, outer_task]++ asyncio.run(_run())asyncio.run(_run())@@ -159,6 +210,182 @@ def test_stream_wait_does_not_shorten_upstream_read_for_disconnect_poll():asyncio.run(_run())+def test_latched_read_ceiling_covers_the_stall_guard():+ """A lowered first-token env must not cap the whole body under it.++ httpcore reads `extensions["timeout"]["read"]` once, before the body loop+ (`_async/http11.py::_receive_response_body`), so the value armed before the+ FIRST read is the ceiling for every later one and the post-token re-arm+ cannot raise it. With UNSLOTH_OPENAI_COMPAT_FIRST_TOKEN_TIMEOUT below the+ stall timeout, a healthy mid-stream gap would then be cut at the smaller+ first-token value instead of the configured stall guard.+ """++ async def _run():+ response = SimpleNamespace(request = SimpleNamespace(extensions = {"timeout": {}}))+ armed = []++ class _Items:+ def __init__(self):+ self.count = 0++ async def __anext__(self):+ armed.append(response.request.extensions["timeout"].get("read"))+ self.count += 1+ if self.count > 1:+ raise StopAsyncIteration+ return "data: {}"++ async for _ in inf_mod._aiter_llama_stream_items(+ _Items(),+ response = response,+ first_token_deadline = time.monotonic() + 30.0,+ post_first_item_read_timeout_s = 120.0,+ ):+ pass++ # The latched (first) ceiling is the stall bound, not the 30s first-token+ # budget; the wall clock still enforces the 30s on its own.+ assert armed[0] == 120.0, armed++ asyncio.run(_run())+++def test_closing_the_pump_under_cancellation_re_raises_it(monkeypatch):+ """The pump must not absorb a cancellation aimed at the request task.++ `_aclose_stream_resources` closes the pump, the iterator, the response and+ the client, records a CancelledError from any of them, and re-raises it only+ once everything is shut. If the pump's own teardown swallows that+ cancellation instead, `aclose()` returns normally, the recording never+ happens, and the caller carries on down its completion path -- the Anthropic+ surface would emit `emitter.finish()` for a stream the client cancelled.+ """++ async def _run():+ class _Blocks:+ async def __anext__(self):+ await asyncio.Future()++ agen = inf_mod._aiter_llama_stream_items(+ _Blocks(),+ first_token_deadline = time.monotonic() + 30,+ keepalive_interval_s = 0.01,+ )+ # One keepalive, so a read task is in flight when the close arrives.+ assert await agen.__anext__() is inf_mod._LLAMA_STREAM_KEEPALIVE++ # The bounded stop is where an ambient cancellation lands, since awaiting+ # a cancelled task re-raises immediately. Forcing it is what separates+ # "recorded and re-raised" from "swallowed"; the pump's own loop is past+ # its last wait by now, so only the teardown sees this. monkeypatch, not+ # assignment: `inf_mod.asyncio` IS the stdlib module, so an unrestored+ # patch would break every other test sharing this process.+ async def _cancelled_wait(*args, **kwargs):+ raise asyncio.CancelledError()++ monkeypatch.setattr(inf_mod.asyncio, "wait", _cancelled_wait)+ try:+ await agen.aclose()+ outcome = "swallowed"+ except asyncio.CancelledError:+ outcome = "re-raised"+ finally:+ monkeypatch.undo()++ assert outcome == "re-raised", (+ "the pump absorbed a cancellation that _aclose_stream_resources "+ "needs to see, so a cancelled stream would report a clean close"+ )++ asyncio.run(_run())+++def test_a_callable_bound_latches_no_socket_ceiling():+ """A callable bound can RISE later, so no first-read value is safe.++ The passthrough's `_terminal_read_timeout_s` returns the stall timeout until+ a finish chunk lands and the terminal grace (2s) after it. With the stall+ timeout set below that grace, any ceiling latched from the arm-time value+ would cut the promised grace short and drop a late usage chunk, and httpcore+ ignores the re-arm that was supposed to raise it. The range of an opaque+ callable is not knowable here, so the socket is left unbounded and the+ wall-clock deadline -- authoritative either way -- does the enforcing.+ """++ async def _run():+ response = SimpleNamespace(request = SimpleNamespace(extensions = {"timeout": {}}))+ armed = []+ # Below the 2.0s terminal grace, which is the case that used to lose usage.+ values = iter([0.5, inf_mod._OPENAI_PASSTHROUGH_TERMINAL_GRACE_S])++ class _Items:+ def __init__(self):+ self.count = 0++ async def __anext__(self):+ armed.append(response.request.extensions["timeout"].get("read"))+ self.count += 1+ if self.count > 2:+ raise StopAsyncIteration+ return "data: {}"++ async for _ in inf_mod._aiter_llama_stream_items(+ _Items(),+ response = response,+ first_token_deadline = time.monotonic() + 0.5,+ post_first_item_read_timeout_s = lambda: next(values, 0.5),+ ):+ pass++ assert armed[0] is None, armed++ asyncio.run(_run())+++def test_deadline_does_not_discard_a_read_that_already_landed():+ """A token that arrives while the pump is suspended on a keepalive yield.++ Downstream backpressure can hold the generator past the deadline after the+ read has already completed. Timing out then would throw away a valid item+ and report a stall that did not happen, so the deadline is only allowed to+ fire on an empty `asyncio.wait`.+ """++ async def _run():+ gate = asyncio.Event()++ class _Items:+ def __init__(self):+ self.count = 0++ async def __anext__(self):+ self.count += 1+ if self.count > 1:+ raise StopAsyncIteration+ await gate.wait()+ return "data: {}"++ out = []+ agen = inf_mod._aiter_llama_stream_items(+ _Items(),+ first_token_deadline = time.monotonic() + 0.2,+ keepalive_interval_s = 0.05,+ )+ async for item in agen:+ if item is inf_mod._LLAMA_STREAM_KEEPALIVE:+ # Let the read finish, then stay suspended here until the+ # first-token deadline has certainly gone by.+ gate.set()+ await asyncio.sleep(0.4)+ continue+ out.append(item)++ assert out == ["data: {}"], out++ asyncio.run(_run())++def test_preheader_send_cleanup_on_disconnect_and_cancel():async def _run(cancel_parent):state = SimpleNamespace(disconnected = False, closed = False, cancelled = False)@@ -275,8 +502,10 @@ def test_stream_stall_timeout_disabled_clears_read_timeout():):seen.append(response.request.extensions["timeout"].get("read"))- # The first-token path armed a finite read timeout; after the first chunk- # with the guard disabled, it is cleared to None on every subsequent read.+ # With the guard off there is no socket ceiling at any point, including+ # the latched first read: the first-token wall clock is what bounds the+ # prefill, and a leftover finite read timeout would trip a deadline the+ # operator asked to turn off.assert seen == [None, None], seenasyncio.run(_run())diff --git a/tests/studio/test_passthrough_prefill_keepalive.py b/tests/studio/test_passthrough_prefill_keepalive.pynew file mode 100644index 00000000000..6286a14495e--- /dev/null+++ b/tests/studio/test_passthrough_prefill_keepalive.py@@ -0,0 +1,567 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""A passthrough relay must not go silent while llama-server prefills.++llama-server sends nothing until the first token and undici aborts a response+after 300s with no bytes. Behavioural checks that the pump keepalives across a+stalled read without restarting it, that the stall guard still fires, and that+teardown leaves no pending read; structural checks that no fifth passthrough+surface can be added without translating the sentinel.+"""++from __future__ import annotations++import ast+import math+import asyncio+import time+from pathlib import Path++import httpx+import pytest+++SOURCE_PATH = Path(__file__).resolve().parents[2] / "studio" / "backend" / "routes" / "inference.py"+SRC = SOURCE_PATH.read_text(encoding = "utf-8")+_TREE = ast.parse(SRC)++_TICK_S = 0.05++_WANTED = {"_LlamaStreamKeepalive", "_LLAMA_STREAM_KEEPALIVE", "_aiter_llama_stream_items"}+++def _load_pump():+ """The real pump, cut from disk and exec'd against stubs: importing+ `routes.inference` would pull in the whole backend package."""+ chunks = []+ for node in _TREE.body:+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):+ wanted = node.name in _WANTED+ elif isinstance(node, ast.Assign):+ wanted = any(t.id in _WANTED for t in node.targets if isinstance(t, ast.Name))+ else:+ wanted = False+ if not wanted:+ continue+ segment = ast.get_source_segment(SRC, node)+ assert segment is not None, f"could not cut {getattr(node, 'name', node)} from source"+ chunks.append(segment)+ assert len(chunks) == len(_WANTED), f"expected {len(_WANTED)} definitions, cut {len(chunks)}"++ namespace = {+ "asyncio": asyncio,+ "httpx": httpx,+ "time": time,+ "Optional": __import__("typing").Optional,+ "Union": __import__("typing").Union,+ "Callable": __import__("typing").Callable,+ "Request": object,+ "_DEFAULT_STREAM_STALL_TIMEOUT_S": 120.0,+ "_DEFAULT_FIRST_TOKEN_TIMEOUT_S": 1200.0,+ "_first_token_timeout_s": lambda: 1200.0,+ "_TEARDOWN_TASK_STOP_TIMEOUT_S": 5.0,+ "_set_stream_response_read_timeout": lambda response, read_timeout_s = None: None,+ "_discard_task_outcome": lambda task: None,+ }+ exec("\n\n".join(chunks), namespace)+ return namespace+++class _ScriptedIter:+ """Yields, blocks on a gate, yields again. Counts `__anext__` entries so a+ test can prove the pump waited on one read rather than restarting per tick."""++ def __init__(+ self,+ immediate = (),+ gate = None,+ after_gate = (),+ ):+ self._immediate = list(immediate)+ self._gate = gate+ self._after_gate = list(after_gate)+ self.anext_calls = 0+ self.cancelled = 0++ def __aiter__(self):+ return self++ async def __anext__(self):+ self.anext_calls += 1+ if self._immediate:+ return self._immediate.pop(0)+ if self._gate is not None:+ gate, self._gate = self._gate, None+ try:+ await gate.wait()+ except asyncio.CancelledError:+ self.cancelled += 1+ raise+ if self._after_gate:+ return self._after_gate.pop(0)+ raise StopAsyncIteration+++def test_keepalives_flow_during_prefill_without_restarting_the_read():+ pump_ns = _load_pump()+ keepalive = pump_ns["_LLAMA_STREAM_KEEPALIVE"]++ async def _run():+ gate = asyncio.Event()+ upstream = _ScriptedIter(gate = gate, after_gate = ["data: first-token"])+ seen_keepalives = 0+ items = []+ stream = pump_ns["_aiter_llama_stream_items"](+ upstream,+ first_token_deadline = time.monotonic() + 30.0,+ keepalive_interval_s = _TICK_S,+ )+ try:+ async for got in stream:+ if got is keepalive:+ seen_keepalives += 1+ if seen_keepalives >= 3:+ gate.set()+ continue+ items.append(got)+ break+ finally:+ await stream.aclose()+ return seen_keepalives, items, upstream++ seen_keepalives, items, upstream = asyncio.run(_run())++ assert (+ seen_keepalives >= 3+ ), f"pump must keep emitting keepalives while upstream is silent; got {seen_keepalives}"+ assert items == [+ "data: first-token"+ ], f"the real item must still arrive after the keepalives; got {items}"+ assert upstream.anext_calls == 1, (+ "keepalive ticks must await the SAME __anext__, not restart the read "+ f"(httpcore closes the body on any streaming exception); got {upstream.anext_calls} calls"+ )+++def test_keepalives_flow_during_a_post_first_token_stall_then_the_guard_fires():+ pump_ns = _load_pump()+ keepalive = pump_ns["_LLAMA_STREAM_KEEPALIVE"]++ async def _run():+ upstream = _ScriptedIter(immediate = ["data: a"], gate = asyncio.Event())+ seen_keepalives = 0+ items = []+ stream = pump_ns["_aiter_llama_stream_items"](+ upstream,+ first_token_deadline = time.monotonic() + 30.0,+ post_first_item_read_timeout_s = 0.4,+ keepalive_interval_s = _TICK_S,+ )+ try:+ with pytest.raises(httpx.ReadTimeout) as excinfo:+ async for got in stream:+ if got is keepalive:+ seen_keepalives += 1+ continue+ items.append(got)+ finally:+ await stream.aclose()+ return seen_keepalives, items, str(excinfo.value)++ seen_keepalives, items, message = asyncio.run(_run())++ assert items == ["data: a"], f"the first item must be relayed; got {items}"+ assert (+ seen_keepalives >= 3+ ), f"a stall after the first token must keepalive too; got {seen_keepalives}"+ assert (+ message == "The model stopped producing tokens mid-response."+ ), f"the stall guard must still fire, with its own message; got {message!r}"+++def test_first_token_deadline_still_fires_and_no_sentinel_when_disabled():+ pump_ns = _load_pump()+ keepalive = pump_ns["_LLAMA_STREAM_KEEPALIVE"]++ async def _run():+ upstream = _ScriptedIter(gate = asyncio.Event())+ seen = []+ stream = pump_ns["_aiter_llama_stream_items"](+ upstream,+ first_token_deadline = time.monotonic() + 0.2,+ keepalive_interval_s = None,+ )+ try:+ with pytest.raises(httpx.ReadTimeout) as excinfo:+ async for got in stream:+ seen.append(got)+ finally:+ await stream.aclose()+ return seen, str(excinfo.value)++ seen, message = asyncio.run(_run())++ assert (+ seen == []+ ), f"keepalive_interval_s=None must relay in silence, emitting no sentinel; got {seen}"+ assert (+ message == "The model did not produce a first token in time."+ ), f"the first-token deadline must still bound the wait; got {message!r}"+ assert keepalive is not None+++def test_teardown_cancels_the_in_flight_read():+ pump_ns = _load_pump()+ keepalive = pump_ns["_LLAMA_STREAM_KEEPALIVE"]++ async def _run():+ upstream = _ScriptedIter(gate = asyncio.Event())+ stream = pump_ns["_aiter_llama_stream_items"](+ upstream,+ first_token_deadline = time.monotonic() + 30.0,+ keepalive_interval_s = _TICK_S,+ )+ async for got in stream:+ assert got is keepalive+ break+ # A live __anext__ here would raise "already running" on the close.+ await stream.aclose()+ await asyncio.sleep(0)+ return upstream++ upstream = asyncio.run(_run())++ assert (+ upstream.cancelled == 1+ ), f"aclose() must cancel the pending read exactly once; got {upstream.cancelled}"+++def test_closing_the_pump_first_leaves_the_iterator_closable():+ """Closing the iterator while the pump still holds its read raises+ "already running"; closing the pump first must make it clean."""+ pump_ns = _load_pump()+ keepalive = pump_ns["_LLAMA_STREAM_KEEPALIVE"]++ async def _run(close_pump_first):+ gate = asyncio.Event()++ async def _upstream():+ try:+ await gate.wait()+ yield "data: never"+ finally:+ pass++ iterator = _upstream()+ stream = pump_ns["_aiter_llama_stream_items"](+ iterator,+ first_token_deadline = time.monotonic() + 30.0,+ keepalive_interval_s = _TICK_S,+ )+ async for got in stream:+ assert got is keepalive+ break # parked at a keepalive yield, read in flight++ errors = []+ if close_pump_first:+ try:+ await stream.aclose()+ except Exception as exc: # pragma: no cover - would be a real defect+ errors.append(f"pump: {type(exc).__name__}: {exc}")+ try:+ await iterator.aclose()+ except Exception as exc:+ errors.append(f"iterator: {type(exc).__name__}: {exc}")+ if not close_pump_first:+ await stream.aclose()+ return errors++ # Without the ordering, the iterator close lands on a running generator.+ unordered = asyncio.run(_run(close_pump_first = False))+ assert any("already running" in e for e in unordered), (+ "expected the unordered close to hit 'asynchronous generator is already "+ f"running'; got {unordered}. If this stops reproducing the ordering "+ "contract may no longer be load-bearing."+ )++ ordered = asyncio.run(_run(close_pump_first = True))+ assert ordered == [], f"closing the pump first must leave a clean close; got {ordered}"+++def _load_env_accessors():+ wanted = {+ "_positive_float_env",+ "_finite_positive_float_env",+ "_openai_passthrough_stream_keepalive_interval",+ "_first_token_timeout_s",+ "_OPENAI_COMPAT_STREAM_KEEPALIVE_ENV",+ "_OPENAI_COMPAT_FIRST_TOKEN_TIMEOUT_ENV",+ "_OPENAI_PASSTHROUGH_PENDING_RESPONSE_KEEPALIVE_S",+ }+ chunks = []+ for node in _TREE.body:+ if isinstance(node, (ast.FunctionDef, ast.ClassDef)):+ ok = node.name in wanted+ elif isinstance(node, ast.Assign):+ ok = any(t.id in wanted for t in node.targets if isinstance(t, ast.Name))+ else:+ ok = False+ if ok:+ chunks.append(ast.get_source_segment(SRC, node))+ ns = {+ "os": __import__("os"),+ "math": math,+ "_DEFAULT_FIRST_TOKEN_TIMEOUT_S": 1200.0,+ }+ exec("\n\n".join(chunks), ns)+ return ns+++ "raw,expected",+ [+ (None, 5.0), # unset: pace like the header wait already does+ ("", 5.0), # blank: same as unset+ ("0", None), # documented off switch+ ("-1", None), # non-positive is also off+ ("2.5", 2.5),+ ("garbage", 5.0), # unparseable falls back, never crashes a stream+ ],+)+def test_keepalive_interval_env(monkeypatch, raw, expected):+ ns = _load_env_accessors()+ name = ns["_OPENAI_COMPAT_STREAM_KEEPALIVE_ENV"]+ monkeypatch.delenv(name, raising = False)+ if raw is not None:+ monkeypatch.setenv(name, raw)+ assert ns["_openai_passthrough_stream_keepalive_interval"]() == expected+++ "raw,expected",+ [+ (None, 1200.0),+ ("", 1200.0),+ ("0", 1200.0), # unlike the stall guard, 0 must NOT remove the bound+ ("-5", 1200.0),+ ("garbage", 1200.0),+ ("2400", 2400.0),+ # `inf` is positive, so a `value > 0` parser used to let it through and+ # the deadline stopped existing. `1e309` is the same value written by a+ # human who meant "very large".+ ("inf", 1200.0),+ ("Infinity", 1200.0),+ ("1e309", 1200.0),+ ("nan", 1200.0),+ ],+)+def test_first_token_timeout_env_never_unbounded(monkeypatch, raw, expected):+ ns = _load_env_accessors()+ name = ns["_OPENAI_COMPAT_FIRST_TOKEN_TIMEOUT_ENV"]+ monkeypatch.delenv(name, raising = False)+ if raw is not None:+ monkeypatch.setenv(name, raw)+ got = ns["_first_token_timeout_s"]()+ assert got == expected+ assert isinstance(got, float) and got > 0, (+ "the first-token deadline is unconditional downstream, so this accessor "+ f"must never return None or a non-positive value; got {got!r}"+ )+ assert math.isfinite(got), (+ "a non-finite bound is the same as no bound: this value also builds the "+ f"non-streaming httpx.Timeout, whose positional form covers connect, "+ f"read, write and pool; got {got!r}"+ )+++_PUMP_LOCAL = "items_iter"+++def _pump_constructions():+ """`items_iter = _aiter_llama_stream_items(...)` assignments."""+ made = []+ for node in ast.walk(_TREE):+ if not isinstance(node, ast.Assign):+ continue+ call = node.value+ if not isinstance(call, ast.Call):+ continue+ if not (isinstance(call.func, ast.Name) and call.func.id == "_aiter_llama_stream_items"):+ continue+ targets = [t.id for t in node.targets if isinstance(t, ast.Name)]+ made.append((node, call, targets))+ return made+++def _passthrough_relay_loops():+ return [+ node+ for node in ast.walk(_TREE)+ if isinstance(node, ast.AsyncFor)+ and isinstance(node.iter, ast.Name)+ and node.iter.id == _PUMP_LOCAL+ ]+++def test_pump_is_bound_not_inlined_so_teardown_can_close_it():+ """Inlining the pump in the `async for` leaves it unnameable, so teardown+ cannot aclose() it before the iterator it is still reading."""+ made = _pump_constructions()+ assert len(made) == 4, (+ "expected the 4 passthrough surfaces to each bind the pump to a local; "+ f"found {len(made)}"+ )+ for node, call, targets in made:+ assert targets == [+ _PUMP_LOCAL+ ], f"pump at line {node.lineno} must bind to {_PUMP_LOCAL!r}, got {targets}"+ keywords = {kw.arg for kw in call.keywords}+ assert "keepalive_interval_s" in keywords, (+ f"pump at line {node.lineno} must pass keepalive_interval_s, or it "+ "relays in silence for the whole prefill"+ )++ inlined = [+ node+ for node in ast.walk(_TREE)+ if isinstance(node, ast.AsyncFor)+ and isinstance(node.iter, ast.Call)+ and isinstance(node.iter.func, ast.Name)+ and node.iter.func.id == "_aiter_llama_stream_items"+ ]+ assert not inlined, (+ "the pump must not be inlined into an `async for`; teardown cannot "+ f"aclose() what it cannot name (lines {[n.lineno for n in inlined]})"+ )+++def test_every_teardown_closes_the_pump_before_the_iterator():+ calls = [+ node+ for node in ast.walk(_TREE)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "_aclose_stream_resources"+ ]+ with_iterator = [c for c in calls if any(kw.arg == "iterator" for kw in c.keywords)]+ assert (+ len(with_iterator) == 4+ ), f"expected 4 teardowns closing a relay iterator; found {len(with_iterator)}"+ for call in with_iterator:+ names = [kw.arg for kw in call.keywords]+ assert "items" in names, (+ f"teardown at line {call.lineno} closes `iterator` but not `items`: "+ "the pump would still be running on it"+ )+ assert names.index("items") < names.index("iterator"), (+ f"teardown at line {call.lineno} must pass `items` before `iterator` "+ "to match the documented close order"+ )++ helper = next(+ n+ for n in ast.walk(_TREE)+ if isinstance(n, ast.AsyncFunctionDef) and n.name == "_aclose_stream_resources"+ )+ args = [a.arg for a in helper.args.kwonlyargs]+ assert "items" in args and args.index("items") < args.index(+ "iterator"+ ), f"_aclose_stream_resources must take `items` before `iterator`; got {args}"+ body_src = ast.get_source_segment(SRC, helper) or ""+ assert body_src.index("items.aclose()") < body_src.index(+ "iterator.aclose()"+ ), "_aclose_stream_resources must await items.aclose() before iterator.aclose()"+++def test_every_relay_loop_translates_the_sentinel_first():+ loops = _passthrough_relay_loops()+ assert len(loops) == 4, (+ "expected the 4 passthrough surfaces (/v1/completions, /v1/responses, "+ f"/v1/messages, /v1/chat/completions); found {len(loops)}. A new surface "+ "must handle _LLAMA_STREAM_KEEPALIVE too."+ )++ for node in loops:+ line = node.lineno+ first = node.body[0]+ assert isinstance(first, ast.If), (+ f"relay loop at line {line} must test the sentinel as its FIRST "+ f"statement; found {type(first).__name__}"+ )+ test = first.test+ assert (+ isinstance(test, ast.Compare)+ and len(test.ops) == 1+ and isinstance(test.ops[0], ast.Is)+ and isinstance(test.comparators[0], ast.Name)+ and test.comparators[0].id == "_LLAMA_STREAM_KEEPALIVE"+ ), (+ f"relay loop at line {line} must begin with `<item> is "+ "_LLAMA_STREAM_KEEPALIVE`, before any startswith()/truthiness filter "+ "could drop it or any bookkeeping could count it as an upstream item"+ )+++def test_sentinel_is_an_object_not_a_string():+ # A string would be eaten by the call sites' startswith("data:") filters.+ pump_ns = _load_pump()+ keepalive = pump_ns["_LLAMA_STREAM_KEEPALIVE"]+ assert not isinstance(+ keepalive, (str, bytes)+ ), f"sentinel must not be a string; got {type(keepalive).__name__}"++[email protected]("module_name", ["openai", "anthropic"])+def test_sdk_sse_readers_ignore_the_keepalive_comment(module_name):+ """The whole fix rests on `:` comments being invisible to SSE readers."""+ streaming = pytest.importorskip(f"{module_name}._streaming")+ decoder = streaming.SSEDecoder()+ # split, not splitlines: the trailing blank line is the dispatch point.+ events = [+ event+ for line in ": keep-alive\n\n".split("\n")+ for event in [decoder.decode(line)]+ if event is not None+ ]+ assert events == [], f"{module_name} SSE reader must ignore a comment; got {events}"+++def test_the_tick_is_a_whole_comment_frame_not_a_bare_line():+ """The tick must be a complete SSE comment frame, blank line included.++ A bare `: keep-alive\\n` looks tempting: it puts bytes on the wire without+ closing a block, which avoids an SDK decoder bug where a data-less block+ dispatches an empty event once an `id:` has been seen. But a bare line rides+ at the head of the NEXT frame, and a reader that classifies a frame by its+ first character -- comment if it starts with ":", data if it starts with+ "data:" -- then files the whole frame as a comment and DROPS THE CHUNK. Raw+ curl and Node undici readers both do exactly that, and both lose the token.++ So the frame form is deliberate: it costs an ignorable empty event on two+ Python decoders, and only when the upstream sends `id:`, which llama-server+ does not. Losing a token is much worse than emitting an ignorable one.+ """+ assert '_OPENAI_PASSTHROUGH_SSE_KEEPALIVE = ": keep-alive\\n\\n"' in SRC+ assert (+ "_OPENAI_PASSTHROUGH_SSE_KEEPALIVE_LINE" not in SRC+ ), "the bare-line form drops a chunk for frame-prefix readers"+ emitters = SRC.count("yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE")+ assert emitters >= 4, f"expected at least the 4 tick emitters, found {emitters}"++ # A frame-prefix reader, which is what curl and undici consumers do.+ def frame_prefix_reader(stream):+ text = []+ for frame in stream.split("\n\n"):+ if frame.startswith(":") or not frame.strip():+ continue+ if frame.startswith("data: "):+ text.append(frame[6:])+ return text++ tick_frame = "data: a\n\n: keep-alive\n\ndata: b\n\n"+ tick_line = "data: a\n\n: keep-alive\ndata: b\n\n"+ assert frame_prefix_reader(tick_frame) == ["a", "b"]+ assert frame_prefix_reader(tick_line) == [+ "a"+ ], "this is the data loss the frame form exists to avoid"