From a389b102ddd94128904988c251c70262bb3eb98c Mon Sep 17 00:00:00 2001 From: David Lechner Date: Mon, 23 Nov 2026 20:12:47 -0600 Subject: [PATCH] pb-service: say at once that firmware 4.0 cannot take a paste Pasting into the REPL of a hub on Pybricks 4.0 waited 10 s and then said the hub was not reading its input. 4.0 sized its stdin buffer at 21 bytes, or 64 on hubs with USB, while reporting a write size of up to 512, so a write bigger than the buffer was refused for good. It is a firmware bug, fixed in 4.1.0b3 (pybricks-micropython a363d48f5f, discussions/2788). It is not worked around: Pybricks Code writes at the reported size too. Instead, on 4.0 a refused write bigger than the hub's buffer is reported at once as HUB_BUSY, saying to update the firmware first, since pb repl shows it in a status line cut to the terminal's width. A smaller write refused on 4.0 still means nothing is reading. The betas between 4.0 and the fix are not told apart. Measured on a Prime hub on 4.0.1: 63 bytes are taken at the prompt and 64 refused for good. A paste now fails in 0.2 s with the remedy, where it took 10 s to fail with the wrong one. The fake hub now reports firmware 4.1.3, as it has no small buffer. The hardware paste test skips on 4.0, and the hardware tests say when they skip because several hubs are on rather than none. --- packages/pb-service/CHANGELOG.md | 4 + .../pb-service/src/pb_service/hub/fake.py | 2 +- .../src/pb_service/methods/stdio.py | 83 +++++++++++++++++-- packages/pb-service/tests/test_stdio.py | 61 ++++++++++++++ tests/hardware/conftest.py | 10 +++ tests/hardware/test_hub.py | 8 ++ 6 files changed, 161 insertions(+), 7 deletions(-) diff --git a/packages/pb-service/CHANGELOG.md b/packages/pb-service/CHANGELOG.md index 2119e7b..3aedc02 100644 --- a/packages/pb-service/CHANGELOG.md +++ b/packages/pb-service/CHANGELOG.md @@ -31,6 +31,10 @@ Notable changes to `pybricks-service`. The format is based on ### Fixed +- Input too big for the buffer of a hub on Pybricks 4.0 is refused at once, + saying to update the firmware, rather than after 10 s as a hub not reading + its input. 4.0 takes 20 bytes at a time, or 63 on + hubs with USB, whatever write size it reports. - A Bluetooth hub was sometimes first reported without its hub type, before its scan response arrived. Hubs are now reported only once it has, and one that never sends it is logged as a firmware bug rather than listed. diff --git a/packages/pb-service/src/pb_service/hub/fake.py b/packages/pb-service/src/pb_service/hub/fake.py index d7088e1..9a24dc5 100644 --- a/packages/pb-service/src/pb_service/hub/fake.py +++ b/packages/pb-service/src/pb_service/hub/fake.py @@ -60,7 +60,7 @@ class FakeHub: name: str = "Fake Hub" address: str = "AA:BB:CC:DD:EE:FF" profile: p.Version = (1, 5, 0) - firmware: str = "4.0.1" + firmware: str = "4.1.3" hub_type: int = p.HubType.TECHNIC_LARGE_HUB variant: int = 0 """Product id and version, as the PnP ID reports them.""" diff --git a/packages/pb-service/src/pb_service/methods/stdio.py b/packages/pb-service/src/pb_service/methods/stdio.py index f3ae9b9..74ad74a 100644 --- a/packages/pb-service/src/pb_service/methods/stdio.py +++ b/packages/pb-service/src/pb_service/methods/stdio.py @@ -28,6 +28,11 @@ on the hub rather than here -- which is what :data:`STDIN_PATIENCE_SECONDS` eventually says. +The one exception is firmware 4.0, whose buffer is smaller than the write size +it reports: a write bigger than the buffer is refused for good, which is a +firmware bug fixed in 4.1. That is said at once, and not worked around; see +:data:`FIRMWARE_4_0_STDIN_BYTES`. + **Nothing here adapts the write size, and that is deliberate.** It used to halve on a refusal that lasted, on the theory that a long refusal meant the buffer was smaller than advertised, remembering where it settled. The theory @@ -45,7 +50,7 @@ from __future__ import annotations import logging -from typing import Any +from typing import Any, Final import anyio @@ -59,7 +64,7 @@ from pb_core.protocol import HUB_STATE, HUB_STATUS, HUB_STDOUT from pb_service.errors import hub_errors from pb_service.hub import protocol as p -from pb_service.hub.connection import HubConnection +from pb_service.hub.connection import HubConnection, HubInfo from pb_service.hub.events import Channel, StateEvent, StatusEvent, StdoutEvent from pb_service.methods import method, require from pb_service.methods.hub import hub_of, report_json, status_json @@ -179,7 +184,8 @@ async def _write_stdin(connection: HubConnection, data: bytes) -> int: over and over at that size until the hub takes it. **The size never changes**, because a refusal carries no information about it: the firmware tests the buffer's *free space*, which is whatever the reader on the hub has - not read yet, so a refusal says only that nothing has read lately. See the + not read yet, so a refusal says only that nothing has read lately -- except + on firmware 4.0, where a piece bigger than its buffer never fits. See the module docstring for the version of this that tried to be clever and what it cost. @@ -197,7 +203,9 @@ async def _write_stdin(connection: HubConnection, data: bytes) -> int: Raises: JsonRpcError: If the hub is not ready, or stayed busy for longer than - its patience allows. + its patience allows. ``HUB_BUSY`` at once, with ``firmware_limit`` + in its data, if the hub runs firmware 4.0 and was offered more than + its buffer holds. """ info = connection.info if info is None: @@ -205,14 +213,31 @@ async def _write_stdin(connection: HubConnection, data: bytes) -> int: offset = 0 limit = connection.stdin_limit + too_small = _firmware_4_0_limit(info) with anyio.move_on_after(STDIN_PATIENCE_SECONDS) as patience: while offset < len(data): - if await _offer(connection, data[offset : offset + limit], info.profile): - offset += min(limit, len(data) - offset) + chunk = data[offset : offset + limit] + + if await _offer(connection, chunk, info.profile): + offset += len(chunk) continue + if too_small is not None and len(chunk) > too_small: + # Not a program that has not read yet: this firmware has no + # room for this much, now or ever, and the fix is to update it. + # Nothing here cuts the input smaller to get round that. + # + # The remedy first: a REPL shows this in a status line cut to + # the terminal's width. + raise JsonRpcError( + ErrorCode.HUB_BUSY, + f"update the hub's firmware: {info.firmware} takes at most " + f"{too_small} bytes of input at once", + {"written": offset, "firmware_limit": too_small}, + ) + # Nothing on the hub has read its input yet. There is nothing to # conclude and nothing to adjust, so wait for the soonest moment # the answer could be different and ask again. @@ -228,6 +253,52 @@ async def _write_stdin(connection: HubConnection, data: bytes) -> int: return offset +FIRMWARE_4_0_STDIN_BYTES: Final = 20 +"""The most input Pybricks 4.0 takes in one write, on most hubs. + +4.0 sized its input buffer to 21 bytes, less the byte a ring buffer keeps empty, +while reporting a write size of up to 512: a write bigger than the buffer could +never fit, however long it waited. 4.1 sized the buffer to the write size +(pybricks-micropython a363d48f5f, discussions/2788). The betas between are not +worth telling apart: nobody stays on a beta. +""" + +FIRMWARE_4_0_STDIN_BYTES_WITH_USB: Final = 63 +"""The most input Pybricks 4.0 takes in one write, on hubs with USB. + +Their buffer was 64 bytes, to match the USB endpoint. Measured on a Prime hub +on 4.0.1: 63 bytes are taken at the prompt, and 64 are refused for good. +""" + +_HUBS_WITH_USB: Final = frozenset( + {p.HubType.TECHNIC_LARGE_HUB, p.HubType.TECHNIC_SMALL_HUB, p.HubType.NXT} +) + + +def _firmware_4_0_limit(info: HubInfo) -> int | None: + """How much input a hub takes at once, if its firmware has too small a buffer. + + Args: + info: The hub. + + Returns: + The most it takes in one write, or ``None`` for firmware without the + bug, including firmware whose version cannot be read. + """ + try: + version = p.parse_version(info.firmware) + except ValueError: + return None + + if version[:2] != (4, 0): + return None + + if info.pnp is not None and info.pnp.product_id in _HUBS_WITH_USB: + return FIRMWARE_4_0_STDIN_BYTES_WITH_USB + + return FIRMWARE_4_0_STDIN_BYTES + + @method( "hub.attach", "Stream a hub's output, status and connection state until cancelled. " diff --git a/packages/pb-service/tests/test_stdio.py b/packages/pb-service/tests/test_stdio.py index 78efcb4..1138efd 100644 --- a/packages/pb-service/tests/test_stdio.py +++ b/packages/pb-service/tests/test_stdio.py @@ -166,3 +166,64 @@ async def test_the_write_size_is_what_the_hub_said_and_nothing_else( await _write_stdin(connection, b"x" * 100) assert connection.stdin_limit == was + + +# ------------------------------------------------------------ firmware 4.0 + + +@pytest.mark.parametrize( + ("hub_type", "buffer", "most"), + [ + (p.HubType.TECHNIC_LARGE_HUB, 64, 63), + (p.HubType.CITY_HUB, 21, 20), + ], +) +async def test_firmware_4_0_says_its_buffer_is_too_small_at_once( + hub_type: p.HubType, buffer: int, most: int +) -> None: + # 4.0 reported a write size it had no room for, so a paste waited out + # the whole of its patience and was then blamed on nothing reading. It is + # a firmware bug with a fix, which is what the user needs to hear, and + # straight away: no amount of waiting makes room that is not there. + hub = FakeHub(firmware="4.0.1", hub_type=hub_type, stdin_capacity=buffer - 1) + transport = FakeHubTransport(hub) + + async with anyio.create_task_group() as tg: + connection = await _start(tg, transport, hub) + + try: + assert await _write_stdin(connection, b"x" * most) == most + hub.stdin.clear() + + with anyio.fail_after(1), pytest.raises(JsonRpcError) as caught: + await _write_stdin(connection, b"x" * 100) + + assert caught.value.code == ErrorCode.HUB_BUSY + assert caught.value.message.startswith("update the hub's firmware") + assert f"at most {most} bytes" in caught.value.message + assert caught.value.data["firmware_limit"] == most + + finally: + connection.close("test finished") + + +async def test_firmware_4_0_not_reading_small_input_is_still_not_reading( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Input that would fit says nothing about the firmware when it is refused. + monkeypatch.setattr(stdio, "STDIN_PATIENCE_SECONDS", 0.3) + hub = FakeHub(firmware="4.0.1", hub_type=p.HubType.CITY_HUB, stdin_capacity=20) + hub.stdin += b"y" * 15 + transport = FakeHubTransport(hub) + + async with anyio.create_task_group() as tg: + connection = await _start(tg, transport, hub) + + try: + with pytest.raises(JsonRpcError) as caught: + await _write_stdin(connection, b"x" * 10) + + assert "not reading its input" in caught.value.message + + finally: + connection.close("test finished") diff --git a/tests/hardware/conftest.py b/tests/hardware/conftest.py index 5bf206b..015fd53 100644 --- a/tests/hardware/conftest.py +++ b/tests/hardware/conftest.py @@ -29,6 +29,7 @@ import pytest import pb_client +from pb_core.jsonrpc import ErrorCode SCAN_SECONDS = 15.0 """How long to look for a hub before deciding there is none to test against.""" @@ -173,6 +174,15 @@ async def _connected(service: pb_client.Service) -> str: except _UNAVAILABLE as exc: _no_hub = f"no hub switched on and in range: {exc}" + + # Several hubs on and none chosen is refused rather than guessed at, + # and the remedy is not to switch one on. + if ( + isinstance(exc, pb_client.JsonRpcError) + and exc.code == ErrorCode.HUB_AMBIGUOUS + ): + _no_hub = f"{exc}; switch the others off, or choose one with pb use" + pytest.skip(_no_hub) return info.name diff --git a/tests/hardware/test_hub.py b/tests/hardware/test_hub.py index ca9bdaf..d482608 100644 --- a/tests/hardware/test_hub.py +++ b/tests/hardware/test_hub.py @@ -25,6 +25,7 @@ import pytest import pb_client +from pb_service.hub.protocol import parse_version pytestmark = [pytest.mark.hardware, pytest.mark.anyio] @@ -189,6 +190,13 @@ async def test_a_program_that_ignores_input_does_not_slow_the_hub_afterwards( # the buffer was smaller than advertised, halved the write size, and # remembered that for the life of the connection. The connection outlives # every command, so pasting stayed slow for the rest of the day. + firmware = (await service.hub_info(hub)).firmware + + if parse_version(firmware)[:2] == (4, 0): + # Its input buffer is smaller than a paste, so nothing pasted fits, + # and the service says so rather than waiting. Fixed in 4.1. + pytest.skip(f"Pybricks {firmware} cannot take a paste this size") + await service.start_repl(hub_id=hub) await anyio.sleep(1.0) before = await _paste_ms(service, hub)