Skip to content

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.

Fix expected non-streaming cancellation handling (#9616)

Apoze27e124cfb527
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 0fd2be01f56..b85efd55f12 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -5585,6 +5585,17 @@ def _cancelable_nonstreaming_client() -> httpx.AsyncClient:
)
+class _NonStreamingRequestCancelled(Exception):
+ """Internal signal for an expected non-streaming cancel/disconnect."""
+
+ __slots__ = ()
+
+
+def _raise_if_nonstreaming_request_cancelled(cancel_event) -> None:
+ if cancel_event is not None and cancel_event.is_set():
+ raise _NonStreamingRequestCancelled("Request cancelled.")
+
+
async def _await_cancel_or_disconnect_then_close_client(
*, cancel_event, request: Optional[Request], client: httpx.AsyncClient
) -> None:
@@ -35400,11 +35411,12 @@ async def openai_completions(request: Request, current_subject: str = Depends(ge
)
except httpx.RequestError:
# The watcher closed the client out from under the request: report the cancel, not a transport failure.
- if _cancel_event.is_set():
- raise asyncio.CancelledError()
+ _raise_if_nonstreaming_request_cancelled(_cancel_event)
raise
- if _cancel_event.is_set():
- raise asyncio.CancelledError()
+ _raise_if_nonstreaming_request_cancelled(_cancel_event)
+ except _NonStreamingRequestCancelled as exc:
+ api_monitor.finish(monitor_id, "cancelled")
+ raise _openai_admission_http_exception(exc, status_code = 499)
except asyncio.CancelledError:
api_monitor.finish(monitor_id, "cancelled")
raise
@@ -35790,13 +35802,15 @@ async def _studio_embeddings(
while not acquire.done():
await asyncio.wait({acquire}, timeout = 0.25)
if not acquire.done() and await _embeddings_client_gone(request):
- raise asyncio.CancelledError()
- except asyncio.CancelledError:
+ raise _NonStreamingRequestCancelled("Request cancelled.")
+ except (asyncio.CancelledError, _NonStreamingRequestCancelled) as exc:
if not acquire.done():
acquire.cancel()
elif not acquire.cancelled() and acquire.exception() is None:
semaphore.release()
api_monitor.finish(monitor_id, "cancelled")
+ if isinstance(exc, _NonStreamingRequestCancelled):
+ raise _openai_admission_http_exception(exc, status_code = 499)
raise
try:
gone = await _embeddings_client_gone(request)
@@ -35807,7 +35821,9 @@ async def _studio_embeddings(
if gone:
semaphore.release()
api_monitor.finish(monitor_id, "cancelled")
- raise asyncio.CancelledError()
+ raise _openai_admission_http_exception(
+ _NonStreamingRequestCancelled("Request cancelled."), status_code = 499
+ )
worker = asyncio.ensure_future(asyncio.to_thread(_embed))
def _release_embed_permit(finished) -> None:
@@ -36021,11 +36037,12 @@ async def openai_embeddings(request: Request, current_subject: str = Depends(get
)
except httpx.RequestError:
# The watcher closed the client out from under the request: report the cancel, not a transport failure.
- if _cancel_event.is_set():
- raise asyncio.CancelledError()
+ _raise_if_nonstreaming_request_cancelled(_cancel_event)
raise
- if _cancel_event.is_set():
- raise asyncio.CancelledError()
+ _raise_if_nonstreaming_request_cancelled(_cancel_event)
+ except _NonStreamingRequestCancelled as exc:
+ api_monitor.finish(monitor_id, "cancelled")
+ raise _openai_admission_http_exception(exc, status_code = 499)
except asyncio.CancelledError:
api_monitor.finish(monitor_id, "cancelled")
raise
@@ -40216,6 +40233,9 @@ async def anthropic_messages(
async def _monitored_anthropic(coro):
try:
response = await coro
+ except _NonStreamingRequestCancelled as exc:
+ api_monitor.finish(monitor_id, "cancelled")
+ raise _anthropic_admission_http_exception(exc, status_code = 499)
except asyncio.CancelledError:
cancel_event.set()
api_monitor.finish(monitor_id, "cancelled")
@@ -42165,19 +42185,26 @@ async def _anthropic_passthrough_non_streaming(
)
)
- async def _post(payload_body):
- nonlocal target_url
+ async def _post_once(payload_body):
try:
- return await _client.post(
+ response = await _client.post(
target_url,
json = payload_body,
timeout = _llama_non_streaming_generation_timeout(),
)
- except httpx.RequestError as exc:
+ except httpx.RequestError:
# The watcher closes the client to break a blocked POST, so a transport error
# with the event set is the cancel, not a failure.
- if cancel_event is not None and cancel_event.is_set():
- raise asyncio.CancelledError()
+ _raise_if_nonstreaming_request_cancelled(cancel_event)
+ raise
+ _raise_if_nonstreaming_request_cancelled(cancel_event)
+ return response
+
+ async def _post(payload_body):
+ nonlocal target_url
+ try:
+ return await _post_once(payload_body)
+ except httpx.RequestError as exc:
# 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 = (
@@ -42188,11 +42215,7 @@ async def _anthropic_passthrough_non_streaming(
if retry_url is None:
raise
target_url = retry_url
- return await _client.post(
- target_url,
- json = payload_body,
- timeout = _llama_non_streaming_generation_timeout(),
- )
+ return await _post_once(payload_body)
try:
resp = await _post(body)
@@ -44092,6 +44115,9 @@ async def _openai_passthrough_non_streaming(
status_code = 499,
detail = _openai_admission_error_body(exc, status_code = 499),
)
+ except _NonStreamingRequestCancelled as exc:
+ api_monitor.finish(monitor_id, "cancelled")
+ raise _openai_admission_http_exception(exc, status_code = 499)
except asyncio.CancelledError:
api_monitor.finish(monitor_id, "cancelled")
reservation.cancel()
@@ -44170,11 +44196,9 @@ async def _openai_passthrough_non_streaming_upstream(
timeout = _llama_non_streaming_generation_timeout(),
)
except httpx.RequestError:
- if cancel.is_set():
- raise asyncio.CancelledError()
+ _raise_if_nonstreaming_request_cancelled(cancel)
raise
- if cancel.is_set():
- raise asyncio.CancelledError()
+ _raise_if_nonstreaming_request_cancelled(cancel)
return response
finally:
# Bounded: the watcher polls Request.is_disconnected(), which can swallow
diff --git a/studio/backend/tests/test_active_generations.py b/studio/backend/tests/test_active_generations.py
index 9e1d0d574bc..102a848b904 100644
--- a/studio/backend/tests/test_active_generations.py
+++ b/studio/backend/tests/test_active_generations.py
@@ -1353,9 +1353,10 @@ def test_completions_proxy_non_stream_is_visible_to_the_swap_gate(monkeypatch):
request = _CompletionsRequest({"prompt": "hi", "model": "org/M-GGUF", "max_tokens": 8})
- with pytest.raises(asyncio.CancelledError):
+ with pytest.raises(inf_mod.HTTPException) as exc:
asyncio.run(inf_mod.openai_completions(request, "tester"))
+ assert exc.value.status_code == 499
assert seen["count"] == 1
assert seen["snapshot"][0]["model"] == "org/M-GGUF"
assert seen["cancelled"] == 1
@@ -1426,9 +1427,10 @@ def test_embeddings_proxy_is_visible_to_the_swap_gate(monkeypatch):
request = _EmbeddingsRequest({"input": "hi", "model": "org/M-GGUF"})
- with pytest.raises(asyncio.CancelledError):
+ with pytest.raises(inf_mod.HTTPException) as exc:
asyncio.run(inf_mod.openai_embeddings(request, "tester"))
+ assert exc.value.status_code == 499
assert seen["count"] == 1
assert seen["snapshot"][0]["model"] == "org/M-GGUF"
assert seen["cancelled"] == 1
@@ -2224,11 +2226,14 @@ def test_anthropic_passthrough_non_stream_is_visible_to_the_swap_gate(monkeypatc
tools = [{"name": "lookup", "input_schema": {"type": "object", "properties": {}}}],
)
- response = asyncio.run(
- inf_mod.anthropic_messages(payload, request = _MessagesRequest(), current_subject = "tester")
- )
+ with pytest.raises(inf_mod.HTTPException) as exc:
+ asyncio.run(
+ inf_mod.anthropic_messages(
+ payload, request = _MessagesRequest(), current_subject = "tester"
+ )
+ )
- assert response.status_code == 200
+ assert exc.value.status_code == 499
assert seen["count"] == 1
assert seen["snapshot"][0]["model"] == "org/M-GGUF"
assert seen["cancelled"] == 1
@@ -2269,13 +2274,14 @@ def test_anthropic_passthrough_non_stream_stops_when_the_swap_cancels_it(monkeyp
tools = [{"name": "lookup", "input_schema": {"type": "object", "properties": {}}}],
)
- with pytest.raises(asyncio.CancelledError):
+ with pytest.raises(inf_mod.HTTPException) as exc:
asyncio.run(
inf_mod.anthropic_messages(
payload, request = _MessagesRequest(), current_subject = "tester"
)
)
+ assert exc.value.status_code == 499
assert seen["cancelled"] == 1
# Cancelled or not, the entry must go, or one message 409s every later reload.
assert active_generations.count() == 0
diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.py
index 80ce02e5072..cbe9c739b22 100644
--- a/studio/backend/tests/test_anthropic_messages.py
+++ b/studio/backend/tests/test_anthropic_messages.py
@@ -3762,6 +3762,35 @@ class TestAnthropicMessagesToolRouting:
assert entry["status"] == "completed"
assert entry["reply_preview"] == 'Tool call: lookup({"query": "weather"})'
+ def test_client_tool_non_streaming_expected_cancel_returns_anthropic_499(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ async def _cancelled(*_args, **_kwargs):
+ raise inf_mod._NonStreamingRequestCancelled("Request cancelled.")
+
+ _mock_backend(monkeypatch, base_url = "http://llama.test")
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "_anthropic_passthrough_non_streaming", _cancelled)
+ payload = _basic_payload(
+ tools = [
+ {
+ "name": "lookup",
+ "description": "Look something up",
+ "input_schema": {"type": "object", "properties": {}},
+ }
+ ]
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ _drive(anthropic_messages(payload, request = self._Request(), current_subject = "t"))
+
+ assert exc.value.status_code == 499
+ assert exc.value.detail["type"] == "error"
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "cancelled"
+ assert monitor.active_count() == 0
+
def test_plain_streaming_records_active_and_completed_monitor_entry(self, monkeypatch):
import routes.inference as inf_mod
diff --git a/studio/backend/tests/test_anthropic_passthrough_respawn.py b/studio/backend/tests/test_anthropic_passthrough_respawn.py
index 5e2193f9097..91769f2714e 100644
--- a/studio/backend/tests/test_anthropic_passthrough_respawn.py
+++ b/studio/backend/tests/test_anthropic_passthrough_respawn.py
@@ -98,8 +98,7 @@ def _install_stream_transport(monkeypatch, calls):
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"
+ f"data: {json.dumps({'choices': [{'delta': {'content': 'hi'}}]})}\n\ndata: [DONE]\n\n"
)
return httpx.Response(
200,
@@ -136,7 +135,7 @@ async def _run_stream(backend):
return "".join(chunks)
-async def _run_non_streaming(backend):
+async def _run_non_streaming(backend, **kwargs):
return await _anthropic_passthrough_non_streaming(
backend,
[{"role": "user", "content": "hi"}],
@@ -147,6 +146,7 @@ async def _run_non_streaming(backend):
16,
"msg_1",
"test-model",
+ **kwargs,
)
@@ -225,6 +225,79 @@ def test_non_streaming_does_not_retry_an_mtp_crash(monkeypatch):
assert backend.respawn_calls == 0
+def test_non_streaming_cancel_after_respawn_retry_is_not_a_transport_error(monkeypatch):
+ class CancelAfterRespawnClient:
+ def __init__(self):
+ self.urls = []
+ self.retry_started = asyncio.Event()
+ self.closed = asyncio.Event()
+
+ async def post(self, url, **_kwargs):
+ self.urls.append(url)
+ if len(self.urls) == 1:
+ raise httpx.ConnectError("connection refused")
+ self.retry_started.set()
+ await self.closed.wait()
+ raise httpx.ReadError("client closed")
+
+ async def aclose(self):
+ self.closed.set()
+
+ async def _run():
+ client = CancelAfterRespawnClient()
+ monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)
+ backend = _Backend()
+ cancel_event = threading.Event()
+ task = asyncio.create_task(
+ _run_non_streaming(
+ backend,
+ request = _Request(),
+ cancel_event = cancel_event,
+ )
+ )
+ await asyncio.wait_for(client.retry_started.wait(), 0.2)
+ cancel_event.set()
+
+ with pytest.raises(inf_mod._NonStreamingRequestCancelled):
+ await asyncio.wait_for(task, 0.5)
+
+ assert client.urls == [f"{_DEAD}/v1/chat/completions", f"{_FRESH}/v1/chat/completions"]
+ assert client.closed.is_set()
+
+ asyncio.run(_run())
+
+
+def test_non_streaming_cancel_wins_response_race(monkeypatch):
+ async def _run():
+ cancel_event = threading.Event()
+
+ class RacingClient(_FakeNonStreamingClient):
+ async def post(self, url, **_kwargs):
+ self.urls.append(url)
+ cancel_event.set()
+ return httpx.Response(
+ 200,
+ json = {
+ "choices": [{"message": {"content": "too late"}, "finish_reason": "stop"}],
+ "usage": {"prompt_tokens": 2, "completion_tokens": 2},
+ },
+ )
+
+ client = RacingClient()
+ monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)
+
+ with pytest.raises(inf_mod._NonStreamingRequestCancelled):
+ await _run_non_streaming(
+ _Backend(),
+ request = _Request(),
+ cancel_event = cancel_event,
+ )
+
+ assert client.closed
+
+ asyncio.run(_run())
+
+
# ── Streaming ─────────────────────────────────────────────────
diff --git a/studio/backend/tests/test_openai_embeddings_studio_fallback.py b/studio/backend/tests/test_openai_embeddings_studio_fallback.py
index 19e9aa22479..12062632922 100644
--- a/studio/backend/tests/test_openai_embeddings_studio_fallback.py
+++ b/studio/backend/tests/test_openai_embeddings_studio_fallback.py
@@ -10,6 +10,7 @@ from types import SimpleNamespace
import numpy as np
import pytest
+from fastapi import HTTPException
_backend = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _backend not in sys.path:
@@ -1155,8 +1156,9 @@ def test_disconnected_client_leaves_the_queue_without_embedding(studio_embedder)
await asyncio.sleep(0.01)
if calls["n"] == cap:
break
- with pytest.raises(asyncio.CancelledError):
+ with pytest.raises(HTTPException) as exc:
await inference_route.openai_embeddings(_Gone({"input": "gone"}), "t")
+ assert exc.value.status_code == 499
assert calls["n"] == cap
gate.set()
await asyncio.gather(*blockers)
@@ -1243,8 +1245,9 @@ def test_disconnected_client_is_dropped_even_with_a_free_permit(studio_embedder)
)
async def run():
- with pytest.raises(asyncio.CancelledError):
+ with pytest.raises(HTTPException) as exc:
await inference_route.openai_embeddings(_Gone({"input": "gone"}), "t")
+ assert exc.value.status_code == 499
assert calls == []
response = await inference_route.openai_embeddings(_Request({"input": "later"}), "t")
assert response.status_code == 200
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index ac98434e6ac..3df8c045aab 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -8543,6 +8543,61 @@ class TestApiMonitorProviderAndCompletionStreams:
asyncio.run(_run())
+ @pytest.mark.parametrize(
+ ("route", "path", "body"),
+ [
+ (openai_completions, "/v1/completions", {"prompt": "hi", "stream": False}),
+ (openai_embeddings, "/v1/embeddings", {"input": ["hi"], "model": "embed"}),
+ ],
+ )
+ def test_non_streaming_proxy_disconnect_returns_499(self, monkeypatch, route, path, body):
+ import routes.inference as inf_mod
+ async def _run():
+ class Request:
+ state = SimpleNamespace()
+ url = SimpleNamespace(path = path)
+ method = "POST"
+
+ def __init__(self):
+ self.disconnected = False
+
+ async def json(self):
+ return body
+
+ async def is_disconnected(self):
+ return self.disconnected
+
+ client = HangingCancelableClient()
+ request = Request()
+ monitor = ApiMonitor(max_entries = 3)
+ monkeypatch.setattr(inf_mod, "api_monitor", monitor)
+ monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = True,
+ base_url = "http://llama.test",
+ context_length = 4096,
+ model_identifier = "gguf",
+ ),
+ )
+
+ task = asyncio.create_task(route(request, current_subject = "test"))
+ await asyncio.wait_for(client.started.wait(), 0.2)
+ request.disconnected = True
+
+ with pytest.raises(HTTPException) as exc:
+ await asyncio.wait_for(task, 0.5)
+
+ assert exc.value.status_code == 499
+ assert client.closed.is_set()
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "cancelled"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
def test_passthrough_stream_task_cancel_finalizes_monitor(self, monkeypatch):
import routes.inference as inf_mod
async def _run():
@@ -9303,6 +9358,41 @@ class TestApiMonitorProviderAndCompletionStreams:
asyncio.run(_run())
+ def test_passthrough_non_streaming_task_cancel_propagates(self, monkeypatch):
+ import routes.inference as inf_mod
+ async def _run():
+ client = HangingCancelableClient()
+ monitor, monitor_id = _install_monitor(monkeypatch)
+ monkeypatch.setattr(inf_mod, "_cancelable_nonstreaming_client", lambda: client)
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "hi")],
+ tools = [_LOOKUP_TOOL],
+ )
+
+ task = asyncio.create_task(
+ _openai_passthrough_non_streaming(
+ _passthrough_backend(),
+ payload,
+ "gguf",
+ monitor_id = monitor_id,
+ request = _ConnectedRequest(),
+ cancel_event = threading.Event(),
+ )
+ )
+ await asyncio.wait_for(client.started.wait(), 0.2)
+ task.cancel()
+
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ assert client.closed.is_set()
+ [entry] = monitor.snapshot()
+ assert entry["status"] == "cancelled"
+ assert monitor.active_count() == 0
+
+ asyncio.run(_run())
+
def test_passthrough_non_streaming_cancel_closes_blocked_upstream_post(self, monkeypatch):
import routes.inference as inf_mod
async def _run():
@@ -9335,9 +9425,10 @@ class TestApiMonitorProviderAndCompletionStreams:
await asyncio.wait_for(client.started.wait(), 0.2)
cancel_event.set()
- with pytest.raises(asyncio.CancelledError):
+ with pytest.raises(HTTPException) as exc:
await asyncio.wait_for(task, 0.5)
+ assert exc.value.status_code == 499
assert client.closed.is_set()
[entry] = monitor.snapshot()
assert entry["status"] == "cancelled"
@@ -9399,9 +9490,10 @@ class TestApiMonitorProviderAndCompletionStreams:
assert cancel_id in inf_mod._CANCEL_REGISTRY
assert inf_mod._cancel_by_cancel_id_or_stash(cancel_id) == 1
- with pytest.raises(asyncio.CancelledError):
+ with pytest.raises(HTTPException) as exc:
await asyncio.wait_for(task, 5.0)
+ assert exc.value.status_code == 499
assert client.closed.is_set()
assert cancel_id not in inf_mod._CANCEL_REGISTRY
[entry] = monitor.snapshot()
@@ -9450,9 +9542,10 @@ class TestApiMonitorProviderAndCompletionStreams:
await asyncio.wait_for(client.started.wait(), 0.2)
request.disconnected = True
- with pytest.raises(asyncio.CancelledError):
+ with pytest.raises(HTTPException) as exc:
await asyncio.wait_for(task, 0.5)
+ assert exc.value.status_code == 499
assert client.closed.is_set()
assert cancel_event.is_set()
[entry] = monitor.snapshot()
diff --git a/studio/backend/tests/test_passthrough_healing.py b/studio/backend/tests/test_passthrough_healing.py
index c38f8fe22ba..bba89f3f4be 100644
--- a/studio/backend/tests/test_passthrough_healing.py
+++ b/studio/backend/tests/test_passthrough_healing.py
@@ -886,6 +886,61 @@ class TestNudgeRetryOpenai:
asyncio.run(_run())
+ def test_expected_cancel_during_nudge_retry_is_not_absorbed(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ class ImmediateClient:
+ async def post(self, *_args, **_kwargs):
+ return httpx.Response(200, json = _upstream_message(GARBAGE_SIGNAL))
+
+ async def aclose(self):
+ return None
+
+ class HangingClient:
+ def __init__(self):
+ self.started = asyncio.Event()
+ self.closed = asyncio.Event()
+
+ async def post(self, *_args, **_kwargs):
+ self.started.set()
+ await self.closed.wait()
+ raise httpx.ReadError("client closed")
+
+ async def aclose(self):
+ self.closed.set()
+
+ class Request:
+ async def is_disconnected(self):
+ return False
+
+ hanging = HangingClient()
+ clients = iter((ImmediateClient(), hanging))
+ monkeypatch.setattr(
+ inf_mod,
+ "_cancelable_nonstreaming_client",
+ lambda: next(clients),
+ )
+ cancel_event = threading.Event()
+ task = asyncio.create_task(
+ inf_mod._openai_passthrough_non_streaming_upstream(
+ _llama_backend(),
+ _payload(nudge_tool_calls = True),
+ "gguf",
+ request = Request(),
+ cancel_event = cancel_event,
+ )
+ )
+ await asyncio.wait_for(hanging.started.wait(), 0.2)
+ cancel_event.set()
+
+ with pytest.raises(inf_mod._NonStreamingRequestCancelled):
+ await asyncio.wait_for(task, 0.5)
+
+ assert hanging.closed.is_set()
+
+ asyncio.run(_run())
+
def test_default_off_single_post(self, monkeypatch):
async def _run():
client, _ = await _drive_non_streaming(