Flaky CI: teardown of `test_gateway_startup_failure` fails on a lingering `asyncio_0` executor thread (Python 3.14)

Aperta
#900 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
22/100
Tipo di issue
Bug
Chiarezza
Da chiarire
Stato di attività
Attiva
Stack tecnologico
python
Ambito
testing

Direzione di ricerca

Start with verify_cleanup in tests/conftest.py (around lines 176 and 209-213), which runs shutdown_default_executor() before the thread-name assertion, and with test_gateway_startup_failure in tests/test_gateway.py (around line 171), which spawns the asyncio_0 worker via Gateway.async_from_config. The issue has no agreed fix, so first work out the race window or confirm a mitigation. Done means a reproduction or a reasoned fix, with the flaky teardown no longer failing.

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

Descrizione

code quality

Seen on the Run tests Python 3.14 job of https://github.com/zigpy/zha/actions/runs/32916926775/job/98022510877 (a CI run on #788). All 1383 tests passed; the job failed only in teardown, and a re-run of the same commit went green — so this is non-deterministic, not a regression from that PR.

==================================== ERRORS ====================================
______________ ERROR at teardown of test_gateway_startup_failure _______________
[gw2] linux -- Python 3.14.7 /home/runner/work/zha/zha/.venv/bin/python

event_loop = <Looptime_UnixSelectorEventLoop running=False closed=True debug=False>
expected_lingering_tasks = False, expected_lingering_timers = False
...
>           assert isinstance(thread, threading._DummyThread) or thread.name.startswith(
                "waitpid-"
            )
E           AssertionError: assert (False or False)
E            +  where False = isinstance(<Thread(asyncio_0, started 140462833911488)>, <class 'threading._DummyThread'>)
E            +      where 'asyncio_0' = <Thread(asyncio_0, started 140462833911488)>.name

The failing assertion is the "no threads left behind" check at the end of verify_cleanup (tests/conftest.py:209-213).

Where the thread comes from

asyncio_0 is a worker of the loop's default executor — CPython builds it as ThreadPoolExecutor(thread_name_prefix='asyncio'), so loop.run_in_executor(None, ...) is the only thing that can produce that name.

zha has exactly one such call: ZHAAsyncHelper.async_add_executor_job() (zha/async_.py:364), whose only production call site is Gateway.async_from_config() loading quirks (zha/application/gateway.py:236). test_gateway_startup_failure calls Gateway.async_from_config(zha_data) in the test body (tests/test_gateway.py:171) — i.e. after verify_cleanup captured threads_before — so the worker is genuinely a new thread for this test and correctly shows up in the set difference.

What should have cleaned it up

verify_cleanup calls event_loop.run_until_complete(event_loop.shutdown_default_executor()) (tests/conftest.py:176) before the thread check, and BaseEventLoop.shutdown_default_executor() ends in executor.shutdown(wait=True) followed by thread.join(). On a normal run the worker is therefore joined and gone by the time the assertion runs; this failure means that on this run it wasn't (or wasn't yet).

What I could not pin down

The exact window. It did not reproduce, and one observation is not enough to bisect. Two leads, both unverified:

  • shutdown_default_executor() returns immediately when self._default_executor is None, so if the loop the fixture resolves is ever not the loop the test actually ran on, nothing joins the worker and the assertion fires. Ruled out. Probing dev directly (a sync autouse fixture of the same shape recording id(event_loop) at setup and teardown against id(asyncio.get_running_loop()) in the test body) gives the same loop object in all three phases, for a default looptime test, a @pytest.mark.looptime(False) test, and a test using the real zha_gateway fixture. So the injected event_loop is the loop the test ran on, and the teardown's run_until_complete(shutdown_default_executor()) runs on it. (HA Core's fixture is a @pytest_asyncio.fixture specifically to avoid such a mismatch — "Use @pytest_asyncio.fixture to make sure the correct event loop is set regardless before calling the fixture" — but ours does not appear to suffer from it.)
  • The await future inside shutdown_default_executor() runs on a Looptime_UnixSelectorEventLoop (every test outside test_async_.py gets the looptime marker via pytest_collection_modifyitems), so a fake-clock interaction is worth ruling out.

What #695 does and does not change

#695 rewrites verify_cleanup as an async @pytest_asyncio.fixture that takes the loop from asyncio.get_running_loop() and awaits shutdown_default_executor() instead of driving it with run_until_complete().

That is worth knowing here, but it should not be assumed to fix this flake. It changes how the cleanup is driven — pytest-asyncio's runner task rather than a sync fixture — while running the same executor-shutdown call on the same per-test loop, before the same thread check. Since the loop-mismatch lead above is ruled out, there is no known mechanism by which it makes the race more or less likely. Treat it as unrelated until an occurrence says otherwise.

An earlier revision of this issue claimed #695 removed the loop-mismatch lead "by construction"; that was wrong and is corrected above.

If it recurs before that lands

Cheapest mitigations, in order: make verify_cleanup a @pytest_asyncio.fixture like HA Core's (= what #695 does), or give the thread check a short bounded join/retry for asyncio_* workers instead of asserting on the first snapshot.

Filed for the record — currently a single observation, no other occurrence found in the tracker. All file and line references re-verified against dev at c556ae20 (2026-09-20); they are unchanged since the run above.

Lingua principale
Python
Stelle
96
Fork
84
Merge medio
2g 4h
PR unite (30g)
30

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/zha

Tutte le issue di zigpy/zha

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.