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

Aperta
#740 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

@zigpy-review-bot ci sta già lavorando.

Dal 29/7/2026.

  • #741 di @zigpy-review-bot — aperta

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
35/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Ferma
Stack tecnologico
python
Ambito
backend

Direzione di ricerca

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.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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.

Lingua principale
Python
Stelle
221
Fork
104
Merge medio
5g 15h
PR unite (30g)
4

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di zigpy/bellows

Tutte le issue di zigpy/bellows

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.