ThreadsafeProxy can still raise `RuntimeError: Event loop is closed` — remaining check-then-use race after #727/#739

オープン
#740 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

@zigpy-review-bot がすでに取り組んでいます。

2026年7月29日 から。

  • #741 @zigpy-review-bot による — オープン

評価

難易度
3/5
見積もり時間
1〜2日
初心者へのやさしさ
35/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
停滞
技術スタック
python
領域
backend

調査の方向性

Read bellows/thread.py around ThreadsafeProxy.func_wrapper, then inspect the related shutdown fixes in #727 and #739. Add coverage for the coroutine and callback dispatch paths when the loop closes between the check and dispatch, including verifying the coroutine is closed on failure. Done when both paths return None with the existing warning and the tests pass.

索引モデルが issue の本文から書いたものです。

説明

Follow-up to #727 and #739. Those two fixed the read side (force_stop, #727) and the write side (_thread_main, #739) of the RuntimeError: Event loop is closed shutdown race in EventLoopThread. One member of the family remains, in ThreadsafeProxy — and it is structurally out of reach of #739's fix.

The race

ThreadsafeProxy.func_wrapper does a check-then-use on the loop it dispatches to (https://github.com/zigpy/bellows/blob/553ec35059c5062cb3e82e9879cbaf9eb0a373ab/bellows/thread.py#L102-L121):

if loop.is_closed():
    # Disconnected
    LOGGER.warning("Attempted to use a closed event loop")
    return
if asyncio.iscoroutinefunction(func):
    future = asyncio.run_coroutine_threadsafe(call(), loop)
    return asyncio.wrap_future(future, loop=curr_loop)
else:
    ...
    loop.call_soon_threadsafe(check_result_wrapper)

The worker thread can close the loop between the is_closed() check and the dispatch, and both asyncio.run_coroutine_threadsafe() and loop.call_soon_threadsafe() raise RuntimeError: Event loop is closed on a closed loop — the exact exception #727 suppressed in force_stop (which even documents the pattern: "The worker thread may close the loop after our is_closed() check").

#739 can't help here: it guarantees EventLoopThread.loop (the attribute) is never a closed loop, but the proxy captures the loop object at construction (https://github.com/zigpy/bellows/blob/553ec35059c5062cb3e82e9879cbaf9eb0a373ab/bellows/uart.py#L132 and https://github.com/zigpy/bellows/blob/553ec35059c5062cb3e82e9879cbaf9eb0a373ab/bellows/uart.py#L138), so publishing None before closing never reaches the proxy — its snapshot just becomes a closed loop.

When it fires

The threaded path is the production default (use_thread=True; zha wires it through CONF_USE_THREAD). When the connection dies, connection_done's callback runs thread.force_stop(), which cancels tasks, stops the worker loop, and lets the worker thread close it. Any call still going through a ThreadsafeProxy at that moment — e.g. application teardown invoking close() on the gateway/EZSP proxies while the radio just disconnected — can pass the is_closed() check and then hit the closed loop. Same flake family as the #727 traceback, different entry point.

Suggested fix

Treat close-during-dispatch identically to already-closed: catch RuntimeError around the dispatch, log the existing "Attempted to use a closed event loop" warning, and return None (which is what the is_closed() branch already returns). One subtlety: a naive contextlib.suppress around the coroutine branch would leave call()'s coroutine created-but-never-awaited (→ RuntimeWarning: coroutine ... was never awaited), so the coroutine needs an explicit .close() on the failure path, e.g.:

if asyncio.iscoroutinefunction(func):
    coro = call()
    try:
        future = asyncio.run_coroutine_threadsafe(coro, loop)
    except RuntimeError:
        coro.close()
        LOGGER.warning("Attempted to use a closed event loop")
        return
    return asyncio.wrap_future(future, loop=curr_loop)

(and the plain try/except RuntimeError equivalent around the call_soon_threadsafe() branch.)

Related cleanup for whoever picks this up

EventLoopThread.run_coroutine_threadsafe (https://github.com/zigpy/bellows/blob/553ec35059c5062cb3e82e9879cbaf9eb0a373ab/bellows/thread.py#L17-L20) passes self.loop straight through, and after #739 the shutdown-window failure mode there is AttributeError: 'NoneType' object has no attribute 'call_soon_threadsafe' (when self.loop is already None) rather than the old RuntimeError — verified on 3.14. The sole caller (uart.connect) wraps it in except Exception, so nothing misbehaves today, but an explicit if self.loop is None: raise RuntimeError("Event loop is not running") guard would keep that error legible.

主要言語
Python
スター
221
フォーク
104
平均マージ
5日 15時間
マージ済み PR(30日)
4

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

zigpy/bellows のほかの issue

zigpy/bellows の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。