Repository navigation
Description
🐛 Describe the bug
On Python 3.12+, SessionRuntime.aclose_worker() can get stuck in a loop in _shutdown_native that never yields to the event loop. The event-loop thread then spins at 100% CPU forever, and asyncio timeouts or cancellation (for example asyncio.wait_for(runtime.aclose_worker(), 5)) cannot fire. Python 3.11 is not affected; the llm_server CI job runs on 3.11, so CI does not catch it.
The loop at the end of SessionRuntime._shutdown_native (lines 908-912):
while self._native_tasks or self._operations:
await asyncio.gather(
*tuple(self._native_tasks | self._operations),
return_exceptions=True,
)Why it spins
Futures leave these sets only through done-callbacks:
_own_taskdiscards finished tasks from_native_tasks._operationregistersself._operations.discardon each admission'sreleasedfuture, which_release_admissioncompletes.
asyncio runs done-callbacks via loop.call_soon, so a future that just completed stays in its set until a later loop iteration.
Since CPython 3.12 (python/cpython#104138), asyncio.gather() handles children that are already done immediately. If all of them are done, it returns a future that is already finished, and awaiting a finished future does not yield to the event loop.
So suppose _shutdown_native checks the while condition when every tracked future is done but at least one discard callback is still queued. Every iteration then completes synchronously, the queued discard never runs, and the condition never changes. On 3.11, gather() always returns a pending future, so the await yields and the queued discards run first.
That state occurs when the last tracked operation completes in the same loop iteration that resumes _shutdown_native. Lifecycle operations queued on one named session make this deterministic. Once shutdown starts, each queued operation takes the session lock, fails and releases it, one loop iteration after the previous one.
Reproduction
The script uses the public SessionRuntime and MultiplexedWorkerClient APIs with a small stand-in worker process, and needs only the standard library:
- A generation holds session
"s". - Four lifecycle operations queue on
"s". aclose_worker()runs underasyncio.wait_for(..., timeout=5).
The watchdog thread reports where the event-loop thread is stuck, then exits after 10 s.
import asyncio
import os
import sys
import threading
from executorch.examples.llm_server.python.multiplexed_worker_client import (
MultiplexedWorkerClient,
)
from executorch.examples.llm_server.python.session_runtime import (
GenerationOptions,
PromptInput,
SessionRuntime,
)
# Stand-in worker process: streams one token per generation and never finishes it.
WORKER = """
import json, sys
for line in sys.stdin:
request = json.loads(line)
if request["op"] == "generate":
print(json.dumps({"request_id": request["request_id"], "token": "a"}), flush=True)
"""
def watchdog(proc, thread_id): # report where the event-loop thread is stuck, then exit
frame = sys._current_frames()[thread_id]
while frame is not None and frame.f_code.co_name != "_shutdown_native":
frame = frame.f_back
line = frame.f_lineno if frame is not None else "?"
print(f"after 10 s: still in _shutdown_native (session_runtime.py:{line}), "
f"worker exit code {proc.returncode}", flush=True)
os._exit(1)
async def main():
proc = await asyncio.create_subprocess_exec(
sys.executable, "-c", WORKER,
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,
)
runtime = SessionRuntime(MultiplexedWorkerClient(proc))
generation = runtime.generate_stream(
"s", PromptInput(text="hi"), GenerationOptions(max_new_tokens=8)
)
await generation.wait_ready() # the generation now holds session "s"
ops = (runtime.open, runtime.reset, runtime.close, runtime.open)
waiters = [asyncio.create_task(op("s")) for op in ops]
await asyncio.sleep(0.1) # all four are queued on session "s"
timer = threading.Timer(10, watchdog, (proc, threading.get_ident()))
timer.start()
await asyncio.wait_for(runtime.aclose_worker(), timeout=5)
timer.cancel()
await asyncio.gather(*waiters, return_exceptions=True)
print(f"aclose_worker() returned, worker exit code {proc.returncode}")
asyncio.run(main())Save it as repro_shutdown_spin.py in the directory that contains the executorch checkout, and run it from there:
$ time PYTHONPATH=. python3.13 repro_shutdown_spin.py
after 10 s: still in _shutdown_native (session_runtime.py:909), worker exit code -15
python3.13 repro_shutdown_spin.py 10.07s user 0.04s system 98% cpu 10.215 total
$ time PYTHONPATH=. python3.11 repro_shutdown_spin.py
aclose_worker() returned, worker exit code -15
python3.11 repro_shutdown_spin.py 0.05s user 0.02s system 39% cpu 0.189 total
3.12.15 and 3.14.7 behave like 3.13.15. The reported line is 908-910, depending on when the stack is sampled. The wait_for timeout never fires. The worker child has already been reaped (-15), so the spin is in the parent process.
Expected: aclose_worker() returns once the worker is reaped, as it does on 3.11, and the queued operations fail with WorkerError.
Whether it hangs depends on the queue depth. In this shape only 4 queued operations hang; 0-3, 5-8 and 12 return. The last waiter has to complete in exactly the iteration that resumes _shutdown_native, and the number of iterations depends on how many close() and Generation.aclose() take, so it can shift with unrelated changes.
The existing test test_native_shutdown_waits_for_all_queued_lifecycle_admissions builds the same shape with the in-process fake worker and passes with 12 queued operations. With 4 it hangs on 3.12+, and _run's asyncio.wait_for(..., timeout=10) does not stop it.
The asyncio behavior on its own:
import asyncio
import sys
import time
async def main():
ops = set()
fut = asyncio.get_running_loop().create_future()
ops.add(fut)
fut.add_done_callback(ops.discard)
fut.set_result(None) # ops.discard is now queued with call_soon, not run
deadline, n = time.monotonic() + 2, 0
while ops: # same shape as SessionRuntime._shutdown_native
await asyncio.gather(*tuple(ops), return_exceptions=True)
n += 1
if time.monotonic() > deadline:
return f"still looping after 2 s ({n} iterations); wait_for(..., 1) never fired"
return f"loop exited after {n} iteration(s)"
print("Python", sys.version.split()[0], "->", asyncio.run(asyncio.wait_for(main(), 1)))Python 3.11.17 -> loop exited after 1 iteration(s)
Python 3.12.15 -> still looping after 2 s (1756658 iterations); wait_for(..., 1) never fired
Python 3.13.15 -> still looping after 2 s (1640426 iterations); wait_for(..., 1) never fired
Python 3.14.7 -> still looping after 2 s (1519843 iterations); wait_for(..., 1) never fired
Suggested fix
Yield once after each gather(), so queued discard callbacks run before the condition is checked again:
--- a/examples/llm_server/python/session_runtime.py
+++ b/examples/llm_server/python/session_runtime.py
@@ -910,6 +910,9 @@ class SessionRuntime:
*tuple(self._native_tasks | self._operations),
return_exceptions=True,
)
+ # gather() of already-done futures does not yield on Python 3.12+,
+ # so let their queued discard callbacks run before re-checking.
+ await asyncio.sleep(0)
for result in results:
if isinstance(result, BaseException):
raise resultWith this change the repro returns in about 0.2 s on 3.11-3.14, and test_session_runtime.py and test_multiplexed_worker_client.py still pass. An alternative is to loop only while some tracked future is still pending.
A regression test, such as the existing test with 4 queued operations, has two caveats:
- It needs a signal-based timeout, such as pytest-timeout's signal method, because asyncio timeouts cannot fire while the loop spins.
- It only fails on 3.12+, and the llm_server CI job runs on 3.11 (default image, Python version).
Impact
This only affects shutdown. The loop runs after the worker has been reaped, so no work is lost, but the process has to be stopped from outside.
Under uvicorn, whose signal handlers only set exit flags, a second SIGINT and a SIGTERM were ignored; only SIGKILL stopped the process. This was tested with uvicorn 0.54.0 and a test app that queues the operations itself during lifespan shutdown. The same shapes also hang under uvloop 0.23.0.
The shipped servers (serve.py, serve_batching.py) call aclose_worker() at lifespan shutdown, but I did not reproduce the hang through them: uvicorn finishes in-flight requests before lifespan shutdown, and ServingChat serializes work per session. Direct SessionRuntime users with several operations queued on one session at shutdown are affected.
The loop and its bookkeeping came from 128e126 (#23284). It only spins on CPython 3.12+, because of the gather() change. Found while reviewing #24984.
Versions
- ExecuTorch: main at 56e1495
- Python: CPython 3.12.15, 3.13.15 and 3.14.7 hang; CPython 3.11.17 does not.
- OS: macOS (arm64). The code is pure-Python asyncio, so this is not platform specific.
This issue was written with AI assistance (Claude Code).
Activity
Fix LLM serving shutdown spin on Python 3.12+ (pytorch#25121)