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.

Studio: bound every teardown await so a swallowed cancel cannot wedge the API (#7881)

Maheswar Kumard2b51fae497b
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 54b71267946..fa641038b2d 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1128,6 +1128,10 @@ _OPENAI_PASSTHROUGH_PREHEADER_STATUS_WINDOW_S = 0.1
_OPENAI_PASSTHROUGH_PENDING_RESPONSE_KEEPALIVE_S = 5.0
_OPENAI_PASSTHROUGH_SSE_KEEPALIVE = ": keep-alive\n\n"
_OPENAI_LLAMA_ADMISSION_POLL_S = 0.25
+# Cap on waiting for a cancelled teardown task. Request.is_disconnected() can swallow
+# cancel() (#7617), so teardown abandons the task rather than hold the response, and
+# the process-wide slot, open forever.
+_TEARDOWN_TASK_STOP_TIMEOUT_S = 5.0
# Idle window before a local tool-loop stream emits an SSE keepalive comment
# (e.g. prompt prefill between tool iterations). A second layer atop the
# tool_stream_exec heartbeats, keeping proxies (Cloudflare drops idle at ~100s).
@@ -1648,17 +1652,26 @@ async def _aclose_stream_resources(
client = None,
) -> None:
"""Tear down an httpx streaming generator's resources in the required order:
- cancel + await each watcher task, then aclose() the byte/line iterator, the
- response, and the client. Each step swallows its own exceptions so teardown
+ 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."""
- for watcher in watchers:
- if watcher is not None:
+ # 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
+ live = [w for w in watchers if w is not None]
+ if live:
+ # Cancel before the first await, else a cancel here stops the gather before it
+ # steps its children, leaving watchers never cancelled.
+ for watcher in live:
watcher.cancel()
- try:
- await watcher
- except (asyncio.CancelledError, Exception):
- pass
+ try:
+ await asyncio.gather(
+ *(_stop_local_disconnect_cancel_watcher(w) for w in live),
+ return_exceptions = True,
+ )
+ except (asyncio.CancelledError, Exception):
+ pass
close_cancelled = False
if iterator is not None:
try:
@@ -1685,6 +1698,56 @@ async def _aclose_stream_resources(
raise asyncio.CancelledError()
+# The loop holds only weak refs to tasks, so a bare ensure_future() close can be collected
+# before it runs. Strong ref until done.
+_LATE_CLOSE_TASKS: set = set()
+
+
+async def _aclose_quietly(obj) -> None:
+ try:
+ await obj.aclose()
+ except Exception:
+ pass
+
+
+def _discard_task_outcome(task: asyncio.Task) -> None:
+ """Drain an abandoned teardown task, closing a late response rather than dropping it.
+
+ Closing the per-request client does not close a response the send produces on a
+ connection opened after that close. Never raises: this is a done callback. #7617
+ """
+ try:
+ if task.cancelled():
+ return
+ if task.exception() is not None:
+ return
+ result = task.result()
+ except Exception:
+ return
+ if result is not None and hasattr(result, "aclose") and not getattr(result, "is_closed", False):
+ try:
+ closing = asyncio.ensure_future(_aclose_quietly(result))
+ except RuntimeError:
+ return
+ _LATE_CLOSE_TASKS.add(closing)
+ closing.add_done_callback(_LATE_CLOSE_TASKS.discard)
+
+
+def _release_admission(admission_lease = None, tracker = None) -> None:
+ """Give back the process-wide llama-server slot and the cancel-registry entry.
+
+ Must run after the upstream response is closed: on disconnect llama-server keeps
+ decoding until ``resp`` is closed, so releasing first admits a second request past
+ --parallel. Safe behind the closes only because every teardown await is bounded. #7617
+ """
+ try:
+ if admission_lease is not None:
+ admission_lease.release()
+ finally:
+ if tracker is not None:
+ tracker.__exit__(None, None, None)
+
+
async def _preheader_cancelled(cancel_event = None, request: Optional[Request] = None) -> bool:
if cancel_event is not None and cancel_event.is_set():
return True
@@ -1720,9 +1783,18 @@ async def _send_stream_with_preheader_cancel(
await client.aclose()
except Exception:
pass
+ # Bounded: the client is already closed, so an abandoned send owns nothing and
+ # the callback drains its result. #7617
send_task.cancel()
+ done, _pending = await asyncio.wait({send_task}, timeout = _TEARDOWN_TASK_STOP_TIMEOUT_S)
+ if not done:
+ send_task.add_done_callback(_discard_task_outcome)
+ return
try:
- await send_task
+ # The aclose() above does not close a response the send produced during it.
+ sent = send_task.result()
+ if sent is not None:
+ await _aclose_quietly(sent)
except (asyncio.CancelledError, Exception):
pass
@@ -1742,9 +1814,10 @@ async def _send_stream_with_preheader_cancel(
await _stop_send_task()
raise
finally:
- cancel_task.cancel()
+ # Bounded: cancel_task polls Request.is_disconnected(), which can swallow cancel(),
+ # and this finally also runs on the success path, before the first byte. #7617
try:
- await cancel_task
+ await _stop_local_disconnect_cancel_watcher(cancel_task)
except (asyncio.CancelledError, Exception):
pass
@@ -2595,13 +2668,18 @@ async def _await_cancel_or_disconnect_then_close_client(
return
-async def _stop_local_disconnect_cancel_watcher(watcher, timeout_s: float = 5.0) -> None:
+async def _stop_local_disconnect_cancel_watcher(
+ watcher, timeout_s: float = _TEARDOWN_TASK_STOP_TIMEOUT_S
+) -> None:
# Bounded: this runs in the stream's finally, so awaiting the watcher outright would let a
# wedged poll loop hold the response open forever. asyncio.wait neither cancels nor re-raises,
# and an abandoned watcher owns no resources.
watcher.cancel()
done, _pending = await asyncio.wait({watcher}, timeout = timeout_s)
if not done:
+ # _wait_preheader_cancel has no exception handler, so a raise after we stop
+ # waiting would surface as "Task exception was never retrieved".
+ watcher.add_done_callback(_discard_task_outcome)
return
try:
watcher.result()
@@ -17027,8 +17105,8 @@ async def _anthropic_passthrough_stream(
yield event
return
finally:
- # Same shape as the OpenAI passthrough: a close-time CancelledError
- # re-raised by _aclose_stream_resources must not skip the tracker exit.
+ # Same shape as the OpenAI passthrough: the tracker exits after the closes,
+ # and the bounded teardown awaits cannot hold it indefinitely.
try:
await _aclose_stream_resources(
watchers = (cancel_watcher, disconnect_watcher),
@@ -17037,7 +17115,7 @@ async def _anthropic_passthrough_stream(
client = client,
)
finally:
- _tracker.__exit__(None, None, None)
+ _release_admission(tracker = _tracker)
for line in emitter.finish():
yield line
@@ -17867,8 +17945,15 @@ async def _openai_passthrough_stream_admitted(
return
if not task.done():
task.cancel()
+ # Bounded: the send polls Request.is_disconnected() before dispatch, which can
+ # swallow cancel(). Abandoning it is safe because the caller closes the per-request
+ # client right after, tearing down whatever response it later produces. #7617
+ done, _pending = await asyncio.wait({task}, timeout = _TEARDOWN_TASK_STOP_TIMEOUT_S)
+ if not done:
+ task.add_done_callback(_discard_task_outcome)
+ return
try:
- task_resp = await task
+ task_resp = task.result()
if task_resp is not None:
try:
await task_resp.aclose()
@@ -17929,8 +18014,15 @@ async def _openai_passthrough_stream_admitted(
# llama-server subprocess crashed / starting / unreachable.
logger.error("openai passthrough stream: upstream unreachable: %s", e)
api_monitor.fail(monitor_id, _friendly_error(e))
- await _aclose_send_task(send_task)
- await _aclose_stream_resources(resp = resp, client = client)
+ # Nested so a cancel inside _aclose_send_task's wait cannot skip the closes.
+ # The outer handler releases too, but _release_admission is idempotent.
+ try:
+ await _aclose_send_task(send_task)
+ finally:
+ try:
+ await _aclose_stream_resources(resp = resp, client = client)
+ finally:
+ _release_admission(admission_lease, _tracker)
raise HTTPException(
status_code = 502,
detail = _friendly_error(e),
@@ -17943,12 +18035,11 @@ async def _openai_passthrough_stream_admitted(
api_monitor.finish(monitor_id, "cancelled")
try:
await _aclose_send_task(send_task)
- await _aclose_stream_resources(client = client)
finally:
try:
- admission_lease.release()
+ await _aclose_stream_resources(client = client)
finally:
- _tracker.__exit__(None, None, None)
+ _release_admission(admission_lease, _tracker)
return _SameTaskStreamingResponse(
iter(()),
media_type = "text/event-stream",
@@ -18483,21 +18574,23 @@ async def _openai_passthrough_stream_admitted(
err = _openai_stream_error_chunk(e)
yield _openai_stream_error_sse(err)
finally:
- # _aclose_stream_resources re-raises a close-time CancelledError
- # only after finishing teardown, and the tracker exits either way.
+ # Close the upstream stream first: on disconnect llama-server keeps decoding
+ # until resp is closed, so releasing the slot earlier admits a second request
+ # past --parallel. Safe to hold the slot across these closes because every
+ # task await in them is bounded, and the aclose() calls do not block on
+ # HTTP/1.1 to a local llama-server. #7617
try:
await _aclose_send_task(send_task)
- await _aclose_stream_resources(
- watchers = (cancel_watcher, disconnect_watcher),
- iterator = lines_iter,
- resp = resp,
- client = client,
- )
finally:
try:
- admission_lease.release()
+ await _aclose_stream_resources(
+ watchers = (cancel_watcher, disconnect_watcher),
+ iterator = lines_iter,
+ resp = resp,
+ client = client,
+ )
finally:
- _tracker.__exit__(None, None, None)
+ _release_admission(admission_lease, _tracker)
async def _unstarted_cleanup() -> None:
# Client disconnected before the body stream started, so _stream()'s
@@ -18506,12 +18599,11 @@ async def _openai_passthrough_stream_admitted(
# are created inside _stream(), so there is nothing else to close.
try:
await _aclose_send_task(send_task)
- await _aclose_stream_resources(resp = resp, client = client)
finally:
try:
- admission_lease.release()
+ await _aclose_stream_resources(resp = resp, client = client)
finally:
- _tracker.__exit__(None, None, None)
+ _release_admission(admission_lease, _tracker)
return _SameTaskStreamingResponse(
_stream(),
@@ -18533,12 +18625,11 @@ async def _openai_passthrough_stream_admitted(
api_monitor.fail(monitor_id, str(detail))
try:
await _aclose_send_task(send_task)
- await _aclose_stream_resources(resp = resp, client = client)
finally:
try:
- admission_lease.release()
+ await _aclose_stream_resources(resp = resp, client = client)
finally:
- _tracker.__exit__(None, None, None)
+ _release_admission(admission_lease, _tracker)
raise
@@ -18706,9 +18797,10 @@ async def _openai_passthrough_non_streaming_upstream(
raise asyncio.CancelledError()
return response
finally:
- watcher.cancel()
+ # Bounded: the watcher polls Request.is_disconnected(), which can swallow
+ # cancel(). The client it owns is closed below either way. #7617
try:
- await watcher
+ await _stop_local_disconnect_cancel_watcher(watcher)
except (asyncio.CancelledError, Exception):
pass
try:
diff --git a/studio/backend/tests/test_disconnect_watcher_teardown.py b/studio/backend/tests/test_disconnect_watcher_teardown.py
new file mode 100644
index 00000000000..63cd9e8cb50
--- /dev/null
+++ b/studio/backend/tests/test_disconnect_watcher_teardown.py
@@ -0,0 +1,347 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""A disconnect watcher that never settles must not block a stream's teardown.
+
+Starlette's Request.is_disconnected() awaits receive() inside an anyio CancelScope it has
+already cancelled, and under uvicorn's h11 protocol that receive() genuinely parks. A cancel()
+arriving in that window counts as a second cancellation, so the scope's __exit__ uncancel()s
+and swallows the CancelledError as its own: the watcher survives cancel() and keeps polling.
+
+Teardown that awaited such a watcher outright therefore blocked until the client itself
+disconnected, holding the ASGI response open and stranding the llama-server admission lease
+released behind it. #7617.
+
+These tests wait on a task rather than asyncio.wait_for: a stub that ignores cancel() cannot
+be unblocked by cancelling it, so a wait_for here would hang instead of failing.
+"""
+
+import ast
+import asyncio
+import inspect
+import textwrap
+import threading
+
+import httpx
+import pytest
+from starlette.requests import Request
+
+import routes.inference as inference_route
+
+_TEARDOWN_CALLS = ("_aclose_send_task", "_aclose_stream_resources")
+
+
+class _Closeable:
+ def __init__(self):
+ self.closed = False
+
+ async def aclose(self):
+ self.closed = True
+
+
+def _bounded_stop(monkeypatch, collected):
+ """Keep the real bounded stop, record what it was handed, shorten its 5s default."""
+ real_stop = inference_route._stop_local_disconnect_cancel_watcher
+
+ def _stop(task, timeout_s = 0.05):
+ collected.append(task)
+ return real_stop(task, timeout_s)
+
+ monkeypatch.setattr(inference_route, "_stop_local_disconnect_cancel_watcher", _stop)
+
+
+def _swallowing_watcher(release, created):
+ """Stands in for a watcher suspended inside is_disconnected()'s cancelled scope.
+
+ Records its own task so cleanup has a handle even when the teardown never hands it
+ to the bounded stop.
+ """
+
+ async def _poll(*_args, **_kwargs):
+ created.append(asyncio.current_task())
+ while not release.is_set():
+ try:
+ await asyncio.sleep(0.01)
+ except asyncio.CancelledError:
+ continue
+
+ return _poll
+
+
+async def _finished(coro, timeout_s = 5.0):
+ """Run coro to completion without cancelling it on timeout; report whether it ended."""
+ task = asyncio.create_task(coro)
+ done, _pending = await asyncio.wait({task}, timeout = timeout_s)
+ return task, bool(done)
+
+
+async def _release(release, tasks):
+ """Must run even on failure: a stub that swallows cancel() wedges loop shutdown."""
+ release.set()
+ for task in tasks:
+ if task is None:
+ continue
+ await asyncio.wait({task}, timeout = 2.0)
+ if not task.done():
+ task.cancel()
+ await asyncio.wait({task}, timeout = 2.0)
+
+
+def test_aclose_stream_resources_is_not_blocked_by_a_wedged_watcher(monkeypatch):
+ """_aclose_stream_resources runs in the stream's finally; it must stay bounded."""
+ stopped = []
+ _bounded_stop(monkeypatch, stopped)
+
+ async def _run():
+ release = asyncio.Event()
+ watcher = asyncio.create_task(_swallowing_watcher(release, [])())
+ teardown = None
+ try:
+ await asyncio.sleep(0)
+ iterator, resp, client = _Closeable(), _Closeable(), _Closeable()
+
+ teardown, finished = await _finished(
+ inference_route._aclose_stream_resources(
+ watchers = (watcher,),
+ iterator = iterator,
+ resp = resp,
+ client = client,
+ )
+ )
+
+ assert finished, "teardown blocked on a watcher that ignores cancel()"
+ assert stopped == [watcher], "the watcher must go through the bounded stop"
+ assert not watcher.done(), "watcher should have been abandoned, not awaited"
+ assert (
+ iterator.closed and resp.closed and client.closed
+ ), "teardown must still close the upstream resources after abandoning it"
+ finally:
+ await _release(release, [watcher, teardown])
+
+ asyncio.run(_run())
+
+
+def test_send_stream_preheader_finally_is_not_blocked_by_a_wedged_watcher(monkeypatch):
+ """The preheader finally runs on the success path too, before the first byte."""
+ stopped = []
+ _bounded_stop(monkeypatch, stopped)
+
+ async def _run():
+ release = asyncio.Event()
+ created = []
+ sent = httpx.Response(200)
+
+ class _Client:
+ async def send(
+ self,
+ req,
+ stream = False,
+ ):
+ return sent
+
+ async def aclose(self):
+ pass
+
+ class _Request:
+ async def is_disconnected(self):
+ return False
+
+ monkeypatch.setattr(
+ inference_route, "_wait_preheader_cancel", _swallowing_watcher(release, created)
+ )
+ send = None
+ try:
+ send, finished = await _finished(
+ inference_route._send_stream_with_preheader_cancel(
+ _Client(),
+ httpx.Request("POST", "http://llama.test/v1/chat/completions"),
+ threading.Event(),
+ request = _Request(),
+ )
+ )
+
+ assert finished, "preheader send blocked on a cancel task that ignores cancel()"
+ assert send.result() is sent, "the upstream response must still be returned"
+ assert stopped, "the preheader cancel task must go through the bounded stop"
+ assert not stopped[0].done(), "cancel task should have been abandoned"
+ finally:
+ await _release(release, created + [send])
+
+ asyncio.run(_run())
+
+
+def test_real_disconnect_watcher_can_survive_cancel_inside_is_disconnected():
+ """Pins the upstream behaviour the bounded teardown exists for.
+
+ A real watcher on a real starlette Request, cancelled while suspended inside
+ is_disconnected()'s already-cancelled anyio scope, keeps running. The window is a
+ single loop iteration, so sweep the ticks around the poll rather than assume one.
+
+ If this stops reproducing, the unbounded awaits are still wrong to restore: the point
+ is that cancel() is not guaranteed to land here.
+ """
+
+ async def _survives_cancel_at(offset):
+ parked = asyncio.Queue()
+ release = asyncio.Event()
+
+ scope = {
+ "type": "http",
+ "method": "POST",
+ "path": "/v1/chat/completions",
+ "headers": [],
+ "query_string": b"",
+ "client": ("127.0.0.1", 12345),
+ }
+
+ async def receive():
+ parked.put_nowait(None)
+ await release.wait()
+ return {"type": "http.disconnect"}
+
+ watcher = asyncio.create_task(
+ inference_route._await_disconnect_then_close(
+ Request(scope, receive), _Closeable(), threading.Event()
+ )
+ )
+ try:
+ await parked.get()
+ for _ in range(offset):
+ await asyncio.sleep(0)
+ watcher.cancel()
+ done, _pending = await asyncio.wait({watcher}, timeout = 0.5)
+ return not done
+ finally:
+ await _release(release, [watcher])
+
+ async def _run():
+ for offset in range(8):
+ if await _survives_cancel_at(offset):
+ return offset
+ return None
+
+ offset = asyncio.run(_run())
+ if offset is None:
+ pytest.skip("is_disconnected() delivered cancel() at every tick on this runtime")
+
+
+def _blocks(tree):
+ """Every statement list in the tree, so ordering is checked within one scope."""
+ for node in ast.walk(tree):
+ for field in ("body", "orelse", "finalbody"):
+ block = getattr(node, field, None)
+ if isinstance(block, list) and block and isinstance(block[0], ast.stmt):
+ yield block
+
+
+def _called_name(stmt):
+ """The name a bare `foo(...)` / `await foo(...)` statement calls, else None.
+
+ Structural rather than textual so an enclosing try/finally does not match on the calls
+ nested inside it.
+ """
+ if not isinstance(stmt, ast.Expr):
+ return None
+ value = stmt.value
+ if isinstance(value, ast.Await):
+ value = value.value
+ if isinstance(value, ast.Call) and isinstance(value.func, ast.Name):
+ return value.func.id
+ return None
+
+
+def _first_index(block, names):
+ for index, stmt in enumerate(block):
+ if _called_name(stmt) in names:
+ return index
+ return None
+
+
+ "func_name",
+ ["_openai_passthrough_stream_admitted", "_anthropic_passthrough_stream"],
+)
+def test_admission_is_released_after_the_upstream_stream_is_closed(func_name):
+ """The slot must be handed back only once the upstream response is closed.
+
+ On disconnect llama-server keeps decoding until resp is closed, so releasing first
+ admits another request past --parallel. The release must still always run, from the
+ finally of the same try, which is bounded only because every teardown await is.
+ """
+ func = getattr(inference_route, func_name)
+ tree = ast.parse(textwrap.dedent(inspect.getsource(func)))
+
+ # a release must never sit ahead of a close in the same block
+ for block in _blocks(tree):
+ release_at = _first_index(block, ("_release_admission",))
+ teardown_at = _first_index(block, _TEARDOWN_CALLS)
+ if release_at is None or teardown_at is None:
+ continue
+ assert teardown_at < release_at, (
+ f"{func_name}: _release_admission() runs before the upstream closes; on a "
+ f"disconnect that hands the slot back while llama-server is still decoding:\n"
+ + "\n".join(ast.unparse(stmt) for stmt in block)
+ )
+
+ # and every close must sit under a try whose finally releases, so a stalled close cannot
+ # drop the lease. By ancestry, not direct membership: the nesting that stops a cancel in
+ # _aclose_send_task's wait from skipping the later closes puts the first teardown one
+ # level up, which membership would reject even though it is strictly safer.
+ parents = {}
+ for parent in ast.walk(tree):
+ for child in ast.iter_child_nodes(parent):
+ parents[child] = parent
+
+ def _finally_releases(stmts):
+ """A release anywhere under the finally counts, including nested in another try."""
+ for stmt in stmts:
+ for node in ast.walk(stmt):
+ if isinstance(node, ast.Expr) and _called_name(node) == "_release_admission":
+ return True
+ return False
+
+ def _protected(node):
+ seen = node
+ current = parents.get(node)
+ while current is not None:
+ if (
+ isinstance(current, ast.Try)
+ and _finally_releases(current.finalbody)
+ # a teardown sitting *in* the releasing finally is not protected by it
+ and not any(seen is stmt for stmt in current.finalbody)
+ ):
+ return True
+ seen = current
+ current = parents.get(current)
+ return False
+
+ teardowns = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.Expr) and _called_name(node) in _TEARDOWN_CALLS
+ ]
+ assert teardowns, f"{func_name}: found no teardown await to check"
+ for node in teardowns:
+ assert _protected(node), (
+ f"{func_name}: teardown await is not inside a try that releases "
+ f"admission in its finally:\n{ast.unparse(node)}"
+ )
+
+
+def test_release_admission_exits_the_tracker_even_if_the_lease_release_raises():
+ """Both are process-wide; one failing must not strand the other."""
+ exited = []
+
+ class _Lease:
+ def release(self):
+ raise RuntimeError("queue gone")
+
+ class _Tracker:
+ def __exit__(self, *exc):
+ exited.append(exc)
+ return False
+
+ with pytest.raises(RuntimeError):
+ inference_route._release_admission(_Lease(), _Tracker())
+
+ assert exited == [(None, None, None)], "tracker must still exit"