diff --git a/bellows/ezsp/protocol.py b/bellows/ezsp/protocol.py index 841c1b3a..324a045d 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 = { @@ -120,13 +121,22 @@ 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._timed_out_commands.pop(sequence, None) + 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) + # 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: """Set up the policies for what the NCP should do.""" @@ -248,6 +258,16 @@ def __call__(self, data: bytes) -> None: sequence, self.COMMANDS_BY_ID.get(expected_id, [expected_id])[0], ) + 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, + 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 3906eb5e..156f77d5 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 @@ -47,6 +48,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) @@ -72,6 +139,159 @@ 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 + + +@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 ( + 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)