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

Open
#900 2 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
22/100
Issue type
Bug
Clarity
Needs clarification
Activity status
Active
Tech stack
python
Domain
testing

Research direction

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.

Written by the indexing model from the issue text.

Description

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.

Dominant language
Python
Stars
96
Forks
84
Avg merge
2d 4h
Merged PRs (30d)
30

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from zigpy/zha

All issues in zigpy/zha

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.