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
Studio: recover the OpenAI passthrough from a crashed llama-server (#8999)
Michael Han2515c44714ce
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex de7c4155ec7..027872928ca 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -21223,13 +21223,33 @@ def _nudge_retry_messages()-async def _anthropic_passthrough_retry_url(llama_backend, exc):+def _is_lost_upstream_connection(exc) -> bool:+ """True only for errors that mean the connection died, not that it was slow.++ ``httpx.RequestError`` also covers ``TimeoutException`` (ConnectTimeout,+ ReadTimeout, WriteTimeout, PoolTimeout), and a long generation on a HEALTHY+ llama-server surfaces as ``ReadTimeout``. ``_respawn_if_dead`` reports a live+ process healthy, so a respawn retry on a timeout resubmits the same prompt to+ a server that is still decoding the first copy: double the wall clock and two+ slots burnt. ``NetworkError`` (Connect/Read/Write/CloseError) plus+ ``RemoteProtocolError`` (a FIN before the response line) are the dead-server+ set, and they are exactly what ``_open_chat_stream_with_respawn_retry`` retries+ on. RemoteProtocolError is a sibling of NetworkError, not a subclass, so both+ have to be named.+ """+ return isinstance(exc, (httpx.NetworkError, httpx.RemoteProtocolError))+++async def _passthrough_retry_url(llama_backend, exc):"""Fresh upstream URL after respawning a dead llama-server, else None.A crashed server relaunches on a NEW ephemeral port, so a passthrough stillholding the old base_url keeps failing until the next load. Mirrors therespawn-and-retry in generate_chat_completion. None when an MTP+tensor crashalready scheduled its own recovery, or when nothing needed respawning.++ Shared by both passthrough surfaces: /v1/messages and /v1/chat/completions post+ to the same upstream route, and a crash strands whichever one is in use."""recover = getattr(llama_backend, "_maybe_recover_from_mtp_crash", None)if recover is not None and recover(exc):@@ -21389,7 +21409,7 @@ async def _anthropic_passthrough_stream(except httpx.ConnectError as exc:# Nothing has streamed yet, so a respawned server can be retried once# on its new port without duplicating output.- url = await _anthropic_passthrough_retry_url(llama_backend, exc)+ url = await _passthrough_retry_url(llama_backend, exc)if url is None:raisereq = client.build_request("POST", url, json = body, headers = {"Connection": "close"})@@ -21555,7 +21575,7 @@ async def _anthropic_passthrough_non_streaming(# Nothing was returned yet, so retry once against the respawned server's# new port; the nudge retry below then reuses the same fresh URL.retry_url = (- await _anthropic_passthrough_retry_url(llama_backend, exc)+ await _passthrough_retry_url(llama_backend, exc)if isinstance(exc, httpx.ConnectError)else None)@@ -22441,6 +22461,9 @@ async def _openai_passthrough_stream_admitted(_truncate_budget = (_OVERFLOW_TRUNCATE_MAX_RETRIES if _overflow_truncation_requested(payload) else 0)+ # One respawn per request: a second unreachable upstream after a successful+ # relaunch is a real failure, not a stale port.+ _respawn_retried = Falsewhile True:try:@@ -22467,7 +22490,31 @@ async def _openai_passthrough_stream_admitted(resp = await send_tasksend_task = Noneexcept httpx.RequestError as e:- # llama-server subprocess crashed / starting / unreachable.+ # llama-server subprocess crashed / starting / unreachable. Nothing has+ # streamed yet, so a respawned server can be retried once on its new+ # ephemeral port without duplicating output, exactly as /v1/messages does.+ # Without this an OpenAI-API client stays broken until the next explicit+ # load, while an Anthropic-API client on the same backend recovers itself.+ if not _respawn_retried and _is_lost_upstream_connection(e):+ _respawn_retried = True+ retry_url = await _passthrough_retry_url(llama_backend, e)+ if retry_url is not None:+ closed = False+ try:+ await _aclose_send_task(send_task)+ closed = True+ finally:+ # Only a retry that is actually going upstream keeps the slot.+ if not closed:+ _release_admission(admission_lease, _tracker)+ send_task = None+ target_url = retry_url+ # The relaunch minted a fresh --api-key, so the pre-crash+ # Authorization header would come back 401.+ upstream_headers = _openai_passthrough_upstream_headers(+ llama_backend = llama_backend+ )+ continuelogger.error("openai passthrough stream: upstream unreachable: %s", e)api_monitor.fail(monitor_id, _friendly_error(e))# Nested so a cancel inside _aclose_send_task's wait cannot skip the closes.@@ -22549,7 +22596,7 @@ async def _openai_passthrough_stream_admitted(disconnect_watcher = Nonenonlocal resp, send_task, first_token_deadline, _truncate_budget- nonlocal client+ nonlocal client, target_url, upstream_headers, _respawn_retriedmonitor_done = Falsesaw_finish_reason = Falsesaw_done = False@@ -22726,6 +22773,78 @@ async def _openai_passthrough_stream_admitted(try:resp = send_task.result()except httpx.RequestError as e:+ # A crash while the request sat queued or prefilling lands+ # here, not in the pre-header handler: the 100 ms status+ # window closed long ago. Only SSE comments have been+ # emitted, so the same one-shot, connection-failure-only+ # recovery applies without duplicating model output.+ if not _respawn_retried and _is_lost_upstream_connection(e):+ _respawn_retried = True+ # The respawn replays a full load_model, which for a large+ # GGUF outlasts by minutes the five second silence this+ # very loop already treats as too long for a committed SSE+ # response. Awaiting it inline would stop both keepalives+ # and disconnect polling for the whole reload, so the+ # client or proxy can drop the stream before the recovered+ # request is ever submitted. Pump the same loop instead.+ retry_task = asyncio.create_task(+ _passthrough_retry_url(llama_backend, e)+ )+ respawn_cancelled = False+ last_keepalive_at = time.monotonic()+ while not retry_task.done():+ done, _ = await asyncio.wait(+ {retry_task},+ timeout = min(+ _STREAM_DISCONNECT_POLL_TIMEOUT_S,+ _OPENAI_PASSTHROUGH_PENDING_RESPONSE_KEEPALIVE_S,+ ),+ return_when = asyncio.FIRST_COMPLETED,+ )+ if retry_task in done:+ break+ if await _preheader_cancelled(cancel_event, request):+ respawn_cancelled = True+ break+ now = time.monotonic()+ if (+ now - last_keepalive_at+ >= _OPENAI_PASSTHROUGH_PENDING_RESPONSE_KEEPALIVE_S+ ):+ last_keepalive_at = now+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVE+ if respawn_cancelled:+ # The reload runs in a worker thread that cancel()+ # cannot interrupt, and it is serialised and+ # idempotent, so let it finish and drop its URL+ # rather than leave the outcome unretrieved.+ retry_task.add_done_callback(_discard_task_outcome)+ api_monitor.finish(monitor_id, "cancelled")+ return+ retry_url = retry_task.result()+ if retry_url is not None:+ target_url = retry_url+ upstream_headers = _openai_passthrough_upstream_headers(+ llama_backend = llama_backend+ )+ send_task = asyncio.create_task(+ _send_stream_with_preheader_cancel(+ client,+ client.build_request(+ "POST",+ target_url,+ json = body,+ headers = upstream_headers,+ ),+ cancel_event,+ request = request,+ mark_cancel_on_cancel = False,+ )+ )+ first_token_deadline = (+ time.monotonic() + _DEFAULT_FIRST_TOKEN_TIMEOUT_S+ )+ continuelogger.error("openai passthrough stream: upstream unreachable: %s", e)@@ -23215,6 +23334,8 @@ async def _openai_passthrough_non_streaming_upstream(_truncate_budget = (_OVERFLOW_TRUNCATE_MAX_RETRIES if _overflow_truncation_requested(payload) else 0)+ # One respawn per request, as on the streaming twin.+ _respawn_retried = Falseasync def _post(body_to_send):if cancel_event is None and request is None:@@ -23271,9 +23392,22 @@ async def _openai_passthrough_non_streaming_upstream(api_monitor.finish(monitor_id, "cancelled")raiseexcept httpx.RequestError as e:- # llama-server subprocess crashed / starting / unreachable. Surface the- # same friendly message the sync chat path emits so operators don't see- # a bare 500 with no diagnostic.+ # llama-server subprocess crashed / starting / unreachable. Nothing has been+ # sent to the client yet, so retry once on the new port of a respawned server.+ # The helper defers to an MTP fallback already in flight, so nothing respawns+ # underneath it; the recovery call below stays for the paths it declines.+ if not _respawn_retried and _is_lost_upstream_connection(e):+ _respawn_retried = True+ retry_url = await _passthrough_retry_url(llama_backend, e)+ if retry_url is not None:+ target_url = retry_url+ # The relaunch minted a fresh --api-key; the pre-crash header 401s.+ upstream_headers = _openai_passthrough_upstream_headers(+ llama_backend = llama_backend+ )+ continue+ # Surface the same friendly message the sync chat path emits so operators+ # don't see a bare 500 with no diagnostic.logger.error("openai passthrough non-streaming: upstream unreachable: %s", e)api_monitor.fail(monitor_id, _friendly_error(e))get_llama_cpp_backend()._maybe_recover_from_mtp_crash(e)diff --git a/studio/backend/tests/test_anthropic_admission.py b/studio/backend/tests/test_anthropic_admission.pyindex d4fcf85a453..5eb563e6a37 100644--- a/studio/backend/tests/test_anthropic_admission.py+++ b/studio/backend/tests/test_anthropic_admission.py@@ -31,7 +31,7 @@ sys.path.insert(0, _backend)import routes.inference as inf_modfrom routes.inference import (- _anthropic_passthrough_retry_url,+ _passthrough_retry_url,_anthropic_passthrough_stream,anthropic_messages,)@@ -916,7 +916,7 @@ def test_retry_url_stands_down_while_an_mtp_fallback_is_reloading():# underneath the fallback already reloading without it.backend = _RespawnBackend(mtp_handled = False, fallback_in_progress = True)- url = asyncio.run(_anthropic_passthrough_retry_url(backend, httpx.ConnectError("x")))+ url = asyncio.run(_passthrough_retry_url(backend, httpx.ConnectError("x")))assert url is Noneassert backend.respawn_calls == 0diff --git a/studio/backend/tests/test_anthropic_passthrough_respawn.py b/studio/backend/tests/test_anthropic_passthrough_respawn.pyindex daa30e39c20..5e2193f9097 100644--- a/studio/backend/tests/test_anthropic_passthrough_respawn.py+++ b/studio/backend/tests/test_anthropic_passthrough_respawn.py@@ -27,7 +27,7 @@ sys.path.insert(0, _backend)import routes.inference as inf_modfrom routes.inference import (_anthropic_passthrough_non_streaming,- _anthropic_passthrough_retry_url,+ _passthrough_retry_url,_anthropic_passthrough_stream,)@@ -156,7 +156,7 @@ async def _run_non_streaming(backend):def test_retry_url_rebuilds_from_the_respawned_base_url():backend = _Backend()- url = asyncio.run(_anthropic_passthrough_retry_url(backend, httpx.ConnectError("x")))+ url = asyncio.run(_passthrough_retry_url(backend, httpx.ConnectError("x")))assert url == f"{_FRESH}/v1/chat/completions"assert backend.respawn_calls == 1@@ -165,7 +165,7 @@ def test_retry_url_rebuilds_from_the_respawned_base_url():def test_retry_url_is_none_when_nothing_respawned():backend = _Backend(respawn_ok = False)- url = asyncio.run(_anthropic_passthrough_retry_url(backend, httpx.ConnectError("x")))+ url = asyncio.run(_passthrough_retry_url(backend, httpx.ConnectError("x")))assert url is None@@ -174,7 +174,7 @@ def test_retry_url_defers_to_the_mtp_crash_recovery():# An MTP+tensor crash schedules its own reload; retrying would race it.backend = _Backend(mtp_handled = True)- url = asyncio.run(_anthropic_passthrough_retry_url(backend, httpx.ConnectError("x")))+ url = asyncio.run(_passthrough_retry_url(backend, httpx.ConnectError("x")))assert url is Noneassert backend.respawn_calls == 0@@ -183,7 +183,7 @@ def test_retry_url_defers_to_the_mtp_crash_recovery():def test_retry_url_tolerates_a_backend_without_respawn_hooks():backend = SimpleNamespace(base_url = _DEAD)- url = asyncio.run(_anthropic_passthrough_retry_url(backend, httpx.ConnectError("x")))+ url = asyncio.run(_passthrough_retry_url(backend, httpx.ConnectError("x")))assert url is Nonediff --git a/studio/backend/tests/test_openai_passthrough_respawn.py b/studio/backend/tests/test_openai_passthrough_respawn.pynew file mode 100644index 00000000000..d24c1716188--- /dev/null+++ b/studio/backend/tests/test_openai_passthrough_respawn.py@@ -0,0 +1,613 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Restart survival for the OpenAI /v1/chat/completions passthrough.++A crashed llama-server relaunches on a NEW ephemeral port. /v1/messages already+respawns and retries; this surface did not, so a harness on the OpenAI API kept+posting to the dead port and stayed broken until the user reloaded the model by+hand, while an Anthropic-API client on the same backend recovered itself.++Twin of test_anthropic_passthrough_respawn.py, same stubs and same cases.+"""++from __future__ import annotations++import asyncio+import json+import os+import sys+import threading+from types import SimpleNamespace++import httpx+import pytest+from fastapi import HTTPException++_backend = os.path.join(os.path.dirname(__file__), "..")+sys.path.insert(0, _backend)++import routes.inference as inf_mod+from models.inference import ChatCompletionRequest, ChatMessage+from routes.inference import (+ _is_lost_upstream_connection,+ _openai_passthrough_non_streaming_upstream,+ _openai_passthrough_stream_admitted,+ _passthrough_retry_url,+)++_DEAD = "http://127.0.0.1:57953"+_FRESH = "http://127.0.0.1:62933"+++class _Backend:+ """Stub llama backend whose base_url moves to a new port once respawned."""++ def __init__(+ self,+ *,+ respawn_ok = True,+ mtp_handled = False,+ stays_dead = False,+ ):+ self.base_url = _DEAD+ self.context_length = 4096+ self.respawn_calls = 0+ self.mtp_calls = 0+ self._respawn_ok = respawn_ok+ self._mtp_handled = mtp_handled+ # Models a relaunch that reports success but is not actually serving.+ self._stays_dead = stays_dead++ def count_chat_tokens(self, *_args, **_kwargs):+ return 2++ def _request_reasoning_kwargs(self, *_args, **_kwargs):+ return None++ def _maybe_recover_from_mtp_crash(self, _exc):+ self.mtp_calls += 1+ return self._mtp_handled++ def _respawn_if_dead(self):+ self.respawn_calls += 1+ if not self._respawn_ok:+ return False+ if not self._stays_dead:+ self.base_url = _FRESH+ return True+++class _Request:+ async def is_disconnected(self):+ return False+++class _Lease:+ """Records that the slot came back. Repeat calls are fine: the real lease is+ idempotent, and the stream's nested handlers both release."""++ def __init__(self):+ self.released = False++ def release(self):+ self.released = True+++class _Tracker:+ def __exit__(self, *_exc):+ return False+++class _FakeNonStreamingClient:+ def __init__(self):+ self.urls = []++ async def aclose(self):+ pass++ async def post(self, url, **_kwargs):+ self.urls.append(url)+ if url.startswith(_DEAD):+ raise httpx.ConnectError("connection refused")+ return httpx.Response(+ 200,+ json = {+ "id": "chatcmpl-1",+ "choices": [+ {"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}+ ],+ "usage": {"prompt_tokens": 2, "completion_tokens": 1},+ },+ )+++def _install_stream_transport(monkeypatch, calls):+ def handler(request: httpx.Request) -> httpx.Response:+ calls.append(str(request.url))+ if str(request.url).startswith(_DEAD):+ raise httpx.ConnectError("connection refused")+ content = (+ f"data: {json.dumps({'choices': [{'delta': {'content': 'hi'}}]})}\n\n"+ "data: [DONE]\n\n"+ )+ return httpx.Response(+ 200,+ content = content.encode(),+ headers = {"content-type": "text/event-stream"},+ )++ transport = httpx.MockTransport(handler)+ real_client = httpx.AsyncClient++ def _client(*_args, **kwargs):+ return real_client(transport = transport, timeout = kwargs.get("timeout", 600))++ monkeypatch.setattr(inf_mod.httpx, "AsyncClient", _client)+++def _payload():+ return ChatCompletionRequest(+ model = "default",+ messages = [ChatMessage(role = "user", content = "hi")],+ )+++async def _run_non_streaming(backend):+ return await _openai_passthrough_non_streaming_upstream(+ backend,+ _payload(),+ "test-model",+ request = _Request(),+ cancel_event = threading.Event(),+ )+++async def _run_stream(backend, lease = None):+ response = await _openai_passthrough_stream_admitted(+ _Request(),+ threading.Event(),+ backend,+ _payload(),+ "test-model",+ "chatcmpl-local",+ admission_lease = lease or _Lease(),+ tracker = _Tracker(),+ )+ chunks = []+ async for chunk in response.body_iterator:+ chunks.append(chunk.decode() if isinstance(chunk, (bytes, bytearray)) else chunk)+ return "".join(chunks)+++# ── Helper ────────────────────────────────────────────────────+++def test_the_retry_url_is_shared_with_the_anthropic_surface():+ """Both passthroughs post to the same upstream route, so one helper serves both.+ A rename that leaves this surface behind is the bug being fixed."""+ backend = _Backend()++ url = asyncio.run(_passthrough_retry_url(backend, httpx.ConnectError("x")))++ assert url == f"{_FRESH}/v1/chat/completions"+ assert backend.respawn_calls == 1+++# ── Non-streaming ─────────────────────────────────────────────+++def test_non_streaming_retries_against_the_new_port(monkeypatch):+ client = _FakeNonStreamingClient()+ monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)+ backend = _Backend()++ response = asyncio.run(_run_non_streaming(backend))++ assert response.status_code == 200+ assert backend.respawn_calls == 1+ assert client.urls == [f"{_DEAD}/v1/chat/completions", f"{_FRESH}/v1/chat/completions"]+++def test_non_streaming_still_502s_when_the_server_stays_dead(monkeypatch):+ client = _FakeNonStreamingClient()+ monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)+ backend = _Backend(respawn_ok = False)++ with pytest.raises(HTTPException) as exc:+ asyncio.run(_run_non_streaming(backend))++ assert exc.value.status_code == 502+ assert client.urls == [f"{_DEAD}/v1/chat/completions"] # no blind retry+++def test_non_streaming_does_not_retry_an_mtp_crash(monkeypatch):+ # An MTP+tensor crash schedules its own reload; retrying would race it.+ client = _FakeNonStreamingClient()+ monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)+ backend = _Backend(mtp_handled = True)++ with pytest.raises(HTTPException):+ asyncio.run(_run_non_streaming(backend))++ assert backend.respawn_calls == 0+++def test_non_streaming_respawns_at_most_once(monkeypatch):+ """A relaunch that reports success but is not serving must end in a 502, not a+ loop that respawns the model on every attempt."""+ client = _FakeNonStreamingClient()+ monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)+ backend = _Backend(stays_dead = True)++ with pytest.raises(HTTPException) as exc:+ asyncio.run(_run_non_streaming(backend))++ assert exc.value.status_code == 502+ assert backend.respawn_calls == 1+ assert client.urls == [f"{_DEAD}/v1/chat/completions"] * 2+++# ── Streaming ─────────────────────────────────────────────────+++def test_streaming_retries_against_the_new_port(monkeypatch):+ calls = []+ _install_stream_transport(monkeypatch, calls)+ backend = _Backend()++ blob = asyncio.run(_run_stream(backend))++ assert backend.respawn_calls == 1+ assert calls == [f"{_DEAD}/v1/chat/completions", f"{_FRESH}/v1/chat/completions"]+ # The retried stream really produced the turn, not just a clean-looking stop.+ assert "hi" in blob+ assert "[DONE]" in blob+++def test_streaming_still_502s_when_the_server_stays_dead(monkeypatch):+ calls = []+ _install_stream_transport(monkeypatch, calls)+ backend = _Backend(respawn_ok = False)+ lease = _Lease()++ with pytest.raises(HTTPException) as exc:+ asyncio.run(_run_stream(backend, lease))++ assert exc.value.status_code == 502+ assert calls == [f"{_DEAD}/v1/chat/completions"] # no blind retry+ assert lease.released, "the failed dispatch kept its admission slot"+++def test_streaming_does_not_retry_an_mtp_crash(monkeypatch):+ calls = []+ _install_stream_transport(monkeypatch, calls)+ backend = _Backend(mtp_handled = True)++ with pytest.raises(HTTPException):+ asyncio.run(_run_stream(backend))++ assert backend.respawn_calls == 0+ assert calls == [f"{_DEAD}/v1/chat/completions"]+++def test_streaming_respawns_at_most_once(monkeypatch):+ calls = []+ _install_stream_transport(monkeypatch, calls)+ backend = _Backend(stays_dead = True)+ lease = _Lease()++ with pytest.raises(HTTPException):+ asyncio.run(_run_stream(backend, lease))++ assert backend.respawn_calls == 1+ assert calls == [f"{_DEAD}/v1/chat/completions"] * 2+ assert lease.released, "the slot was leaked across the respawn retry"+++def test_a_backend_without_respawn_hooks_is_untouched(monkeypatch):+ """Remote and external backends have no llama-server to relaunch."""+ client = _FakeNonStreamingClient()+ monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)+ backend = SimpleNamespace(+ base_url = _DEAD,+ context_length = 4096,+ count_chat_tokens = lambda *_a, **_k: 2,+ _request_reasoning_kwargs = lambda *_a, **_k: None,+ )++ with pytest.raises(HTTPException):+ asyncio.run(_run_non_streaming(backend))++ assert client.urls == [f"{_DEAD}/v1/chat/completions"]+++# ── Only a lost connection may be replayed ────────────────────+++ "exc, retryable",+ [+ (httpx.ConnectError("refused"), True),+ (httpx.ReadError("reset"), True),+ (httpx.WriteError("broken pipe"), True),+ (httpx.CloseError("close"), True),+ (httpx.RemoteProtocolError("Server disconnected without sending a response."), True),+ (httpx.ReadTimeout("slow"), False),+ (httpx.ConnectTimeout("slow connect"), False),+ (httpx.WriteTimeout("slow write"), False),+ (httpx.PoolTimeout("no free connection"), False),+ ],+)+def test_only_lost_connections_are_replayable(exc, retryable):+ """A timeout means the server is slow, not gone.++ ``httpx.RequestError`` also covers ``TimeoutException``, and a 20-minute+ generation on a live llama-server raises ``ReadTimeout``: replaying it+ resubmits a prompt the server is still decoding. Same split as+ ``_open_chat_stream_with_respawn_retry``. ``RemoteProtocolError`` is a+ sibling of ``NetworkError``, not a subclass, so it is named explicitly.+ """+ assert _is_lost_upstream_connection(exc) is retryable+++class _TimingOutClient:+ """Healthy but slow: every post exceeds the first-token budget."""++ def __init__(self):+ self.urls = []++ async def aclose(self):+ pass++ async def post(self, url, **_kwargs):+ self.urls.append(url)+ raise httpx.ReadTimeout("the model did not produce a first token in time")+++def test_non_streaming_does_not_replay_a_slow_generation(monkeypatch):+ client = _TimingOutClient()+ monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)+ # A live server: _respawn_if_dead reports _healthy, so a retry would go back+ # to the SAME port with the same prompt while the first copy is still decoding.+ backend = _Backend(stays_dead = True)++ with pytest.raises(HTTPException) as exc:+ asyncio.run(_run_non_streaming(backend))++ assert exc.value.status_code == 502+ assert backend.respawn_calls == 0, "a timeout respawned a healthy llama-server"+ assert client.urls == [f"{_DEAD}/v1/chat/completions"], "the slow generation was replayed"+++# ── The retry must follow the respawned server's new api key ──+++class _RotatingKeyBackend(_Backend):+ """llama-server mints a fresh --api-key on every launch (UNSLOTH_DIRECT_STREAM)."""++ def __init__(self, **kw):+ super().__init__(**kw)+ self._api_key = "key-before-the-crash"++ @property+ def _auth_headers(self):+ return {"Authorization": f"Bearer {self._api_key}"}++ def _respawn_if_dead(self):+ started = super()._respawn_if_dead()+ if started:+ self._api_key = "key-after-the-respawn"+ return started+++class _AuthRecordingClient:+ def __init__(self):+ self.sent = []++ async def aclose(self):+ pass++ async def post(self, url, **kwargs):+ self.sent.append((url, dict(kwargs.get("headers") or {})))+ if url.startswith(_DEAD):+ raise httpx.ConnectError("connection refused")+ return httpx.Response(+ 200,+ json = {+ "id": "chatcmpl-1",+ "choices": [+ {"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}+ ],+ },+ )+++def test_non_streaming_retry_uses_the_respawned_api_key(monkeypatch):+ client = _AuthRecordingClient()+ monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)+ backend = _RotatingKeyBackend()++ resp = asyncio.run(_run_non_streaming(backend))++ assert resp.status_code == 200+ assert (+ client.sent[-1][1]["Authorization"] == "Bearer key-after-the-respawn"+ ), "the retry presented the pre-crash key, which the new server 401s"+++def test_streaming_retry_uses_the_respawned_api_key(monkeypatch):+ seen = []++ def handler(request: httpx.Request) -> httpx.Response:+ seen.append((str(request.url), request.headers.get("authorization")))+ if str(request.url).startswith(_DEAD):+ raise httpx.ConnectError("connection refused")+ content = (+ f"data: {json.dumps({'choices': [{'delta': {'content': 'hi'}}]})}\n\n"+ "data: [DONE]\n\n"+ )+ return httpx.Response(+ 200, content = content.encode(), headers = {"content-type": "text/event-stream"}+ )++ transport = httpx.MockTransport(handler)+ real_client = httpx.AsyncClient+ monkeypatch.setattr(+ inf_mod.httpx,+ "AsyncClient",+ lambda *_a, **kw: real_client(transport = transport, timeout = kw.get("timeout", 600)),+ )+ backend = _RotatingKeyBackend()++ blob = asyncio.run(_run_stream(backend))++ assert "[DONE]" in blob+ assert seen[-1][1] == "Bearer key-after-the-respawn"+++# ── A crash after the pre-header status window ────────────────+++class _SlowDeadTransport(httpx.AsyncBaseTransport):+ """The dead port takes longer than the 100 ms pre-header window to fail.++ That is the ordinary shape of a llama-server that dies while the request is+ queued or prefilling: dispatch is still pending when the status window+ closes, so the failure surfaces inside _stream, not in the pre-header+ handler.+ """++ def __init__(+ self,+ calls,+ delay = 0.3,+ ):+ self.calls = calls+ self.delay = delay++ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:+ self.calls.append(str(request.url))+ if str(request.url).startswith(_DEAD):+ await asyncio.sleep(self.delay)+ raise httpx.RemoteProtocolError("Server disconnected without sending a response.")+ content = (+ f"data: {json.dumps({'choices': [{'delta': {'content': 'hi'}}]})}\n\n"+ "data: [DONE]\n\n"+ )+ return httpx.Response(+ 200, content = content.encode(), headers = {"content-type": "text/event-stream"}+ )+++def test_streaming_retries_a_crash_that_lands_after_the_status_window(monkeypatch):+ calls = []+ transport = _SlowDeadTransport(calls)+ real_client = httpx.AsyncClient+ monkeypatch.setattr(+ inf_mod.httpx,+ "AsyncClient",+ lambda *_a, **kw: real_client(transport = transport, timeout = kw.get("timeout", 600)),+ )+ backend = _Backend()++ blob = asyncio.run(_run_stream(backend))++ assert calls == [f"{_DEAD}/v1/chat/completions", f"{_FRESH}/v1/chat/completions"]+ assert backend.respawn_calls == 1+ assert "hi" in blob and "[DONE]" in blob+ # No SSE error chunk leaked to the client before the recovery.+ assert "Lost connection" not in blob+++class _SlowTimeoutTransport(_SlowDeadTransport):+ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:+ self.calls.append(str(request.url))+ await asyncio.sleep(self.delay)+ raise httpx.ReadTimeout("the model did not produce a first token in time")+++def test_streaming_does_not_replay_a_slow_generation_after_the_status_window(monkeypatch):+ calls = []+ transport = _SlowTimeoutTransport(calls)+ real_client = httpx.AsyncClient+ monkeypatch.setattr(+ inf_mod.httpx,+ "AsyncClient",+ lambda *_a, **kw: real_client(transport = transport, timeout = kw.get("timeout", 600)),+ )+ backend = _Backend(stays_dead = True)++ blob = asyncio.run(_run_stream(backend))++ assert calls == [f"{_DEAD}/v1/chat/completions"], "the slow generation was replayed"+ assert backend.respawn_calls == 0+ assert "[DONE]" in blob+++class _SlowRespawnBackend(_Backend):+ """A relaunch that takes real time, the way reloading a large GGUF does.++ Blocks until the consumer reports a keep-alive that arrived AFTER the reload+ began, so the stub records whether the downstream connection was still being+ fed while the model loaded.+ """++ def __init__(self):+ super().__init__()+ self.respawn_started = threading.Event()+ self.keepalive_during_respawn = threading.Event()+ self.fed_while_loading = False++ def _respawn_if_dead(self):+ self.respawn_calls += 1+ self.respawn_started.set()+ self.fed_while_loading = self.keepalive_during_respawn.wait(timeout = 5.0)+ self.base_url = _FRESH+ return True+++def test_streaming_keeps_the_stream_alive_while_the_server_respawns(monkeypatch):+ """The reload is a full model load, minutes for a large GGUF. The response is+ already committed and this loop keeps it alive every five seconds, so going+ silent for the reload lets a proxy or client drop the stream before the+ recovered request is ever submitted."""+ monkeypatch.setattr(inf_mod, "_OPENAI_PASSTHROUGH_PENDING_RESPONSE_KEEPALIVE_S", 0.05)+ calls = []+ transport = _SlowDeadTransport(calls)+ real_client = httpx.AsyncClient+ monkeypatch.setattr(+ inf_mod.httpx,+ "AsyncClient",+ lambda *_a, **kw: real_client(transport = transport, timeout = kw.get("timeout", 600)),+ )+ backend = _SlowRespawnBackend()++ async def _drive():+ response = await _openai_passthrough_stream_admitted(+ _Request(),+ threading.Event(),+ backend,+ _payload(),+ "test-model",+ "chatcmpl-local",+ admission_lease = _Lease(),+ tracker = _Tracker(),+ )+ chunks = []+ async for chunk in response.body_iterator:+ text = chunk.decode() if isinstance(chunk, (bytes, bytearray)) else chunk+ chunks.append(text)+ if (+ backend.respawn_started.is_set()+ and text == inf_mod._OPENAI_PASSTHROUGH_SSE_KEEPALIVE+ ):+ backend.keepalive_during_respawn.set()+ return "".join(chunks)++ blob = asyncio.run(_drive())++ assert backend.respawn_calls == 1+ assert backend.fed_while_loading, "the stream went silent for the whole reload"+ assert calls == [f"{_DEAD}/v1/chat/completions", f"{_FRESH}/v1/chat/completions"]+ assert "hi" in blob and "[DONE]" in blob