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: stop holding a passthrough response 5 s when a watcher swallows its cancel (#11859)

oobabooga2806e93c3b7c
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index f9d0b4d4c48..a052fe93a6f 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1771,6 +1771,7 @@ _OPENAI_LLAMA_ADMISSION_POLL_S = 0.25
# 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
+_TEARDOWN_TASK_RECANCEL_S = 0.01
# 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).
@@ -5003,11 +5004,19 @@ async def _await_cancel_or_disconnect_then_close_client(
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)
+ # Request.is_disconnected() can swallow cancel() (#7617). Retry so successful
+ # passthroughs don't wait out the teardown timeout before their first byte (#11809).
+ # Keep the wait bounded in case the watcher never exits.
+ deadline = time.monotonic() + timeout_s
+ done = set()
+ while not done:
+ watcher.cancel()
+ remaining_s = deadline - time.monotonic()
+ if remaining_s <= 0:
+ break
+ done, _pending = await asyncio.wait(
+ {watcher}, timeout = min(remaining_s, _TEARDOWN_TASK_RECANCEL_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".
diff --git a/studio/backend/tests/test_disconnect_watcher_teardown.py b/studio/backend/tests/test_disconnect_watcher_teardown.py
index 63cd9e8cb50..eefeee3d161 100644
--- a/studio/backend/tests/test_disconnect_watcher_teardown.py
+++ b/studio/backend/tests/test_disconnect_watcher_teardown.py
@@ -225,6 +225,72 @@ def test_real_disconnect_watcher_can_survive_cancel_inside_is_disconnected():
pytest.skip("is_disconnected() delivered cancel() at every tick on this runtime")
+ "make_watcher",
+ [
+ lambda request: inference_route._wait_preheader_cancel(None, request),
+ lambda request: inference_route._await_cancel_or_disconnect_then_close_client(
+ cancel_event = threading.Event(), request = request, client = _Closeable()
+ ),
+ ],
+ ids = ["preheader_send", "non_streaming_post"],
+)
+def test_bounded_stop_ends_a_watcher_whose_first_cancel_was_swallowed(make_watcher):
+ """Real Starlette watchers must stop promptly even after swallowing cancel() (#11809)."""
+
+ async def _stop_at(offset, stop):
+ 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():
+ # Parks like uvicorn's receive() until the request ends.
+ parked.put_nowait(None)
+ await release.wait()
+ return {"type": "http.disconnect"}
+
+ watcher = asyncio.create_task(make_watcher(Request(scope, receive)))
+ try:
+ await parked.get()
+ for _ in range(offset):
+ await asyncio.sleep(0)
+ loop = asyncio.get_running_loop()
+ started = loop.time()
+ await stop(watcher)
+ return watcher.done(), loop.time() - started
+ finally:
+ await _release(release, [watcher])
+
+ async def _single_cancel(watcher):
+ watcher.cancel()
+ await asyncio.wait({watcher}, timeout = 0.5)
+
+ async def _real_stop(watcher):
+ await inference_route._stop_local_disconnect_cancel_watcher(watcher, timeout_s = 2.0)
+
+ async def _run():
+ swallowed = 0
+ for offset in range(8):
+ ended, _elapsed = await _stop_at(offset, _single_cancel)
+ if ended:
+ continue
+ swallowed += 1
+ ended, elapsed = await _stop_at(offset, _real_stop)
+ assert ended, "the bounded stop left a watcher running after a swallowed cancel"
+ assert elapsed < 0.5, f"stopping the watcher took {elapsed:.3f}s"
+ return swallowed
+
+ if not asyncio.run(_run()):
+ 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):