#2213·gevent

在 CPython ≥ 3.13.12 / 3.14.3 上,在 monkey.patch_all() 方法下,asyncio `run_in_executor` / `to_thread` 结果不会在下一个定时器到来之前交付。

作者: jordangarside创建于 2026年9月22日更新于 2026年9月22日

Description

With monkey.patch_all(), loop.run_in_executor(None, ...), asyncio.to_thread(...) and anything that calls them (for example loop.getaddrinfo(), so any loop.create_connection(hostname, ...)) can stall. The executor job finishes, but the awaiting coroutine doesn't resume until an unrelated timer wakes the event loop. With asyncio.wait_for, the call only completes (or gets cancelled) when the timeout fires.
This started with CPython 3.13.12 and 3.14.3. It does not happen on 3.13.11, 3.14.2 or 3.12.x.

Cause

https://GitHub.com/Python/cpython/pull/141696 was backported to 3.13 https://GitHub.com/Python/cpython/pull/142359 and 3.14 https://GitHub.com/Python/cpython/pull/142358. It changed asyncio.futures._chain_future._call_set_state:

python
# before (3.12, 3.13.11, 3.14.2)  
if dest_loop is None or dest_loop is source_loop:  
    _set_state(destination, source)  
else:  
    dest_loop.call_soon_threadsafe(_set_state, destination, source)  
# after (3.13.12+, 3.14.3+)  
if dest_loop is None or dest_loop is events._get_running_loop():  
    _set_state(destination, source)  
else:  
    dest_loop.call_soon_threadsafe(_set_state, destination, source)  

When threading is patched, the default ThreadPoolExecutor workers are greenlets on the same OS thread as the running asyncio loop. events._get_running_loop() is tracked per OS thread, so from inside the worker greenlet it returns the loop. set_state then runs directly: set_result → loop.call_soon, with no self-pipe write. The loop is parked in GeventSelector.select(timeout) and nothing wakes it until the timeout expires.
Before the change, the executor path always went through call_soon_threadsafe, which writes to the self-pipe and wakes the selector.

Minimal reproducer

python
from gevent import monkey  
monkey.patch_all()  
  
import asyncio, sys, time  
  
def work():  
    time.sleep(0.2)  # any cooperative block (DNS via gevent's resolver, socket I/O, ...)  
    return "done"  
  
async def main():  
    loop = asyncio.get_running_loop()  
    t = time.monotonic()  
    await asyncio.wait_for(loop.run_in_executor(None, work), 5)  
    print(sys.version.split()[0], f"result delivered after {time.monotonic() - t:.3f}s")  
  
asyncio.run(main())  
Python gevent Result
3.12.1 25.9.1 0.202s
3.13.15 25.9.1 5.002s (delivered only when wait_for's timer fires)
3.13.15 26.9.0 (greenlet 3.5.6) 5.001s
3.13.15 with the old _chain_future logic monkeypatched back 25.9.1 0.202s

Real-world impact

Possible directions

  • When threading…