Repository navigation
Stop using the EZSP gateway once its transport has closed - #751
zigpy-review-bot wants to merge 8 commits into
Conversation
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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
|
Reproduced your accept-then-close scenario locally against
So the signature match holds: the five closed-loop warnings are attempt 2's I'm not going to run the branch on the live gateway for now: (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
left a comment
There was a problem hiding this comment.
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 instartup_reset()now runs before the per-attempt_switch_protocol_version(v4)from #774;_connect()attaches the worker-stop callback right after thepathlookup that #766 added, with that PR's ESPHomesuppress_ackssetup unchanged; and the new tests of both sides intests/test_ezsp.pyandtests/test_uart.pyare all kept.tests/test_ash.pymerged cleanly and is now identical todev: #760 already made this PR'stest_ash_end_to_endchange, 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 withConnectionResetError("Connection was lost during startup")instead of itsTimeoutError, in both the threaded and the in-loop mode. The flag is now read before disconnecting, andtest_ezsp_connect_failure_keeps_error_when_disconnect_closes_transportpins 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.pyandtest_thread.pyall 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_threadmodes. A server that accepts and then drops the connection fails within a few milliseconds with aConnectionResetError: the transport's ownRemote 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 withConnectionResetError('Connection was lost during startup')(fromTimeoutError) before a1b3d7c and fails withTimeoutErrorafter it, as ondev. - The new regression test fails on 74f690d and passes on a1b3d7c.
- Merge resolution:
git show --remerge-diffshows only the five conflicted hunks, each keeping both sides; the ordering ofGateway.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.
Complements #741 (which makes
ThreadsafeProxysurvive a closed or stopping worker loop) from the other side:EZSPstops talking to a gateway whose transport is gone in the first place. Fixes theTypeError: 'NoneType' object can't be awaitedteardown cascade tracked in #722 at its most common entry point, and thestartup_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:
The first
startup_reset()attempt fails correctly, with the transport'sConnectionResetError(set on the startup-reset future byGateway.connection_lost()). Butconnection_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),TypeErrorfromreset()andwait_for_startup_reset(), thendisconnect()itself raisingTypeError, which masks the real error all the way up throughControllerApplication.connect()and zigpy'sshutdown(). 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 bareCancelledErrorescapesconnect(), 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. Ondev: the cascade above (13/14 runs) orCancelledErrorplus adisconnect()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 aversioncommand that was never sent.What changes
EZSPrecords that its transport closed whenGateway.connection_lost()reports it (via the api proxy; the NCP failed-state route throughenter_failed_state()keeps the transport open and is deliberately not included, so a reset can still recover the NCP anddisconnect()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 aCancelledErrorcaused by the worker teardown (flag set, the caller's own task not cancelling) is reported asConnectionResetErrorso setup fails instead of looking cancelled. Bothexceptclauses 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 theexceptclause first. The flag is read before the finaldisconnect(), since closing a healthy transport ourselves reports it closed too: an NCP that never answers still fails with its ownTimeoutErrorafter the three attempts, as before.disconnect()no longer calls into the gateway once the transport closed (itsSerialProtocol.disconnect()is a no-op at that point: the transport is alreadyNoneand the disconnected event set) and always drops the reference._command()fails immediately withEzspError("Connection was lost")for commands issued after the loss, instead of sending into a dead loop and waiting outEZSP_CMD_TIMEOUT. Commands already in flight still time out as before.ControllerApplication.connect()anddisconnect()drop_ezspeven if disconnecting fails, andconnect()logs a failing follow-up disconnect instead of letting it replace the connection error.With this on top of
devthe reproduction fails in under 10 ms with aConnectionResetError(15/15 runs, including the ones that used to beCancelledError): usually the transport's ownRemote server closed connection, orConnection was lost during startupwhen 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 andadd_done_callback()queued the callback onto the worker loop with a plaincall_soon()from the wrong thread, which does not wake a loop blocked inselect(). The startup retries' own dispatches used to wake it by accident; without them the thread leaked (a process hang at interpreter exit, joining abellows.thread_still inrun_forever()). The callback is now attached inside_connect(), on the worker loop. As a consequence a worker teardown duringconnect()would cancel_connect()itself, soconnect()reports aCancelledErrorthat is not its caller's asConnectionResetError, and a caller cancellingconnect()now also stops the worker thread, whichexcept Exceptionnever 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 inconnect()), and #741's resolve-to-Noneproxy semantics mean that in the microsecond window where the transport closes between the flag check and the first dispatch,wait_for_startup_reset()returningNonereads as "reset received" and the followingversioncommand waits outEZSP_CMD_TIMEOUTbefore the flag ends the attempt. Still a cleanConnectionResetError, just 10 s late in that one window.Tests
Eighteen new tests in
tests/test_ezsp.py,tests/test_application.pyandtests/test_uart.py, including an end-to-end one that runsEZSP.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 ondev; 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 itsTimeoutError). Theuartleak 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 withdevmerged in: 817 passed, repeated runs.