Skip to content

Fix "Event loop is closed" race in EventLoopThread.force_stop#727

Open
nmingam wants to merge 2 commits into
zigpy:devfrom
nmingam:fix-force-stop-loop-closed
Open

Fix "Event loop is closed" race in EventLoopThread.force_stop#727
nmingam wants to merge 2 commits into
zigpy:devfrom
nmingam:fix-force-stop-loop-closed

Conversation

@nmingam

@nmingam nmingam commented Jul 2, 2026

Copy link
Copy Markdown

Independent of any feature work and pre-exists on dev; surfaced while stabilizing CI.

tests/test_thread.py::test_thread_already_stopped intermittently errors at teardown with
RuntimeError: Event loop is closed (observed on the 3.11/3.13 CI legs; passes on 3.12/3.14 and locally).

Root cause: the worker thread's _thread_main finally runs self.loop.close() and then self.loop = None
as two separate statements. force_stop's if self.loop is None guard can therefore pass while the loop is
already closed, and the following call_soon_threadsafe raises.

Fix: snapshot self.loop into a local, also guard on loop.is_closed(), and swallow the RuntimeError
if the worker closes the loop after the check. The is_closed() guard is exercised by the existing
test_thread_already_stopped; the race-only except is marked # pragma: no cover.

The worker thread can close the loop between the None check and
call_soon_threadsafe. Snapshot the loop, also guard on is_closed(),
and swallow the RuntimeError if it is closed after the check.
@codecov

codecov Bot commented Jul 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.54%. Comparing base (cd3378f) to head (19e86f5).

Additional details and impacted files
@@           Coverage Diff           @@
##              dev     #727   +/-   ##
=======================================
  Coverage   99.54%   99.54%           
=======================================
  Files          61       61           
  Lines        4181     4183    +2     
=======================================
+ Hits         4162     4164    +2     
  Misses         19       19           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

The pre-commit ruff hook rejects the try/except-pass form (SIM105).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant