From 787ca6efa8c8d4fe4e6f75d421c6797f676c2f33 Mon Sep 17 00:00:00 2001 From: Jonathan Currie Date: Mon, 16 Nov 2026 19:04:27 +1300 Subject: [PATCH 1/3] Apply the EZSP command timeout to transport sends --- bellows/ezsp/protocol.py | 14 +++++--- tests/test_ezsp_protocol.py | 66 +++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 5 deletions(-) diff --git a/bellows/ezsp/protocol.py b/bellows/ezsp/protocol.py index 841c1b3a8..c138815c3 100644 --- a/bellows/ezsp/protocol.py +++ b/bellows/ezsp/protocol.py @@ -120,13 +120,17 @@ async def command(self, name, *args, **kwargs) -> Any: cmd_id, _, rx_schema = self.COMMANDS[name] future = asyncio.get_running_loop().create_future() - self._awaiting[self._seq] = (cmd_id, rx_schema, future) + sequence = self._seq + self._awaiting[sequence] = (cmd_id, rx_schema, future) self._seq = (self._seq + 1) % 256 - await self._gw.send_data(data) - - async with asyncio_timeout(EZSP_CMD_TIMEOUT): - return await future + try: + async with asyncio_timeout(EZSP_CMD_TIMEOUT): + await self._gw.send_data(data) + return await future + finally: + self._awaiting.pop(sequence, None) + future.cancel() async def update_policies(self, policy_config: dict) -> None: """Set up the policies for what the NCP should do.""" diff --git a/tests/test_ezsp_protocol.py b/tests/test_ezsp_protocol.py index 3906eb5ea..352d3ac0c 100644 --- a/tests/test_ezsp_protocol.py +++ b/tests/test_ezsp_protocol.py @@ -47,6 +47,72 @@ async def test_command(prot_hndl): assert mock_send_data.mock_calls == [call(b"\x00\x00\x05")] +async def test_command_timeout_includes_transport_send(prot_hndl): + """A stuck transport must release the command semaphore and pending reply.""" + send_started = asyncio.Event() + + async def blocked_send(data): + send_started.set() + await asyncio.Event().wait() + + with ( + patch.object(prot_hndl._gw, "send_data", side_effect=blocked_send), + patch("bellows.ezsp.protocol.EZSP_CMD_TIMEOUT", 0.01), + ): + # The outer bound makes the regression fail instead of hanging the suite. + async with asyncio.timeout(1): + task = asyncio.create_task(prot_hndl.command("nop")) + await send_started.wait() + with pytest.raises(TimeoutError): + await task + assert not prot_hndl._awaiting + assert not prot_hndl._send_semaphore.locked() + + with patch.object(prot_hndl._gw, "send_data"): + asyncio.get_running_loop().call_soon( + lambda: prot_hndl._awaiting[prot_hndl._seq - 1][2].set_result(True) + ) + assert await prot_hndl.command("nop") is True + assert not prot_hndl._awaiting + + +@pytest.mark.parametrize("cancel", [False, True]) +async def test_command_cleans_up_failed_transport(prot_hndl, cancel): + """Send failures and caller cancellation must not retain pending replies.""" + send_started = asyncio.Event() + + async def send(data): + send_started.set() + if not cancel: + raise RuntimeError("closed worker") + await asyncio.Event().wait() + + with patch.object(prot_hndl._gw, "send_data", side_effect=send): + task = asyncio.create_task(prot_hndl.command("nop")) + await send_started.wait() + future = next(iter(prot_hndl._awaiting.values()))[2] if cancel else None + if cancel: + task.cancel() + with pytest.raises(asyncio.CancelledError if cancel else RuntimeError): + await task + if cancel: + assert future.cancelled() + assert not prot_hndl._awaiting + assert not prot_hndl._send_semaphore.locked() + + +async def test_command_cleans_up_response_timeout(prot_hndl): + """A response timeout must remove its pending-reply entry.""" + with ( + patch.object(prot_hndl._gw, "send_data"), + patch("bellows.ezsp.protocol.EZSP_CMD_TIMEOUT", 0.01), + pytest.raises(TimeoutError), + ): + await prot_hndl.command("nop") + assert not prot_hndl._awaiting + assert not prot_hndl._send_semaphore.locked() + + def test_receive_reply(prot_hndl): callback_mock = MagicMock(spec_set=asyncio.Future) prot_hndl._awaiting[0] = (0, prot_hndl.COMMANDS["version"][2], callback_mock) From 70658d6200af6d402f1fedb4be4977a65502a807 Mon Sep 17 00:00:00 2001 From: Jonathan Currie Date: Mon, 16 Nov 2026 20:24:58 +1300 Subject: [PATCH 2/3] Drop late EZSP replies after command timeouts --- bellows/ezsp/protocol.py | 13 ++++++ tests/test_ezsp_protocol.py | 90 +++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+) diff --git a/bellows/ezsp/protocol.py b/bellows/ezsp/protocol.py index c138815c3..0c4331fdb 100644 --- a/bellows/ezsp/protocol.py +++ b/bellows/ezsp/protocol.py @@ -36,6 +36,7 @@ class ProtocolHandler(abc.ABC): def __init__(self, cb_handler: Callable, gateway: Gateway) -> None: self._handle_callback = cb_handler self._awaiting = {} + self._timed_out_commands: dict[int, int] = {} self._gw = gateway self._seq = 0 self.COMMANDS_BY_ID = { @@ -121,6 +122,7 @@ async def command(self, name, *args, **kwargs) -> Any: future = asyncio.get_running_loop().create_future() sequence = self._seq + self._timed_out_commands.pop(sequence, None) self._awaiting[sequence] = (cmd_id, rx_schema, future) self._seq = (self._seq + 1) % 256 @@ -128,6 +130,10 @@ async def command(self, name, *args, **kwargs) -> Any: async with asyncio_timeout(EZSP_CMD_TIMEOUT): await self._gw.send_data(data) return await future + except TimeoutError: + # Keep only IDs, bounded by the 256 sequence values until reuse. + self._timed_out_commands[sequence] = cmd_id + raise finally: self._awaiting.pop(sequence, None) future.cancel() @@ -252,6 +258,13 @@ def __call__(self, data: bytes) -> None: sequence, self.COMMANDS_BY_ID.get(expected_id, [expected_id])[0], ) + elif self._timed_out_commands.get(sequence) == frame_id: + self._timed_out_commands.pop(sequence) + LOGGER.debug( + "Error processing %s response. %s command timed out?", + sequence, + frame_name, + ) else: self._handle_callback(frame_name, result) diff --git a/tests/test_ezsp_protocol.py b/tests/test_ezsp_protocol.py index 352d3ac0c..759185f55 100644 --- a/tests/test_ezsp_protocol.py +++ b/tests/test_ezsp_protocol.py @@ -138,6 +138,96 @@ def test_receive_reply_after_timeout(prot_hndl): assert prot_hndl._handle_callback.call_count == 0 +@pytest.mark.parametrize("block_send", [False, True]) +async def test_receive_late_reply_after_command_timeout(prot_hndl, caplog, block_send): + """Late replies are dropped after either the send or response times out.""" + + async def send(data): + if block_send: + await asyncio.Event().wait() + + with ( + patch.object(prot_hndl._gw, "send_data", side_effect=send), + patch("bellows.ezsp.protocol.EZSP_CMD_TIMEOUT", 0.01), + pytest.raises(TimeoutError), + ): + await prot_hndl.command("version", 4) + + assert not prot_hndl._awaiting + with caplog.at_level(logging.DEBUG): + prot_hndl(b"\x00\xff\x00\x04\x05\x06\x00") + + prot_hndl._handle_callback.assert_not_called() + assert "Error processing 0 response. version command timed out?" in caplog.text + assert not prot_hndl._timed_out_commands + + +async def test_timed_out_command_does_not_hide_unrelated_callbacks(prot_hndl): + """Both the sequence and command ID must match a timed-out command.""" + with ( + patch.object(prot_hndl._gw, "send_data"), + patch("bellows.ezsp.protocol.EZSP_CMD_TIMEOUT", 0.01), + pytest.raises(TimeoutError), + ): + await prot_hndl.command("version", 4) + + prot_hndl(b"\x00\xff\x19\x90") + prot_hndl(b"\x01\xff\x00\x04\x05\x06\x00") + assert prot_hndl._handle_callback.call_args_list == [ + call("stackStatusHandler", [t.EmberStatus.NETWORK_UP]), + call("version", [4, 5, 6]), + ] + + prot_hndl._handle_callback.reset_mock() + prot_hndl(b"\x00\xff\x00\x04\x05\x06\x00") + prot_hndl._handle_callback.assert_not_called() + + +@pytest.mark.parametrize( + ("name", "args", "reply", "result"), + [ + ("version", (4,), b"\x00\xff\x00\x04\x05\x06\x00", [4, 5, 6]), + ("nop", (), b"\x00\xff\x05", []), + ], +) +async def test_command_reuses_timed_out_sequence(prot_hndl, name, args, reply, result): + """Reusing a sequence retires its old timeout marker before sending.""" + with ( + patch.object(prot_hndl._gw, "send_data"), + patch("bellows.ezsp.protocol.EZSP_CMD_TIMEOUT", 0.01), + pytest.raises(TimeoutError), + ): + await prot_hndl.command("version", 4) + + prot_hndl._seq = 0 + + async def send(data): + assert not prot_hndl._timed_out_commands + prot_hndl(reply) + + with patch.object(prot_hndl._gw, "send_data", side_effect=send): + assert await prot_hndl.command(name, *args) == result + + assert not prot_hndl._awaiting + prot_hndl._handle_callback.assert_not_called() + + +async def test_timed_out_command_tracking_is_bounded(prot_hndl): + """Timeout tracking wraps with the protocol's sequence byte.""" + with ( + patch.object(prot_hndl._gw, "send_data"), + patch("bellows.ezsp.protocol.EZSP_CMD_TIMEOUT", 0), + ): + for _ in range(257): + with pytest.raises(TimeoutError): + await prot_hndl.command("version", 4) + + assert len(prot_hndl._timed_out_commands) == 256 + assert prot_hndl._seq == 1 + assert not prot_hndl._awaiting + assert not prot_hndl._send_semaphore.locked() + + def test_receive_reply_invalid_command(prot_hndl): callback_mock = MagicMock(spec_set=asyncio.Future) prot_hndl._awaiting[0] = (0, prot_hndl.COMMANDS["invalidCommand"][2], callback_mock) From f337203f23ae68499aff6a37c95fdd4ecc8385cd Mon Sep 17 00:00:00 2001 From: zigpy-review-bot <286747149+zigpy-review-bot@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:11:27 +0100 Subject: [PATCH 3/3] Drop late replies after cancellation and late invalidCommand responses Record the timeout marker in `finally` whenever the command's future holds no consumed reply, so a caller cancellation or a failed send leaves one too, not only a `TimeoutError`. A reply that arrived in time (a result or an `invalidCommand` exception) still leaves no marker. Accept an `invalidCommand` frame for a marked sequence as well: the NCP answers a rejected command with it under the same sequence, so it is the late reply of that command, not a callback. The debug line now names the timed-out command rather than the received frame. --- bellows/ezsp/protocol.py | 17 ++++++---- tests/test_ezsp_protocol.py | 64 +++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 7 deletions(-) diff --git a/bellows/ezsp/protocol.py b/bellows/ezsp/protocol.py index 0c4331fdb..324a045d5 100644 --- a/bellows/ezsp/protocol.py +++ b/bellows/ezsp/protocol.py @@ -130,12 +130,12 @@ async def command(self, name, *args, **kwargs) -> Any: async with asyncio_timeout(EZSP_CMD_TIMEOUT): await self._gw.send_data(data) return await future - except TimeoutError: - # Keep only IDs, bounded by the 256 sequence values until reuse. - self._timed_out_commands[sequence] = cmd_id - raise finally: self._awaiting.pop(sequence, None) + # No reply consumed (timeout, cancellation or a failed send): keep + # only IDs, bounded by the 256 sequence values until reuse. + if not future.done() or future.cancelled(): + self._timed_out_commands[sequence] = cmd_id future.cancel() async def update_policies(self, policy_config: dict) -> None: @@ -258,12 +258,15 @@ def __call__(self, data: bytes) -> None: sequence, self.COMMANDS_BY_ID.get(expected_id, [expected_id])[0], ) - elif self._timed_out_commands.get(sequence) == frame_id: - self._timed_out_commands.pop(sequence) + elif sequence in self._timed_out_commands and frame_id in ( + self._timed_out_commands[sequence], + self.COMMANDS["invalidCommand"][0], + ): + expected_id = self._timed_out_commands.pop(sequence) LOGGER.debug( "Error processing %s response. %s command timed out?", sequence, - frame_name, + self.COMMANDS_BY_ID.get(expected_id, [expected_id])[0], ) else: self._handle_callback(frame_name, result) diff --git a/tests/test_ezsp_protocol.py b/tests/test_ezsp_protocol.py index 759185f55..156f77d57 100644 --- a/tests/test_ezsp_protocol.py +++ b/tests/test_ezsp_protocol.py @@ -4,6 +4,7 @@ import pytest +from bellows.exception import InvalidCommandError from bellows.ezsp import EZSP import bellows.ezsp.v4 import bellows.ezsp.v9 @@ -162,6 +163,69 @@ async def send(data): assert not prot_hndl._timed_out_commands +@pytest.mark.parametrize("block_send", [False, True]) +async def test_receive_late_reply_after_command_cancel(prot_hndl, caplog, block_send): + """Late replies are dropped after the caller cancels during send or response.""" + sent = asyncio.Event() + + async def send(data): + sent.set() + if block_send: + await asyncio.Event().wait() + + with patch.object(prot_hndl._gw, "send_data", side_effect=send): + task = asyncio.create_task(prot_hndl.command("version", 4)) + await sent.wait() + await asyncio.sleep(0) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + assert not prot_hndl._awaiting + with caplog.at_level(logging.DEBUG): + prot_hndl(b"\x00\xff\x00\x04\x05\x06\x00") + + prot_hndl._handle_callback.assert_not_called() + assert "Error processing 0 response. version command timed out?" in caplog.text + assert not prot_hndl._timed_out_commands + + +async def test_receive_late_invalid_command_after_timeout(prot_hndl, caplog): + """A late invalidCommand for a timed-out sequence is dropped, too.""" + with ( + patch.object(prot_hndl._gw, "send_data"), + patch("bellows.ezsp.protocol.EZSP_CMD_TIMEOUT", 0.01), + pytest.raises(TimeoutError), + ): + await prot_hndl.command("version", 4) + + with caplog.at_level(logging.DEBUG): + prot_hndl(b"\x00\xff\x58\x31") + + prot_hndl._handle_callback.assert_not_called() + assert "Error processing 0 response. version command timed out?" in caplog.text + assert not prot_hndl._timed_out_commands + + +@pytest.mark.parametrize("invalid", [False, True]) +async def test_command_answered_in_time_leaves_no_marker(prot_hndl, invalid): + """A reply or invalidCommand consumed in time leaves no timeout marker.""" + + async def send(data): + prot_hndl(b"\x00\xff\x58\x31" if invalid else b"\x00\xff\x00\x04\x05\x06\x00") + + with patch.object(prot_hndl._gw, "send_data", side_effect=send): + if invalid: + with pytest.raises(InvalidCommandError): + await prot_hndl.command("version", 4) + else: + assert await prot_hndl.command("version", 4) == [4, 5, 6] + + assert not prot_hndl._awaiting + assert not prot_hndl._timed_out_commands + prot_hndl._handle_callback.assert_not_called() + + async def test_timed_out_command_does_not_hide_unrelated_callbacks(prot_hndl): """Both the sequence and command ID must match a timed-out command.""" with (