Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

Stop using the EZSP gateway once its transport has closed - #751

Open
zigpy-review-bot wants to merge 8 commits into
devfrom
zigpy-bot/ezsp-transport-lost-teardown
Open

zigpy-review-bot wants to merge 8 commits into
devfrom
zigpy-bot/ezsp-transport-lost-teardown

Conversation

@zigpy-review-bot

@zigpy-review-bot zigpy-review-bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator

Complements #741 (which makes ThreadsafeProxy survive a closed or stopping worker loop) from the other side: EZSP stops talking to a gateway whose transport is gone in the first place. Fixes the TypeError: 'NoneType' object can't be awaited teardown cascade tracked in #722 at its most common entry point, and the startup_reset() retry loop that made it routine on network coordinators.

What happens today

Field logs from an EZSP coordinator behind an ESPHome TCP bridge (Home Assistant 2026.9.x, bellows 1.0.1), where the bridge drops the connection right after ZHA connects:

WARNING (bellows.thread_0) [py.warnings] .../asyncio/base_events.py:744: RuntimeWarning: coroutine 'Gateway.wait_for_startup_reset' was never awaited
ERROR (MainThread) [concurrent.futures] exception calling callback for <Future ... state=cancelled>
RuntimeError: Event loop is closed
WARNING (MainThread) [bellows.thread] Attempted to use a closed event loop   (x5)
WARNING (MainThread) [zigpy.application] Failed to disconnect from radio
Traceback (most recent call last):
  File ".../bellows/ezsp/__init__.py", line 149, in startup_reset
    await self._startup_reset()
  File ".../bellows/ezsp/__init__.py", line 131, in _startup_reset
    await self._gw.wait_for_startup_reset()
TypeError: 'NoneType' object can't be awaited
During handling of the above exception, another exception occurred:
  ...
  File ".../bellows/ezsp/__init__.py", line 231, in disconnect
    await self._gw.disconnect()
TypeError: 'NoneType' object can't be awaited

The first startup_reset() attempt fails correctly, with the transport's ConnectionResetError (set on the startup-reset future by Gateway.connection_lost()). But connection_lost() also resolved the "connection done" future, whose callback force-stops and closes the worker loop, and attempts 2 and 3 then run against that dead gateway: a 2 s wait for a startup reset that is never dispatched (NETWORK_COORDINATOR_STARTUP_RESET_WAIT), TypeError from reset() and wait_for_startup_reset(), then disconnect() itself raising TypeError, which masks the real error all the way up through ControllerApplication.connect() and zigpy's shutdown(). HA retries after its backoff, so each incident costs a retry cycle; in roughly one run in twelve the teardown cancels the startup task instead and a bare CancelledError escapes connect(), which HA treats as a permanent setup error rather than something to retry. The same signature was reported on #730 (SONOFF Dongle Max over TCP, bellows 1.0.0).

Reproduced deterministically with a local TCP server that accepts and then closes the connection while EZSP.connect(use_thread=True) waits for the startup reset. On dev: the cascade above (13/14 runs) or CancelledError plus a disconnect() that never returns (1/14). With #741 alone the crash is gone but connecting still takes 20 s to fail, because attempts 2 and 3 each wait out the 10 s EZSP command timeout on a version command that was never sent.

What changes

EZSP records that its transport closed when Gateway.connection_lost() reports it (via the api proxy; the NCP failed-state route through enter_failed_state() keeps the transport open and is deliberately not included, so a reset can still recover the NCP and disconnect() still closes the port). With that:

  • startup_reset() stops retrying and raises the transport's error; the flag is also checked before every attempt, and a CancelledError caused by the worker teardown (flag set, the caller's own task not cancelling) is reported as ConnectionResetError so setup fails instead of looking cancelled. Both except clauses yield once before deciding, because the notification is queued onto this loop from the worker thread and a synchronously failing proxy call can otherwise reach the except clause first. The flag is read before the final disconnect(), since closing a healthy transport ourselves reports it closed too: an NCP that never answers still fails with its own TimeoutError after the three attempts, as before.
  • disconnect() no longer calls into the gateway once the transport closed (its SerialProtocol.disconnect() is a no-op at that point: the transport is already None and the disconnected event set) and always drops the reference.
  • _command() fails immediately with EzspError("Connection was lost") for commands issued after the loss, instead of sending into a dead loop and waiting out EZSP_CMD_TIMEOUT. Commands already in flight still time out as before.
  • ControllerApplication.connect() and disconnect() drop _ezsp even if disconnecting fails, and connect() logs a failing follow-up disconnect instead of letting it replace the connection error.

With this on top of dev the reproduction fails in under 10 ms with a ConnectionResetError (15/15 runs, including the ones that used to be CancelledError): usually the transport's own Remote server closed connection, or Connection was lost during startup when the loss lands before an attempt starts or cancels it. No closed-loop warnings, and a clean disconnect.

Fixing the retries exposed a second, older problem in uart.connect(): the callback that stops the worker thread was attached to the connection-done future only after _connect() had returned to the calling thread. When the connection was already lost by then, the future was done and add_done_callback() queued the callback onto the worker loop with a plain call_soon() from the wrong thread, which does not wake a loop blocked in select(). The startup retries' own dispatches used to wake it by accident; without them the thread leaked (a process hang at interpreter exit, joining a bellows.thread_ still in run_forever()). The callback is now attached inside _connect(), on the worker loop. As a consequence a worker teardown during connect() would cancel _connect() itself, so connect() reports a CancelledError that is not its caller's as ConnectionResetError, and a caller cancelling connect() now also stops the worker thread, which except Exception never covered.

One note for whichever of this and #741 merges second: both add the same _connect(config, api, thread=None) parameter (a trivial textual conflict in connect()), and #741's resolve-to-None proxy semantics mean that in the microsecond window where the transport closes between the flag check and the first dispatch, wait_for_startup_reset() returning None reads as "reset received" and the following version command waits out EZSP_CMD_TIMEOUT before the flag ends the attempt. Still a clean ConnectionResetError, just 10 s late in that one window.

Tests

Eighteen new tests in tests/test_ezsp.py, tests/test_application.py and tests/test_uart.py, including an end-to-end one that runs EZSP.connect(use_thread=True) against a real local TCP server and drops the connection while it waits for the startup reset. Most of them fail on dev; the rest pin behaviour that must not change (an NCP failed state still closes the transport, a caller's cancellation still wins, a startup timeout keeps its TimeoutError). The uart leak test fails on the old code by finding the worker thread still alive, and stops it itself so a regression cannot hang the test run. Full suite with dev merged in: 817 passed, repeated runs.

When the serial/TCP transport closes, `Gateway.connection_lost()` resolves
the "connection done" future, which stops the gateway's worker thread and
closes its event loop. Anything the application still routes through the
`ThreadsafeProxy` after that point lands on a dead loop: a bare `None` that
is then awaited (`TypeError: 'NoneType' object can't be awaited`), a
dispatch that never runs, or a `CancelledError` from the teardown
cancelling the dispatched task.

`EZSP.startup_reset()` made this common on network coordinators: a
connection dropped while waiting for the startup reset frame raised the
transport error on the first attempt, and the two retries then went to the
torn-down gateway -- a two-second hang, `TypeError`s from `reset()` and
`wait_for_startup_reset()`, and finally `disconnect()` itself failing the
same way, masking the real error all the way up through
`ControllerApplication.connect()` and `shutdown()`.

`EZSP` now records that its transport closed (`Gateway.connection_lost()`
only -- an NCP failed state keeps the transport open and is still reset
and closed normally) and:

- `startup_reset()` stops retrying and raises the transport's error;
  a `CancelledError` caused by the worker teardown (not by the caller) is
  reported as a `ConnectionResetError` so setup fails instead of looking
  cancelled
- `disconnect()` no longer calls into the gateway, which has nothing left
  to close, and always drops the reference
- `_command()` fails immediately instead of waiting out the command
  timeout

`ControllerApplication.connect()` and `disconnect()` drop the `EZSP`
reference even if disconnecting fails.
Two windows around the startup retry loop, from review:

- The transport-closed notification from a threaded gateway is queued onto
  this loop with `call_soon_threadsafe()`. A proxy call that fails
  synchronously (the check-then-dispatch window of `ThreadsafeProxy`) can
  reach `startup_reset()`'s `except` clause before that notification is
  delivered, so the retry guard would not see it. Yield once before deciding.
- If the transport closes between `uart.connect()` returning and the first
  attempt, or `startup_reset()` is entered with the flag already set, the
  attempt itself would dispatch into the dead gateway. Check the flag at the
  top of every attempt.

`ControllerApplication.connect()` now logs a failing follow-up disconnect
instead of letting it replace the connection error, which is the masking
this series is about. The end-to-end test synchronises on the server side
accepting the client and cancels the connect task on failure.
The two "request fails due to a connectivity issue" steps created the send
task and slept `15 * t_rx_ack` (a few milliseconds at the test's scaled-down
timeouts) before unpausing the transport, expecting all `ACK_TIMEOUTS`
retries to have expired inside that window. Any scheduling hiccup of a few
milliseconds -- a garbage collection pass triggered by an earlier test is
enough -- leaves a retry pending, the unpaused transport delivers it, and
the test fails with `DID NOT RAISE TimeoutError`. Seen deterministically
when `tests/test_application.py` gained a test that leaves a reference
cycle behind.

A paused `FakeTransport` drops writes rather than buffering them, so the
failure can simply be awaited inside the paused block.
When the transport closed but the failure that surfaced is incidental to
it (a proxy `TypeError`/`RuntimeError` from the closing worker loop), raise
`ConnectionResetError` chained from it instead of the incidental error, so
every window reports the same thing to the caller.

Add the test for the `except CancelledError` branch's yield -- the
notification queued but not yet delivered when the cancellation arrives --
which was not pinned, and disconnect in the end-to-end test's cleanup so a
failing run doesn't leave the worker thread to the garbage collector.
`uart.connect()` attached the callback that stops the worker thread to the
connection-done future only after `_connect()` had returned to the calling
thread. If the connection was lost before that -- the bridge closing the
socket right after accepting it -- the future was already resolved, and
`add_done_callback()` queued the callback onto the worker loop with a plain
`call_soon()` from the wrong thread, which does not wake the loop. Nothing
in the worker's own queue would ever run it, so the thread stayed asleep in
`select()` until something else was dispatched to it.

Until now the startup retries always were that something. With `EZSP` no
longer dispatching to a gateway whose transport closed, the worker thread
leaked: seen as a hang at interpreter exit joining a `bellows.thread_`
thread still in `run_forever()`.

Attach the callback inside `_connect()`, on the loop that resolves the
future, before the connection can be lost.
With the worker-stop callback attached before `_connect()` returns, a
transport lost while `_connect()` is still running would have the worker
cancel `_connect()` itself, and the resulting `CancelledError` would cross
`run_coroutine_threadsafe()` past `connect()`'s `except Exception` and reach
the application looking like a caller cancellation. Not reachable with
asyncio's `create_connection()` (its waiter resolves after
`connection_made()`, so `wait_until_connected()` never suspends), but cheap
to rule out: a `CancelledError` that is not our caller's is raised as
`ConnectionResetError`.

A caller cancelling `connect()` now also stops the worker thread, which
`except Exception` never covered.

The leak regression test stops a leaked worker itself before asserting, so
a regression fails the test instead of hanging the interpreter at exit.
@codecov

codecov Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.60%. Comparing base (231d385) to head (a1b3d7c).

Additional details and impacted files
@@           Coverage Diff           @@
##              dev     #751   +/-   ##
=======================================
  Coverage   99.59%   99.60%           
=======================================
  Files          64       64           
  Lines        4484     4520   +36     
=======================================
+ Hits         4466     4502   +36     
  Misses         18       18           

☔ 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.

@realKim-dotcom

Copy link
Copy Markdown

Reproduced your accept-then-close scenario locally against dev (8f9d87b) and this branch, EZSP.connect(use_thread=True) through ControllerApplication.startup(), Python 3.12, 12 runs each:

  • dev: 9/12 the same cascade as my 2026-09-05 log — RuntimeWarning: coroutine 'Gateway.wait_for_startup_reset' was never awaited, then exactly 2.01 s later five Attempted to use a closed event loop warnings and the TypeError chain through startup_reset → disconnect → ControllerApplication.connect → shutdown. The other 3/12 ended in a bare CancelledError within 10 ms — which Home Assistant's config_entries.py treats as "not a real cancellation" and files as a permanent setup_error, not a retry.
  • Stop using the EZSP gateway once its transport has closed #751: 12/12 TransientConnectionError in under 10 ms, no closed-loop warnings, no never awaited, clean disconnect. Your 14 new tests fail on dev and the full suite (460) passes on the branch.

So the signature match holds: the five closed-loop warnings are attempt 2's reset(), attempt 3's wait_for_startup_reset(), and the three disconnect() calls, and the 2 s gap is NETWORK_COORDINATOR_STARTUP_RESET_WAIT. On the production side, use_thread: false (since 2026-09-06) has had the same practical effect — details on #730.

I'm not going to run the branch on the live gateway for now: use_thread: false has kept the site stable for eleven days, so I'll stay on that until this ships in a release, and report back then.

(Reproduction and log triage done with Claude Code, as before; the field numbers are real.)

Conflicts, each resolved by keeping both sides:

- bellows/ezsp/__init__.py: dev (#774) replaced the per-attempt
  `self._protocol = v4.EZSPv4(...)` in `startup_reset()` with
  `self._switch_protocol_version(v4.EZSPv4.VERSION)`; this branch added the
  transport-closed check before that line. Kept the check, followed by dev's
  version reset.
- bellows/uart.py: dev (#766) added `path = config[...]` and the ESPHome
  `suppress_acks` argument to `AshProtocol`; this branch attaches the
  worker-stop callback in `_connect()`. Kept dev's setup with the callback
  attached right after `path`.
- tests/test_ezsp.py, tests/test_uart.py: both sides appended new tests at the
  same place (dev: #774's protocol-version retry test, #766's ESPHome ACK
  tests). Kept all of them.

tests/test_ash.py merged without conflict and is now identical to dev: #760
made the same `test_ash_end_to_end` change as this branch's f6bb448.
After the last startup attempt fails, `startup_reset()` disconnects and then
checks `_transport_closed` to decide whether the failure was caused by a lost
connection. But closing a healthy transport ourselves also reports it closed
(`Gateway.connection_lost()` -> `EZSP.connection_lost()`), so the flag was
always set by then: an NCP that simply never answered failed with
`ConnectionResetError("Connection was lost during startup")` instead of its
`TimeoutError`, in both the threaded and the in-loop mode.

Read the flag before disconnecting.

@zigpy-review-bot zigpy-review-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of my own PR (so a comment, not an approval): ready from my side after two pushes in this run. One merge of dev and one fix for a defect the review found; nothing else needs a change.

Pushed

  • 74f690d merges dev (the PR conflicted with it). Five conflicted hunks in four files, all from both sides changing or appending at the same spot, resolved by keeping both: the transport-closed check in startup_reset() now runs before the per-attempt _switch_protocol_version(v4) from #774; _connect() attaches the worker-stop callback right after the path lookup that #766 added, with that PR's ESPHome suppress_acks setup unchanged; and the new tests of both sides in tests/test_ezsp.py and tests/test_uart.py are all kept. tests/test_ash.py merged cleanly and is now identical to dev: #760 already made this PR's test_ash_end_to_end change, so that commit no longer changes anything.
  • a1b3d7c fixes a regression this PR introduced. After the last startup attempt failed, startup_reset() disconnected first and only then checked _transport_closed. Closing a healthy transport ourselves reports it closed too, so an NCP that simply never answered failed with ConnectionResetError("Connection was lost during startup") instead of its TimeoutError, in both the threaded and the in-loop mode. The flag is now read before disconnecting, and test_ezsp_connect_failure_keeps_error_when_disconnect_closes_transport pins it.

The PR body now describes the merged code: the new timeout behaviour, eighteen tests, the suite count after the merge, the test_ash_end_to_end paragraph removed, and full references.

Still open, by design

When disconnect() runs after the worker teardown has begun but while its connection_lost() notification is still queued on the main loop, it still calls into the gateway: it gets TypeError from the proxy's None once the worker loop has closed, or waits forever in the instant between the loop stopping and closing. Reaching either takes one synchronous step on the main loop that spans the whole worker teardown, and #741's resolve-to-None proxy covers both cases, so this PR leaves them alone.

Verified (6 checks)
  • Full suite on the merged tree: 817 passed (Python 3.14), five repeated runs of test_ezsp.py, test_uart.py, test_application.py and test_thread.py all green; pre-commit clean on the touched files.
  • The PR's 18 new tests against dev's library code: 14 fail and the other 4 pass. Those 4 pin behaviour that must not change (an NCP failed state, a caller's cancellation, a cancellation without a lost transport, a startup timeout).
  • End to end against a real local socket, both use_thread modes. A server that accepts and then drops the connection fails within a few milliseconds with a ConnectionResetError: the transport's own Remote server closed connection, or, in the threaded mode when the loss lands before an attempt starts, Connection was lost during startup. A server that accepts and never answers failed with ConnectionResetError('Connection was lost during startup') (from TimeoutError) before a1b3d7c and fails with TimeoutError after it, as on dev.
  • The new regression test fails on 74f690d and passes on a1b3d7c.
  • Merge resolution: git show --remerge-diff shows only the five conflicted hunks, each keeping both sides; the ordering of Gateway.connection_lost() (queues the main-loop notification before the worker teardown cancels anything) is unchanged by the merge.
  • Copilot (two models) read the merged diff: one finding was the timeout regression above, now fixed; the other the residual disconnect() window above, possible but narrow and covered by #741. A review round (a second Claude reviewer plus Copilot) then checked the fix and this text; it found no code defect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-watch: fix zigpy-review-bot follows this thread and also pushes fixes (review + fix) bugfix This PR fixes a bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants