From ac523874483201515500823627317fe726aa2960 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:28:17 -0700 Subject: [PATCH 01/33] feat(models): say whether a circuit declares a breaker rating --- CHANGELOG.md | 6 ++ README.md | 6 +- packages/schema-1/CHANGELOG.md | 8 +++ .../src/span_panel_api_schema_1/circuits.py | 3 + src/span_panel_api/models.py | 7 +++ tests/adapter_fidelity/rules.py | 4 ++ tests/adapter_fidelity/rules_captured.py | 1 + tests/test_schema_one_circuits.py | 56 +++++++++++++++++++ 8 files changed, 88 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 923b93e..0227c2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), Pre-releases are not listed separately. A beta is a step towards the next public version, so its changes are folded into that version's entry as they land and are described against the **last public release**, never against the beta before it. What one beta corrected in an earlier beta does not appear at all: from the point of view of somebody upgrading between released versions, it never happened. +## [3.9.0] + +### Added + +- **`SpanCircuitSnapshot.breaker_rating_declared`** says whether a circuit declares a breaker rating, so a consumer can tell a rating the panel does not publish from one that has not arrived yet; `None` where the adapter does not say. + ## [3.8.0] Snapshot fields that held a fabricated constant can now be unknown, and with `span-panel-api-schema-0` 1.3.0 and `span-panel-api-schema-1` 1.4.0 or newer the parsers report them as unknown and stop synthesising unoccupied positions. diff --git a/README.md b/README.md index fdd546f..94b0586 100644 --- a/README.md +++ b/README.md @@ -157,9 +157,9 @@ All panel state is represented as immutable, frozen dataclasses: grid and feedthrough power and energy, grid/DSM state, run configuration, dominant power source, grid islandability, per-leg voltages, power flows, lugs current and whether the lugs are the service entrance, busbar current, line frequency, the rating of the protection ahead of the upstream lugs, the first and last breaker positions, whether any circuit declares what it feeds, shed policy and forecast. It holds `circuits`, `battery`, `pv`, `pv_inverters`, `evse`, `mid`, `pcs`, `adopted_devices` and `extension_properties`. -- **`SpanCircuitSnapshot`**: one circuit. Id, name, relay state and requester, power, energy and their update times, tabs, 240 V, breaker rating, current, priority, user controllability, sheddable / never-backup / always-on flags, device type, relative - position, PCS management and priority, the `$target` pending state for relay and priority, nominal voltage, the breaker's protection functions, the role it declares for what it feeds, the other circuits its meter or relay is shared with, and whether it - is a meter outside the panel, which has no breaker space, relay or shed priority and reads import-positive. +- **`SpanCircuitSnapshot`**: one circuit. Id, name, relay state and requester, power, energy and their update times, tabs, 240 V, breaker rating and whether it declares one, current, priority, user controllability, sheddable / never-backup / always-on + flags, device type, relative position, PCS management and priority, the `$target` pending state for relay and priority, nominal voltage, the breaker's protection functions, the role it declares for what it feeds, the other circuits its meter or relay is + shared with, and whether it is a meter outside the panel, which has no breaker space, relay or shed priority and reads import-positive. - **`SpanBatterySnapshot`**: the BESS. Whether the panel declares one, SoE percentage and kWh, its own meter reading, communication state, link health, the circuit that feeds it, vendor / `model` / `part_number` / serial / version, nameplate capacity. - **`SpanPVSnapshot`**: one PV inverter. Link health, vendor / `model` / serial / version, nameplate capacity (the array's DC size), feeding circuit, relative position, its wire `device_id` and its `node_id`, which is its key in `pv_inverters`. `SpanPanelSnapshot.pv` is the lone inverter, or describes several together. diff --git a/packages/schema-1/CHANGELOG.md b/packages/schema-1/CHANGELOG.md index 6b92b68..076e017 100644 --- a/packages/schema-1/CHANGELOG.md +++ b/packages/schema-1/CHANGELOG.md @@ -9,6 +9,14 @@ number. A release here means this parser changed, never that the panel did. Pre-releases are not listed separately. A beta is a step towards the next public version, so its changes are folded into that version's entry as they land and are described against the last public release, never against the beta before it. +## [1.5.0] + +Requires `span-panel-api` **3.9.0 or newer**, whose circuit snapshot carries the field this parser now fills. + +### Added + +- **Circuits report whether they declare a breaker rating** (`breaker_rating_declared`). + ## [1.4.0] Requires `span-panel-api` **3.8.0 or newer**, whose snapshot fields accept the unknown values this parser now reports and carry the fields it now fills. diff --git a/packages/schema-1/src/span_panel_api_schema_1/circuits.py b/packages/schema-1/src/span_panel_api_schema_1/circuits.py index ddfde7a..2078211 100644 --- a/packages/schema-1/src/span_panel_api_schema_1/circuits.py +++ b/packages/schema-1/src/span_panel_api_schema_1/circuits.py @@ -377,6 +377,9 @@ def build_circuit( is_240v=None if poles is None else poles >= 2, current_a=_number(device, NODE_METER, PROP_CURRENT), breaker_rating_a=_number(device, NODE_BREAKER, PROP_RATING), + # The declaration, not the value: a rating that has not arrived yet + # reads as `None` above whether or not the panel will ever publish one. + breaker_rating_declared=PROP_RATING in node_properties(device, NODE_BREAKER), # A relay locked closed. A device with no relay is not "on" at all. always_on=declares_node(device, NODE_SWITCH) and not relay_controllable, relay_requester=_text(device, NODE_SWITCH, PROP_RELAY_REQUESTER, UNKNOWN), diff --git a/src/span_panel_api/models.py b/src/span_panel_api/models.py index b544d4c..2edc822 100644 --- a/src/span_panel_api/models.py +++ b/src/span_panel_api/models.py @@ -64,6 +64,13 @@ class SpanCircuitSnapshot: is_240v: bool | None = False current_a: float | None = None breaker_rating_a: float | None = None + # Whether the circuit's description declares a breaker rating, as distinct + # from whether its value has arrived. `True`: declared, so `breaker_rating_a` + # is `None` only until the retained value lands. `False`: the panel + # publishes no rating for this circuit. `None`: the adapter does not say + # (flat, REST, a hand-built snapshot) and the consumer must treat it as + # not known, never as `False`. + breaker_rating_declared: bool | None = None always_on: bool = False # v2 new: circuit/always-on relay_requester: str = "UNKNOWN" # v2 new: circuit/relay-requester # Epoch seconds at which the reading last changed, as received over MQTT. diff --git a/tests/adapter_fidelity/rules.py b/tests/adapter_fidelity/rules.py index 0ad63dd..f1fbc9d 100644 --- a/tests/adapter_fidelity/rules.py +++ b/tests/adapter_fidelity/rules.py @@ -500,6 +500,10 @@ def add( "circuit.measures_outside_panel", "circuits.declares_spaces: whether the description declares info/spaces, not a value", ), + Derivation( + "circuit.breaker_rating_declared", + "circuits.build_circuit: whether the description declares breaker/rating, not a value", + ), Derivation( "panel.publishes_solar_roles", "snapshot.build_snapshot: whether any circuit's description declares connection/feeds-role, not a value", diff --git a/tests/adapter_fidelity/rules_captured.py b/tests/adapter_fidelity/rules_captured.py index 0e34a8d..d2c9c27 100644 --- a/tests/adapter_fidelity/rules_captured.py +++ b/tests/adapter_fidelity/rules_captured.py @@ -22,6 +22,7 @@ _SHARED: Final = frozenset( { "battery.present", + "circuit.breaker_rating_declared", "circuit.circuit_id", "circuit.device_type", "circuit.is_never_backup", diff --git a/tests/test_schema_one_circuits.py b/tests/test_schema_one_circuits.py index 8d0b756..2d04d9f 100644 --- a/tests/test_schema_one_circuits.py +++ b/tests/test_schema_one_circuits.py @@ -15,13 +15,18 @@ from __future__ import annotations import json +from dataclasses import replace from pathlib import Path import pytest from ebus_sdk.homie import DiscoveredDevice +from conftest import flat_schema from reference_payloads.schema_one import device_from_topics, parent_child_tree +from reference_payloads.synthetic_trees import SyntheticDevice, discovered, hosted_circuit, space_less_meter, without_values +from span_panel_api_schema_0 import SchemaZeroAdapter +from span_panel_api_schema_0.const import TYPE_CIRCUIT from span_panel_api_schema_1.circuits import build_circuit _TREE = parent_child_tree() @@ -116,6 +121,57 @@ def test_breaker_rating_and_current(kitchen: DiscoveredDevice) -> None: assert circuit.current_a == pytest.approx(1.00833, rel=1e-4) +# --------------------------------------------------------------------------- +# Whether the breaker rating is declared +# --------------------------------------------------------------------------- + + +def _undeclared_rating(device: SyntheticDevice) -> SyntheticDevice: + """The same circuit, its `breaker` node kept but `rating` neither declared nor valued.""" + breaker = {prop: declaration for prop, declaration in device.nodes["breaker"].items() if prop != "rating"} + values = {path: value for path, value in device.values.items() if path != "breaker/rating"} + return replace(device, nodes={**device.nodes, "breaker": breaker}, values=values) + + +def test_rating_declared_and_valued() -> None: + circuit = build_circuit(discovered(hosted_circuit("c-1", (1,)))) + + assert circuit.breaker_rating_a == 20.0 + assert circuit.breaker_rating_declared is True + + +def test_rating_declared_not_yet_valued() -> None: + """Declared before it is valued: the rating is coming, which is not the same as never.""" + circuit = build_circuit(discovered(without_values(hosted_circuit("c-1", (1,)), "breaker/rating"))) + + assert circuit.breaker_rating_a is None + assert circuit.breaker_rating_declared is True + + +def test_rating_not_declared() -> None: + circuit = build_circuit(discovered(_undeclared_rating(hosted_circuit("c-1", (1,))))) + + assert circuit.breaker_rating_a is None + assert circuit.breaker_rating_declared is False + + +def test_no_breaker_node() -> None: + circuit = build_circuit(discovered(space_less_meter("meter-a"))) + + assert circuit.breaker_rating_a is None + assert circuit.breaker_rating_declared is False + + +def test_schema_zero_does_not_say() -> None: + serial = "sim-40t-001" + circuit_id = "ac3dccda46a94b98878a227df6fed588" + adapter = SchemaZeroAdapter(serial_number=serial, schema=flat_schema(40)) + adapter.handle_message(f"ebus/5/{serial}/$description", json.dumps({"nodes": {circuit_id: {"type": TYPE_CIRCUIT}}})) + adapter.handle_message(f"ebus/5/{serial}/$state", "ready") + + assert adapter.build_snapshot().circuits[circuit_id].breaker_rating_declared is None + + # --------------------------------------------------------------------------- # The three flat booleans v1.0 retired # --------------------------------------------------------------------------- From 2f3584c96c52edd0dc8490437600a295baf84c3f Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:54:28 -0800 Subject: [PATCH 02/33] feat(models): say whether a panel publishes shared meters SpanPanelSnapshot.publishes_shared_meters is true where any circuit declares meter/shared-with-device-ids, which the panel models that describe their multi-load breakers declare on every circuit, a standard breaker included, valued only where a meter is shared. MAIN 32 declares neither list. The declaration decides, as for publishes_solar_roles, so a list that has not arrived yet still marks the panel. Consumers that cannot tell a tandem from a single-pole circuit on MAIN 32 need this to know whether the panel describes its breakers at all. --- CHANGELOG.md | 1 + README.md | 4 +- packages/schema-1/CHANGELOG.md | 1 + .../src/span_panel_api_schema_1/snapshot.py | 5 +++ src/span_panel_api/models.py | 11 +++++ tests/adapter_fidelity/rules.py | 4 ++ tests/adapter_fidelity/rules_captured.py | 1 + tests/test_schema_one_shared_meters.py | 41 +++++++++++++++++++ tests/test_shared_meters_captures.py | 10 +++++ 9 files changed, 76 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0227c2b..c7dbfd0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ beta corrected in an earlier beta does not appear at all: from the point of view ### Added - **`SpanCircuitSnapshot.breaker_rating_declared`** says whether a circuit declares a breaker rating, so a consumer can tell a rating the panel does not publish from one that has not arrived yet; `None` where the adapter does not say. +- **`SpanPanelSnapshot.publishes_shared_meters`** says whether any circuit declares `meter/shared-with-device-ids`, so a consumer can tell a panel that describes its multi-load breakers from one, such as MAIN 32, that publishes each as a single circuit. ## [3.8.0] diff --git a/README.md b/README.md index 94b0586..6fcd5a9 100644 --- a/README.md +++ b/README.md @@ -155,8 +155,8 @@ All panel state is represented as immutable, frozen dataclasses: - **`SpanPanelSnapshot`**: complete panel state. Identity (serial, firmware, vendor, model, hardware version), panel size, main breaker rating, main relay, door state, connection uptime on a flat panel, network links with the Wi-Fi SSID and vendor cloud, grid and feedthrough power and energy, grid/DSM state, run configuration, dominant power source, grid islandability, per-leg voltages, power flows, lugs current and whether the lugs are the service entrance, busbar current, line frequency, the rating of - the protection ahead of the upstream lugs, the first and last breaker positions, whether any circuit declares what it feeds, shed policy and forecast. It holds `circuits`, `battery`, `pv`, `pv_inverters`, `evse`, `mid`, `pcs`, `adopted_devices` and - `extension_properties`. + the protection ahead of the upstream lugs, the first and last breaker positions, whether any circuit declares what it feeds or a shared meter, shed policy and forecast. It holds `circuits`, `battery`, `pv`, `pv_inverters`, `evse`, `mid`, `pcs`, + `adopted_devices` and `extension_properties`. - **`SpanCircuitSnapshot`**: one circuit. Id, name, relay state and requester, power, energy and their update times, tabs, 240 V, breaker rating and whether it declares one, current, priority, user controllability, sheddable / never-backup / always-on flags, device type, relative position, PCS management and priority, the `$target` pending state for relay and priority, nominal voltage, the breaker's protection functions, the role it declares for what it feeds, the other circuits its meter or relay is shared with, and whether it is a meter outside the panel, which has no breaker space, relay or shed priority and reads import-positive. diff --git a/packages/schema-1/CHANGELOG.md b/packages/schema-1/CHANGELOG.md index 076e017..cd7dd1c 100644 --- a/packages/schema-1/CHANGELOG.md +++ b/packages/schema-1/CHANGELOG.md @@ -16,6 +16,7 @@ Requires `span-panel-api` **3.9.0 or newer**, whose circuit snapshot carries the ### Added - **Circuits report whether they declare a breaker rating** (`breaker_rating_declared`). +- **The snapshot reports whether any circuit declares a shared-meter list** (`publishes_shared_meters`). ## [1.4.0] diff --git a/packages/schema-1/src/span_panel_api_schema_1/snapshot.py b/packages/schema-1/src/span_panel_api_schema_1/snapshot.py index 99f8ed9..3d9533f 100644 --- a/packages/schema-1/src/span_panel_api_schema_1/snapshot.py +++ b/packages/schema-1/src/span_panel_api_schema_1/snapshot.py @@ -16,10 +16,12 @@ from span_panel_api_schema_1.const import ( NODE_CONNECTION, NODE_INFO, + NODE_METER, PROP_FEEDS_DEVICE_ID, PROP_FEEDS_ROLE, PROP_MODEL, PROP_SERIAL_NUMBER, + PROP_SHARED_WITH_DEVICE_IDS, TYPE_BESS, TYPE_CIRCUIT, TYPE_EVSE, @@ -289,6 +291,9 @@ def build_snapshot(panel: DiscoveredDevice, children: list[DiscoveredDevice]) -> publishes_solar_roles=any( PROP_FEEDS_ROLE in node_properties(circuit, NODE_CONNECTION) for circuit in roles.circuits ), + publishes_shared_meters=any( + PROP_SHARED_WITH_DEVICE_IDS in node_properties(circuit, NODE_METER) for circuit in roles.circuits + ), shed_policy=fields.shed_policy, shed_policy_algorithm=fields.shed_policy_algorithm, shed_soc_threshold_shed_percent=fields.shed_soc_threshold_shed_percent, diff --git a/src/span_panel_api/models.py b/src/span_panel_api/models.py index 2edc822..b70e37f 100644 --- a/src/span_panel_api/models.py +++ b/src/span_panel_api/models.py @@ -1347,6 +1347,17 @@ class SpanPanelSnapshot: which declares no roles. """ + publishes_shared_meters: bool = False + """Whether any circuit declares `meter/shared-with-device-ids`. + + The declaration decides, not the value: a panel model that describes its + multi-load breakers declares the list on every circuit, a standard breaker + included, and publishes a value only where a meter is shared. Such a panel + publishes each circuit of a multi-load breaker as its own device with its + own rating. `False` where no circuit declares the list, as on MAIN 32, and + on the flat schema, which declares none. + """ + # `shed/policy`, v1.0 only: how the panel decides what to shed, and the two # SoC thresholds that make its behaviour predictable. The wire carries one # `json` document; these are the parsed answer plus the document itself. diff --git a/tests/adapter_fidelity/rules.py b/tests/adapter_fidelity/rules.py index f1fbc9d..34d7451 100644 --- a/tests/adapter_fidelity/rules.py +++ b/tests/adapter_fidelity/rules.py @@ -508,6 +508,10 @@ def add( "panel.publishes_solar_roles", "snapshot.build_snapshot: whether any circuit's description declares connection/feeds-role, not a value", ), + Derivation( + "panel.publishes_shared_meters", + "snapshot.build_snapshot: whether any circuit's description declares meter/shared-with-device-ids, not a value", + ), Derivation("pv.device_id", "devices.build_pv: the inverter's device id"), Derivation("pv.node_id", "devices.pv_inverter_key: the feeding circuit's id, else the inverter's device id"), Derivation("pv_inverter.device_id", "devices.build_pv: the inverter's device id"), diff --git a/tests/adapter_fidelity/rules_captured.py b/tests/adapter_fidelity/rules_captured.py index d2c9c27..ba74eaa 100644 --- a/tests/adapter_fidelity/rules_captured.py +++ b/tests/adapter_fidelity/rules_captured.py @@ -30,6 +30,7 @@ "circuit.measures_outside_panel", "ctl.dps_target", "ctl.priority_target", + "panel.publishes_shared_meters", "panel.publishes_solar_roles", } ) diff --git a/tests/test_schema_one_shared_meters.py b/tests/test_schema_one_shared_meters.py index 2a6bb96..76231ee 100644 --- a/tests/test_schema_one_shared_meters.py +++ b/tests/test_schema_one_shared_meters.py @@ -113,3 +113,44 @@ def test_a_flat_panel_shares_nothing() -> None: assert all(circuit.meter_shared_with is None for circuit in snapshot.circuits.values()) assert shared_meter_groups(snapshot.circuits) == {} + + +# --- whether a panel publishes shared meters structurally --------------------- + + +def test_a_panel_whose_circuits_declare_a_shared_meter_publishes_shared_meters() -> None: + assert _snapshot(*shared_pair("c-1", "c-2")).publishes_shared_meters is True + + +def test_a_declared_list_with_no_value_still_marks_the_panel() -> None: + """The declaration decides: a standard breaker declares the list and publishes no value.""" + first, second = shared_pair("c-1", "c-2") + snapshot = _snapshot( + without_values(first, "meter/shared-with-device-ids"), + without_values(second, "meter/shared-with-device-ids"), + ) + + assert snapshot.publishes_shared_meters is True + + +def test_a_list_naming_no_known_circuit_still_marks_the_panel() -> None: + assert _snapshot(hosted_circuit("c-1", (1,), meter_shared_with=("ghost",))).publishes_shared_meters is True + + +def test_only_the_meter_list_counts() -> None: + """A relay shared with nothing on the meter says nothing about how the meters are described.""" + snapshot = _snapshot(hosted_circuit("c-1", (1,), relay_shared_with=("c-2",)), hosted_circuit("c-2", (3,))) + + assert snapshot.publishes_shared_meters is False + + +def test_a_panel_with_no_circuit_declaring_the_list_does_not() -> None: + assert _snapshot(hosted_circuit("c-1", (1,)), hosted_circuit("c-2", (3,))).publishes_shared_meters is False + + +def test_main_32_and_the_flat_schema_do_not() -> None: + reference = replay(parent_child_tree(), _REFERENCE_PANEL).build_snapshot() + flat = SchemaZeroAdapter(serial_number="sim-40t-001", schema=flat_schema(40)).build_snapshot() + + assert reference.publishes_shared_meters is False + assert flat.publishes_shared_meters is False diff --git a/tests/test_shared_meters_captures.py b/tests/test_shared_meters_captures.py index 553f1b3..67a9dcd 100644 --- a/tests/test_shared_meters_captures.py +++ b/tests/test_shared_meters_captures.py @@ -50,6 +50,16 @@ def test_the_captures_hold_shared_meters() -> None: assert any(shared_meter_groups(capture_snapshot(stem).circuits) for stem in CAPTURES) +@pytest.mark.parametrize("stem", CAPTURES) +def test_shared_meters_are_published_exactly_where_a_circuit_declares_the_list(stem: str) -> None: + """Every one of these models declares the list, on standard breakers too, whether or not any group exists.""" + tree = capture_tree(stem) + declared = any(tree.declares(circuit_id, _SHARED_WITH[0]) for circuit_id in tree.circuits()) + + assert declared + assert capture_snapshot(stem).publishes_shared_meters is declared + + @pytest.mark.parametrize("stem", CAPTURES) def test_shared_with_is_neither_discovered_nor_an_extension_reading(stem: str) -> None: adapter = capture_adapter(stem) From b700808354cc106bdb866a8725357446a11f8608 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Tue, 10 Nov 2026 14:35:10 -0800 Subject: [PATCH 03/33] chore(release): span-panel-api 3.9.0b1 and schema-1 1.5.0b1 span-panel-api 3.9.0b1 adds SpanCircuitSnapshot.breaker_rating_declared and SpanPanelSnapshot.publishes_shared_meters, which span-panel-api-schema-1 1.5.0b1 fills, so schema-1 floors on span-panel-api>=3.9.0b1. The changelogs carry the public versions, 3.9.0 and 1.5.0. schema-0 stays at 1.3.0, and the core schema-1 extra stays at 1.4.0, which 1.5.0b1 still satisfies. Replaces the 3.8.0b2 / 1.4.0b3 bump this branch carried before 3.8.0 and 1.4.0 were released without the field. --- packages/schema-1/pyproject.toml | 7 +++++-- pyproject.toml | 2 +- uv.lock | 4 ++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/packages/schema-1/pyproject.toml b/packages/schema-1/pyproject.toml index ed26793..6064288 100644 --- a/packages/schema-1/pyproject.toml +++ b/packages/schema-1/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "span-panel-api-schema-1" -version = "1.4.0" +version = "1.5.0b1" description = "Parent/child schema (data-model-version 1.x) parser for span-panel-api" authors = [ {name = "SpanPanel"} @@ -34,7 +34,10 @@ dependencies = [ # it, imports `device_id_order` from its models, implements the masked-tree # protocol and types new in it, and relies on its client reading a cleared # value as unpublished. - "span-panel-api>=3.8.0,<4.0", + # Raised to 3.9.0b1: this parser fills `SpanCircuitSnapshot.breaker_rating_declared`, + # which that release adds. A beta floor while this is a beta; the final + # restores a stable one (RELEASE.md, "Pre-releases"). + "span-panel-api>=3.9.0b1,<4.0", # Only this distribution depends on the eBus SDK. The bootstrap and # schema-0 stay clean, so a flat-panel install never pulls it in — which is # what bounds the release coupling this dependency introduces to panels on diff --git a/pyproject.toml b/pyproject.toml index 0d4f80a..7d4a0a1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "span-panel-api" -version = "3.8.0" +version = "3.9.0b1" description = "A client library for SPAN Panel API" authors = [ {name = "SpanPanel"} diff --git a/uv.lock b/uv.lock index e1e1cc6..850e567 100644 --- a/uv.lock +++ b/uv.lock @@ -974,7 +974,7 @@ wheels = [ [[package]] name = "span-panel-api" -version = "3.8.0" +version = "3.9.0b1" source = { editable = "." } dependencies = [ { name = "httpx" }, @@ -1057,7 +1057,7 @@ requires-dist = [{ name = "span-panel-api", editable = "." }] [[package]] name = "span-panel-api-schema-1" -version = "1.4.0" +version = "1.5.0b1" source = { editable = "packages/schema-1" } dependencies = [ { name = "ebus-sdk" }, From 1d85404e2a4d5f9d19d424247b111bfc0a34ea6e Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:06:46 -0800 Subject: [PATCH 04/33] fix(mqtt): subscribe each broker session once Every connection is a clean session, and the broker answers each SUBSCRIBE by replaying every retained message on the filter. The connection callback subscribed on the CONNACK and connect() subscribed again once the bridge returned, so the first connection asked for the panel's tree twice and received it twice. The bridge now owns subscription. SpanMqttClient hands it the topics of every parser it builds, and the bridge subscribes them once on each accepted CONNACK -- the initial connect, each reconnect, each rebuilt client -- before the connection is announced; neither connect() nor the connection callback subscribes any more. On a live session a new set is subscribed at once, which is how a parser swapped in for another schema generation receives the tree, and a filter that left the set is unsubscribed, where the old generation's filter stayed until the next reconnect and the broker delivered every message under the panel's own device once per overlapping filter. AsyncMqttBridge.subscribe(topic, qos) is replaced by set_subscriptions(topics). --- CHANGELOG.md | 5 + src/span_panel_api/mqtt/client.py | 157 ++++----- src/span_panel_api/mqtt/connection.py | 74 ++++- tests/test_mqtt_bridge.py | 7 +- tests/test_mqtt_client_connection.py | 38 +-- tests/test_mqtt_connect_flow.py | 38 ++- tests/test_one_subscribe_per_session.py | 410 ++++++++++++++++++++++++ tests/test_redispatch_on_reconnect.py | 12 +- 8 files changed, 623 insertions(+), 118 deletions(-) create mode 100644 tests/test_one_subscribe_per_session.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c7dbfd0..1ab2448 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,11 @@ beta corrected in an earlier beta does not appear at all: from the point of view - **`SpanCircuitSnapshot.breaker_rating_declared`** says whether a circuit declares a breaker rating, so a consumer can tell a rating the panel does not publish from one that has not arrived yet; `None` where the adapter does not say. - **`SpanPanelSnapshot.publishes_shared_meters`** says whether any circuit declares `meter/shared-with-device-ids`, so a consumer can tell a panel that describes its multi-load breakers from one, such as MAIN 32, that publishes each as a single circuit. +### Fixed + +- **Each broker connection subscribes once, so the panel's retained tree arrives once per connection**, where `connect()` subscribed twice and received the whole tree twice, and a panel that changes schema generation while connected no longer has every + message under its own device delivered twice until the next reconnect. + ## [3.8.0] Snapshot fields that held a fabricated constant can now be unknown, and with `span-panel-api-schema-0` 1.3.0 and `span-panel-api-schema-1` 1.4.0 or newer the parsers report them as unknown and stop synthesising unoccupied positions. diff --git a/src/span_panel_api/mqtt/client.py b/src/span_panel_api/mqtt/client.py index 45a9a78..1b23f12 100644 --- a/src/span_panel_api/mqtt/client.py +++ b/src/span_panel_api/mqtt/client.py @@ -310,12 +310,20 @@ async def _preload_adapter(self, schema: V2HomieSchema) -> None: await asyncio.to_thread(resolve_adapter, adapter_key, dispatch_reason) def _build_adapter(self, schema: V2HomieSchema) -> SchemaAdapter: - """Construct the parser for this session. + """Construct the parser for this session, and subscribe the bridge to its topics. - Called from connect() and from the reconnect path — the only two - places a parser is built today. Both await ``_preload_adapter`` first, - so the resolve below is a cache hit and this stays safe to call from a - synchronous context. + Called from connect(), from the pre-rebuild hook and from a generation + swap — every place a parser is built. connect() and the swap await + ``_preload_adapter`` first, and the hook rebuilds from the schema one of + them resolved, so the resolve below is a cache hit and this stays safe to + call from a synchronous context. + + Handing the topics to the bridge here, rather than at each caller, is + what ties a subscription to every parser: the bridge subscribes each + session to them on its CONNACK, and a live session at once, which is how + a parser swapped in mid-session receives the tree it has not seen. The + bridge exists before the first parser is built (see connect()), so no + parser goes without. With no injected factory this dispatches on the schema rather than assuming the flat adapter. That matters because a client can be built @@ -343,9 +351,12 @@ def _build_adapter(self, schema: V2HomieSchema) -> SchemaAdapter: self._data_model_version = schema.data_model_version self._schema_dispatch_reason = dispatch_reason factory = resolve_adapter(adapter_key, dispatch_reason) - self._adapter = factory(self._serial_number, schema) - self._observe(self._adapter) - return self._adapter + adapter = factory(self._serial_number, schema) + self._adapter = adapter + self._observe(adapter) + if self._bridge is not None: + self._bridge.set_subscriptions(adapter.topics_to_subscribe()) + return adapter @property def adapter(self) -> SchemaAdapter | None: @@ -444,10 +455,10 @@ async def connect(self) -> None: """Connect to MQTT broker and wait for Homie device ready. Flow: - 1. Fetch Homie schema to determine panel size - 2. Create AsyncMqttBridge with broker credentials - 3. Connect to MQTT broker - 4. Subscribe to the adapter's topics + 1. Create AsyncMqttBridge with broker credentials + 2. Fetch Homie schema to determine panel size + 3. Build the adapter, which hands the bridge its topics + 4. Connect to MQTT broker, whose CONNACK the bridge subscribes on 5. Wait for $state==ready and $description parsed Raises: @@ -458,6 +469,40 @@ async def connect(self) -> None: self._loop = asyncio.get_running_loop() self._ready_event = asyncio.Event() + # Before the adapter, because building one is what gives the bridge the + # topics every session subscribes to (see `_build_adapter`). + _LOGGER.debug( + "MQTT: Creating bridge to %s:%s (serial=%s)", + self._broker_config.broker_host, + self._broker_config.effective_port, + self._serial_number, + ) + bridge = AsyncMqttBridge( + host=self._broker_config.broker_host, + port=self._broker_config.effective_port, + username=self._broker_config.username, + password=self._broker_config.password, + panel_host=self._host, + serial_number=self._serial_number, + transport=self._broker_config.transport, + use_tls=self._broker_config.use_tls, + loop=self._loop, + panel_http_port=self._panel_http_port, + ca_pem=self._broker_config.ca_pem, + ) + self._bridge = bridge + + # Wire message handler + bridge.set_message_callback(self._on_message) + bridge.set_connection_callback(self._on_connection_change) + bridge.set_fatal_error_callback(self._on_fatal_error) + bridge.set_leaf_mismatch_callback(self._on_leaf_mismatch) + # Pre-rebuild hook: reset Homie accumulator before the bridge swaps + # paho clients, so retained messages on the new subscription start + # from a clean slate (no stale `$state=disconnected` cached from + # the original outage). + bridge.set_pre_rebuild_callback(self._on_pre_rebuild) + # create_span_client already fetched this to dispatch on; refetching # would be a second call to the same unauthenticated endpoint for a # value that cannot have changed. A directly-constructed client has no @@ -498,48 +543,12 @@ async def connect(self) -> None: self._schema_hash = new_hash self._previous_schema_types = schema.types - _LOGGER.debug( - "MQTT: Creating bridge to %s:%s (serial=%s)", - self._broker_config.broker_host, - self._broker_config.effective_port, - self._serial_number, - ) - - self._bridge = AsyncMqttBridge( - host=self._broker_config.broker_host, - port=self._broker_config.effective_port, - username=self._broker_config.username, - password=self._broker_config.password, - panel_host=self._host, - serial_number=self._serial_number, - transport=self._broker_config.transport, - use_tls=self._broker_config.use_tls, - loop=self._loop, - panel_http_port=self._panel_http_port, - ca_pem=self._broker_config.ca_pem, - ) - - # Wire message handler - self._bridge.set_message_callback(self._on_message) - self._bridge.set_connection_callback(self._on_connection_change) - self._bridge.set_fatal_error_callback(self._on_fatal_error) - self._bridge.set_leaf_mismatch_callback(self._on_leaf_mismatch) - # Pre-rebuild hook: reset Homie accumulator before the bridge swaps - # paho clients, so retained messages on the new subscription start - # from a clean slate (no stale `$state=disconnected` cached from - # the original outage). - self._bridge.set_pre_rebuild_callback(self._on_pre_rebuild) - - # Connect to broker + # Connect to broker. Its CONNACK is what subscribes the session, to the + # topics `_build_adapter` gave the bridge; nothing here subscribes again, + # since every SUBSCRIBE makes the broker replay the whole retained tree. _LOGGER.debug("MQTT: Connecting to broker...") - await self._bridge.connect() - _LOGGER.debug("MQTT: Broker connected, subscribing...") - - # Subscribe to all device topics - topics = self._require_adapter().topics_to_subscribe() - for topic in topics: - self._bridge.subscribe(topic, qos=0) - _LOGGER.debug("MQTT: Subscribed to %s, waiting for Homie ready...", topics) + await bridge.connect() + _LOGGER.debug("MQTT: Broker connected, waiting for Homie ready...") # Wait for Homie ready state try: @@ -1472,27 +1481,26 @@ def _on_message(self, topic: str, payload: str) -> None: def _on_connection_change(self, connected: bool) -> None: """Handle MQTT connection state change (called from asyncio loop). - Re-subscribes to the wildcard topic on reconnect (pre-existing - behavior), then fans out an edge-only notification to registered - connection callbacks. Duplicate state transitions are suppressed - so subscribers only see real edges. + Fans out an edge-only notification to registered connection + callbacks. Duplicate state transitions are suppressed so subscribers + only see real edges. + + Subscribing is not this handler's job. The bridge subscribes each + session on the CONNACK that opened it, before this runs, and + subscribing again here would not be harmless: the broker answers every + SUBSCRIBE by replaying the whole retained tree, so each one adds another + copy of the tree to the burst a connection receives. On disconnect, any pending snapshot-debounce timer is cancelled so a stale timer cannot dispatch a post-disconnect snapshot. """ - # Re-subscribe runs on every connected=True, including duplicates — - # paho may re-emit connected events after session restoration, and - # re-subscribing is broker-benign. Callback fan-out below is - # edge-only (see the guard after this block). if connected: _LOGGER.debug("MQTT connection established") - if self._bridge is not None and self._adapter is not None: - for topic in self._adapter.topics_to_subscribe(): - self._bridge.subscribe(topic, qos=0) # A reconnect can be a different panel generation than the one we - # dispatched on. Checked only on a real edge, because paho re-emits - # connected=True after session restoration and refetching the schema - # on each of those would be a HTTP round trip per duplicate. + # dispatched on. Checked only on a real edge: connected=True can repeat + # with no disconnect between, when paho's `reconnect()` replaces a + # socket without reporting one, and refetching the schema on each of + # those would be a HTTP round trip per duplicate. if not self._live: self._schedule_redispatch() else: @@ -1754,14 +1762,15 @@ async def _redispatch_once(self) -> None: # skips that branch, and would go on reporting the generation it started with # after having been rebuilt for a different one. self._data_model_version = schema.data_model_version - adapter = self._build_adapter(schema) + # The new parser has seen none of the tree, so it needs the replay a + # SUBSCRIBE brings. `_build_adapter` hands the bridge its topics, which on a + # live session subscribes them at once and drops the old generation's + # filter, and between sessions waits for the next CONNACK. + self._build_adapter(schema) # Ready is a property of the tree, and this is a different tree. Leaving the # old event set would let `is_ready()` answer for a parser that has not seen # a single message yet. self._ready_event = asyncio.Event() - if self._bridge is not None: - for topic in adapter.topics_to_subscribe(): - self._bridge.subscribe(topic, qos=0) # Announced after the swap, so a consumer inspecting the client from inside # the callback sees the generation it is being told about. Iterate a copy — @@ -1780,8 +1789,10 @@ def _on_pre_rebuild(self) -> None: old paho client is torn down and the new one is wired up. Discards any stale `$state=disconnected` cached during the outage so the new subscription's retained messages repopulate from a clean slate. - The fresh adapter is unsettled by construction, so nothing is - dispatched from it until its labels have passed the readiness gate. + The fresh adapter hands its topics to the bridge, which subscribes the + rebuilt client's session on its CONNACK. It is unsettled by + construction, so nothing is dispatched from it until its labels have + passed the readiness gate. Schema-derived state (`_schema`, `_schema_hash`, `_previous_schema_types`) is intentionally preserved — the Homie diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index 6846cae..c217fe5 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -10,7 +10,7 @@ from __future__ import annotations import asyncio -from collections.abc import Callable +from collections.abc import Callable, Sequence from functools import partial import logging import ssl @@ -114,6 +114,9 @@ def __init__( # `_resolve_pending_publishes` when the outbound queue ceases to exist. self._pending_publishes: dict[int, asyncio.Future[bool]] = {} + # What every session is subscribed to. See `set_subscriptions`. + self._subscriptions: tuple[str, ...] = () + self._connected = False self._client: AsyncMQTTClient | None = None self._connect_event: asyncio.Event | None = None @@ -546,10 +549,49 @@ async def disconnect(self) -> None: self._client = None self._initial_connect_done = False - def subscribe(self, topic: str, qos: int = 0) -> None: - """Subscribe to a topic. Must be called after connect().""" - if self._client is not None: - self._client.subscribe(topic, qos=qos) + def set_subscriptions(self, topics: Sequence[str]) -> None: + """Make `topics` the subscription of every session this bridge opens, replacing the last one. + + The bridge owns subscription because it is the one place that sees each + session begin. Every connection is a clean session, so the broker keeps + nothing from the one before, and `_on_connect` subscribes the set on each + CONNACK that accepts a connection -- the initial connect, each reconnect, + each rebuilt client. That is the only place a beginning session is + subscribed, so none is left without the subscription and none starts + with it twice. + + Twice would not be harmless. The broker answers a SUBSCRIBE for a filter + it already holds by replacing the subscription and sending every + retained message on it again, which for the panel's filter is its whole + tree. + + With no session up this only records the set, for the next CONNACK. On a + live session it subscribes every topic in the set now, one already held + included, then unsubscribes each topic that left. That is the call for a + new consumer of the tree: a parser built for another schema generation + has seen none of it, and the SUBSCRIBE is what delivers it. A topic that + left is unsubscribed because overlapping filters each deliver their own + copy of every message they share. + + Topics are subscribed at QoS 0. + """ + previous = self._subscriptions + self._subscriptions = tuple(dict.fromkeys(topics)) + client = self._client + if client is None or not self._connected: + return + self._subscribe_session(client) + departed = [topic for topic in previous if topic not in self._subscriptions] + if departed: + _LOGGER.debug("MQTT unsubscribing from %s", ", ".join(departed)) + client.unsubscribe(departed) + + def _subscribe_session(self, client: paho.Client) -> None: + """Send the subscription on `client`'s session, as one SUBSCRIBE.""" + if not self._subscriptions: + return + _LOGGER.debug("MQTT subscribing to %s", ", ".join(self._subscriptions)) + client.subscribe([(topic, 0) for topic in self._subscriptions]) def publish(self, topic: str, payload: str) -> asyncio.Future[bool] | None: """Hand one QoS-1 control message to paho, or refuse to hand it over. @@ -755,13 +797,21 @@ def _async_on_socket_unregister_write(self, _client: paho.Client, _userdata: obj def _on_connect( self, - _client: paho.Client, + client: paho.Client, _userdata: object, _flags: ConnectFlags, reason_code: ReasonCode, _properties: Properties | None, ) -> None: - """Handle CONNACK from broker.""" + """Handle CONNACK from broker. + + paho calls this once per CONNACK, and an accepted CONNACK is a new clean + session, so this is where each session is subscribed: once, on the client + whose session it is, and before anyone is told the broker is connected. + A CONNACK with no disconnect reported before it is still a new session -- + paho's `reconnect()` closes the socket it replaces without one -- so it is + subscribed like any other. + """ connected = not reason_code.is_failure self._connected = connected @@ -776,6 +826,7 @@ def _on_connect( if self._reconnect_task is not None: self._reconnect_task.cancel() self._reconnect_task = None + self._subscribe_session(client) else: self._connack_refusal = reason_code _LOGGER.warning("MQTT connection refused: %s", reason_code) @@ -906,10 +957,11 @@ async def _rebuild_client(self) -> bool: _LOGGER.debug("Old paho client disconnect raised", exc_info=True) # Build fresh client and assign it BEFORE the executor await so - # that a CONNACK arriving during the await sees the right client. - # Without this, the _on_connect → re-subscribe path would route - # through self._client which would still be the (disconnected) - # old_client, and the new client's subscription would never run. + # that a CONNACK arriving during the await finds it as the live + # client. `_on_connect` subscribes the client that sent the CONNACK + # whatever this holds, but `publish` and `set_subscriptions` act on + # a live session through `self._client`, and would otherwise reach + # the (disconnected) old_client. new_client = self._make_paho_client(ssl_context) new_client.on_socket_open = self._on_socket_open_sync new_client.on_socket_register_write = self._on_socket_register_write_sync diff --git a/tests/test_mqtt_bridge.py b/tests/test_mqtt_bridge.py index 9f125b0..8be4d14 100644 --- a/tests/test_mqtt_bridge.py +++ b/tests/test_mqtt_bridge.py @@ -52,11 +52,12 @@ def cb(connected: bool) -> None: class TestBridgeSubscribePublish: - """Verify subscribe/publish with no client are safe no-ops.""" + """Verify setting a subscription and publishing with no client are safe.""" - def test_subscribe_no_client(self) -> None: + def test_set_subscriptions_no_client(self) -> None: + """Recorded for the first CONNACK, with nothing to send it on yet.""" bridge = _make_bridge() - bridge.subscribe("test/topic") # Should not raise + bridge.set_subscriptions(["test/topic"]) # Should not raise def test_publish_no_client(self) -> None: bridge = _make_bridge() diff --git a/tests/test_mqtt_client_connection.py b/tests/test_mqtt_client_connection.py index d2cc27e..b4aa6e1 100644 --- a/tests/test_mqtt_client_connection.py +++ b/tests/test_mqtt_client_connection.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections.abc import Sequence import logging import pytest @@ -30,7 +31,8 @@ class _FakeBridge(AsyncMqttBridge): """Minimal bridge stub for get_snapshot() and fan-out tests. Bypasses AsyncMqttBridge.__init__ (which does TLS/CA/network setup) — - only is_connected() and subscribe() are invoked on this stub. + only is_connected() and set_subscriptions() are invoked on this stub, + and the second is recorded so a test can show it was not. """ def __init__(self, connected: bool = True) -> None: @@ -39,21 +41,22 @@ def __init__(self, connected: bool = True) -> None: # No terminal failure: get_snapshot() and ping() consult this before the # liveness checks, so a stub that omits it is a bridge with no answer. self._fatal_error = None - self.subscribed_topics: list[tuple[str, int]] = [] + self.subscriptions_set: list[list[str]] = [] def is_connected(self) -> bool: return self._connected - def subscribe(self, topic: str, qos: int = 0) -> None: - self.subscribed_topics.append((topic, qos)) + def set_subscriptions(self, topics: Sequence[str]) -> None: + self.subscriptions_set.append(list(topics)) class _FakeAdapter: - """Minimal SchemaAdapter stub for get_snapshot()/resubscribe tests. + """Minimal SchemaAdapter stub for get_snapshot() and connection-edge tests. Only the methods SpanMqttClient actually calls on the adapter are implemented: is_ready() and build_snapshot() for liveness/dispatch - tests, topics_to_subscribe() for resubscribe tests. + tests, topics_to_subscribe() so a handler that wrongly subscribed would + have topics to subscribe with. """ def __init__(self, ready: bool = True, snapshot: SpanPanelSnapshot | None = None) -> None: @@ -216,7 +219,12 @@ def second(_connected: bool) -> None: assert order == ["first", "second"] assert first not in client._connection_callbacks - def test_reconnect_triggers_resubscribe_and_callback(self) -> None: + def test_reconnect_notifies_without_subscribing(self) -> None: + """The bridge subscribed the session on its CONNACK; the notification asks for nothing more. + + Each SUBSCRIBE makes the broker replay the whole retained tree, so a + handler that subscribed here would double every reconnect's burst. + """ client = _make_client() bridge = _FakeBridge(connected=True) client._bridge = bridge @@ -227,18 +235,11 @@ def test_reconnect_triggers_resubscribe_and_callback(self) -> None: client._on_connection_change(True) - expected_topic = WILDCARD_TOPIC_FMT.format(serial="test-serial") - assert len(bridge.subscribed_topics) == 1 - assert bridge.subscribed_topics[0] == (expected_topic, 0) + assert bridge.subscriptions_set == [] assert calls == [True] - def test_resubscribe_fires_even_on_duplicate_true(self) -> None: - """Duplicate connected=True still triggers re-subscribe (intentional). - - Paho may re-emit connected events; re-subscribing is broker-benign - and ensures subscriptions survive session restoration. Callback - fan-out is separately edge-only. - """ + def test_duplicate_true_neither_subscribes_nor_notifies(self) -> None: + """A repeated connected=True is no edge for subscribers and no reason to subscribe.""" client = _make_client() bridge = _FakeBridge(connected=True) client._bridge = bridge @@ -249,8 +250,7 @@ def test_resubscribe_fires_even_on_duplicate_true(self) -> None: client._on_connection_change(True) - # Re-subscribe fires (side effect preserved) but no callback edge - assert len(bridge.subscribed_topics) == 1 + assert bridge.subscriptions_set == [] assert calls == [] diff --git a/tests/test_mqtt_connect_flow.py b/tests/test_mqtt_connect_flow.py index 0b8209e..3cc6e7d 100644 --- a/tests/test_mqtt_connect_flow.py +++ b/tests/test_mqtt_connect_flow.py @@ -235,12 +235,27 @@ async def test_span_client_connect_propagates_auth_error(self, mqtt_client_mock: class TestBridgeSubscribePublish: @pytest.mark.asyncio - async def test_subscribe_after_connect(self, mqtt_client_mock: MagicMock) -> None: + async def test_subscriptions_set_before_connect_are_sent_by_the_connack(self, mqtt_client_mock: MagicMock) -> None: bridge = _make_bridge() + bridge.set_subscriptions(["test/topic"]) + mqtt_client_mock.subscribe.assert_not_called() + await bridge.connect() - bridge.subscribe("test/topic", qos=1) - mqtt_client_mock.subscribe.assert_called_once_with("test/topic", qos=1) + mqtt_client_mock.subscribe.assert_called_once_with([("test/topic", 0)]) + + @pytest.mark.asyncio + async def test_subscriptions_set_on_a_live_session_are_sent_at_once(self, mqtt_client_mock: MagicMock) -> None: + """A new consumer on a live session is subscribed now, and a filter it no longer wants is dropped.""" + bridge = _make_bridge() + bridge.set_subscriptions(["old/topic"]) + await bridge.connect() + mqtt_client_mock.subscribe.reset_mock() + + bridge.set_subscriptions(["test/topic"]) + + mqtt_client_mock.subscribe.assert_called_once_with([("test/topic", 0)]) + mqtt_client_mock.unsubscribe.assert_called_once_with(["old/topic"]) @pytest.mark.asyncio async def test_publish_after_connect(self, mqtt_client_mock: MagicMock) -> None: @@ -580,9 +595,17 @@ async def test_reconnect_resubscribes(self, mqtt_client_mock: MagicMock) -> None mqtt_client_mock.subscribe.reset_mock() - # Simulate reconnection - client._on_connection_change(True) - mqtt_client_mock.subscribe.assert_called_once() + # Simulate reconnection: a fresh CONNACK, which opens a new clean session + bridge = client._bridge + assert bridge is not None + bridge._on_connect( + mqtt_client_mock, + None, + ConnectFlags(session_present=False), + ReasonCode(packetType=2, aName="Success"), + None, + ) + mqtt_client_mock.subscribe.assert_called_once_with([(f"{TOPIC_PREFIX_SERIAL}/#", 0)]) await client.close() @@ -1091,7 +1114,8 @@ async def test_client_assigned_before_executor_await( ) -> None: """The bridge's `_client` reference must point at the new client before the executor await — so a CONNACK arriving during the await - sees the right client when callbacks dispatch to bridge.subscribe.""" + finds it as the live client that `publish` and `set_subscriptions` + act through.""" monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.01) bridge = _make_bridge() await bridge.connect() diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py new file mode 100644 index 0000000..b6c92db --- /dev/null +++ b/tests/test_one_subscribe_per_session.py @@ -0,0 +1,410 @@ +"""Every broker session is subscribed exactly once, whichever path opened it. + +Under MQTT a SUBSCRIBE makes the broker deliver every retained message on its +filter, so each one is a replay of the panel's whole tree. A broker logging every +packet showed the initial connection send two identical SUBSCRIBEs and receive a +1,527-topic tree twice: one from the connection callback, one from `connect()`. + +The connection is clean-session, so the broker holds nothing from an earlier +session and every new one must be subscribed again -- once. These tests drive the +real `SpanMqttClient` and `AsyncMqttBridge` against a fake paho client and a fake +broker that behaves as mosquitto does: a SUBSCRIBE replays every retained message +on each of its filters, a publish is delivered once per matching filter, and a +subscribe or unsubscribe on a closed socket reaches nobody (paho answers it with +`MQTT_ERR_NO_CONN`). What they count is what the broker received on each session +and what it sent back, which is what the packet log measured. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import AsyncIterator, Callable +from dataclasses import dataclass, field +import ssl +from unittest.mock import patch + +from paho.mqtt.client import ConnectFlags, DisconnectFlags, MQTTMessage, topic_matches_sub +from paho.mqtt.enums import CallbackAPIVersion, MQTTErrorCode +from paho.mqtt.packettypes import PacketTypes +from paho.mqtt.properties import Properties +from paho.mqtt.reasoncodes import ReasonCode +import pytest + +from span_panel_api.models import V2HomieSchema +from span_panel_api.mqtt.client import SpanMqttClient +from span_panel_api.mqtt.models import MqttClientConfig, MqttTransport +from span_panel_api_schema_0.const import WILDCARD_TOPIC_FMT + +from conftest import MINIMAL_DESCRIPTION, SERIAL, TOPIC_PREFIX_SERIAL, flat_schema, parent_child_schema + +_FLAT_FILTER = WILDCARD_TOPIC_FMT.format(serial=SERIAL) +"""What the flat parser subscribes to: the panel's own device.""" + +_PARENT_CHILD_FILTER = "ebus/5/#" +"""What the parent/child parser subscribes to: every device, since children are the panel's peers.""" + +_DATA_MODEL_VERSION_TOPIC = f"{TOPIC_PREFIX_SERIAL}/info/data-model-version" + +_FLAT_TREE: dict[str, str] = { + f"{TOPIC_PREFIX_SERIAL}/$description": MINIMAL_DESCRIPTION, + f"{TOPIC_PREFIX_SERIAL}/$state": "ready", + **{f"{TOPIC_PREFIX_SERIAL}/core/property-{index}": str(index) for index in range(8)}, +} +"""A retained tree the flat parser reads as ready: described first, then `$state`.""" + + +@dataclass +class _Session: + """One network connection, as the broker saw it.""" + + subscribed: list[str] = field(default_factory=list) + """Each topic filter of each SUBSCRIBE received, in order.""" + unsubscribed: list[str] = field(default_factory=list) + delivered: list[str] = field(default_factory=list) + """The topic of every PUBLISH the broker sent on this session.""" + filters: list[str] = field(default_factory=list) + """The filters currently held for this session.""" + open: bool = True + + +ConnackHandler = Callable[["_FakePaho", object, ConnectFlags, ReasonCode, Properties | None], None] +DisconnectHandler = Callable[["_FakePaho", object, DisconnectFlags, ReasonCode, Properties | None], None] +MessageHandler = Callable[["_FakePaho", object, MQTTMessage], None] + + +class _Broker: + """The retained tree, the sessions opened against it, and the clients that opened them.""" + + def __init__(self, loop: asyncio.AbstractEventLoop, retained: dict[str, str]) -> None: + self.loop = loop + self.retained = dict(retained) + self.sessions: list[_Session] = [] + self.clients: list[_FakePaho] = [] + self.refusing = False + """While set, every connect and reconnect is refused, as a broker that is down refuses them.""" + self.pending = 0 + """Deliveries scheduled and not yet made.""" + + def client( + self, *, callback_api_version: CallbackAPIVersion, transport: MqttTransport, reconnect_on_failure: bool + ) -> _FakePaho: + """Stands in for `AsyncMQTTClient(...)`: the bridge builds one per connect and per rebuild.""" + assert callback_api_version is CallbackAPIVersion.VERSION2 + assert transport == "tcp" + assert reconnect_on_failure is False + built = _FakePaho(self) + self.clients.append(built) + return built + + def open_session(self) -> _Session: + session = _Session() + self.sessions.append(session) + return session + + def subscribe(self, client: _FakePaho, session: _Session, filters: list[str]) -> None: + for topic_filter in filters: + session.subscribed.append(topic_filter) + if topic_filter not in session.filters: + session.filters.append(topic_filter) + for topic, payload in self.retained.items(): + if topic_matches_sub(topic_filter, topic): + self._schedule(client, session, topic, payload) + + def unsubscribe(self, session: _Session, filters: list[str]) -> None: + for topic_filter in filters: + session.unsubscribed.append(topic_filter) + if topic_filter in session.filters: + session.filters.remove(topic_filter) + + def publish(self, topic: str, payload: str) -> None: + """A retained publish from the panel, delivered once per matching filter of every open session.""" + self.retained[topic] = payload + for client in self.clients: + session = client.session + if session is None or not session.open: + continue + for topic_filter in session.filters: + if topic_matches_sub(topic_filter, topic): + self._schedule(client, session, topic, payload) + + def _schedule(self, client: _FakePaho, session: _Session, topic: str, payload: str) -> None: + self.pending += 1 + self.loop.call_soon_threadsafe(self._deliver, client, session, topic, payload) + + def _deliver(self, client: _FakePaho, session: _Session, topic: str, payload: str) -> None: + self.pending -= 1 + if not session.open or client.on_message is None: + return + session.delivered.append(topic) + message = MQTTMessage(topic=topic.encode("utf-8")) + message.payload = payload.encode("utf-8") + client.on_message(client, None, message) + + +class _FakePaho: + """The slice of paho the bridge drives, opening sessions on a `_Broker` instead of a socket.""" + + def __init__(self, broker: _Broker) -> None: + self._broker = broker + self.session: _Session | None = None + self.next_reconnect_error: OSError | ssl.SSLError | None = None + self.on_connect: ConnackHandler | None = None + self.on_disconnect: DisconnectHandler | None = None + self.on_message: MessageHandler | None = None + # Assigned by the bridge and never called: no real socket is opened. + self.on_publish: object = None + self.on_socket_open: object = None + self.on_socket_close: object = None + self.on_socket_register_write: object = None + self.on_socket_unregister_write: object = None + + def setup(self) -> None: + """The lock swap `AsyncMQTTClient` does; nothing to swap here.""" + + def username_pw_set(self, username: str, password: str | None = None) -> None: + """Credentials are not checked by this broker.""" + + def connect(self, host: str, port: int = 1883, keepalive: int = 60) -> MQTTErrorCode: + """Open a session and schedule its CONNACK, as paho's executor connect does.""" + assert host and port > 0 and keepalive > 0 + self._open() + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def reconnect(self) -> MQTTErrorCode: + """paho closes the previous socket without reporting a disconnect, then opens another.""" + error = self.next_reconnect_error + self.next_reconnect_error = None + self._close() + if error is not None: + raise error + self._open() + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def subscribe(self, topic: str | list[tuple[str, int]], qos: int = 0) -> tuple[MQTTErrorCode, int | None]: + assert qos == 0 + session = self.session + if session is None or not session.open: + return (MQTTErrorCode.MQTT_ERR_NO_CONN, None) + self._broker.subscribe(self, session, [topic] if isinstance(topic, str) else [name for name, _ in topic]) + return (MQTTErrorCode.MQTT_ERR_SUCCESS, 1) + + def unsubscribe(self, topic: str | list[str]) -> tuple[MQTTErrorCode, int | None]: + session = self.session + if session is None or not session.open: + return (MQTTErrorCode.MQTT_ERR_NO_CONN, None) + self._broker.unsubscribe(session, [topic] if isinstance(topic, str) else list(topic)) + return (MQTTErrorCode.MQTT_ERR_SUCCESS, 1) + + def disconnect(self) -> MQTTErrorCode: + self._close() + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def drop(self) -> None: + """The network goes away under an open session: paho closes the socket and reports it.""" + self._close() + if self.on_disconnect is not None: + self.on_disconnect( + self, + None, + DisconnectFlags(is_disconnect_packet_from_server=False), + ReasonCode(PacketTypes.DISCONNECT, "Unspecified error"), + None, + ) + + def _open(self) -> None: + if self._broker.refusing: + raise ConnectionRefusedError(61, "Connection refused") + session = self._broker.open_session() + self.session = session + self._broker.loop.call_soon_threadsafe(self._connack, session) + + def _connack(self, session: _Session) -> None: + if session is not self.session or not session.open or self.on_connect is None: + return + self.on_connect(self, None, ConnectFlags(session_present=False), ReasonCode(PacketTypes.CONNACK, "Success"), None) + + def _close(self) -> None: + if self.session is not None: + self.session.open = False + + +@dataclass +class _Panel: + client: SpanMqttClient + broker: _Broker + + async def until(self, condition: Callable[[], bool], what: str, timeout: float = 10.0) -> None: + deadline = self.broker.loop.time() + timeout + while not condition(): + if self.broker.loop.time() > deadline: + raise AssertionError(f"timed out waiting for {what}") + await asyncio.sleep(0.01) + + async def quiesce(self) -> None: + """Wait until every delivery the broker scheduled has been made and handled.""" + await self.until(lambda: self.broker.pending == 0, "the broker's deliveries") + for _ in range(5): + await asyncio.sleep(0) + + +@pytest.fixture +async def panel(monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[_Panel]: + """A connected-on-demand client on a plaintext broker serving `_FLAT_TREE`.""" + # Short enough that a refused reconnect is retried inside a test's patience. + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.01) + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + client = SpanMqttClient( + host="192.168.1.1", + serial_number=SERIAL, + broker_config=MqttClientConfig(broker_host="broker.local", username="u", password="p", use_tls=False), + schema=flat_schema(), + ) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + yield _Panel(client, broker) + await client.close() + + +async def _connected(panel: _Panel) -> _Session: + await panel.client.connect() + await panel.quiesce() + [session] = panel.broker.sessions + return session + + +@pytest.mark.asyncio +async def test_connect_subscribes_once_and_receives_the_tree_once(panel: _Panel) -> None: + """The defect as measured: the first connection asked for the tree twice and got it twice.""" + session = await _connected(panel) + + assert session.subscribed == [_FLAT_FILTER] + assert sorted(session.delivered) == sorted(_FLAT_TREE) + + +@pytest.mark.asyncio +async def test_a_repeated_connection_notification_does_not_resubscribe(panel: _Panel) -> None: + """Being told again that the broker is connected is not a new session. + + Subscription belongs to the CONNACK that opened the session, so a connection + notification on its own -- the edge a consumer is told about -- asks the broker + for nothing. + """ + session = await _connected(panel) + subscribed = list(session.subscribed) + delivered = len(session.delivered) + + panel.client._on_connection_change(True) + await panel.quiesce() + + assert session.subscribed == subscribed + assert len(session.delivered) == delivered + + +@pytest.mark.asyncio +async def test_a_session_paho_replaces_without_a_disconnect_is_subscribed_once(panel: _Panel) -> None: + """A CONNACK with no disconnect before it is still a new session, and needs the subscription. + + paho's `reconnect()` closes the socket it had without reporting a disconnect, + so two connected events in a row can each be a session of their own. The clean + session holds nothing over, so suppressing the second would leave the + connection live and silent. + """ + await _connected(panel) + [paho] = panel.broker.clients + + paho.reconnect() + await panel.until(lambda: len(panel.broker.sessions) == 2, "the replacement session") + await panel.quiesce() + + second = panel.broker.sessions[1] + assert second.subscribed == [_FLAT_FILTER] + assert sorted(second.delivered) == sorted(_FLAT_TREE) + + +@pytest.mark.asyncio +async def test_a_reconnect_subscribes_its_session_once(panel: _Panel) -> None: + """A dropped connection comes back subscribed, once, and serving again.""" + await _connected(panel) + [paho] = panel.broker.clients + + paho.drop() + await panel.until(lambda: len(panel.broker.sessions) == 2, "the reconnected session") + await panel.quiesce() + + reconnected = panel.broker.sessions[1] + assert reconnected.subscribed == [_FLAT_FILTER] + assert sorted(reconnected.delivered) == sorted(_FLAT_TREE) + assert await panel.client.ping() is True + + +@pytest.mark.asyncio +async def test_a_rebuilt_client_subscribes_its_session_once(panel: _Panel) -> None: + """The rebuild path replaces paho and the parser; the new session is subscribed once and the new parser is fed.""" + await _connected(panel) + [old] = panel.broker.clients + old_parser = panel.client.adapter + old.next_reconnect_error = ssl.SSLError("handshake failed") + + old.drop() + await panel.until(lambda: len(panel.broker.sessions) == 2, "the rebuilt client's session") + await panel.quiesce() + + rebuilt = panel.broker.sessions[1] + assert [built.session for built in panel.broker.clients] == [panel.broker.sessions[0], rebuilt] + assert rebuilt.subscribed == [_FLAT_FILTER] + assert sorted(rebuilt.delivered) == sorted(_FLAT_TREE) + parser = panel.client.adapter + assert parser is not None and parser is not old_parser + assert parser.is_ready() + + +@pytest.mark.asyncio +async def test_a_generation_swap_moves_the_live_session_to_the_new_parsers_filter(panel: _Panel) -> None: + """The new parser has seen none of the tree, so it is subscribed for it once, and the old filter is dropped. + + Left subscribed, the flat parser's filter overlaps the parent/child one, and the + broker delivers every message under the panel's device once per matching + filter: every reading twice until the next reconnect. + """ + session = await _connected(panel) + subscribed = len(session.subscribed) + + with patch("span_panel_api.mqtt.client.get_homie_schema", return_value=parent_child_schema()): + panel.broker.publish(_DATA_MODEL_VERSION_TOPIC, "1.0") + await panel.until(lambda: panel.client.data_model_version == "1.0", "the parser swap") + await panel.quiesce() + + assert session.subscribed[subscribed:] == [_PARENT_CHILD_FILTER] + assert session.unsubscribed == [_FLAT_FILTER] + assert session.filters == [_PARENT_CHILD_FILTER] + + delivered = len(session.delivered) + panel.broker.publish(f"{TOPIC_PREFIX_SERIAL}/core/property-0", "changed") + await panel.quiesce() + assert session.delivered[delivered:] == [f"{TOPIC_PREFIX_SERIAL}/core/property-0"] + + +@pytest.mark.asyncio +async def test_a_swap_finished_while_disconnected_is_subscribed_by_the_next_session(panel: _Panel) -> None: + """Nothing is lost when the swap lands between sessions: the next one subscribes the new parser's filter, once.""" + await _connected(panel) + [paho] = panel.broker.clients + release = asyncio.Event() + + async def schema_once_released(*_args: object, **_kwargs: object) -> V2HomieSchema: + await release.wait() + return parent_child_schema() + + with patch("span_panel_api.mqtt.client.get_homie_schema", side_effect=schema_once_released): + panel.broker.publish(_DATA_MODEL_VERSION_TOPIC, "1.0") + await panel.quiesce() + panel.broker.refusing = True + paho.drop() + release.set() + await panel.until(lambda: panel.client.data_model_version == "1.0", "the parser swap") + assert len(panel.broker.sessions) == 1 + panel.broker.refusing = False + await panel.until(lambda: len(panel.broker.sessions) == 2, "the reconnected session") + await panel.quiesce() + + reconnected = panel.broker.sessions[1] + assert reconnected.subscribed == [_PARENT_CHILD_FILTER] diff --git a/tests/test_redispatch_on_reconnect.py b/tests/test_redispatch_on_reconnect.py index 553b0f3..26e654f 100644 --- a/tests/test_redispatch_on_reconnect.py +++ b/tests/test_redispatch_on_reconnect.py @@ -24,7 +24,7 @@ from __future__ import annotations -from collections.abc import Callable +from collections.abc import Callable, Sequence import asyncio from typing import Any @@ -85,11 +85,13 @@ def register_property_callback(self, callback: Callable[[str, str, str, str | No class _Bridge: + """Records the subscription the client hands the bridge.""" + def __init__(self) -> None: - self.subscribed: list[str] = [] + self.subscriptions: list[str] = [] - def subscribe(self, topic: str, qos: int = 0) -> None: - self.subscribed.append(topic) + def set_subscriptions(self, topics: Sequence[str]) -> None: + self.subscriptions = list(topics) def _client(initial: str | None) -> tuple[SpanMqttClient, _Bridge]: @@ -148,7 +150,7 @@ async def test_the_new_parsers_topics_are_subscribed() -> None: with patch("span_panel_api.mqtt.client.get_homie_schema", return_value=_Schema("1.0")): await _panel_publishes_version(client, "1.0") - assert "topics/for/1.0" in bridge.subscribed + assert bridge.subscriptions == ["topics/for/1.0"] @pytest.mark.asyncio From cc80bbb863b2617286a36bbf16823d50925a80c7 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:54:06 -0800 Subject: [PATCH 05/33] fix(mqtt): stop a closed connect() and refuse malformed subscriptions connect() now creates its bridge before the parser, so a close() that landed while it was suspended dropped the client's only reference to that bridge, and connect() went on to connect it: before the parser was built the session carried no subscription, connect() timed out waiting for a tree that never came, and the bridge stayed connected with its reconnect loop armed and nothing left to close it. connect() now checks, before building the parser, before connecting the bridge, when that connect fails or returns, when the wait for the panel times out, and before returning, that the client still holds its bridge, and otherwise disconnects it and raises SpanPanelConnectionError. In 3.8.0 the same close() was undone instead, connect() carrying on to connect the client it had been asked to close. set_subscriptions refuses a bare string, which a Sequence[str] admits and which would subscribe one filter per character, and refuses any filter MQTT 3.1.1 does not accept, in the caller's frame and before anything is recorded, rather than at the next CONNACK, where paho's refusal escapes the read callback and the connect times out. The parser is installed only once the bridge has accepted its topics. A swap landing between a CONNECT and its CONNACK is now pinned as subscribed once, by the CONNACK. --- CHANGELOG.md | 1 + src/span_panel_api/mqtt/client.py | 66 ++++- src/span_panel_api/mqtt/connection.py | 52 +++- tests/test_one_subscribe_per_session.py | 374 +++++++++++++++++++++++- 4 files changed, 471 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ab2448..2f8751f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ beta corrected in an earlier beta does not appear at all: from the point of view - **Each broker connection subscribes once, so the panel's retained tree arrives once per connection**, where `connect()` subscribed twice and received the whole tree twice, and a panel that changes schema generation while connected no longer has every message under its own device delivered twice until the next reconnect. +- **`connect()` raises `SpanPanelConnectionError` when `close()` is called while it is connecting**, where it could carry on and return as if connected, or wait for the panel and report a timeout. ## [3.8.0] diff --git a/src/span_panel_api/mqtt/client.py b/src/span_panel_api/mqtt/client.py index 1b23f12..d75a9cb 100644 --- a/src/span_panel_api/mqtt/client.py +++ b/src/span_panel_api/mqtt/client.py @@ -321,9 +321,15 @@ def _build_adapter(self, schema: V2HomieSchema) -> SchemaAdapter: Handing the topics to the bridge here, rather than at each caller, is what ties a subscription to every parser: the bridge subscribes each session to them on its CONNACK, and a live session at once, which is how - a parser swapped in mid-session receives the tree it has not seen. The - bridge exists before the first parser is built (see connect()), so no - parser goes without. + a parser swapped in mid-session receives the tree it has not seen. They + are handed over before the parser is installed, so topics the bridge + refuses leave the previous parser and its subscription in place. + + connect() creates the bridge before building the first parser, and + gives up rather than connect a bridge that close() let go of while + connect() was suspended (see `_stop_if_closed`). Between them, no + session opens without the topics of the parser it feeds. A parser built + after close() has no bridge to hand them to, and none is needed. With no injected factory this dispatches on the schema rather than assuming the flat adapter. That matters because a client can be built @@ -344,6 +350,8 @@ def _build_adapter(self, schema: V2HomieSchema) -> SchemaAdapter: whose schema major cannot be determined. SpanPanelAdapterMissingError: No adapter_factory was supplied and no installed package registers the key this panel needs. + ValueError: The parser names a topic that is not a valid MQTT + topic filter (see `AsyncMqttBridge.set_subscriptions`). """ factory = self._adapter_factory if factory is None: @@ -352,10 +360,10 @@ def _build_adapter(self, schema: V2HomieSchema) -> SchemaAdapter: self._schema_dispatch_reason = dispatch_reason factory = resolve_adapter(adapter_key, dispatch_reason) adapter = factory(self._serial_number, schema) - self._adapter = adapter - self._observe(adapter) if self._bridge is not None: self._bridge.set_subscriptions(adapter.topics_to_subscribe()) + self._adapter = adapter + self._observe(adapter) return adapter @property @@ -461,9 +469,17 @@ async def connect(self) -> None: 4. Connect to MQTT broker, whose CONNACK the bridge subscribes on 5. Wait for $state==ready and $description parsed + close() may land while this is suspended at any of its awaits. It then + stops before the next of its steps -- building the parser, connecting + the bridge, waiting on the panel, returning -- rather than go on to + connect a bridge nothing can close or report a connection the caller + has already closed (see `_stop_if_closed`). A close() during the wait + for the panel is noticed when that wait ends. + Raises: SpanPanelAuthError: The broker refused the credentials - SpanPanelConnectionError: Cannot connect or device not ready + SpanPanelConnectionError: Cannot connect, device not ready, or + close() was called while connecting SpanPanelTimeoutError: Connection or ready timed out """ self._loop = asyncio.get_running_loop() @@ -510,6 +526,10 @@ async def connect(self) -> None: schema = self._schema if self._schema is not None else await self._fetch_schema() self._schema = schema await self._preload_adapter(schema) + # After both awaits the build waits on, with none between this and the + # build, so the parser's topics go to this bridge and a client closed + # before it had a parser does not grow one. + await self._stop_if_closed(bridge) adapter = self._build_adapter(schema) # Both halves of this line read distribution metadata off disk, and both @@ -521,6 +541,7 @@ async def connect(self) -> None: # Threaded on their own account rather than relying on the preload above, # which skips discovery entirely when a factory was injected. installed, library_version = await asyncio.to_thread(_metadata_for_the_log) + await self._stop_if_closed(bridge) _LOGGER.info( "MQTT adapter selected: %s (span-panel-api %s)\n data-model-version: %r\n reason: %s\n installed: %s", adapter.schema_major, @@ -547,13 +568,23 @@ async def connect(self) -> None: # topics `_build_adapter` gave the bridge; nothing here subscribes again, # since every SUBSCRIBE makes the broker replay the whole retained tree. _LOGGER.debug("MQTT: Connecting to broker...") - await bridge.connect() + try: + await bridge.connect() + except SpanPanelError: + # A connect that close() cut short reports the close, not the failure + # the close caused. + await self._stop_if_closed(bridge) + raise + await self._stop_if_closed(bridge) _LOGGER.debug("MQTT: Broker connected, waiting for Homie ready...") # Wait for Homie ready state try: await asyncio.wait_for(self._ready_event.wait(), timeout=MQTT_READY_TIMEOUT_S) except TimeoutError as exc: + # A close() during the wait is why nothing arrived, and the bridge to + # tear down is this one, whatever the client holds by now. + await self._stop_if_closed(bridge) await self.close() raise SpanPanelConnectionError(f"Timed out waiting for Homie device ready ({self._serial_number})") from exc @@ -565,15 +596,36 @@ async def connect(self) -> None: # caller can take carries them. # `wait` rather than awaiting the task: `close()` cancels it, and that must # end this wait rather than surface here as a cancellation of connect(). + # The close is then reported as one, below. settle = self._settle_task if settle is not None: await asyncio.wait([settle]) if not settle.cancelled(): settle.result() + await self._stop_if_closed(bridge) self._assert_transports_agree_on_schema_generation() _LOGGER.debug("MQTT: Connection fully established") + async def _stop_if_closed(self, bridge: AsyncMqttBridge) -> None: + """End connect() if close() let go of `bridge` while connect() was suspended. + + close() disconnects the bridge it finds and drops it, and a connect() + suspended at that moment holds the only other reference. Going on would + connect it: a session nobody reads, its reconnect loop armed, that no + later close() can reach -- and, before the parser is built, one with no + subscription at all. So this disconnects `bridge`, which is harmless + when close() already has, and raises rather than let connect() report a + connection the caller has closed. + + Raises: + SpanPanelConnectionError: close() was called while connecting. + """ + if self._bridge is bridge: + return + await bridge.disconnect() + raise SpanPanelConnectionError(f"Closed while connecting ({self._serial_number})") + def _assert_transports_agree_on_schema_generation(self) -> None: """Refuse a panel whose two schema-generation signals disagree. diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index c217fe5..cde8964 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -55,6 +55,32 @@ # return codes 4 and 5 as these same MQTT 5 reason codes. _CONNACK_AUTH_REFUSALS = frozenset({0x86, 0x87}) +# The longest UTF-8 string an MQTT packet can carry (MQTT 3.1.1, section 1.5.3). +_MQTT_MAX_STRING_BYTES = 65535 + + +def _check_topic_filter(topic: str) -> None: + """Refuse what MQTT 3.1.1 does not accept as a topic filter (section 4.7). + + A filter is at least one character, carries no null character, and fits an + MQTT string. `#` is a whole level and the last one; `+` is a whole level. + + Raises: + ValueError: `topic` is not a valid topic filter, saying why. + """ + if not topic: + raise ValueError("A topic filter cannot be empty") + if "\x00" in topic: + raise ValueError(f"Topic filter {topic!r} contains a null character") + if len(topic.encode("utf-8")) > _MQTT_MAX_STRING_BYTES: + raise ValueError(f"Topic filter {topic[:40]!r}... is longer than the {_MQTT_MAX_STRING_BYTES} bytes MQTT allows") + levels = topic.split("/") + for index, level in enumerate(levels): + if "#" in level and (level != "#" or index != len(levels) - 1): + raise ValueError(f"Topic filter {topic!r} uses '#' other than as its whole last level") + if "+" in level and level != "+": + raise ValueError(f"Topic filter {topic!r} uses '+' other than as a whole level") + class AsyncMqttBridge: """Event-loop-driven paho-mqtt wrapper with async callback dispatch. @@ -573,10 +599,32 @@ def set_subscriptions(self, topics: Sequence[str]) -> None: left is unsubscribed because overlapping filters each deliver their own copy of every message they share. - Topics are subscribed at QoS 0. + Live means the CONNACK has arrived, not merely that a socket is open: paho + sends a SUBSCRIBE on a socket still waiting for its CONNACK, and that + CONNACK would then subscribe the session a second time. + + Topics are subscribed at QoS 0. Call this on the event loop, like every + other call into this bridge: paho runs there with its locks removed (see + `AsyncMQTTClient`), so a call from another thread would race it. + + Raises: + TypeError: `topics` is one string. It is a `Sequence[str]` to the + type checker, and read as one would subscribe each character + as a filter of its own. + ValueError: A topic is not a valid MQTT topic filter. Refused here, + before anything is recorded. Accepted, it would fail only at + the next CONNACK, inside `_on_connect`: paho's own refusal + escapes the read callback there and the connect it belongs to + times out, and a null character, which paho does not check, is + one MQTT requires the broker to close the connection over. """ + if isinstance(topics, str): + raise TypeError(f"set_subscriptions takes a sequence of topic filters, not one string: {topics!r}") + wanted = tuple(dict.fromkeys(topics)) + for topic in wanted: + _check_topic_filter(topic) previous = self._subscriptions - self._subscriptions = tuple(dict.fromkeys(topics)) + self._subscriptions = wanted client = self._client if client is None or not self._connected: return diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index b6c92db..864faeb 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -19,8 +19,10 @@ import asyncio from collections.abc import AsyncIterator, Callable +import contextlib from dataclasses import dataclass, field import ssl +import threading from unittest.mock import patch from paho.mqtt.client import ConnectFlags, DisconnectFlags, MQTTMessage, topic_matches_sub @@ -30,12 +32,24 @@ from paho.mqtt.reasoncodes import ReasonCode import pytest +from span_panel_api.adapters import resolve_adapter +from span_panel_api.exceptions import SpanPanelConnectionError from span_panel_api.models import V2HomieSchema from span_panel_api.mqtt.client import SpanMqttClient +from span_panel_api.mqtt.connection import AsyncMqttBridge from span_panel_api.mqtt.models import MqttClientConfig, MqttTransport +from span_panel_api.protocol import SchemaAdapter +from span_panel_api_schema_0.adapter import SchemaZeroAdapter from span_panel_api_schema_0.const import WILDCARD_TOPIC_FMT -from conftest import MINIMAL_DESCRIPTION, SERIAL, TOPIC_PREFIX_SERIAL, flat_schema, parent_child_schema +from conftest import ( + DESCRIPTION_WITH_CIRCUIT, + MINIMAL_DESCRIPTION, + SERIAL, + TOPIC_PREFIX_SERIAL, + flat_schema, + parent_child_schema, +) _FLAT_FILTER = WILDCARD_TOPIC_FMT.format(serial=SERIAL) """What the flat parser subscribes to: the panel's own device.""" @@ -82,9 +96,18 @@ def __init__(self, loop: asyncio.AbstractEventLoop, retained: dict[str, str]) -> self.clients: list[_FakePaho] = [] self.refusing = False """While set, every connect and reconnect is refused, as a broker that is down refuses them.""" + self.holding_connacks = False + """While set, a session opens without its CONNACK, which waits in `held` for `release_connacks`.""" + self.held: list[tuple[_FakePaho, _Session]] = [] self.pending = 0 """Deliveries scheduled and not yet made.""" + def release_connacks(self) -> None: + self.holding_connacks = False + held, self.held = self.held, [] + for client, session in held: + self.loop.call_soon_threadsafe(client.connack, session) + def client( self, *, callback_api_version: CallbackAPIVersion, transport: MqttTransport, reconnect_on_failure: bool ) -> _FakePaho: @@ -164,6 +187,9 @@ def setup(self) -> None: def username_pw_set(self, username: str, password: str | None = None) -> None: """Credentials are not checked by this broker.""" + def tls_set_context(self, context: ssl.SSLContext | None = None) -> None: + """TLS is not negotiated with this broker.""" + def connect(self, host: str, port: int = 1883, keepalive: int = 60) -> MQTTErrorCode: """Open a session and schedule its CONNACK, as paho's executor connect does.""" assert host and port > 0 and keepalive > 0 @@ -216,9 +242,13 @@ def _open(self) -> None: raise ConnectionRefusedError(61, "Connection refused") session = self._broker.open_session() self.session = session - self._broker.loop.call_soon_threadsafe(self._connack, session) + if self._broker.holding_connacks: + self._broker.held.append((self, session)) + return + self._broker.loop.call_soon_threadsafe(self.connack, session) - def _connack(self, session: _Session) -> None: + def connack(self, session: _Session) -> None: + """The broker's answer to the CONNECT that opened `session`, if that session is still this client's.""" if session is not self.session or not session.open or self.on_connect is None: return self.on_connect(self, None, ConnectFlags(session_present=False), ReasonCode(PacketTypes.CONNACK, "Success"), None) @@ -247,21 +277,52 @@ async def quiesce(self) -> None: await asyncio.sleep(0) -@pytest.fixture -async def panel(monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[_Panel]: - """A connected-on-demand client on a plaintext broker serving `_FLAT_TREE`.""" - # Short enough that a refused reconnect is retried inside a test's patience. - monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.01) - broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) +@contextlib.asynccontextmanager +async def _serving(tree: dict[str, str], schema: V2HomieSchema | None, use_tls: bool = False) -> AsyncIterator[_Panel]: + """A client, connected on demand, on a broker serving `tree`. + + With no `schema` the client fetches one at connect, as a directly constructed + client does. With `use_tls` it has no pinned CA, so its bridge fetches one + from the panel on every connect. + """ + broker = _Broker(asyncio.get_running_loop(), tree) client = SpanMqttClient( host="192.168.1.1", serial_number=SERIAL, - broker_config=MqttClientConfig(broker_host="broker.local", username="u", password="p", use_tls=False), - schema=flat_schema(), + broker_config=MqttClientConfig(broker_host="broker.local", username="u", password="p", use_tls=use_tls), + schema=schema, ) with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): - yield _Panel(client, broker) - await client.close() + try: + yield _Panel(client, broker) + finally: + await client.close() + + +def _bridge() -> AsyncMqttBridge: + """A bare bridge for the broker `AsyncMQTTClient` is patched to.""" + return AsyncMqttBridge( + host="broker.local", + port=1883, + username="u", + password="p", + panel_host="192.168.1.1", + serial_number=SERIAL, + use_tls=False, + ) + + +@pytest.fixture(autouse=True) +def _quick_reconnects(monkeypatch: pytest.MonkeyPatch) -> None: + """Short enough that a refused reconnect is retried inside a test's patience.""" + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.01) + + +@pytest.fixture +async def panel() -> AsyncIterator[_Panel]: + """A connected-on-demand client on a plaintext broker serving `_FLAT_TREE`.""" + async with _serving(_FLAT_TREE, flat_schema()) as served: + yield served async def _connected(panel: _Panel) -> _Session: @@ -408,3 +469,290 @@ async def schema_once_released(*_args: object, **_kwargs: object) -> V2HomieSche reconnected = panel.broker.sessions[1] assert reconnected.subscribed == [_PARENT_CHILD_FILTER] + + +@pytest.mark.asyncio +async def test_a_swap_between_connect_and_connack_is_subscribed_once_by_the_connack( + panel: _Panel, monkeypatch: pytest.MonkeyPatch +) -> None: + """A parser installed after a CONNECT and before its CONNACK waits for the CONNACK. + + paho sends a SUBSCRIBE on any open socket, including one still waiting for its + CONNACK, and the CONNACK then subscribes the session again. So a session is + live, for the bridge, only once its CONNACK has arrived. + """ + # One reconnect attempt and then a long pause, so no second CONNECT overtakes the held CONNACK. + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 5.0) + await _connected(panel) + [paho] = panel.broker.clients + release = asyncio.Event() + + async def schema_once_released(*_args: object, **_kwargs: object) -> V2HomieSchema: + await release.wait() + return parent_child_schema() + + with patch("span_panel_api.mqtt.client.get_homie_schema", side_effect=schema_once_released): + panel.broker.publish(_DATA_MODEL_VERSION_TOPIC, "1.0") + await panel.quiesce() + panel.broker.holding_connacks = True + paho.drop() + await panel.until(lambda: len(panel.broker.sessions) == 2, "the reconnect's CONNECT") + awaiting = panel.broker.sessions[1] + release.set() + await panel.until(lambda: panel.client.data_model_version == "1.0", "the parser swap") + assert awaiting.subscribed == [], "nothing may be subscribed before the CONNACK" + panel.broker.release_connacks() + await panel.until(lambda: bool(awaiting.subscribed), "the CONNACK's SUBSCRIBE") + await panel.quiesce() + + assert awaiting.subscribed == [_PARENT_CHILD_FILTER] + + +@pytest.mark.asyncio +async def test_one_string_is_refused_rather_than_read_as_one_filter_per_character() -> None: + """A `str` is a `Sequence[str]` to the type checker, and would subscribe `e`, `b`, ..., `#`.""" + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + bridge.set_subscriptions([_FLAT_FILTER]) + + with pytest.raises(TypeError, match="not one string"): + bridge.set_subscriptions(_PARENT_CHILD_FILTER) + + await bridge.connect() + await bridge.disconnect() + + assert broker.sessions[0].subscribed == [_FLAT_FILTER], "a refused call changes nothing" + + +@pytest.mark.parametrize( + "topic_filter", + [ + pytest.param("", id="empty"), + pytest.param("ebus/5/#/core", id="hash-not-last"), + pytest.param("ebus/5#", id="hash-inside-a-level"), + pytest.param("ebus/+5/core", id="plus-inside-a-level"), + pytest.param("ebus/5/\x00", id="null-character"), + pytest.param("e" * 65536, id="longer-than-mqtt-allows"), + ], +) +@pytest.mark.asyncio +async def test_a_malformed_filter_is_refused_where_it_is_set(topic_filter: str) -> None: + """Refused in the caller's frame, before anything is recorded. + + Accepted, it would reach paho only at the next CONNACK, inside `_on_connect`, + where paho's own refusal escapes the read callback and the connect it belongs + to waits out its timeout instead. + """ + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + bridge.set_subscriptions([_FLAT_FILTER]) + + with pytest.raises(ValueError, match="(?i)topic filter"): + bridge.set_subscriptions([_PARENT_CHILD_FILTER, topic_filter]) + + await bridge.connect() + await bridge.disconnect() + + assert broker.sessions[0].subscribed == [_FLAT_FILTER], "a refused call changes nothing" + + +@pytest.mark.asyncio +async def test_every_well_formed_filter_is_accepted() -> None: + """The check refuses what MQTT refuses, and nothing more.""" + filters = ["#", "+", "+/+/#", "ebus/5/+/$state", "/", "ebus//5"] + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + bridge.set_subscriptions(filters) + await bridge.connect() + await bridge.disconnect() + + assert broker.sessions[0].subscribed == filters + + +async def _close_while_connect_waits(panel: _Panel, waiting: Callable[[], bool], resume: Callable[[], None]) -> None: + """Start connect(), close the client once `waiting` says connect() is suspended, then let it resume. + + However far connect() had got, it must not report a connection the caller + has already closed. + """ + connecting = asyncio.create_task(panel.client.connect()) + await panel.until(waiting, "connect() to suspend") + await panel.client.close() + resume() + with pytest.raises(SpanPanelConnectionError, match="Closed while connecting"): + await asyncio.wait_for(connecting, timeout=5) + await panel.quiesce() + + +@pytest.mark.asyncio +async def test_close_while_connect_fetches_the_schema_opens_no_session() -> None: + """The window the review found: close() lets go of the bridge, and connect() went on to connect it. + + The bridge it connected had no subscription -- the parser was built after + close() had dropped the client's reference -- so the broker saw a CONNECT and + no SUBSCRIBE, connect() timed out waiting for a tree that never came, and the + bridge stayed connected with its reconnect loop armed and nothing to close it. + """ + fetching = asyncio.Event() + fetched = asyncio.Event() + + async def schema_once_released(*_args: object, **_kwargs: object) -> V2HomieSchema: + fetching.set() + await fetched.wait() + return flat_schema() + + async with _serving(_FLAT_TREE, None) as panel: + with patch("span_panel_api.mqtt.client.get_homie_schema", side_effect=schema_once_released): + await _close_while_connect_waits(panel, fetching.is_set, fetched.set) + + assert panel.broker.clients == [], "no paho client is built for a closed client" + assert panel.broker.sessions == [] + assert panel.client.adapter is None, "nor a parser" + + +@pytest.mark.asyncio +async def test_close_while_connect_preloads_the_parser_opens_no_session() -> None: + """The same window one await later: the parser's import, which runs in a thread.""" + loading = threading.Event() + loaded = threading.Event() + resolved: list[str] = [] + + def resolve_once_released(key: str, reason: str) -> type[SchemaAdapter]: + resolved.append(key) + if len(resolved) == 1: + loading.set() + assert loaded.wait(timeout=5), "the test never released the preload" + return resolve_adapter(key, reason) + + async with _serving(_FLAT_TREE, flat_schema()) as panel: + with patch("span_panel_api.mqtt.client.resolve_adapter", resolve_once_released): + await _close_while_connect_waits(panel, loading.is_set, loaded.set) + + assert panel.broker.clients == [] + assert panel.broker.sessions == [] + assert panel.client.adapter is None + + +@pytest.mark.asyncio +async def test_close_while_connect_reads_package_metadata_opens_no_session() -> None: + """After the parser is built, so this bridge did have the topics: connected, it would have been read by nobody.""" + reading = threading.Event() + read = threading.Event() + + def metadata_once_released() -> tuple[list[str], str]: + reading.set() + assert read.wait(timeout=5), "the test never released the metadata read" + return ["schema_0"], "0.0.0" + + async with _serving(_FLAT_TREE, flat_schema()) as panel: + with patch("span_panel_api.mqtt.client._metadata_for_the_log", metadata_once_released): + await _close_while_connect_waits(panel, reading.is_set, read.set) + + assert panel.broker.clients == [] + assert panel.broker.sessions == [] + + +@pytest.mark.asyncio +async def test_close_while_the_bridge_awaits_its_connack_reports_the_close(monkeypatch: pytest.MonkeyPatch) -> None: + """The bridge's connect fails because close() disconnected it; connect() names the close, not the timeout.""" + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_CONNECT_TIMEOUT_S", 0.3) + + async with _serving(_FLAT_TREE, flat_schema()) as panel: + panel.broker.holding_connacks = True + await _close_while_connect_waits(panel, lambda: bool(panel.broker.held), lambda: None) + + [session] = panel.broker.sessions + assert not session.open + assert session.subscribed == [] + + +@pytest.mark.asyncio +async def test_close_while_the_bridge_fetches_an_unpinned_ca_stops_once_it_connects() -> None: + """The one window in which the bridge connects after close() has disconnected it. + + Unpinned, the bridge fetches the panel's CA before building its paho client, + so a close() in that fetch finds nothing to disconnect, and the bridge then + connects and subscribes. connect() disconnects it as soon as it returns, + rather than wait out a tree it will not read. + """ + fetching = asyncio.Event() + fetched = asyncio.Event() + + async def ca_once_released(*_args: object, **_kwargs: object) -> str: + fetching.set() + await fetched.wait() + return "PEM" + + never_ready = {f"{TOPIC_PREFIX_SERIAL}/$description": MINIMAL_DESCRIPTION} + async with _serving(never_ready, flat_schema(), use_tls=True) as panel: + with ( + patch("span_panel_api.mqtt.connection.download_ca_cert", side_effect=ca_once_released), + patch("span_panel_api.mqtt.connection.build_panel_ssl_context", return_value=ssl.create_default_context()), + ): + await _close_while_connect_waits(panel, fetching.is_set, fetched.set) + + assert [session.open for session in panel.broker.sessions] == [False] + + +@pytest.mark.asyncio +async def test_close_while_connect_waits_for_ready_reports_the_close(monkeypatch: pytest.MonkeyPatch) -> None: + """Connected and subscribed, then closed: connect() says so rather than blaming the panel for never being ready.""" + monkeypatch.setattr("span_panel_api.mqtt.client.MQTT_READY_TIMEOUT_S", 0.5) + never_ready = {f"{TOPIC_PREFIX_SERIAL}/$description": MINIMAL_DESCRIPTION} + + async with _serving(never_ready, flat_schema()) as panel: + await _close_while_connect_waits( + panel, lambda: bool(panel.broker.sessions) and bool(panel.broker.sessions[0].subscribed), lambda: None + ) + + [session] = panel.broker.sessions + assert not session.open + + +@pytest.mark.asyncio +async def test_close_while_connect_waits_for_labels_reports_the_close() -> None: + """The tree is ready and its circuit's name is still to come when close() lands: connect() does not return as if connected.""" + unnamed = {f"{TOPIC_PREFIX_SERIAL}/$description": DESCRIPTION_WITH_CIRCUIT, f"{TOPIC_PREFIX_SERIAL}/$state": "ready"} + + async with _serving(unnamed, flat_schema()) as panel: + + def settling() -> bool: + parser = panel.client.adapter + return parser is not None and parser.is_ready() + + await _close_while_connect_waits(panel, settling, lambda: None) + + [session] = panel.broker.sessions + assert not session.open + + +class _MalformedTopics(SchemaZeroAdapter): + """A flat parser naming a filter MQTT refuses.""" + + def topics_to_subscribe(self) -> list[str]: + return ["ebus/#/core"] + + +@pytest.mark.asyncio +async def test_a_parser_whose_topics_are_refused_is_not_installed() -> None: + """The refusal reaches connect()'s caller, and leaves no parser that no session could ever feed.""" + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + client = SpanMqttClient( + host="192.168.1.1", + serial_number=SERIAL, + broker_config=MqttClientConfig(broker_host="broker.local", username="u", password="p", use_tls=False), + adapter_factory=_MalformedTopics, + schema=flat_schema(), + ) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + try: + with pytest.raises(ValueError, match="(?i)topic filter"): + await client.connect() + finally: + await client.close() + + assert client.adapter is None + assert broker.sessions == [] From a266c4c37786ca5b3f580f1ef3405205bb38ea57 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:03:06 -0800 Subject: [PATCH 06/33] fix(mqtt): keep AsyncMqttBridge.subscribe(), held on every session subscribe(topic, qos=0) is kept from 3.8.0 and now held the way set_subscriptions holds its set: subscribed at once on a live session and on every later CONNACK, where in 3.8.0 it was one SUBSCRIBE on the current session, dropped when no paho client existed yet and gone after the next reconnect. The bridge keeps its subscription in two parts with one writer each: the set set_subscriptions replaces whole, the parser's, and the topics subscribe() adds, which nothing removes. A session holds both, each topic once, at the highest QoS either asks, so replacing the parser's set on a swap never drops a consumer's topic, including one both held. A topic already held at the QoS asked sends nothing; a higher one is subscribed again at that QoS, as 3.8.0 honoured qos. subscribe() refuses a malformed filter or a QoS other than 0, 1 or 2 where it is called. --- src/span_panel_api/mqtt/connection.py | 85 +++++++++++--- tests/test_one_subscribe_per_session.py | 146 ++++++++++++++++++++++-- 2 files changed, 208 insertions(+), 23 deletions(-) diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index cde8964..892c44d 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -140,8 +140,12 @@ def __init__( # `_resolve_pending_publishes` when the outbound queue ceases to exist. self._pending_publishes: dict[int, asyncio.Future[bool]] = {} - # What every session is subscribed to. See `set_subscriptions`. - self._subscriptions: tuple[str, ...] = () + # What every session is subscribed to, in two parts with one writer each: + # the set `set_subscriptions` replaces whole, and the topics `subscribe` + # adds, at the QoS asked, which nothing removes. `_held` combines them, and + # nothing but this bridge sends a SUBSCRIBE. See `set_subscriptions`. + self._subscription_set: tuple[str, ...] = () + self._added: dict[str, int] = {} self._connected = False self._client: AsyncMQTTClient | None = None @@ -576,7 +580,7 @@ async def disconnect(self) -> None: self._initial_connect_done = False def set_subscriptions(self, topics: Sequence[str]) -> None: - """Make `topics` the subscription of every session this bridge opens, replacing the last one. + """Make `topics` the set every session of this bridge is subscribed to, replacing the last set given here. The bridge owns subscription because it is the one place that sees each session begin. Every connection is a clean session, so the broker keeps @@ -599,13 +603,19 @@ def set_subscriptions(self, topics: Sequence[str]) -> None: left is unsubscribed because overlapping filters each deliver their own copy of every message they share. + Topics added with `subscribe` are not part of the set and are never + dropped by replacing it: a parser swap replaces the parser's topics, and + a consumer's are not its to remove. A topic in both is held once, at the + higher QoS, and stays while either holds it. + Live means the CONNACK has arrived, not merely that a socket is open: paho sends a SUBSCRIBE on a socket still waiting for its CONNACK, and that CONNACK would then subscribe the session a second time. - Topics are subscribed at QoS 0. Call this on the event loop, like every - other call into this bridge: paho runs there with its locks removed (see - `AsyncMQTTClient`), so a call from another thread would race it. + The set's topics are subscribed at QoS 0. Call this on the event loop, + like every other call into this bridge: paho runs there with its locks + removed (see `AsyncMQTTClient`), so a call from another thread would race + it. Raises: TypeError: `topics` is one string. It is a `Sequence[str]` to the @@ -623,23 +633,70 @@ def set_subscriptions(self, topics: Sequence[str]) -> None: wanted = tuple(dict.fromkeys(topics)) for topic in wanted: _check_topic_filter(topic) - previous = self._subscriptions - self._subscriptions = wanted + previous = self._subscription_set + self._subscription_set = wanted client = self._client if client is None or not self._connected: return - self._subscribe_session(client) - departed = [topic for topic in previous if topic not in self._subscriptions] + held = self._held() + if wanted: + _LOGGER.debug("MQTT subscribing to %s", ", ".join(wanted)) + client.subscribe([(topic, held[topic]) for topic in wanted]) + departed = [topic for topic in previous if topic not in held] if departed: _LOGGER.debug("MQTT unsubscribing from %s", ", ".join(departed)) client.unsubscribe(departed) + def subscribe(self, topic: str, qos: int = 0) -> None: + """Add `topic` at `qos` to what every session of this bridge is subscribed to, for the bridge's life. + + Kept from 3.8.0 for a caller that subscribes a topic of its own, and now + held the way `set_subscriptions` holds its set: subscribed at once on a + live session, and on every later CONNACK. In 3.8.0 it was one SUBSCRIBE + on the current session only, dropped with no paho client to send it on + and gone after the next reconnect. + + A topic already held at `qos` or higher sends nothing: a second + SUBSCRIBE would only replay its retained messages. It is still recorded + as this caller's, so replacing the set with `set_subscriptions` -- a + parser swap -- never drops it. Asked for at a higher QoS than it is held + at, it is subscribed again at that QoS, since nothing else would grant + it; a lower one changes nothing. Nothing removes a topic added here. + + Call this on the event loop, as `set_subscriptions` says. + + Raises: + ValueError: `topic` is not a valid MQTT topic filter, or `qos` is + not 0, 1 or 2. Refused here, before anything is recorded, for + the reason `set_subscriptions` gives. + """ + _check_topic_filter(topic) + if qos not in (0, 1, 2): + raise ValueError(f"MQTT has no QoS {qos!r}: a subscription is at QoS 0, 1 or 2") + before = self._held().get(topic) + self._added[topic] = max(qos, self._added.get(topic, 0)) + if before is not None and before >= qos: + return + client = self._client + if client is None or not self._connected: + return + _LOGGER.debug("MQTT subscribing to %s at QoS %d", topic, qos) + client.subscribe([(topic, qos)]) + + def _held(self) -> dict[str, int]: + """Every topic a session is subscribed to, at the highest QoS either part asks of it.""" + held = dict.fromkeys(self._subscription_set, 0) + for topic, qos in self._added.items(): + held[topic] = max(qos, held.get(topic, 0)) + return held + def _subscribe_session(self, client: paho.Client) -> None: - """Send the subscription on `client`'s session, as one SUBSCRIBE.""" - if not self._subscriptions: + """Send the whole subscription on `client`'s session, as one SUBSCRIBE.""" + held = self._held() + if not held: return - _LOGGER.debug("MQTT subscribing to %s", ", ".join(self._subscriptions)) - client.subscribe([(topic, 0) for topic in self._subscriptions]) + _LOGGER.debug("MQTT subscribing to %s", ", ".join(held)) + client.subscribe(list(held.items())) def publish(self, topic: str, payload: str) -> asyncio.Future[bool] | None: """Hand one QoS-1 control message to paho, or refuse to hand it over. diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 864faeb..6dd6033 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -78,6 +78,8 @@ class _Session: """The topic of every PUBLISH the broker sent on this session.""" filters: list[str] = field(default_factory=list) """The filters currently held for this session.""" + qos: dict[str, int] = field(default_factory=dict) + """The QoS each filter was last subscribed at.""" open: bool = True @@ -124,9 +126,10 @@ def open_session(self) -> _Session: self.sessions.append(session) return session - def subscribe(self, client: _FakePaho, session: _Session, filters: list[str]) -> None: - for topic_filter in filters: + def subscribe(self, client: _FakePaho, session: _Session, filters: list[tuple[str, int]]) -> None: + for topic_filter, qos in filters: session.subscribed.append(topic_filter) + session.qos[topic_filter] = qos if topic_filter not in session.filters: session.filters.append(topic_filter) for topic, payload in self.retained.items(): @@ -207,11 +210,10 @@ def reconnect(self) -> MQTTErrorCode: return MQTTErrorCode.MQTT_ERR_SUCCESS def subscribe(self, topic: str | list[tuple[str, int]], qos: int = 0) -> tuple[MQTTErrorCode, int | None]: - assert qos == 0 session = self.session if session is None or not session.open: return (MQTTErrorCode.MQTT_ERR_NO_CONN, None) - self._broker.subscribe(self, session, [topic] if isinstance(topic, str) else [name for name, _ in topic]) + self._broker.subscribe(self, session, [(topic, qos)] if isinstance(topic, str) else list(topic)) return (MQTTErrorCode.MQTT_ERR_SUCCESS, 1) def unsubscribe(self, topic: str | list[str]) -> tuple[MQTTErrorCode, int | None]: @@ -258,17 +260,22 @@ def _close(self) -> None: self.session.open = False +async def _until(condition: Callable[[], bool], what: str, timeout: float = 10.0) -> None: + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + while not condition(): + if loop.time() > deadline: + raise AssertionError(f"timed out waiting for {what}") + await asyncio.sleep(0.01) + + @dataclass class _Panel: client: SpanMqttClient broker: _Broker async def until(self, condition: Callable[[], bool], what: str, timeout: float = 10.0) -> None: - deadline = self.broker.loop.time() + timeout - while not condition(): - if self.broker.loop.time() > deadline: - raise AssertionError(f"timed out waiting for {what}") - await asyncio.sleep(0.01) + await _until(condition, what, timeout) async def quiesce(self) -> None: """Wait until every delivery the broker scheduled has been made and handled.""" @@ -756,3 +763,124 @@ async def test_a_parser_whose_topics_are_refused_is_not_installed() -> None: assert client.adapter is None assert broker.sessions == [] + + +_CONSUMER_TOPIC = "homeassistant/status" +"""A topic a consumer of the bridge subscribes to itself, outside any parser's set.""" + + +async def _reconnected(broker: _Broker) -> _Session: + """Drop the latest session and return the one the bridge's reconnect opens.""" + opened = len(broker.sessions) + broker.clients[-1].drop() + await _until(lambda: len(broker.sessions) == opened + 1, "the reconnected session") + return broker.sessions[-1] + + +@pytest.mark.asyncio +async def test_subscribe_adds_a_topic_once_and_every_later_session_renews_it() -> None: + """The 3.8.0 method, kept: one SUBSCRIBE for a topic not yet held, none for one that is, and each renewed once.""" + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + bridge.set_subscriptions([_FLAT_FILTER]) + await bridge.connect() + [first] = broker.sessions + + bridge.subscribe(_CONSUMER_TOPIC) + assert first.subscribed == [_FLAT_FILTER, _CONSUMER_TOPIC] + bridge.subscribe(_CONSUMER_TOPIC) + bridge.subscribe(_FLAT_FILTER) + assert first.subscribed == [_FLAT_FILTER, _CONSUMER_TOPIC], "a topic already held sends nothing" + + second = await _reconnected(broker) + await bridge.disconnect() + + assert sorted(second.subscribed) == sorted([_FLAT_FILTER, _CONSUMER_TOPIC]) + + +@pytest.mark.asyncio +async def test_subscribe_before_connect_is_sent_by_the_connack() -> None: + """In 3.8.0 this was dropped: with no paho client yet there was nothing to send it on, and nothing kept it.""" + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + bridge.subscribe(_CONSUMER_TOPIC) + await bridge.connect() + await bridge.disconnect() + + assert broker.sessions[0].subscribed == [_CONSUMER_TOPIC] + + +@pytest.mark.asyncio +async def test_replacing_the_set_never_drops_what_subscribe_added() -> None: + """A parser swap replaces its own topics; a consumer's are not its to drop, even one both held.""" + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + bridge.set_subscriptions([_FLAT_FILTER]) + await bridge.connect() + [first] = broker.sessions + bridge.subscribe(_CONSUMER_TOPIC) + bridge.subscribe(_FLAT_FILTER) + + bridge.set_subscriptions([_PARENT_CHILD_FILTER]) + + assert first.unsubscribed == [] + assert sorted(first.filters) == sorted([_FLAT_FILTER, _CONSUMER_TOPIC, _PARENT_CHILD_FILTER]) + + bridge.set_subscriptions([]) + assert first.unsubscribed == [_PARENT_CHILD_FILTER], "the set's own topic goes when the set lets it go" + + second = await _reconnected(broker) + await bridge.disconnect() + + assert sorted(second.subscribed) == sorted([_FLAT_FILTER, _CONSUMER_TOPIC]) + + +@pytest.mark.asyncio +async def test_subscribe_honours_its_qos_and_a_topic_is_held_at_the_highest_asked() -> None: + """3.8.0 passed `qos` to paho. A topic asked for at a higher QoS than it is held at is subscribed again, at that QoS; never lower.""" + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + bridge.set_subscriptions([_FLAT_FILTER]) + await bridge.connect() + [first] = broker.sessions + + bridge.subscribe(_CONSUMER_TOPIC, qos=1) + bridge.subscribe(_FLAT_FILTER, qos=1) + bridge.subscribe(_FLAT_FILTER, qos=0) + assert first.subscribed == [_FLAT_FILTER, _CONSUMER_TOPIC, _FLAT_FILTER] + assert first.qos == {_FLAT_FILTER: 1, _CONSUMER_TOPIC: 1} + + bridge.set_subscriptions([_FLAT_FILTER]) + assert first.qos[_FLAT_FILTER] == 1, "a new consumer of the set does not lower what another asked for" + + second = await _reconnected(broker) + await bridge.disconnect() + + assert second.qos == {_FLAT_FILTER: 1, _CONSUMER_TOPIC: 1} + + +@pytest.mark.parametrize( + ("topic", "qos"), + [ + pytest.param("", 0, id="empty-filter"), + pytest.param("ebus/#/core", 0, id="malformed-filter"), + pytest.param("a/b", 3, id="no-such-qos"), + ], +) +@pytest.mark.asyncio +async def test_subscribe_refuses_what_mqtt_would_where_it_is_called(topic: str, qos: int) -> None: + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + + with pytest.raises(ValueError, match="(?i)topic filter|qos"): + bridge.subscribe(topic, qos=qos) + + await bridge.connect() + await bridge.disconnect() + + assert broker.sessions[0].subscribed == [], "a refused call records nothing" From d28a5e88cf2c80ea6730ed896722ed886bc31735 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:08:14 -0800 Subject: [PATCH 07/33] fix(models): read publishes_shared_meters as unknown where the adapter does not say SpanPanelSnapshot.publishes_shared_meters, added in 3.9.0b1, defaulted to False, so a snapshot from an adapter that does not answer -- the flat schema's, or a span-panel-api-schema-1 older than the field, which the core 3.9.0 extra still admits -- read as "this panel does not describe its multi-load breakers". It is now bool | None and None by default, as breaker_rating_declared is. span-panel-api-schema-1 1.5.0b1 already sets it to True or False from the declarations and is unchanged; schema-0 now reads None. --- src/span_panel_api/models.py | 10 ++++++---- tests/test_schema_one_shared_meters.py | 15 +++++++++++---- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/span_panel_api/models.py b/src/span_panel_api/models.py index b70e37f..034e648 100644 --- a/src/span_panel_api/models.py +++ b/src/span_panel_api/models.py @@ -1347,15 +1347,17 @@ class SpanPanelSnapshot: which declares no roles. """ - publishes_shared_meters: bool = False - """Whether any circuit declares `meter/shared-with-device-ids`. + publishes_shared_meters: bool | None = None + """Whether any circuit declares `meter/shared-with-device-ids`, or `None` where the adapter does not say. The declaration decides, not the value: a panel model that describes its multi-load breakers declares the list on every circuit, a standard breaker included, and publishes a value only where a meter is shared. Such a panel publishes each circuit of a multi-load breaker as its own device with its - own rating. `False` where no circuit declares the list, as on MAIN 32, and - on the flat schema, which declares none. + own rating. `False` where no circuit declares the list, as on MAIN 32. + `None` where the adapter does not answer -- the flat schema's, one older + than this field, a hand-built snapshot -- and the consumer must treat it as + not known, never as `False`. """ # `shed/policy`, v1.0 only: how the panel decides what to shed, and the two diff --git a/tests/test_schema_one_shared_meters.py b/tests/test_schema_one_shared_meters.py index 76231ee..14aa710 100644 --- a/tests/test_schema_one_shared_meters.py +++ b/tests/test_schema_one_shared_meters.py @@ -148,9 +148,16 @@ def test_a_panel_with_no_circuit_declaring_the_list_does_not() -> None: assert _snapshot(hosted_circuit("c-1", (1,)), hosted_circuit("c-2", (3,))).publishes_shared_meters is False -def test_main_32_and_the_flat_schema_do_not() -> None: - reference = replay(parent_child_tree(), _REFERENCE_PANEL).build_snapshot() +def test_the_reference_tree_declares_no_shared_meter_list() -> None: + assert replay(parent_child_tree(), _REFERENCE_PANEL).build_snapshot().publishes_shared_meters is False + + +def test_an_adapter_that_does_not_say_reads_unknown() -> None: + """The flat adapter sets nothing, as an adapter older than the field would not. + + `False` there would tell a consumer the panel does not describe its + multi-load breakers, which nothing has said. + """ flat = SchemaZeroAdapter(serial_number="sim-40t-001", schema=flat_schema(40)).build_snapshot() - assert reference.publishes_shared_meters is False - assert flat.publishes_shared_meters is False + assert flat.publishes_shared_meters is None From 25b3b6b8a58b3497f5512e35c34e1215e0d9a790 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:28:50 -0800 Subject: [PATCH 08/33] fix(mqtt): end connect()'s waits on close() and notice a disconnect mid-connect SpanMqttClient.connect() waited out MQTT_READY_TIMEOUT_S when close() landed during its wait for a ready tree. The wait now runs as a background task, as the label wait does, so close() -- which cancels every one -- ends it at once and connect() reports the close. AsyncMqttBridge.connect() did not notice a disconnect() made while it was suspended: during the unpinned CA fetch it went on to build a client and connect, during the executor connect its finally read the cleared self._client and raised AttributeError, and during the CONNACK wait it waited out its timeout. Each connect() now carries a token disconnect() clears, checked after each of its awaits. It raises SpanPanelConnectionError instead, closes the socket the executor opened, and disconnect() ends the CONNACK wait. The executor's finally uses the client connect() built. A CONNACK from a client the bridge has let go of is ignored, so the abandoned socket's late CONNACK cannot mark the bridge connected or subscribe it. With the bridge refusing to return from a connect that disconnect() interrupted, SpanMqttClient.connect() no longer checks after a successful bridge connect; a failed one that close() caused still reports the close. --- src/span_panel_api/mqtt/client.py | 34 ++++--- src/span_panel_api/mqtt/connection.py | 82 +++++++++++++--- tests/test_leaf_name_mismatch.py | 14 ++- tests/test_one_subscribe_per_session.py | 125 +++++++++++++++++++++--- 4 files changed, 210 insertions(+), 45 deletions(-) diff --git a/src/span_panel_api/mqtt/client.py b/src/span_panel_api/mqtt/client.py index d75a9cb..24555ee 100644 --- a/src/span_panel_api/mqtt/client.py +++ b/src/span_panel_api/mqtt/client.py @@ -125,6 +125,11 @@ def _discard_verification(verification: _Verification, acknowledged: asyncio.Fut verification.observed.set_result(False) +async def _until_set(event: asyncio.Event) -> None: + """Return once `event` is set: a wait that can run as a task of its own, and be cancelled.""" + await event.wait() + + def _metadata_for_the_log() -> tuple[list[str], str]: """Every distribution-metadata read connect() needs, in one place. @@ -473,8 +478,8 @@ async def connect(self) -> None: stops before the next of its steps -- building the parser, connecting the bridge, waiting on the panel, returning -- rather than go on to connect a bridge nothing can close or report a connection the caller - has already closed (see `_stop_if_closed`). A close() during the wait - for the panel is noticed when that wait ends. + has already closed (see `_stop_if_closed`). A close() during a wait -- + for the broker, for the tree, for its labels -- ends that wait. Raises: SpanPanelAuthError: The broker refused the credentials @@ -568,25 +573,28 @@ async def connect(self) -> None: # topics `_build_adapter` gave the bridge; nothing here subscribes again, # since every SUBSCRIBE makes the broker replay the whole retained tree. _LOGGER.debug("MQTT: Connecting to broker...") + # The bridge raises rather than return from a connect that close() + # disconnected, so only its failure needs checking: one that close() caused + # reports the close. try: await bridge.connect() except SpanPanelError: - # A connect that close() cut short reports the close, not the failure - # the close caused. await self._stop_if_closed(bridge) raise - await self._stop_if_closed(bridge) _LOGGER.debug("MQTT: Broker connected, waiting for Homie ready...") - # Wait for Homie ready state - try: - await asyncio.wait_for(self._ready_event.wait(), timeout=MQTT_READY_TIMEOUT_S) - except TimeoutError as exc: - # A close() during the wait is why nothing arrived, and the bridge to - # tear down is this one, whatever the client holds by now. - await self._stop_if_closed(bridge) + # Wait for Homie ready state. A background task, as the label wait below + # is, so that close() -- which cancels every one -- ends it at once rather + # than leaving it to run out. + ready = self._loop.create_task(_until_set(self._ready_event), name="span_mqtt_wait_ready") + self._background_tasks.add(ready) + ready.add_done_callback(self._background_tasks.discard) + done, _ = await asyncio.wait([ready], timeout=MQTT_READY_TIMEOUT_S) + await self._stop_if_closed(bridge) + if not done: + ready.cancel() await self.close() - raise SpanPanelConnectionError(f"Timed out waiting for Homie device ready ({self._serial_number})") from exc + raise SpanPanelConnectionError(f"Timed out waiting for Homie device ready ({self._serial_number})") _LOGGER.debug("MQTT: Homie device ready, waiting for its labels...") diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index 892c44d..43b3db3 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -150,6 +150,9 @@ def __init__( self._connected = False self._client: AsyncMQTTClient | None = None self._connect_event: asyncio.Event | None = None + # The connect() in progress, by identity, until disconnect() abandons it. + # See `_abandoned`. + self._connect_attempt: object | None = None # Reason code of the most recent refused CONNACK; `connect()` reads it. self._connack_refusal: ReasonCode | None = None @@ -463,7 +466,8 @@ async def connect(self) -> None: Raises: SpanPanelAuthError: The broker refused the username or password (CONNACK "Bad user name or password" or "Not authorized"). - SpanPanelConnectionError: Cannot connect to broker. + SpanPanelConnectionError: Cannot connect to broker, or disconnect() + was called while connecting. SpanPanelTimeoutError: Connection timed out. SpanPanelCAChangedError: The panel is pinned and now advertises a different CA. If the CA rotated while the consumer was down, the @@ -474,7 +478,10 @@ async def connect(self) -> None: if self._loop is None: self._loop = asyncio.get_running_loop() - self._connect_event = asyncio.Event() + attempt = object() + self._connect_attempt = attempt + connack = asyncio.Event() + self._connect_event = connack self._connack_refusal = None self._should_reconnect = True @@ -494,24 +501,28 @@ async def connect(self) -> None: ssl_context = build_panel_ssl_context(ca_pem) except (ssl.SSLError, ValueError) as exc: raise SpanPanelConnectionError(f"Failed to build SSL context for {self._panel_host}") from exc + # Before a paho client exists, so a disconnect() during the CA fetch -- which + # had no client to disconnect -- does not leave one connecting after it. + self._raise_if_abandoned(attempt) - self._client = self._make_paho_client(ssl_context) + # Held locally as well as on `self._client`: disconnect() clears the + # attribute, and everything below must still reach the client it built. + client = self._make_paho_client(ssl_context) + self._client = client # Connect in executor (blocking: DNS, TCP, TLS handshake). # During executor connect, socket callbacks bridge to the event # loop via call_soon_threadsafe. def _blocking_connect() -> None: - if self._client is None: - raise RuntimeError("MQTT client not initialised before connect") - self._client.connect( + client.connect( host=self._host, port=self._port, keepalive=MQTT_KEEPALIVE_S, ) try: - self._client.on_socket_open = self._on_socket_open_sync - self._client.on_socket_register_write = self._on_socket_register_write_sync + client.on_socket_open = self._on_socket_open_sync + client.on_socket_register_write = self._on_socket_register_write_sync _LOGGER.debug("BRIDGE: Running connect in executor to %s:%s", self._host, self._port) try: await self._loop.run_in_executor(None, _blocking_connect) @@ -538,15 +549,23 @@ def _blocking_connect() -> None: finally: # Switch to async-only socket callbacks now that we are # back on the event loop thread. - self._client.on_socket_open = self._async_on_socket_open - self._client.on_socket_register_write = self._async_on_socket_register_write + client.on_socket_open = self._async_on_socket_open + client.on_socket_register_write = self._async_on_socket_register_write - # Wait for CONNACK + if self._abandoned(attempt): + # disconnect() ran while the executor held the client, and the socket + # the executor then opened is one it could not reach. Closed here, on + # the loop, now that nothing else is using the client. + client.disconnect() + self._raise_if_abandoned(attempt) + + # Wait for CONNACK, or for disconnect(), which sets the same event. try: - await asyncio.wait_for(self._connect_event.wait(), timeout=MQTT_CONNECT_TIMEOUT_S) + await asyncio.wait_for(connack.wait(), timeout=MQTT_CONNECT_TIMEOUT_S) except TimeoutError as exc: await self.disconnect() raise SpanPanelTimeoutError(f"Timed out connecting to MQTT broker at {self._host}:{self._port}") from exc + self._raise_if_abandoned(attempt) if not self._connected: refusal = self._connack_refusal @@ -557,8 +576,17 @@ def _blocking_connect() -> None: self._initial_connect_done = True async def disconnect(self) -> None: - """Disconnect from the MQTT broker.""" + """Disconnect from the MQTT broker. + + Also abandons a connect() in progress: it raises `SpanPanelConnectionError` + at its next step rather than go on to connect, and its wait for a CONNACK + ends here rather than running out. + """ self._should_reconnect = False + self._connect_attempt = None + connack = self._connect_event + if connack is not None and not connack.is_set(): + connack.set() # Cancel reconnect task if self._reconnect_task is not None: @@ -579,6 +607,26 @@ async def disconnect(self) -> None: self._client = None self._initial_connect_done = False + def _abandoned(self, attempt: object) -> bool: + """Whether disconnect() has abandoned the connect() that `attempt` identifies. + + A token rather than a flag because connect() may be called again after a + disconnect(): each attempt carries its own, and only a disconnect() made + after it began abandons it. + """ + return self._connect_attempt is not attempt + + def _raise_if_abandoned(self, attempt: object) -> None: + """End a connect() that disconnect() abandoned while it was suspended. + + Raises: + SpanPanelConnectionError: disconnect() was called while connecting. + """ + if self._abandoned(attempt): + raise SpanPanelConnectionError( + f"disconnect() was called while connecting to the MQTT broker at {self._host}:{self._port}" + ) + def set_subscriptions(self, topics: Sequence[str]) -> None: """Make `topics` the set every session of this bridge is subscribed to, replacing the last set given here. @@ -916,7 +964,15 @@ def _on_connect( A CONNACK with no disconnect reported before it is still a new session -- paho's `reconnect()` closes the socket it replaces without one -- so it is subscribed like any other. + + A CONNACK from a client this bridge no longer holds changes nothing: one + whose connect() disconnect() abandoned, or one a rebuild replaced. Its + socket is already being closed, and acting on it would mark the bridge + connected and subscribe a session nothing reads. """ + if client is not self._client: + _LOGGER.debug("MQTT CONNACK from a client this bridge has let go of; ignored") + return connected = not reason_code.is_failure self._connected = connected diff --git a/tests/test_leaf_name_mismatch.py b/tests/test_leaf_name_mismatch.py index 9a14f87..244b4b4 100644 --- a/tests/test_leaf_name_mismatch.py +++ b/tests/test_leaf_name_mismatch.py @@ -63,9 +63,15 @@ def _bridge(chain: Chain | None, host: str, port: int) -> AsyncMqttBridge: def _succeed_connect(bridge: AsyncMqttBridge) -> None: - """Drive the CONNACK the bridge would see on a successful (re)connect.""" + """Drive the CONNACK the bridge would see on a successful (re)connect. + + Delivered from the client the bridge holds, as paho delivers it: the bridge + ignores a CONNACK from a client it has let go of. + """ + client = bridge._client + assert client is not None, "a bridge receives a CONNACK only on a client it holds" bridge._on_connect( - MagicMock(), + client, None, ConnectFlags(session_present=0), ReasonCode(packetType=2, aName="Success"), @@ -126,7 +132,7 @@ async def test_the_warning_names_the_certificate_and_the_configuration(self, cap assert "would both look like this" not in caplog.text @pytest.mark.asyncio - async def test_reported_once_until_a_successful_connect(self) -> None: + async def test_reported_once_until_a_successful_connect(self, mqtt_client_mock: MagicMock) -> None: """A mismatch that lasts a week is one condition, not one per backoff tick. And a mismatch that comes back after a recovery is a second condition, @@ -137,6 +143,7 @@ async def test_reported_once_until_a_successful_connect(self) -> None: with tls_server(chain) as (host, port): bridge = _bridge(chain, host, port) + await bridge.connect() bridge.set_leaf_mismatch_callback(seen.append) with patch("span_panel_api.mqtt.connection.download_ca_cert", return_value=chain.ca_pem): await bridge._diagnose_verification_failure() @@ -145,6 +152,7 @@ async def test_reported_once_until_a_successful_connect(self) -> None: _succeed_connect(bridge) await bridge._diagnose_verification_failure() + await bridge.disconnect() assert len(seen) == 2 assert seen[0] == seen[1] diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 6dd6033..025df3e 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -101,6 +101,10 @@ def __init__(self, loop: asyncio.AbstractEventLoop, retained: dict[str, str]) -> self.holding_connacks = False """While set, a session opens without its CONNACK, which waits in `held` for `release_connacks`.""" self.held: list[tuple[_FakePaho, _Session]] = [] + self.connecting = threading.Event() + """Set when a client's blocking connect starts, in the executor thread.""" + self.connect_gate: threading.Event | None = None + """While set to an unset event, a blocking connect waits on it before opening its socket.""" self.pending = 0 """Deliveries scheduled and not yet made.""" @@ -196,6 +200,10 @@ def tls_set_context(self, context: ssl.SSLContext | None = None) -> None: def connect(self, host: str, port: int = 1883, keepalive: int = 60) -> MQTTErrorCode: """Open a session and schedule its CONNACK, as paho's executor connect does.""" assert host and port > 0 and keepalive > 0 + self._broker.connecting.set() + gate = self._broker.connect_gate + if gate is not None: + assert gate.wait(timeout=5), "the test never released the blocking connect" self._open() return MQTTErrorCode.MQTT_ERR_SUCCESS @@ -663,10 +671,8 @@ def metadata_once_released() -> tuple[list[str], str]: @pytest.mark.asyncio -async def test_close_while_the_bridge_awaits_its_connack_reports_the_close(monkeypatch: pytest.MonkeyPatch) -> None: - """The bridge's connect fails because close() disconnected it; connect() names the close, not the timeout.""" - monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_CONNECT_TIMEOUT_S", 0.3) - +async def test_close_while_the_bridge_awaits_its_connack_reports_the_close_at_once() -> None: + """The bridge's wait for its CONNACK ends when close() disconnects it, rather than running out its 15 s.""" async with _serving(_FLAT_TREE, flat_schema()) as panel: panel.broker.holding_connacks = True await _close_while_connect_waits(panel, lambda: bool(panel.broker.held), lambda: None) @@ -677,13 +683,23 @@ async def test_close_while_the_bridge_awaits_its_connack_reports_the_close(monke @pytest.mark.asyncio -async def test_close_while_the_bridge_fetches_an_unpinned_ca_stops_once_it_connects() -> None: - """The one window in which the bridge connects after close() has disconnected it. +async def test_close_during_the_bridges_blocking_connect_reports_the_close() -> None: + """The executor connect returned to a bridge close() had disconnected: in 3.8.0 an `AttributeError`.""" + async with _serving(_FLAT_TREE, flat_schema()) as panel: + gate = threading.Event() + panel.broker.connect_gate = gate + await _close_while_connect_waits(panel, panel.broker.connecting.is_set, gate.set) + + assert all(not session.open for session in panel.broker.sessions) + assert all(session.subscribed == [] for session in panel.broker.sessions) + + +@pytest.mark.asyncio +async def test_close_while_the_bridge_fetches_an_unpinned_ca_opens_no_session() -> None: + """Unpinned, the bridge fetches the panel's CA before it has a paho client, so close() finds nothing to disconnect. - Unpinned, the bridge fetches the panel's CA before building its paho client, - so a close() in that fetch finds nothing to disconnect, and the bridge then - connects and subscribes. connect() disconnects it as soon as it returns, - rather than wait out a tree it will not read. + The bridge notices the disconnect() when the fetch returns and builds no + client, where it used to go on to connect and subscribe. """ fetching = asyncio.Event() fetched = asyncio.Event() @@ -693,21 +709,20 @@ async def ca_once_released(*_args: object, **_kwargs: object) -> str: await fetched.wait() return "PEM" - never_ready = {f"{TOPIC_PREFIX_SERIAL}/$description": MINIMAL_DESCRIPTION} - async with _serving(never_ready, flat_schema(), use_tls=True) as panel: + async with _serving(_FLAT_TREE, flat_schema(), use_tls=True) as panel: with ( patch("span_panel_api.mqtt.connection.download_ca_cert", side_effect=ca_once_released), patch("span_panel_api.mqtt.connection.build_panel_ssl_context", return_value=ssl.create_default_context()), ): await _close_while_connect_waits(panel, fetching.is_set, fetched.set) - assert [session.open for session in panel.broker.sessions] == [False] + assert panel.broker.clients == [] + assert panel.broker.sessions == [] @pytest.mark.asyncio -async def test_close_while_connect_waits_for_ready_reports_the_close(monkeypatch: pytest.MonkeyPatch) -> None: - """Connected and subscribed, then closed: connect() says so rather than blaming the panel for never being ready.""" - monkeypatch.setattr("span_panel_api.mqtt.client.MQTT_READY_TIMEOUT_S", 0.5) +async def test_close_while_connect_waits_for_ready_reports_the_close_at_once() -> None: + """Connected and subscribed, then closed: the wait for a ready tree ends there, rather than running out its 30 s.""" never_ready = {f"{TOPIC_PREFIX_SERIAL}/$description": MINIMAL_DESCRIPTION} async with _serving(never_ready, flat_schema()) as panel: @@ -884,3 +899,81 @@ async def test_subscribe_refuses_what_mqtt_would_where_it_is_called(topic: str, await bridge.disconnect() assert broker.sessions[0].subscribed == [], "a refused call records nothing" + + +async def _disconnect_while_bridge_connects( + broker: _Broker, bridge: AsyncMqttBridge, waiting: Callable[[], bool], resume: Callable[[], None] +) -> None: + """Start the bridge's connect(), disconnect it once `waiting` says connect() is suspended, then let it resume.""" + connecting = asyncio.create_task(bridge.connect()) + await _until(waiting, "the bridge's connect() to suspend") + await bridge.disconnect() + resume() + with pytest.raises(SpanPanelConnectionError, match="disconnect"): + await asyncio.wait_for(connecting, timeout=5) + await _until(lambda: broker.pending == 0, "the broker's deliveries") + for _ in range(5): + await asyncio.sleep(0) + + +@pytest.mark.asyncio +async def test_the_bridge_notices_a_disconnect_during_its_blocking_connect() -> None: + """A SpanPanelError, not 3.8.0's `AttributeError`, and the socket the executor opened is closed and never subscribed. + + The CONNACK for that socket can still arrive after `disconnect()`. It belongs + to a client the bridge has let go of, so it changes nothing: the bridge is + not connected again by it and the session is not subscribed. + """ + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + bridge.set_subscriptions([_FLAT_FILTER]) + gate = threading.Event() + broker.connect_gate = gate + + await _disconnect_while_bridge_connects(broker, bridge, broker.connecting.is_set, gate.set) + + assert not bridge.is_connected() + [session] = broker.sessions + assert not session.open + assert session.subscribed == [] + + +@pytest.mark.asyncio +async def test_the_bridge_ends_its_connack_wait_on_disconnect() -> None: + """Rather than waiting out MQTT_CONNECT_TIMEOUT_S for a CONNACK nobody will read.""" + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + broker.holding_connacks = True + + await _disconnect_while_bridge_connects(broker, bridge, lambda: bool(broker.held), lambda: None) + + assert not bridge.is_connected() + assert [session.open for session in broker.sessions] == [False] + + +@pytest.mark.asyncio +async def test_the_bridge_builds_no_client_after_a_disconnect_during_its_ca_fetch() -> None: + """Unpinned, the CA is fetched before there is a paho client for disconnect() to reach.""" + fetching = asyncio.Event() + fetched = asyncio.Event() + + async def ca_once_released(*_args: object, **_kwargs: object) -> str: + fetching.set() + await fetched.wait() + return "PEM" + + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with ( + patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client), + patch("span_panel_api.mqtt.connection.download_ca_cert", side_effect=ca_once_released), + patch("span_panel_api.mqtt.connection.build_panel_ssl_context", return_value=ssl.create_default_context()), + ): + bridge = AsyncMqttBridge( + host="broker.local", port=8883, username="u", password="p", panel_host="192.168.1.1", serial_number=SERIAL + ) + await _disconnect_while_bridge_connects(broker, bridge, fetching.is_set, fetched.set) + + assert broker.clients == [] + assert not bridge.is_connected() From bf7f5f1f124dc0213d18d232862b78a82c2fce19 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:42:02 -0800 Subject: [PATCH 09/33] fix(mqtt): ignore a let-go client's disconnect and keep the client a rebuild made AsyncMqttBridge._on_disconnect now ignores a disconnect reported by a client the bridge no longer holds, as _on_connect already ignores its CONNACK, so a replaced client reporting its end cannot mark the bridge disconnected under the new client's live session, tell consumers the panel was lost, and start a reconnect that replaces that session. The guard depends on self._client being the live client, and _rebuild_client broke that: cancelled during its executor connect, it restored the old client. disconnect() cancels it so, after letting every client go, and the restore put one back; a CONNACK from the new client cancels it so too, and the restore left the bridge acting through a client whose session was over, publishing and subscribing into nothing and, with these guards, deaf to the live session's own disconnect. A cancelled rebuild now leaves self._client as it is. --- src/span_panel_api/mqtt/connection.py | 31 +++++++---- tests/test_one_subscribe_per_session.py | 70 +++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 9 deletions(-) diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index 43b3db3..3d20d00 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -1002,13 +1002,24 @@ def _on_connect( def _on_disconnect( self, - _client: paho.Client, + client: paho.Client, _userdata: object, _flags: DisconnectFlags, reason_code: ReasonCode, _properties: Properties | None, ) -> None: - """Handle disconnect from broker.""" + """Handle disconnect from broker. + + A disconnect reported by a client this bridge no longer holds changes + nothing, as its CONNACK would not (see `_on_connect`): that client's + session already ended when it was let go of. Acted on, a rebuild's + replaced client reporting late would mark the bridge disconnected under + the new client's live session, tell consumers the panel was lost, and + start a reconnect that replaced that session. + """ + if client is not self._client: + _LOGGER.debug("MQTT disconnect from a client this bridge has let go of; ignored") + return self._connected = False if reason_code.is_failure: _LOGGER.warning("MQTT disconnected abnormally: %s", reason_code) @@ -1135,15 +1146,17 @@ def _blocking_connect() -> None: keepalive=MQTT_KEEPALIVE_S, ) + # A CancelledError here -- bridge teardown or _on_connect cancelling us + # mid-rebuild -- passes the clause below, as a BaseException, and + # propagates with `self._client` as it is: neither leaves the old + # client to restore. disconnect() has let every client go, and putting + # the old one back would undo that; a CONNACK from the new client made + # it the live one. The bridge acts through `self._client` -- `publish`, + # `set_subscriptions` -- and `_on_connect` and `_on_disconnect` hear + # only from it, so holding a client whose session is over would leave + # the live session's own disconnect unheard. try: await self._loop.run_in_executor(None, _blocking_connect) - except asyncio.CancelledError: - # Bridge teardown or _on_connect cancelled us mid-rebuild. - # Restore the previous client reference so post-teardown - # state stays consistent, then re-raise — CancelledError - # must propagate to keep the loop's cancel semantics intact. - self._client = old_client - raise except Exception as exc: # pylint: disable=broad-exception-caught _LOGGER.warning("Client rebuild — initial connect failed: %s", exc) # Restore the previous client so the loop keeps retrying diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 025df3e..a524653 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -977,3 +977,73 @@ async def ca_once_released(*_args: object, **_kwargs: object) -> str: assert broker.clients == [] assert not bridge.is_connected() + + +@pytest.mark.asyncio +async def test_a_replaced_clients_late_disconnect_does_not_end_the_rebuilt_session(panel: _Panel) -> None: + """The rebuild's new client is connected; the client it replaced reporting its own end changes nothing. + + Acted on, it marked the bridge disconnected under a live session, told every + consumer the panel was lost, and started a reconnect that tore down the + session the rebuild had just opened and replayed the tree into another. + """ + edges: list[bool] = [] + panel.client.register_connection_callback(edges.append) + await _connected(panel) + [old] = panel.broker.clients + old.next_reconnect_error = ssl.SSLError("handshake failed") + old.drop() + await panel.until(lambda: len(panel.broker.sessions) == 2, "the rebuilt client's session") + await panel.quiesce() + assert edges == [True, False, True], "precondition: rebuilt and announced" + + old.drop() + await asyncio.sleep(0.1) + await panel.quiesce() + + assert edges == [True, False, True] + assert len(panel.broker.sessions) == 2, "no reconnect replaces the rebuilt session" + assert panel.broker.sessions[1].open + assert await panel.client.ping() is True + + +async def _rebuilt(broker: _Broker) -> _Session: + """Drop the bridge's session with a TLS failure, so the reconnect rebuilds paho, and return the rebuilt client's session.""" + opened = len(broker.sessions) + old = broker.clients[-1] + old.next_reconnect_error = ssl.SSLError("handshake failed") + old.drop() + await _until(lambda: len(broker.sessions) == opened + 1, "the rebuilt client's session") + return broker.sessions[-1] + + +@pytest.mark.asyncio +async def test_after_a_rebuild_the_bridge_acts_through_the_client_it_rebuilt() -> None: + """A subscription made on the rebuilt session reaches that session, not the client it replaced.""" + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + bridge.set_subscriptions([_FLAT_FILTER]) + await bridge.connect() + rebuilt = await _rebuilt(broker) + + bridge.subscribe(_CONSUMER_TOPIC) + await bridge.disconnect() + + assert rebuilt.subscribed == [_FLAT_FILTER, _CONSUMER_TOPIC] + + +@pytest.mark.asyncio +async def test_a_rebuilt_clients_own_drop_is_noticed_and_reconnected() -> None: + """Ignoring a let-go client's disconnect must not mean ignoring the live one's: that would leave readings stale with no error.""" + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + bridge.set_subscriptions([_FLAT_FILTER]) + await bridge.connect() + await _rebuilt(broker) + + reconnected = await _reconnected(broker) + await bridge.disconnect() + + assert reconnected.subscribed == [_FLAT_FILTER] From 456d2ad1edc4bedc865ce7f1d08fffa1df8638cf Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:09:17 -0800 Subject: [PATCH 10/33] fix(mqtt): leave a client to the thread inside paho until its blocking call returns paho runs here with its locks removed, so only one thread may be inside a client at a time, and three paths broke that. disconnect() called paho's disconnect() on the loop while an executor thread was inside the same client's connect() or reconnect(). And when disconnect() cancelled the reconnect task, the coroutine's finally switched the socket callbacks back to the loop-only ones at the cancel, while the thread was still inside paho and could call them from the wrong thread. On the rebuild path nothing closed the socket the new client's connect went on to open, so it stayed open. Every blocking call now goes through _run_blocking. The client is marked held and given the thread-safe socket callbacks. disconnect() never calls into a held client, only lets it go. The loop takes the client back in _executor_returned when the call returns, not when its caller resumes: loop callbacks again, and a client let go of meanwhile is disconnected there, closing whatever the call opened. The caller awaits a future that hand-back resolves, so a cancelled caller cancels only its wait, and a failure nobody awaits is retrieved without being reported; asyncio.shield would report it through the loop's exception handler. --- src/span_panel_api/mqtt/connection.py | 155 +++++++++++++------- tests/test_one_subscribe_per_session.py | 184 ++++++++++++++++++++++-- 2 files changed, 272 insertions(+), 67 deletions(-) diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index 3d20d00..9378d67 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -153,6 +153,9 @@ def __init__( # The connect() in progress, by identity, until disconnect() abandons it. # See `_abandoned`. self._connect_attempt: object | None = None + # Clients a blocking call is running inside, in the executor. See + # `_run_blocking`: nothing on the loop calls into one until it returns. + self._executor_clients: set[AsyncMQTTClient] = set() # Reason code of the most recent refused CONNACK; `connect()` reads it. self._connack_refusal: ReasonCode | None = None @@ -520,44 +523,32 @@ def _blocking_connect() -> None: keepalive=MQTT_KEEPALIVE_S, ) + _LOGGER.debug("BRIDGE: Running connect in executor to %s:%s", self._host, self._port) try: - client.on_socket_open = self._on_socket_open_sync - client.on_socket_register_write = self._on_socket_register_write_sync - _LOGGER.debug("BRIDGE: Running connect in executor to %s:%s", self._host, self._port) - try: - await self._loop.run_in_executor(None, _blocking_connect) - except ssl.SSLCertVerificationError as exc: - # The pinned handshake failed on the very first attempt, which is - # what a CA rotated while the consumer was shut down looks like. - # Wrapped as a connection error this became a setup-retry loop - # with nothing for the user to act on, forever. - # `_diagnose_verification_failure` is what distinguishes it from an - # expired leaf or a moved host, and returns None for both of those - # so they keep their old retryable shape — announcing the moved - # host on its own channel on the way past. - fatal = await self._diagnose_verification_failure() - if fatal is not None: - raise fatal from exc - raise SpanPanelConnectionError(f"Cannot connect to MQTT broker at {self._host}:{self._port}: {exc}") from exc - except Exception as exc: # pylint: disable=broad-exception-caught - # paho raises OSError for TCP failures and transport-specific - # errors (e.g. WebsocketConnectionError) that do not inherit - # from OSError. Wrap all of them uniformly so callers only - # see the documented SpanPanelConnectionError. - raise SpanPanelConnectionError(f"Cannot connect to MQTT broker at {self._host}:{self._port}: {exc}") from exc - _LOGGER.debug("BRIDGE: Executor connect returned, waiting for CONNACK...") - finally: - # Switch to async-only socket callbacks now that we are - # back on the event loop thread. - client.on_socket_open = self._async_on_socket_open - client.on_socket_register_write = self._async_on_socket_register_write - - if self._abandoned(attempt): - # disconnect() ran while the executor held the client, and the socket - # the executor then opened is one it could not reach. Closed here, on - # the loop, now that nothing else is using the client. - client.disconnect() - self._raise_if_abandoned(attempt) + await self._run_blocking(self._loop, client, _blocking_connect) + except ssl.SSLCertVerificationError as exc: + # The pinned handshake failed on the very first attempt, which is + # what a CA rotated while the consumer was shut down looks like. + # Wrapped as a connection error this became a setup-retry loop + # with nothing for the user to act on, forever. + # `_diagnose_verification_failure` is what distinguishes it from an + # expired leaf or a moved host, and returns None for both of those + # so they keep their old retryable shape — announcing the moved + # host on its own channel on the way past. + fatal = await self._diagnose_verification_failure() + if fatal is not None: + raise fatal from exc + raise SpanPanelConnectionError(f"Cannot connect to MQTT broker at {self._host}:{self._port}: {exc}") from exc + except Exception as exc: # pylint: disable=broad-exception-caught + # paho raises OSError for TCP failures and transport-specific + # errors (e.g. WebsocketConnectionError) that do not inherit + # from OSError. Wrap all of them uniformly so callers only + # see the documented SpanPanelConnectionError. + raise SpanPanelConnectionError(f"Cannot connect to MQTT broker at {self._host}:{self._port}: {exc}") from exc + _LOGGER.debug("BRIDGE: Executor connect returned, waiting for CONNACK...") + # A disconnect() while the executor held the client left it to the + # thread, and `_executor_returned` has closed it by now. + self._raise_if_abandoned(attempt) # Wait for CONNACK, or for disconnect(), which sets the same event. try: @@ -600,13 +591,76 @@ async def disconnect(self) -> None: self._resolve_pending_publishes(False, "bridge disconnected") + # Not a client a blocking call is still inside: paho runs with its locks + # removed, so only the thread may touch it. Letting it go is enough -- + # `_executor_returned` closes it on the loop once the call returns. client = self._client - if client is not None: + if client is not None and client not in self._executor_clients: client.disconnect() self._connected = False self._client = None self._initial_connect_done = False + def _run_blocking( + self, loop: asyncio.AbstractEventLoop, client: AsyncMQTTClient, call: Callable[[], object] + ) -> asyncio.Future[object]: + """Run one blocking paho call on `client` in the executor: the only way this bridge does. + + While the call runs the executor thread owns the client. Its socket + callbacks are the thread-safe bridges, and nothing on the loop calls into + it -- paho runs with its locks removed, so a second thread inside the + same client could corrupt it. `disconnect()` in particular only lets it + go. + + The loop takes it back when the call returns (`_executor_returned`), not + when its caller resumes. Cancelling the caller does not stop the thread, + so the caller awaits a future the hand-back resolves rather than the + executor's own: a cancelled caller -- a reconnect task that disconnect() + cancelled -- cancels only its wait, and the hand-back still runs when the + thread is really done. Not `asyncio.shield`, which reports a failure that + arrives after its caller was cancelled through the loop's exception + handler; here that failure is the abandoned attempt's, and expected. + """ + client.on_socket_open = self._on_socket_open_sync + client.on_socket_register_write = self._on_socket_register_write_sync + self._executor_clients.add(client) + caller: asyncio.Future[object] = loop.create_future() + loop.run_in_executor(None, call).add_done_callback(partial(self._executor_returned, client, caller)) + return caller + + def _executor_returned( + self, client: AsyncMQTTClient, caller: asyncio.Future[object], call: asyncio.Future[object] + ) -> None: + """Take `client` back on the loop once its blocking `call` has returned, then answer its `caller`. + + Async socket callbacks again, and a client this bridge let go of while the + thread held it -- disconnect() ran meanwhile -- is disconnected here, + closing whatever socket the call went on to open. Only then is `caller` + given the call's outcome, so whoever awaits it resumes with the client + already back. A caller that was cancelled is told nothing: the outcome is + retrieved here, so a failure nobody is waiting for is not reported as + never retrieved. + """ + self._executor_clients.discard(client) + client.on_socket_open = self._async_on_socket_open + client.on_socket_register_write = self._async_on_socket_register_write + if client is not self._client: + try: + client.disconnect() + except Exception: # pylint: disable=broad-exception-caught + _LOGGER.debug("Disconnecting a let-go paho client raised", exc_info=True) + if call.cancelled(): + if not caller.done(): + caller.cancel() + return + failure = call.exception() + if caller.done(): + return + if failure is not None: + caller.set_exception(failure) + else: + caller.set_result(call.result()) + def _abandoned(self, attempt: object) -> bool: """Whether disconnect() has abandoned the connect() that `attempt` identifies. @@ -1135,8 +1189,6 @@ async def _rebuild_client(self) -> bool: # a live session through `self._client`, and would otherwise reach # the (disconnected) old_client. new_client = self._make_paho_client(ssl_context) - new_client.on_socket_open = self._on_socket_open_sync - new_client.on_socket_register_write = self._on_socket_register_write_sync self._client = new_client def _blocking_connect() -> None: @@ -1156,16 +1208,14 @@ def _blocking_connect() -> None: # only from it, so holding a client whose session is over would leave # the live session's own disconnect unheard. try: - await self._loop.run_in_executor(None, _blocking_connect) + await self._run_blocking(self._loop, new_client, _blocking_connect) except Exception as exc: # pylint: disable=broad-exception-caught _LOGGER.warning("Client rebuild — initial connect failed: %s", exc) # Restore the previous client so the loop keeps retrying - # with what it had. The new client's socket was never opened. + # with what it had. Whatever the failed connect left of the new + # one, `_executor_returned` has disconnected, as a let-go client. self._client = old_client return False - finally: - new_client.on_socket_open = self._async_on_socket_open - new_client.on_socket_register_write = self._async_on_socket_register_write _LOGGER.info("MQTT client rebuilt for reconnect (TLS=%s)", self._use_tls) return True @@ -1198,14 +1248,12 @@ async def _reconnect_loop(self) -> None: delay = MQTT_RECONNECT_MIN_DELAY_S failures_since_rebuild_attempt = 0 while self._should_reconnect: - if not self._connected and self._client is not None: + client = self._client + if not self._connected and client is not None: try: if self._loop is None: break - # Use sync socket callbacks for executor reconnect - self._client.on_socket_open = self._on_socket_open_sync - self._client.on_socket_register_write = self._on_socket_register_write_sync - await self._loop.run_in_executor(None, self._client.reconnect) + await self._run_blocking(self._loop, client, client.reconnect) except ssl.SSLCertVerificationError as exc: # Certificate verification, specifically -- caught ahead of # `ssl.SSLError` because it is a subclass, and separated from @@ -1263,10 +1311,9 @@ async def _reconnect_loop(self) -> None: # behind a recovery action whose effect we cannot predict. failures_since_rebuild_attempt += 1 _LOGGER.warning("Reconnect failed, retrying in %ss", delay, exc_info=True) - finally: - if self._client is not None: - self._client.on_socket_open = self._async_on_socket_open - self._client.on_socket_register_write = self._async_on_socket_register_write + # The socket callbacks go back to the loop's in `_executor_returned`, + # when the thread is done, not here: a cancelled loop reaches this + # point while the thread may still be inside paho. else: failures_since_rebuild_attempt = 0 await asyncio.sleep(delay) diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index a524653..0aee901 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -18,8 +18,9 @@ from __future__ import annotations import asyncio -from collections.abc import AsyncIterator, Callable +from collections.abc import AsyncIterator, Callable, Iterator import contextlib +import gc from dataclasses import dataclass, field import ssl import threading @@ -105,6 +106,16 @@ def __init__(self, loop: asyncio.AbstractEventLoop, retained: dict[str, str]) -> """Set when a client's blocking connect starts, in the executor thread.""" self.connect_gate: threading.Event | None = None """While set to an unset event, a blocking connect waits on it before opening its socket.""" + self.reconnecting = threading.Event() + """Set when a client's blocking reconnect starts, in the executor thread.""" + self.reconnect_gate: threading.Event | None = None + """As `connect_gate`, for a blocking reconnect.""" + self.calls_while_held: list[str] = [] + """Every call that reached a client while a blocking connect or reconnect was inside it. + + paho runs with its locks removed, so the thread holding a client is the + only one that may call into it; anything listed here came from another. + """ self.pending = 0 """Deliveries scheduled and not yet made.""" @@ -178,6 +189,7 @@ def __init__(self, broker: _Broker) -> None: self._broker = broker self.session: _Session | None = None self.next_reconnect_error: OSError | ssl.SSLError | None = None + self.held_by_a_thread = False self.on_connect: ConnackHandler | None = None self.on_disconnect: DisconnectHandler | None = None self.on_message: MessageHandler | None = None @@ -200,24 +212,43 @@ def tls_set_context(self, context: ssl.SSLContext | None = None) -> None: def connect(self, host: str, port: int = 1883, keepalive: int = 60) -> MQTTErrorCode: """Open a session and schedule its CONNACK, as paho's executor connect does.""" assert host and port > 0 and keepalive > 0 - self._broker.connecting.set() - gate = self._broker.connect_gate - if gate is not None: - assert gate.wait(timeout=5), "the test never released the blocking connect" - self._open() + self.held_by_a_thread = True + try: + self._broker.connecting.set() + gate = self._broker.connect_gate + if gate is not None: + assert gate.wait(timeout=5), "the test never released the blocking connect" + session = self._open() + finally: + self.held_by_a_thread = False + self._answer(session) return MQTTErrorCode.MQTT_ERR_SUCCESS def reconnect(self) -> MQTTErrorCode: """paho closes the previous socket without reporting a disconnect, then opens another.""" - error = self.next_reconnect_error - self.next_reconnect_error = None - self._close() - if error is not None: - raise error - self._open() + self.held_by_a_thread = True + try: + self._broker.reconnecting.set() + gate = self._broker.reconnect_gate + if gate is not None: + assert gate.wait(timeout=5), "the test never released the blocking reconnect" + error = self.next_reconnect_error + self.next_reconnect_error = None + self._close() + if error is not None: + raise error + session = self._open() + finally: + self.held_by_a_thread = False + self._answer(session) return MQTTErrorCode.MQTT_ERR_SUCCESS + def _record_if_held(self, call: str) -> None: + if self.held_by_a_thread: + self._broker.calls_while_held.append(call) + def subscribe(self, topic: str | list[tuple[str, int]], qos: int = 0) -> tuple[MQTTErrorCode, int | None]: + self._record_if_held("subscribe") session = self.session if session is None or not session.open: return (MQTTErrorCode.MQTT_ERR_NO_CONN, None) @@ -225,6 +256,7 @@ def subscribe(self, topic: str | list[tuple[str, int]], qos: int = 0) -> tuple[M return (MQTTErrorCode.MQTT_ERR_SUCCESS, 1) def unsubscribe(self, topic: str | list[str]) -> tuple[MQTTErrorCode, int | None]: + self._record_if_held("unsubscribe") session = self.session if session is None or not session.open: return (MQTTErrorCode.MQTT_ERR_NO_CONN, None) @@ -232,6 +264,7 @@ def unsubscribe(self, topic: str | list[str]) -> tuple[MQTTErrorCode, int | None return (MQTTErrorCode.MQTT_ERR_SUCCESS, 1) def disconnect(self) -> MQTTErrorCode: + self._record_if_held("disconnect") self._close() return MQTTErrorCode.MQTT_ERR_SUCCESS @@ -247,11 +280,19 @@ def drop(self) -> None: None, ) - def _open(self) -> None: + def _open(self) -> _Session: if self._broker.refusing: raise ConnectionRefusedError(61, "Connection refused") session = self._broker.open_session() self.session = session + return session + + def _answer(self, session: _Session) -> None: + """Schedule the CONNACK for `session`, or hold it. + + Only once the blocking call has returned: paho writes the CONNECT from the + loop's write callback after that, so no CONNACK can come sooner. + """ if self._broker.holding_connacks: self._broker.held.append((self, session)) return @@ -268,6 +309,16 @@ def _close(self) -> None: self.session.open = False +async def _let_the_loop_run() -> None: + """Run what the last call scheduled, while a gated executor call is still held. + + Released at once, a gated call could finish before anything the loop had + yet to run, and a call that reached the held client would go unrecorded. + """ + for _ in range(5): + await asyncio.sleep(0) + + async def _until(condition: Callable[[], bool], what: str, timeout: float = 10.0) -> None: loop = asyncio.get_running_loop() deadline = loop.time() + timeout @@ -596,6 +647,7 @@ async def _close_while_connect_waits(panel: _Panel, waiting: Callable[[], bool], connecting = asyncio.create_task(panel.client.connect()) await panel.until(waiting, "connect() to suspend") await panel.client.close() + await _let_the_loop_run() resume() with pytest.raises(SpanPanelConnectionError, match="Closed while connecting"): await asyncio.wait_for(connecting, timeout=5) @@ -690,6 +742,7 @@ async def test_close_during_the_bridges_blocking_connect_reports_the_close() -> panel.broker.connect_gate = gate await _close_while_connect_waits(panel, panel.broker.connecting.is_set, gate.set) + assert panel.broker.calls_while_held == [], "close() reached into a client the executor held" assert all(not session.open for session in panel.broker.sessions) assert all(session.subscribed == [] for session in panel.broker.sessions) @@ -908,6 +961,7 @@ async def _disconnect_while_bridge_connects( connecting = asyncio.create_task(bridge.connect()) await _until(waiting, "the bridge's connect() to suspend") await bridge.disconnect() + await _let_the_loop_run() resume() with pytest.raises(SpanPanelConnectionError, match="disconnect"): await asyncio.wait_for(connecting, timeout=5) @@ -933,6 +987,7 @@ async def test_the_bridge_notices_a_disconnect_during_its_blocking_connect() -> await _disconnect_while_bridge_connects(broker, bridge, broker.connecting.is_set, gate.set) + assert broker.calls_while_held == [], "disconnect() reached into a client the executor held" assert not bridge.is_connected() [session] = broker.sessions assert not session.open @@ -1047,3 +1102,106 @@ async def test_a_rebuilt_clients_own_drop_is_noticed_and_reconnected() -> None: await bridge.disconnect() assert reconnected.subscribed == [_FLAT_FILTER] + + +@contextlib.contextmanager +def _unobserved_loop_errors() -> Iterator[list[dict[str, object]]]: + """Collect what the loop's exception handler is handed: an error no awaiter retrieved.""" + loop = asyncio.get_running_loop() + seen: list[dict[str, object]] = [] + previous = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, context: seen.append(context)) + try: + yield seen + finally: + loop.set_exception_handler(previous) + + +@pytest.mark.asyncio +async def test_disconnect_during_a_blocking_reconnect_waits_for_the_thread_then_closes_its_socket() -> None: + """disconnect() leaves the client to the thread inside paho's reconnect(), and the socket it opens is closed after. + + Before, disconnect() called paho's disconnect() on the loop while the thread + was inside reconnect() on the same client, with paho's locks removed, and + the socket that reconnect() went on to open was never closed. + """ + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client), _unobserved_loop_errors() as errors: + bridge = _bridge() + bridge.set_subscriptions([_FLAT_FILTER]) + await bridge.connect() + gate = threading.Event() + broker.reconnect_gate = gate + broker.clients[-1].drop() + await _until(broker.reconnecting.is_set, "the blocking reconnect") + + await bridge.disconnect() + await _let_the_loop_run() + gate.set() + await _until(lambda: not broker.clients[-1].held_by_a_thread, "the reconnect to return") + for _ in range(5): + await asyncio.sleep(0) + + assert broker.calls_while_held == [] + assert [session.open for session in broker.sessions] == [False, False] + assert not bridge.is_connected() + assert errors == [] + + +@pytest.mark.asyncio +async def test_disconnect_during_a_rebuilds_blocking_connect_waits_for_the_thread_then_closes_its_socket() -> None: + """The rebuild path, where nothing closed the new client's socket at all once disconnect() had let it go.""" + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client), _unobserved_loop_errors() as errors: + bridge = _bridge() + bridge.set_subscriptions([_FLAT_FILTER]) + await bridge.connect() + gate = threading.Event() + broker.connecting.clear() + broker.connect_gate = gate + [old] = broker.clients + old.next_reconnect_error = ssl.SSLError("handshake failed") + old.drop() + await _until(broker.connecting.is_set, "the rebuilt client's blocking connect") + + await bridge.disconnect() + await _let_the_loop_run() + gate.set() + await _until(lambda: not broker.clients[-1].held_by_a_thread, "the rebuild's connect to return") + for _ in range(5): + await asyncio.sleep(0) + + assert len(broker.clients) == 2, "precondition: the rebuild built a client" + assert broker.calls_while_held == [] + assert [session.open for session in broker.sessions] == [False, False] + assert all(session.subscribed == [_FLAT_FILTER] for session in broker.sessions[:1]) + assert broker.sessions[1].subscribed == [] + assert not bridge.is_connected() + assert errors == [] + + +@pytest.mark.asyncio +async def test_a_blocking_reconnect_that_fails_after_disconnect_is_not_reported_as_unretrieved() -> None: + """Its caller was cancelled, so nothing awaits the failure; the bridge takes it, rather than the loop reporting it on collection.""" + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client), _unobserved_loop_errors() as errors: + bridge = _bridge() + await bridge.connect() + gate = threading.Event() + broker.reconnect_gate = gate + held = broker.clients[-1] + held.next_reconnect_error = ConnectionRefusedError(61, "Connection refused") + held.drop() + await _until(broker.reconnecting.is_set, "the blocking reconnect") + + await bridge.disconnect() + await _let_the_loop_run() + gate.set() + await _until(lambda: not held.held_by_a_thread, "the reconnect to fail") + for _ in range(5): + await asyncio.sleep(0) + del held + gc.collect() + await asyncio.sleep(0) + + assert errors == [] From 8938cdd2e1b6a5408032bd384b9898f43cbec739 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:14:52 -0800 Subject: [PATCH 11/33] docs(changelog): describe the 3.9.0b2 fixes under 3.9.0 The close() line names AttributeError among the outcomes a close during connect() could have. Adds AsyncMqttBridge.connect() raising on a concurrent disconnect() and AsyncMqttBridge.subscribe() holding its topic on every later connection, and says publishes_shared_meters is None where the adapter does not say. --- CHANGELOG.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f8751f..9edff76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,13 +12,16 @@ beta corrected in an earlier beta does not appear at all: from the point of view ### Added - **`SpanCircuitSnapshot.breaker_rating_declared`** says whether a circuit declares a breaker rating, so a consumer can tell a rating the panel does not publish from one that has not arrived yet; `None` where the adapter does not say. -- **`SpanPanelSnapshot.publishes_shared_meters`** says whether any circuit declares `meter/shared-with-device-ids`, so a consumer can tell a panel that describes its multi-load breakers from one, such as MAIN 32, that publishes each as a single circuit. +- **`SpanPanelSnapshot.publishes_shared_meters`** says whether any circuit declares `meter/shared-with-device-ids`, so a consumer can tell a panel that describes its multi-load breakers from one, such as MAIN 32, that publishes each as a single circuit; + `None` where the adapter does not say, as with `span-panel-api-schema-0` or a `span-panel-api-schema-1` older than 1.5.0. ### Fixed - **Each broker connection subscribes once, so the panel's retained tree arrives once per connection**, where `connect()` subscribed twice and received the whole tree twice, and a panel that changes schema generation while connected no longer has every message under its own device delivered twice until the next reconnect. -- **`connect()` raises `SpanPanelConnectionError` when `close()` is called while it is connecting**, where it could carry on and return as if connected, or wait for the panel and report a timeout. +- **`connect()` raises `SpanPanelConnectionError` when `close()` is called while it is connecting**, where it could carry on and return as if connected, raise `AttributeError`, or wait for the panel and report a timeout. +- **`AsyncMqttBridge.connect()` raises `SpanPanelConnectionError` when `disconnect()` is called while it is connecting**, where it could raise `AttributeError` or carry on and connect. +- **`AsyncMqttBridge.subscribe()` keeps its topic subscribed on every later connection**, where the subscription ended with the connection it was made on and was lost if made before the first. ## [3.8.0] From becd7eaf6e03b71a2ec87e29ccf059c5d1dba97e Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:19:21 -0800 Subject: [PATCH 12/33] test(mqtt): wait for the parser in test_close rather than a fixed sleep test_close delivered the tree's messages after sleep(0.05), assuming connect() had built its parser by then, and a message delivered before it is dropped. connect() reaches the parser only after resolving the adapter in a thread, so a loaded machine made the test wait out its timeout. It now waits until the client has a parser. With that resolve slowed by 200 ms the old test fails every time and this one passes. --- tests/test_mqtt_connect_flow.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/tests/test_mqtt_connect_flow.py b/tests/test_mqtt_connect_flow.py index 3cc6e7d..7e1a510 100644 --- a/tests/test_mqtt_connect_flow.py +++ b/tests/test_mqtt_connect_flow.py @@ -396,6 +396,20 @@ async def test_no_reconnect_before_initial_connect(self, mqtt_client_mock: Magic # --------------------------------------------------------------------------- +async def _until_the_parser_exists(client: SpanMqttClient) -> None: + """Wait until connect() has built its parser, from which point a delivered message is read. + + A message delivered before then is dropped. A fixed sleep guessed at the + moment: connect() reaches the parser only after resolving the adapter in a + thread, which a loaded machine stretches past any guess. + """ + loop = asyncio.get_running_loop() + deadline = loop.time() + 5.0 + while client.adapter is None: + assert loop.time() < deadline, "connect() never built its parser" + await asyncio.sleep(0.005) + + def _make_span_client(snapshot_interval: float = 1.0) -> SpanMqttClient: config = MqttClientConfig( broker_host="broker.local", @@ -503,7 +517,7 @@ async def test_close(self, mqtt_client_mock: MagicMock) -> None: client = _make_span_client() connect_task = asyncio.create_task(client.connect()) - await asyncio.sleep(0.05) + await _until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", MINIMAL_DESCRIPTION) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$state", "ready") From 0611df9cf3950d293b0fefccb8e328f712d8fd48 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:23:07 -0800 Subject: [PATCH 13/33] test(mqtt): wait for the parser in the rest of test_mqtt_connect_flow Eight more tests in the file delivered the tree's messages after sleep(0.05), with the same race test_close had: a message that arrives before connect() has built its parser is dropped, and resolving the adapter in a thread can outlast the sleep on a loaded machine. Each now waits until the client has a parser. With that resolve slowed by 200 ms all eight failed before and the whole file passes now. --- tests/test_mqtt_connect_flow.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/tests/test_mqtt_connect_flow.py b/tests/test_mqtt_connect_flow.py index 7e1a510..8ef68d1 100644 --- a/tests/test_mqtt_connect_flow.py +++ b/tests/test_mqtt_connect_flow.py @@ -434,8 +434,8 @@ async def test_connect_and_ready(self, mqtt_client_mock: MagicMock) -> None: # Start connect in background — it will wait for Homie ready connect_task = asyncio.create_task(client.connect()) - # Let the bridge connect complete - await asyncio.sleep(0.05) + # Messages are read once connect() has built its parser + await _until_the_parser_exists(client) # Feed Homie messages via _on_message to trigger ready detection. # Description first (not yet ready), then state (transitions to ready). @@ -500,7 +500,7 @@ def _version(name: str) -> str: patch("span_panel_api.mqtt.client.version", side_effect=_version), ): connect_task = asyncio.create_task(client.connect()) - await asyncio.sleep(0.05) + await _until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", MINIMAL_DESCRIPTION) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$state", "ready") await asyncio.wait_for(connect_task, timeout=5.0) @@ -531,7 +531,7 @@ async def test_set_circuit_relay(self, mqtt_client_mock: MagicMock) -> None: client = _make_span_client() connect_task = asyncio.create_task(client.connect()) - await asyncio.sleep(0.05) + await _until_the_parser_exists(client) # With the circuit declared: a command aimed at an id the panel never # published is refused, so a publishing test needs a panel that carries @@ -551,7 +551,7 @@ async def test_set_circuit_priority(self, mqtt_client_mock: MagicMock) -> None: client = _make_span_client() connect_task = asyncio.create_task(client.connect()) - await asyncio.sleep(0.05) + await _until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", DESCRIPTION_WITH_CIRCUIT) # Named, or connect() spends its whole circuit-name wait on this one. @@ -567,7 +567,7 @@ async def test_streaming_dispatches_snapshot(self, mqtt_client_mock: MagicMock) client = _make_span_client() connect_task = asyncio.create_task(client.connect()) - await asyncio.sleep(0.05) + await _until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", MINIMAL_DESCRIPTION) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$state", "ready") @@ -601,7 +601,7 @@ async def test_reconnect_resubscribes(self, mqtt_client_mock: MagicMock) -> None client = _make_span_client() connect_task = asyncio.create_task(client.connect()) - await asyncio.sleep(0.05) + await _until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", MINIMAL_DESCRIPTION) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$state", "ready") @@ -935,7 +935,7 @@ async def test_pre_rebuild_resets_accumulator(self, mqtt_client_mock: MagicMock) client = _make_span_client() connect_task = asyncio.create_task(client.connect()) - await asyncio.sleep(0.05) + await _until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", MINIMAL_DESCRIPTION) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$state", "ready") await asyncio.wait_for(connect_task, timeout=5.0) @@ -961,7 +961,7 @@ async def test_pre_rebuild_preserves_schema_state(self, mqtt_client_mock: MagicM client = _make_span_client() connect_task = asyncio.create_task(client.connect()) - await asyncio.sleep(0.05) + await _until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", MINIMAL_DESCRIPTION) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$state", "ready") await asyncio.wait_for(connect_task, timeout=5.0) From 8f0ed28b750595b37a5b2ca7374f306b4fa568ad Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:30:03 -0800 Subject: [PATCH 14/33] test: wait for the parser wherever a test feeds a background connect() The wait test_mqtt_connect_flow used moves to conftest as until_the_parser_exists, and the last two fixed sleeps standing in for it go: the one in test_factory_dispatch, and the one in test_mqtt_debounce's shared connect helper, which nine tests go through. A message delivered before connect() has built its parser is dropped, and connect() reaches the parser only after resolving the adapter in a thread. With that resolve slowed by 200 ms, those ten tests failed before and pass now, and the whole suite passes. No other test in tests/ waits on a fixed sleep for the parser: the readiness-gate tests wait on a condition, and the remaining fixed sleeps wait for the reconnect loop. --- tests/conftest.py | 17 +++++++++++++++++ tests/test_factory_dispatch.py | 11 +++++++++-- tests/test_mqtt_connect_flow.py | 33 ++++++++++----------------------- tests/test_mqtt_debounce.py | 4 ++-- 4 files changed, 38 insertions(+), 27 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 58712cb..e7dd5be 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -19,6 +19,7 @@ from expected_failures import EXPECTED_FAILURES import span_panel_api._http as _http_mod from span_panel_api.models import V2HomieSchema +from span_panel_api.mqtt.client import SpanMqttClient from span_panel_api.mqtt.control import ControlDeadlines from span_panel_api_schema_0.const import TOPIC_PREFIX, TYPE_CIRCUIT, TYPE_CORE @@ -274,6 +275,22 @@ def _reconnect() -> int: yield mock_client +async def until_the_parser_exists(client: SpanMqttClient) -> None: + """Wait until connect() has built its parser, from which point a delivered message is read. + + For a test that runs connect() in the background and feeds the tree through + `_on_message`: a message delivered before the parser exists is dropped. A + fixed sleep guessed at the moment, and connect() reaches the parser only + after resolving the adapter in a thread, which a loaded machine stretches + past any guess. + """ + loop = asyncio.get_running_loop() + deadline = loop.time() + 5.0 + while client.adapter is None: + assert loop.time() < deadline, "connect() never built its parser" + await asyncio.sleep(0.005) + + def acking_bridge() -> MagicMock: """A bridge stub whose publishes are acknowledged immediately. diff --git a/tests/test_factory_dispatch.py b/tests/test_factory_dispatch.py index 4b51fb5..a9a20fb 100644 --- a/tests/test_factory_dispatch.py +++ b/tests/test_factory_dispatch.py @@ -13,7 +13,14 @@ from span_panel_api.mqtt.client import SpanMqttClient from span_panel_api.mqtt.models import MqttClientConfig -from conftest import MINIMAL_DESCRIPTION, SERIAL, TOPIC_PREFIX_SERIAL, flat_schema, parent_child_schema +from conftest import ( + MINIMAL_DESCRIPTION, + SERIAL, + TOPIC_PREFIX_SERIAL, + flat_schema, + parent_child_schema, + until_the_parser_exists, +) def test_absent_data_model_version_selects_schema_zero() -> None: @@ -169,7 +176,7 @@ async def test_diagnostics_properties_before_and_after_connect(mqtt_client_mock: client._schema_dispatch_reason = "data-model-version absent (flat schema)" # pylint: disable=protected-access connect_task = asyncio.create_task(client.connect()) - await asyncio.sleep(0.05) + await until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", MINIMAL_DESCRIPTION) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$state", "ready") await asyncio.wait_for(connect_task, timeout=5.0) diff --git a/tests/test_mqtt_connect_flow.py b/tests/test_mqtt_connect_flow.py index 8ef68d1..e27d84b 100644 --- a/tests/test_mqtt_connect_flow.py +++ b/tests/test_mqtt_connect_flow.py @@ -27,6 +27,7 @@ MINIMAL_DESCRIPTION, SERIAL, TOPIC_PREFIX_SERIAL, + until_the_parser_exists, ) @@ -396,20 +397,6 @@ async def test_no_reconnect_before_initial_connect(self, mqtt_client_mock: Magic # --------------------------------------------------------------------------- -async def _until_the_parser_exists(client: SpanMqttClient) -> None: - """Wait until connect() has built its parser, from which point a delivered message is read. - - A message delivered before then is dropped. A fixed sleep guessed at the - moment: connect() reaches the parser only after resolving the adapter in a - thread, which a loaded machine stretches past any guess. - """ - loop = asyncio.get_running_loop() - deadline = loop.time() + 5.0 - while client.adapter is None: - assert loop.time() < deadline, "connect() never built its parser" - await asyncio.sleep(0.005) - - def _make_span_client(snapshot_interval: float = 1.0) -> SpanMqttClient: config = MqttClientConfig( broker_host="broker.local", @@ -435,7 +422,7 @@ async def test_connect_and_ready(self, mqtt_client_mock: MagicMock) -> None: connect_task = asyncio.create_task(client.connect()) # Messages are read once connect() has built its parser - await _until_the_parser_exists(client) + await until_the_parser_exists(client) # Feed Homie messages via _on_message to trigger ready detection. # Description first (not yet ready), then state (transitions to ready). @@ -500,7 +487,7 @@ def _version(name: str) -> str: patch("span_panel_api.mqtt.client.version", side_effect=_version), ): connect_task = asyncio.create_task(client.connect()) - await _until_the_parser_exists(client) + await until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", MINIMAL_DESCRIPTION) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$state", "ready") await asyncio.wait_for(connect_task, timeout=5.0) @@ -517,7 +504,7 @@ async def test_close(self, mqtt_client_mock: MagicMock) -> None: client = _make_span_client() connect_task = asyncio.create_task(client.connect()) - await _until_the_parser_exists(client) + await until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", MINIMAL_DESCRIPTION) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$state", "ready") @@ -531,7 +518,7 @@ async def test_set_circuit_relay(self, mqtt_client_mock: MagicMock) -> None: client = _make_span_client() connect_task = asyncio.create_task(client.connect()) - await _until_the_parser_exists(client) + await until_the_parser_exists(client) # With the circuit declared: a command aimed at an id the panel never # published is refused, so a publishing test needs a panel that carries @@ -551,7 +538,7 @@ async def test_set_circuit_priority(self, mqtt_client_mock: MagicMock) -> None: client = _make_span_client() connect_task = asyncio.create_task(client.connect()) - await _until_the_parser_exists(client) + await until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", DESCRIPTION_WITH_CIRCUIT) # Named, or connect() spends its whole circuit-name wait on this one. @@ -567,7 +554,7 @@ async def test_streaming_dispatches_snapshot(self, mqtt_client_mock: MagicMock) client = _make_span_client() connect_task = asyncio.create_task(client.connect()) - await _until_the_parser_exists(client) + await until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", MINIMAL_DESCRIPTION) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$state", "ready") @@ -601,7 +588,7 @@ async def test_reconnect_resubscribes(self, mqtt_client_mock: MagicMock) -> None client = _make_span_client() connect_task = asyncio.create_task(client.connect()) - await _until_the_parser_exists(client) + await until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", MINIMAL_DESCRIPTION) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$state", "ready") @@ -935,7 +922,7 @@ async def test_pre_rebuild_resets_accumulator(self, mqtt_client_mock: MagicMock) client = _make_span_client() connect_task = asyncio.create_task(client.connect()) - await _until_the_parser_exists(client) + await until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", MINIMAL_DESCRIPTION) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$state", "ready") await asyncio.wait_for(connect_task, timeout=5.0) @@ -961,7 +948,7 @@ async def test_pre_rebuild_preserves_schema_state(self, mqtt_client_mock: MagicM client = _make_span_client() connect_task = asyncio.create_task(client.connect()) - await _until_the_parser_exists(client) + await until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", MINIMAL_DESCRIPTION) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$state", "ready") await asyncio.wait_for(connect_task, timeout=5.0) diff --git a/tests/test_mqtt_debounce.py b/tests/test_mqtt_debounce.py index cf26aaf..f402032 100644 --- a/tests/test_mqtt_debounce.py +++ b/tests/test_mqtt_debounce.py @@ -18,7 +18,7 @@ from span_panel_api.mqtt.client import SpanMqttClient from span_panel_api.mqtt.models import MqttClientConfig -from conftest import MINIMAL_DESCRIPTION, SERIAL, TOPIC_PREFIX_SERIAL +from conftest import MINIMAL_DESCRIPTION, SERIAL, TOPIC_PREFIX_SERIAL, until_the_parser_exists def _make_client(snapshot_interval: float = 1.0) -> SpanMqttClient: @@ -38,7 +38,7 @@ def _make_client(snapshot_interval: float = 1.0) -> SpanMqttClient: async def _connect_client(client: SpanMqttClient, mqtt_client_mock: MagicMock) -> None: """Connect the client and bring Homie to ready state.""" connect_task = asyncio.create_task(client.connect()) - await asyncio.sleep(0.05) + await until_the_parser_exists(client) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$description", MINIMAL_DESCRIPTION) client._on_message(f"{TOPIC_PREFIX_SERIAL}/$state", "ready") await asyncio.wait_for(connect_task, timeout=5.0) From 36dbb41ac1cb7bfb8506637108ff1f57db0c7682 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:34:44 -0800 Subject: [PATCH 15/33] fix(mqtt): keep the loop out of a client until its blocking call returns _run_blocking gave the executor thread thread-safe forms of only two of the four socket callbacks paho makes inside a blocking call. reconnect() replacing a socket still awaiting its CONNACK closes that socket on the thread, so the loop-only close and unregister-write handlers ran there. And the loop itself reached into the held client: the socket-open handler, scheduled from the thread, read the client while the thread was still inside paho's connect(); the misc timer called loop_misc() on a client reconnect() was inside; and the reader for the socket being replaced could fire. Every socket event paho makes inside the call is now recorded on the thread and replayed by the hand-back, in order, through the loop's handlers once the call has returned; close and unregister-write carry the descriptor, read while the socket is still open. While the call runs the loop stops watching the client's socket and the misc timer passes the client over. The client is marked held only once the executor has accepted the call, so a refused submission leaves it to the loop. --- src/span_panel_api/mqtt/connection.py | 158 ++++++++---- tests/conftest.py | 2 + tests/test_one_subscribe_per_session.py | 324 +++++++++++++++++++++--- 3 files changed, 402 insertions(+), 82 deletions(-) diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index 9378d67..439a2e6 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -447,9 +447,7 @@ def _make_paho_client(self, ssl_context: ssl.SSLContext | None) -> AsyncMQTTClie ) client.setup() client.username_pw_set(self._username, self._password) - # Wire socket callbacks (async versions by default) - client.on_socket_close = self._async_on_socket_close - client.on_socket_unregister_write = self._async_on_socket_unregister_write + self._give_loop_socket_callbacks(client) # Wire MQTT callbacks (run directly on event loop — no thread dispatch) client.on_connect = self._on_connect client.on_disconnect = self._on_disconnect @@ -606,44 +604,89 @@ def _run_blocking( ) -> asyncio.Future[object]: """Run one blocking paho call on `client` in the executor: the only way this bridge does. - While the call runs the executor thread owns the client. Its socket - callbacks are the thread-safe bridges, and nothing on the loop calls into - it -- paho runs with its locks removed, so a second thread inside the - same client could corrupt it. `disconnect()` in particular only lets it - go. - - The loop takes it back when the call returns (`_executor_returned`), not - when its caller resumes. Cancelling the caller does not stop the thread, - so the caller awaits a future the hand-back resolves rather than the - executor's own: a cancelled caller -- a reconnect task that disconnect() - cancelled -- cancels only its wait, and the hand-back still runs when the - thread is really done. Not `asyncio.shield`, which reports a failure that - arrives after its caller was cancelled through the loop's exception - handler; here that failure is the abandoned attempt's, and expected. + While the call runs the executor thread owns the client, and nothing on + the loop calls into it: paho runs with its locks removed, so a second + thread inside the same client could corrupt it. The loop stops watching + the socket it was reading for this client, `disconnect()` only lets the + client go, and the misc timer passes it over. + + paho makes socket callbacks on whichever thread it is running on, the + executor's inside this call: opening the new socket and queueing its + CONNECT, and -- in `reconnect()` -- closing the one it replaces. Each is + recorded rather than acted on, and `_executor_returned` replays them in + order once the call has returned, so every socket the call touched is + registered or released on the loop, after the thread is done. + + The loop takes the client back when the call returns, not when its + caller resumes. Cancelling the caller does not stop the thread, so the + caller awaits a future the hand-back resolves rather than the + executor's own: a cancelled caller -- a reconnect task that + disconnect() cancelled -- cancels only its wait, and the hand-back still + runs when the thread is really done. Not `asyncio.shield`, which reports + a failure that arrives after its caller was cancelled through the loop's + exception handler; here that failure is the abandoned attempt's, and + expected. """ - client.on_socket_open = self._on_socket_open_sync - client.on_socket_register_write = self._on_socket_register_write_sync + events: list[Callable[[], None]] = [] + + def opened(opener: paho.Client, userdata: object, sock: SocketLike) -> None: + events.append(partial(self._async_on_socket_open, opener, userdata, sock)) + + def write_registered(writer: paho.Client, userdata: object, sock: SocketLike) -> None: + events.append(partial(self._async_on_socket_register_write, writer, userdata, sock)) + + def write_unregistered(writer: paho.Client, _userdata: object, sock: SocketLike) -> None: + # Read now: paho closes the socket as soon as the callbacks return. + events.append(partial(self._socket_write_unregistered, writer, sock.fileno())) + + def closed(closer: paho.Client, _userdata: object, sock: SocketLike) -> None: + events.append(partial(self._socket_closed, closer, sock.fileno())) + + watched = client.socket() + watched_fileno = watched.fileno() if watched is not None else -1 + client.on_socket_open = opened + client.on_socket_register_write = write_registered + client.on_socket_unregister_write = write_unregistered + client.on_socket_close = closed + try: + call_future = loop.run_in_executor(None, call) + except BaseException: + # Refused before a thread took it: the client is still the loop's. + self._give_loop_socket_callbacks(client) + raise self._executor_clients.add(client) + if watched_fileno > -1: + loop.remove_reader(watched_fileno) + loop.remove_writer(watched_fileno) caller: asyncio.Future[object] = loop.create_future() - loop.run_in_executor(None, call).add_done_callback(partial(self._executor_returned, client, caller)) + call_future.add_done_callback(partial(self._executor_returned, client, caller, events)) return caller def _executor_returned( - self, client: AsyncMQTTClient, caller: asyncio.Future[object], call: asyncio.Future[object] + self, + client: AsyncMQTTClient, + caller: asyncio.Future[object], + events: list[Callable[[], None]], + call: asyncio.Future[object], ) -> None: """Take `client` back on the loop once its blocking `call` has returned, then answer its `caller`. - Async socket callbacks again, and a client this bridge let go of while the - thread held it -- disconnect() ran meanwhile -- is disconnected here, - closing whatever socket the call went on to open. Only then is `caller` - given the call's outcome, so whoever awaits it resumes with the client - already back. A caller that was cancelled is told nothing: the outcome is - retrieved here, so a failure nobody is waiting for is not reported as - never retrieved. + The loop's own socket callbacks again, and the socket events the call + made replayed through them, in order. A client this bridge let go of + while the thread held it -- disconnect() ran meanwhile -- is then + disconnected here, closing whatever socket the call went on to open. + Only then is `caller` given the call's outcome, so whoever awaits it + resumes with the client already back. A caller that was cancelled is + told nothing: the outcome is retrieved here, so a failure nobody is + waiting for is not reported as never retrieved. """ self._executor_clients.discard(client) - client.on_socket_open = self._async_on_socket_open - client.on_socket_register_write = self._async_on_socket_register_write + self._give_loop_socket_callbacks(client) + for event in events: + try: + event() + except Exception: # pylint: disable=broad-exception-caught + _LOGGER.warning("Replaying a socket event of a blocking paho call raised", exc_info=True) if client is not self._client: try: client.disconnect() @@ -661,6 +704,13 @@ def _executor_returned( else: caller.set_result(call.result()) + def _give_loop_socket_callbacks(self, client: paho.Client) -> None: + """Hand `client` the loop's own socket callbacks, for paho to call on the loop.""" + client.on_socket_open = self._async_on_socket_open + client.on_socket_register_write = self._async_on_socket_register_write + client.on_socket_unregister_write = self._async_on_socket_unregister_write + client.on_socket_close = self._async_on_socket_close + def _abandoned(self, attempt: object) -> bool: """Whether disconnect() has abandoned the connect() that `attempt` identifies. @@ -938,17 +988,19 @@ def _async_start_misc_periodic(self) -> None: loop = self._loop def _async_misc() -> None: - if self._client is not None and self._client.loop_misc() == paho.MQTT_ERR_SUCCESS: + client = self._client + if client is None: + return + if client in self._executor_clients: + # A thread is inside it: look again next second rather than call in. + self._misc_timer = loop.call_at(loop.time() + 1, _async_misc) + return + if client.loop_misc() == paho.MQTT_ERR_SUCCESS: self._misc_timer = loop.call_at(loop.time() + 1, _async_misc) self._misc_timer = loop.call_at(loop.time() + 1, _async_misc) - # -- Socket open/close (sync bridges for executor, async for event loop) -- - - def _on_socket_open_sync(self, client: paho.Client, userdata: object, sock: SocketLike) -> None: - """Handle socket open during executor connect — bridge to event loop.""" - if self._loop is not None: - self._loop.call_soon_threadsafe(self._async_on_socket_open, client, userdata, sock) + # -- Socket open/close, on the loop (see `_run_blocking` for the executor) -- def _async_on_socket_open(self, client: paho.Client, _userdata: object, sock: SocketLike) -> None: """Handle socket open on the event loop.""" @@ -962,28 +1014,31 @@ def _async_on_socket_open(self, client: paho.Client, _userdata: object, sock: So # Drain initial buffer immediately self._async_reader_callback(client) - def _async_on_socket_close(self, _client: paho.Client, _userdata: object, sock: SocketLike) -> None: - """Handle socket close — remove reader, cancel misc timer.""" + def _async_on_socket_close(self, client: paho.Client, _userdata: object, sock: SocketLike) -> None: + """Handle socket close on the loop.""" + self._socket_closed(client, sock.fileno()) + + def _socket_closed(self, _client: paho.Client, fileno: int) -> None: + """A socket closed: stop reading it, and end a connect still waiting on it. + + Takes the descriptor rather than the socket because a close replayed + from a blocking call (see `_run_blocking`) arrives after paho has closed + the socket, which then has none. + """ if self._loop is None: return # Ensure connect event is signaled if socket closes early if self._connect_event is not None and not self._connect_event.is_set(): self._connected = False self._connect_event.set() - fileno = sock.fileno() if fileno > -1: - self._loop.remove_reader(sock) + self._loop.remove_reader(fileno) if self._misc_timer is not None: self._misc_timer.cancel() self._misc_timer = None # -- Socket write registration ------------------------------------------ - def _on_socket_register_write_sync(self, client: paho.Client, userdata: object, sock: SocketLike) -> None: - """Register socket for writing during executor connect.""" - if self._loop is not None: - self._loop.call_soon_threadsafe(self._async_on_socket_register_write, client, userdata, sock) - def _async_on_socket_register_write(self, client: paho.Client, _userdata: object, sock: SocketLike) -> None: """Register the socket for writing on the event loop.""" if self._loop is None: @@ -992,13 +1047,16 @@ def _async_on_socket_register_write(self, client: paho.Client, _userdata: object if fileno > -1: self._loop.add_writer(sock, partial(self._async_writer_callback, client)) - def _async_on_socket_unregister_write(self, _client: paho.Client, _userdata: object, sock: SocketLike) -> None: - """Unregister the socket for writing.""" + def _async_on_socket_unregister_write(self, client: paho.Client, _userdata: object, sock: SocketLike) -> None: + """Unregister the socket for writing, on the loop.""" + self._socket_write_unregistered(client, sock.fileno()) + + def _socket_write_unregistered(self, _client: paho.Client, fileno: int) -> None: + """Stop watching a socket for writing, by descriptor for the reason `_socket_closed` gives.""" if self._loop is None: return - fileno = sock.fileno() if fileno > -1: - self._loop.remove_writer(sock) + self._loop.remove_writer(fileno) # -- MQTT callbacks (run directly on event loop) ------------------------ diff --git a/tests/conftest.py b/tests/conftest.py index e7dd5be..cb47ad8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -266,6 +266,8 @@ def _reconnect() -> int: mock_client.connect.side_effect = _connect mock_client.reconnect.side_effect = _reconnect mock_client.subscribe.return_value = (0, 1) + # A fresh paho client holds no socket until it connects. + mock_client.socket.return_value = None mock_client.publish.side_effect = _publish mock_client.disconnect.return_value = 0 mock_client.loop_read.return_value = 0 diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 0aee901..068acad 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -22,6 +22,7 @@ import contextlib import gc from dataclasses import dataclass, field +import socket import ssl import threading from unittest.mock import patch @@ -87,6 +88,40 @@ class _Session: ConnackHandler = Callable[["_FakePaho", object, ConnectFlags, ReasonCode, Properties | None], None] DisconnectHandler = Callable[["_FakePaho", object, DisconnectFlags, ReasonCode, Properties | None], None] MessageHandler = Callable[["_FakePaho", object, MQTTMessage], None] +SocketHandler = Callable[["_FakePaho", object, "_FakeSocket"], None] + + +class _FakeSocket: + """What paho hands its socket callbacks. + + No descriptor by default, so the bridge registers none. With `real`, one end + of a socket pair, so the loop's reader and writer are really registered and + a test can make the socket readable from the other end. + """ + + def __init__(self, real: bool) -> None: + self._pair = socket.socketpair() if real else None + + def fileno(self) -> int: + return self._pair[0].fileno() if self._pair is not None else -1 + + def make_readable(self) -> None: + assert self._pair is not None, "only a real socket can be made readable" + self._pair[1].send(b"\x00") + + def drain(self) -> None: + """Read what the other end sent, as paho's `loop_read` would.""" + if self._pair is not None: + self._pair[0].setblocking(False) + try: + self._pair[0].recv(4096) + except BlockingIOError: + pass + + def close(self) -> None: + if self._pair is not None: + for end in self._pair: + end.close() class _Broker: @@ -111,13 +146,45 @@ def __init__(self, loop: asyncio.AbstractEventLoop, retained: dict[str, str]) -> self.reconnect_gate: threading.Event | None = None """As `connect_gate`, for a blocking reconnect.""" self.calls_while_held: list[str] = [] - """Every call that reached a client while a blocking connect or reconnect was inside it. + """Every call that reached a client from another thread while a blocking connect or reconnect was inside it. paho runs with its locks removed, so the thread holding a client is the only one that may call into it; anything listed here came from another. """ + self.loop_thread = threading.current_thread() + self.loop_only_off_loop: list[str] = [] + """Every one of the bridge's loop-only socket handlers (`_async_*`) that paho had to call off the loop. + + paho calls a socket callback on whichever thread it is running on, the + executor's inside a blocking call; a loop-only handler there would touch + the event loop from the wrong thread. + """ + self.real_sockets = False + """While set, clients open sockets the loop really registers. See `_FakeSocket`.""" + self.holding_closes = False + """While set, a DISCONNECT that `disconnect()` queued waits in `held_closes` for `release_closes`.""" + self.held_closes: list[Callable[[], None]] = [] self.pending = 0 - """Deliveries scheduled and not yet made.""" + """Deliveries and DISCONNECT writes scheduled and not yet made.""" + + def defer(self, action: Callable[[], None]) -> None: + """Run `action` on the loop later, as paho writes a queued packet from the loop's write callback.""" + if self.holding_closes: + self.held_closes.append(action) + return + self.pending += 1 + + def run() -> None: + self.pending -= 1 + action() + + self.loop.call_soon_threadsafe(run) + + def release_closes(self) -> None: + self.holding_closes = False + held, self.held_closes = self.held_closes, [] + for action in held: + self.defer(action) def release_connacks(self) -> None: self.holding_connacks = False @@ -183,22 +250,35 @@ def _deliver(self, client: _FakePaho, session: _Session, topic: str, payload: st class _FakePaho: - """The slice of paho the bridge drives, opening sessions on a `_Broker` instead of a socket.""" + """The slice of paho the bridge drives, opening sessions on a `_Broker` instead of a socket. + + Socket callbacks are made where paho makes them: on the executor thread + inside a blocking `connect()` or `reconnect()`, on the loop for a dropped + connection or a written DISCONNECT. + """ def __init__(self, broker: _Broker) -> None: self._broker = broker self.session: _Session | None = None self.next_reconnect_error: OSError | ssl.SSLError | None = None - self.held_by_a_thread = False + self.disconnect_calls = 0 + self.loop_read_calls = 0 + self._holder: threading.Thread | None = None + self._sock: _FakeSocket | None = None + self._write_registered = False self.on_connect: ConnackHandler | None = None self.on_disconnect: DisconnectHandler | None = None self.on_message: MessageHandler | None = None - # Assigned by the bridge and never called: no real socket is opened. + self.on_socket_open: SocketHandler | None = None + self.on_socket_close: SocketHandler | None = None + self.on_socket_register_write: SocketHandler | None = None + self.on_socket_unregister_write: SocketHandler | None = None + # Assigned by the bridge and never called: nothing here publishes. self.on_publish: object = None - self.on_socket_open: object = None - self.on_socket_close: object = None - self.on_socket_register_write: object = None - self.on_socket_unregister_write: object = None + + @property + def held_by_a_thread(self) -> bool: + return self._holder is not None def setup(self) -> None: """The lock swap `AsyncMQTTClient` does; nothing to swap here.""" @@ -209,24 +289,28 @@ def username_pw_set(self, username: str, password: str | None = None) -> None: def tls_set_context(self, context: ssl.SSLContext | None = None) -> None: """TLS is not negotiated with this broker.""" + def socket(self) -> _FakeSocket | None: + return self._sock + def connect(self, host: str, port: int = 1883, keepalive: int = 60) -> MQTTErrorCode: - """Open a session and schedule its CONNACK, as paho's executor connect does.""" + """paho's `connect()` is its `reconnect()` with the address recorded first.""" assert host and port > 0 and keepalive > 0 - self.held_by_a_thread = True + self._holder = threading.current_thread() try: self._broker.connecting.set() gate = self._broker.connect_gate if gate is not None: assert gate.wait(timeout=5), "the test never released the blocking connect" + self._sock_close() session = self._open() finally: - self.held_by_a_thread = False + self._holder = None self._answer(session) return MQTTErrorCode.MQTT_ERR_SUCCESS def reconnect(self) -> MQTTErrorCode: """paho closes the previous socket without reporting a disconnect, then opens another.""" - self.held_by_a_thread = True + self._holder = threading.current_thread() try: self._broker.reconnecting.set() gate = self._broker.reconnect_gate @@ -234,23 +318,33 @@ def reconnect(self) -> MQTTErrorCode: assert gate.wait(timeout=5), "the test never released the blocking reconnect" error = self.next_reconnect_error self.next_reconnect_error = None - self._close() + self._sock_close() if error is not None: raise error session = self._open() finally: - self.held_by_a_thread = False + self._holder = None self._answer(session) return MQTTErrorCode.MQTT_ERR_SUCCESS def _record_if_held(self, call: str) -> None: - if self.held_by_a_thread: + holder = self._holder + if holder is not None and threading.current_thread() is not holder: self._broker.calls_while_held.append(call) + def _call_socket(self, callback: SocketHandler | None, sock: _FakeSocket) -> None: + """Make a socket callback on the calling thread, as paho does, noting a loop-only handler off the loop.""" + if callback is None: + return + name = getattr(callback, "__name__", "") + if name.startswith("_async_") and threading.current_thread() is not self._broker.loop_thread: + self._broker.loop_only_off_loop.append(name) + callback(self, None, sock) + def subscribe(self, topic: str | list[tuple[str, int]], qos: int = 0) -> tuple[MQTTErrorCode, int | None]: self._record_if_held("subscribe") session = self.session - if session is None or not session.open: + if self._sock is None or session is None or not session.open: return (MQTTErrorCode.MQTT_ERR_NO_CONN, None) self._broker.subscribe(self, session, [(topic, qos)] if isinstance(topic, str) else list(topic)) return (MQTTErrorCode.MQTT_ERR_SUCCESS, 1) @@ -258,35 +352,88 @@ def subscribe(self, topic: str | list[tuple[str, int]], qos: int = 0) -> tuple[M def unsubscribe(self, topic: str | list[str]) -> tuple[MQTTErrorCode, int | None]: self._record_if_held("unsubscribe") session = self.session - if session is None or not session.open: + if self._sock is None or session is None or not session.open: return (MQTTErrorCode.MQTT_ERR_NO_CONN, None) self._broker.unsubscribe(session, [topic] if isinstance(topic, str) else list(topic)) return (MQTTErrorCode.MQTT_ERR_SUCCESS, 1) + def loop_read(self) -> MQTTErrorCode: + self._record_if_held("loop_read") + self.loop_read_calls += 1 + if self._sock is not None: + self._sock.drain() + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def loop_write(self) -> MQTTErrorCode: + """Write what is queued; with nothing left, paho stops asking to write.""" + self._record_if_held("loop_write") + sock = self._sock + if sock is not None and self._write_registered: + self._write_registered = False + self._call_socket(self.on_socket_unregister_write, sock) + return MQTTErrorCode.MQTT_ERR_SUCCESS + + def loop_misc(self) -> MQTTErrorCode: + self._record_if_held("loop_misc") + return MQTTErrorCode.MQTT_ERR_SUCCESS + def disconnect(self) -> MQTTErrorCode: + """Queue a DISCONNECT, which the loop writes later; then paho reports the disconnect and closes the socket.""" self._record_if_held("disconnect") - self._close() + self.disconnect_calls += 1 + if self._sock is None: + return MQTTErrorCode.MQTT_ERR_NO_CONN + self._register_write() + self._broker.defer(self._disconnect_written) return MQTTErrorCode.MQTT_ERR_SUCCESS def drop(self) -> None: - """The network goes away under an open session: paho closes the socket and reports it.""" - self._close() + """The network goes away under an open session: paho closes the socket, then reports it.""" + self._sock_close() + self._report_disconnect(ReasonCode(PacketTypes.DISCONNECT, "Unspecified error")) + + def _disconnect_written(self) -> None: + if self._sock is None: + return + self._report_disconnect(ReasonCode(PacketTypes.DISCONNECT, "Normal disconnection")) + self._sock_close() + + def _report_disconnect(self, reason: ReasonCode) -> None: if self.on_disconnect is not None: - self.on_disconnect( - self, - None, - DisconnectFlags(is_disconnect_packet_from_server=False), - ReasonCode(PacketTypes.DISCONNECT, "Unspecified error"), - None, - ) + self.on_disconnect(self, None, DisconnectFlags(is_disconnect_packet_from_server=False), reason, None) def _open(self) -> _Session: if self._broker.refusing: raise ConnectionRefusedError(61, "Connection refused") session = self._broker.open_session() self.session = session + sock = _FakeSocket(self._broker.real_sockets) + self._sock = sock + self._call_socket(self.on_socket_open, sock) + self._register_write() # the CONNECT, queued return session + def _register_write(self) -> None: + sock = self._sock + if sock is None or self._write_registered: + return + self._write_registered = True + self._call_socket(self.on_socket_register_write, sock) + + def _sock_close(self) -> None: + """paho's `_sock_close`: unregister the write if registered, then report the close, on the calling thread.""" + sock = self._sock + if sock is None: + return + self._sock = None + if self.session is not None: + self.session.open = False + if self._write_registered: + self._write_registered = False + self._call_socket(self.on_socket_unregister_write, sock) + self._call_socket(self.on_socket_close, sock) + sock.close() + def _answer(self, session: _Session) -> None: """Schedule the CONNACK for `session`, or hold it. @@ -304,10 +451,6 @@ def connack(self, session: _Session) -> None: return self.on_connect(self, None, ConnectFlags(session_present=False), ReasonCode(PacketTypes.CONNACK, "Success"), None) - def _close(self) -> None: - if self.session is not None: - self.session.open = False - async def _let_the_loop_run() -> None: """Run what the last call scheduled, while a gated executor call is still held. @@ -363,6 +506,7 @@ async def _serving(tree: dict[str, str], schema: V2HomieSchema | None, use_tls: yield _Panel(client, broker) finally: await client.close() + assert broker.loop_only_off_loop == [], "paho called a loop-only socket handler on the executor thread" def _bridge() -> AsyncMqttBridge: @@ -1205,3 +1349,119 @@ async def test_a_blocking_reconnect_that_fails_after_disconnect_is_not_reported_ await asyncio.sleep(0) assert errors == [] + + +@pytest.mark.asyncio +async def test_a_reconnect_replacing_a_socket_still_awaiting_its_connack_leaves_the_loop_out_of_the_client( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """paho closes the old socket from the executor thread, and the loop must not reach into the client meanwhile. + + The close callbacks run on the thread, so they must be the thread-safe + forms; and the misc timer, ticking each second, must not call into the + client while the thread is inside it. Held past one tick to show that. + """ + # Long enough between attempts to gate the second one before it starts. + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.3) + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + bridge.set_subscriptions([_FLAT_FILTER]) + await bridge.connect() + broker.holding_connacks = True + broker.clients[-1].drop() + await _until(lambda: len(broker.sessions) == 2, "the first reconnect's CONNECT") + awaiting = broker.sessions[1] + gate = threading.Event() + broker.reconnecting.clear() + broker.reconnect_gate = gate + await _until(broker.reconnecting.is_set, "the second reconnect, replacing the socket awaiting its CONNACK") + + await asyncio.sleep(1.2) + gate.set() + await _until(lambda: len(broker.sessions) == 3, "the second reconnect's CONNECT") + broker.reconnect_gate = None + broker.release_connacks() + await _until(bridge.is_connected, "the CONNACK") + await _until(lambda: not bridge._executor_clients, "the hand-back") + replaced, live = broker.sessions[1], broker.sessions[2] + await bridge.disconnect() + + assert broker.loop_only_off_loop == [], "a loop-only socket handler ran on the executor thread" + assert broker.calls_while_held == [], "the loop called into a client the executor thread was inside" + assert awaiting is replaced and not replaced.open + assert replaced.subscribed == [] + assert live.subscribed == [_FLAT_FILTER] + + +@pytest.mark.asyncio +async def test_a_blocking_call_the_executor_refuses_leaves_the_client_to_the_loop() -> None: + """The client is the thread's only once the executor has taken the call; refused, it stays the loop's. + + Held regardless, it would be marked as inside a call that never ran, and + disconnect() would leave it alone for a hand-back that never comes. + """ + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + loop = asyncio.get_running_loop() + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + with ( + patch.object(loop, "run_in_executor", side_effect=RuntimeError("cannot schedule new futures after shutdown")), + pytest.raises(SpanPanelConnectionError), + ): + await bridge.connect() + [client] = broker.clients + + await bridge.disconnect() + + assert client.disconnect_calls == 1, "disconnect() treated a client no thread holds as held" + + +@pytest.mark.asyncio +async def test_the_loop_stops_reading_a_clients_socket_while_a_thread_is_inside_the_client( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Data on the socket a reconnect is about to replace must not have the loop read the client meanwhile.""" + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.3) + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + broker.real_sockets = True + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + await bridge.connect() + broker.holding_connacks = True + [client] = broker.clients + client.drop() + await _until(lambda: len(broker.sessions) == 2, "the first reconnect's CONNECT") + awaiting = client.socket() + assert awaiting is not None + gate = threading.Event() + broker.reconnecting.clear() + broker.reconnect_gate = gate + await _until(broker.reconnecting.is_set, "the second reconnect") + + awaiting.make_readable() + await asyncio.sleep(0.05) + gate.set() + await _until(lambda: not bridge._executor_clients, "the hand-back") + broker.reconnect_gate = None + await bridge.disconnect() + + assert broker.calls_while_held == [], "the loop read a client the executor thread was inside" + + +@pytest.mark.asyncio +async def test_the_loop_reads_the_socket_a_blocking_connect_opened() -> None: + """The socket the executor opened is registered on the loop once the call returns, or no CONNACK is ever read.""" + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + broker.real_sockets = True + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + await bridge.connect() + [client] = broker.clients + sock = client.socket() + assert sock is not None + reads = client.loop_read_calls + + sock.make_readable() + await _until(lambda: client.loop_read_calls > reads, "the loop to read the socket") + await bridge.disconnect() From 62c91e7794d7c0b803a6acf5a0c8f45b3e326323 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:40:11 -0800 Subject: [PATCH 16/33] fix(mqtt): let a let-go client's socket close change only that socket The socket-close handler acted for any client, unlike _on_connect and _on_disconnect. disconnect() during a blocking connect and then connect() again on the same bridge left the abandoned client's DISCONNECT to be written later, and its socket closing then set the new attempt's connect event -- "MQTT connection failed" while the broker was accepting -- and cancelled the misc timer the new socket had started. A client the bridge no longer holds now only stops being read when its socket closes. --- src/span_panel_api/mqtt/connection.py | 16 +++++++--- tests/test_one_subscribe_per_session.py | 41 +++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index 439a2e6..857a714 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -1018,21 +1018,29 @@ def _async_on_socket_close(self, client: paho.Client, _userdata: object, sock: S """Handle socket close on the loop.""" self._socket_closed(client, sock.fileno()) - def _socket_closed(self, _client: paho.Client, fileno: int) -> None: - """A socket closed: stop reading it, and end a connect still waiting on it. + def _socket_closed(self, client: paho.Client, fileno: int) -> None: + """A socket of `client` closed: stop reading it, and end a connect still waiting on it. Takes the descriptor rather than the socket because a close replayed from a blocking call (see `_run_blocking`) arrives after paho has closed the socket, which then has none. + + A client this bridge no longer holds only stops being read, as its + CONNACK and its disconnect change nothing (see `_on_connect`). Its + socket can close after the bridge has started connecting again -- an + abandoned connect's DISCONNECT written late -- and the connect waiting + now, and the misc timer the new socket started, are not its to end. """ if self._loop is None: return + if fileno > -1: + self._loop.remove_reader(fileno) + if client is not self._client: + return # Ensure connect event is signaled if socket closes early if self._connect_event is not None and not self._connect_event.is_set(): self._connected = False self._connect_event.set() - if fileno > -1: - self._loop.remove_reader(fileno) if self._misc_timer is not None: self._misc_timer.cancel() self._misc_timer = None diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 068acad..6b3340f 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -263,6 +263,7 @@ def __init__(self, broker: _Broker) -> None: self.next_reconnect_error: OSError | ssl.SSLError | None = None self.disconnect_calls = 0 self.loop_read_calls = 0 + self.loop_misc_calls = 0 self._holder: threading.Thread | None = None self._sock: _FakeSocket | None = None self._write_registered = False @@ -375,6 +376,7 @@ def loop_write(self) -> MQTTErrorCode: def loop_misc(self) -> MQTTErrorCode: self._record_if_held("loop_misc") + self.loop_misc_calls += 1 return MQTTErrorCode.MQTT_ERR_SUCCESS def disconnect(self) -> MQTTErrorCode: @@ -1465,3 +1467,42 @@ async def test_the_loop_reads_the_socket_a_blocking_connect_opened() -> None: sock.make_readable() await _until(lambda: client.loop_read_calls > reads, "the loop to read the socket") await bridge.disconnect() + + +@pytest.mark.asyncio +async def test_a_let_go_clients_socket_closing_late_leaves_the_bridges_next_connect_alone() -> None: + """An abandoned connect's socket closes after the bridge has started connecting again; that close is not the new one's. + + Acted on, it ended the new connect's wait for its CONNACK as a failure -- + `MQTT connection failed` while the broker was accepting -- and cancelled the + misc timer the new socket had started, leaving that session without + keepalives. + """ + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + bridge.set_subscriptions([_FLAT_FILTER]) + gate = threading.Event() + broker.connect_gate = gate + broker.holding_closes = True + await _disconnect_while_bridge_connects(broker, bridge, broker.connecting.is_set, gate.set) + assert broker.held_closes, "precondition: the abandoned client's DISCONNECT is still unwritten" + broker.connect_gate = None + broker.holding_connacks = True + connecting = asyncio.create_task(bridge.connect()) + await _until(lambda: bool(broker.held), "the second connect to await its CONNACK") + + broker.release_closes() + await _until(lambda: broker.pending == 0, "the abandoned client's DISCONNECT write") + broker.release_connacks() + await asyncio.wait_for(connecting, timeout=5) + live = broker.clients[-1] + misc = live.loop_misc_calls + await asyncio.sleep(1.2) + ticked = live.loop_misc_calls > misc + await bridge.disconnect() + await _until(lambda: broker.pending == 0, "the live client's DISCONNECT write") + + assert [session.open for session in broker.sessions] == [False, False] + assert broker.sessions[1].subscribed == [_FLAT_FILTER] + assert ticked, "the late close cancelled the live session's misc timer" From 6f037312df3166145563a5822c20af1b59f39657 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:44:19 -0800 Subject: [PATCH 17/33] fix(mqtt): tell a bridge's user it disconnected when it disconnects In 3.8.0 a direct user of AsyncMqttBridge heard connected=False after its own disconnect(), from paho's report once the DISCONNECT was written. disconnect() now lets the client go before that report, which _on_disconnect then ignores, so the user heard nothing. disconnect() now tells the connection callback False itself, once, when the bridge was connected. SpanMqttClient.close() is no longer live by the time its bridge disconnects, so that False is no edge and its consumers are not told the panel was lost, as in 3.8.0, where paho's report arrived after close() had already marked the client not live. --- src/span_panel_api/mqtt/client.py | 9 +++++-- src/span_panel_api/mqtt/connection.py | 9 +++++++ tests/test_one_subscribe_per_session.py | 35 +++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/span_panel_api/mqtt/client.py b/src/span_panel_api/mqtt/client.py index 24555ee..a30d2a9 100644 --- a/src/span_panel_api/mqtt/client.py +++ b/src/span_panel_api/mqtt/client.py @@ -684,8 +684,14 @@ def _assert_transports_agree_on_schema_generation(self) -> None: ) async def close(self) -> None: - """Disconnect from broker and clean up.""" + """Disconnect from broker and clean up. + + Not live before the bridge disconnects, so the `False` the bridge then + reports is no edge: closing is the consumer's own act, and its + connection callbacks are not told the panel was lost, as in 3.8.0. + """ self._streaming = False + self._live = False self._cancel_snapshot_timer() for task in self._background_tasks: task.cancel() @@ -693,7 +699,6 @@ async def close(self) -> None: if self._bridge is not None: await self._bridge.disconnect() self._bridge = None - self._live = False async def ping(self) -> bool: """Check if MQTT connection is alive and device is ready. diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index 857a714..b8b045f 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -570,7 +570,14 @@ async def disconnect(self) -> None: Also abandons a connect() in progress: it raises `SpanPanelConnectionError` at its next step rather than go on to connect, and its wait for a CONNACK ends here rather than running out. + + A bridge that was connected tells its connection callback `False` here, + once. paho reports the disconnect only after it has written the + DISCONNECT, from a client this bridge has by then let go of and so + ignores (see `_on_disconnect`); the callback hears it from here instead, + as it did from paho in 3.8.0. """ + was_connected = self._connected self._should_reconnect = False self._connect_attempt = None connack = self._connect_event @@ -598,6 +605,8 @@ async def disconnect(self) -> None: self._connected = False self._client = None self._initial_connect_done = False + if was_connected and self._connection_callback is not None: + self._connection_callback(False) def _run_blocking( self, loop: asyncio.AbstractEventLoop, client: AsyncMQTTClient, call: Callable[[], object] diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 6b3340f..7d1f866 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -1506,3 +1506,38 @@ async def test_a_let_go_clients_socket_closing_late_leaves_the_bridges_next_conn assert [session.open for session in broker.sessions] == [False, False] assert broker.sessions[1].subscribed == [_FLAT_FILTER] assert ticked, "the late close cancelled the live session's misc timer" + + +@pytest.mark.asyncio +async def test_a_bridges_own_disconnect_tells_its_user_once() -> None: + """As in 3.8.0, a direct user of the bridge hears connected=False after its own disconnect(), and only once. + + paho's own report of that disconnect now comes from a client the bridge has + let go of, and is ignored, so the bridge says it itself. + """ + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + edges: list[bool] = [] + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + bridge.set_connection_callback(edges.append) + await bridge.connect() + + await bridge.disconnect() + assert edges == [True, False] + await _until(lambda: broker.pending == 0, "paho's own report of the disconnect") + await bridge.disconnect() + + assert edges == [True, False] + + +@pytest.mark.asyncio +async def test_closing_the_client_does_not_tell_its_consumers_the_panel_was_lost(panel: _Panel) -> None: + """As in 3.8.0: close() is the consumer's own act, not an outage to be told about.""" + edges: list[bool] = [] + panel.client.register_connection_callback(edges.append) + await _connected(panel) + + await panel.client.close() + await panel.quiesce() + + assert edges == [True] From 27f7a7e59e7c94b8c5dac002843a677b9d8efc38 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:48:18 -0800 Subject: [PATCH 18/33] fix(mqtt): take only an integer QoS in AsyncMqttBridge.subscribe() subscribe() checked qos by value, so 1.0 and True passed as QoS 1 and reached paho that way. It now refuses anything but the integer 0, 1 or 2, before recording anything. Its CONNACK gate, which keeps a topic subscribed between a CONNECT and its CONNACK from being sent twice, gets the test set_subscriptions already has. --- src/span_panel_api/mqtt/connection.py | 7 ++++--- tests/test_one_subscribe_per_session.py | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index b8b045f..0597e6c 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -828,11 +828,12 @@ def subscribe(self, topic: str, qos: int = 0) -> None: Raises: ValueError: `topic` is not a valid MQTT topic filter, or `qos` is - not 0, 1 or 2. Refused here, before anything is recorded, for - the reason `set_subscriptions` gives. + not the integer 0, 1 or 2 -- `1.0` and `True` compare equal to + 1 and are refused all the same. Refused here, before anything + is recorded, for the reason `set_subscriptions` gives. """ _check_topic_filter(topic) - if qos not in (0, 1, 2): + if isinstance(qos, bool) or not isinstance(qos, int) or qos not in (0, 1, 2): raise ValueError(f"MQTT has no QoS {qos!r}: a subscription is at QoS 0, 1 or 2") before = self._held().get(topic) self._added[topic] = max(qos, self._added.get(topic, 0)) diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 7d1f866..777012f 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -1083,6 +1083,8 @@ async def test_subscribe_honours_its_qos_and_a_topic_is_held_at_the_highest_aske pytest.param("", 0, id="empty-filter"), pytest.param("ebus/#/core", 0, id="malformed-filter"), pytest.param("a/b", 3, id="no-such-qos"), + pytest.param("a/b", 1.0, id="float-qos"), + pytest.param("a/b", True, id="bool-qos"), ], ) @pytest.mark.asyncio @@ -1541,3 +1543,23 @@ async def test_closing_the_client_does_not_tell_its_consumers_the_panel_was_lost await panel.quiesce() assert edges == [True] + + +@pytest.mark.asyncio +async def test_a_topic_subscribed_between_connect_and_connack_is_sent_once_by_the_connack() -> None: + """As for `set_subscriptions`: paho would send it on the socket awaiting its CONNACK, and the CONNACK would send it again.""" + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + broker.holding_connacks = True + connecting = asyncio.create_task(bridge.connect()) + await _until(lambda: bool(broker.held), "the CONNECT") + [awaiting] = broker.sessions + + bridge.subscribe(_CONSUMER_TOPIC) + assert awaiting.subscribed == [], "nothing may be subscribed before the CONNACK" + broker.release_connacks() + await asyncio.wait_for(connecting, timeout=5) + await bridge.disconnect() + + assert awaiting.subscribed == [_CONSUMER_TOPIC] From fff3b237aa0660b3e1f3021109cb8dc7b41843ce Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:51:51 -0800 Subject: [PATCH 19/33] fix(mqtt): end connect()'s ready wait when connect() is cancelled The wait for a ready tree runs as a task of its own, so close() can end it, and a connect() cancelled during it left that task pending until something closed the client. connect() now cancels it however the wait ends. --- src/span_panel_api/mqtt/client.py | 9 +++++++-- tests/test_one_subscribe_per_session.py | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/src/span_panel_api/mqtt/client.py b/src/span_panel_api/mqtt/client.py index a30d2a9..66a8b31 100644 --- a/src/span_panel_api/mqtt/client.py +++ b/src/span_panel_api/mqtt/client.py @@ -589,10 +589,15 @@ async def connect(self) -> None: ready = self._loop.create_task(_until_set(self._ready_event), name="span_mqtt_wait_ready") self._background_tasks.add(ready) ready.add_done_callback(self._background_tasks.discard) - done, _ = await asyncio.wait([ready], timeout=MQTT_READY_TIMEOUT_S) + try: + done, _ = await asyncio.wait([ready], timeout=MQTT_READY_TIMEOUT_S) + finally: + # The wait is this call's own: it ends with the call however the call + # ends -- timed out, or connect() itself cancelled. + if not ready.done(): + ready.cancel() await self._stop_if_closed(bridge) if not done: - ready.cancel() await self.close() raise SpanPanelConnectionError(f"Timed out waiting for Homie device ready ({self._serial_number})") diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 777012f..2a456d8 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -1563,3 +1563,23 @@ async def test_a_topic_subscribed_between_connect_and_connack_is_sent_once_by_th await bridge.disconnect() assert awaiting.subscribed == [_CONSUMER_TOPIC] + + +@pytest.mark.asyncio +async def test_cancelling_connect_during_the_wait_for_ready_ends_that_wait() -> None: + """The ready wait runs as a task of its own; a cancelled connect() must not leave it behind.""" + never_ready = {f"{TOPIC_PREFIX_SERIAL}/$description": MINIMAL_DESCRIPTION} + + def ready_waits() -> list[asyncio.Task[object]]: + return [task for task in asyncio.all_tasks() if task.get_name() == "span_mqtt_wait_ready" and not task.done()] + + async with _serving(never_ready, flat_schema()) as panel: + connecting = asyncio.create_task(panel.client.connect()) + await panel.until(lambda: bool(ready_waits()), "connect() to wait for a ready tree") + + connecting.cancel() + with pytest.raises(asyncio.CancelledError): + await connecting + await asyncio.sleep(0) + + assert ready_waits() == [] From d461d7946cfc16ccc1342ebdddad2ca73203bcf0 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:55:10 -0800 Subject: [PATCH 20/33] fix(mqtt): close what a rebuild's failed connect left of the new client The rebuild's comment said the hand-back disconnected the new client when its connect failed. It did not: at hand-back the new client was still the bridge's, and only afterwards was the old one restored, so a connect that had opened its socket before failing left that socket open. The rebuild now disconnects the new client itself once it has restored the old one. --- src/span_panel_api/mqtt/connection.py | 11 +++++++--- tests/test_one_subscribe_per_session.py | 27 +++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index 0597e6c..f4415ab 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -1287,10 +1287,15 @@ def _blocking_connect() -> None: await self._run_blocking(self._loop, new_client, _blocking_connect) except Exception as exc: # pylint: disable=broad-exception-caught _LOGGER.warning("Client rebuild — initial connect failed: %s", exc) - # Restore the previous client so the loop keeps retrying - # with what it had. Whatever the failed connect left of the new - # one, `_executor_returned` has disconnected, as a let-go client. + # Restore the previous client so the loop keeps retrying with + # what it had, and close whatever the failed connect left of the + # new one. The hand-back has run, so no thread holds it, and it + # did not close the client then: it was still `self._client`. self._client = old_client + try: + new_client.disconnect() + except Exception: # pylint: disable=broad-exception-caught + _LOGGER.debug("Disconnecting the failed rebuild's client raised", exc_info=True) return False _LOGGER.info("MQTT client rebuilt for reconnect (TLS=%s)", self._use_tls) diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 2a456d8..50c1c23 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -159,6 +159,8 @@ def __init__(self, loop: asyncio.AbstractEventLoop, retained: dict[str, str]) -> executor's inside a blocking call; a loop-only handler there would touch the event loop from the wrong thread. """ + self.connect_fails_after_opening: OSError | None = None + """When set, the next blocking connect opens its socket and then raises this, leaving the socket open.""" self.real_sockets = False """While set, clients open sockets the loop really registers. See `_FakeSocket`.""" self.holding_closes = False @@ -304,6 +306,10 @@ def connect(self, host: str, port: int = 1883, keepalive: int = 60) -> MQTTError assert gate.wait(timeout=5), "the test never released the blocking connect" self._sock_close() session = self._open() + failure = self._broker.connect_fails_after_opening + self._broker.connect_fails_after_opening = None + if failure is not None: + raise failure finally: self._holder = None self._answer(session) @@ -1583,3 +1589,24 @@ def ready_waits() -> list[asyncio.Task[object]]: await asyncio.sleep(0) assert ready_waits() == [] + + +@pytest.mark.asyncio +async def test_a_rebuild_whose_connect_fails_closes_what_that_connect_opened() -> None: + """The loop goes on with the old client; the new one, whose socket the failed connect left open, is closed.""" + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + await bridge.connect() + [old] = broker.clients + broker.connect_fails_after_opening = ConnectionResetError(54, "Connection reset by peer") + old.next_reconnect_error = ssl.SSLError("handshake failed") + + old.drop() + await _until(lambda: len(broker.clients) == 2, "the rebuild's client") + await _until(lambda: len(broker.sessions) == 3, "the old client's next reconnect") + await _until(lambda: broker.pending == 0, "the failed client's DISCONNECT write") + await bridge.disconnect() + + failed = broker.sessions[1] + assert broker.clients[1].socket() is None and not failed.open, "the failed connect's socket was left open" From 3860d73728970a21fcd089f086fa1f8b06410ee5 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 18:58:24 -0800 Subject: [PATCH 21/33] refactor(mqtt): drop connect()'s abandon check after the executor disconnect() sets the CONNACK event as it abandons an attempt, so an attempt abandoned while the executor held the client already returns at once from the CONNACK wait, and the check after that wait reports it with the same error. The check right after the executor added nothing a mutation could take away; that window now rests on the one check, which the blocking-connect tests pin. --- src/span_panel_api/mqtt/connection.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index f4415ab..89b78d6 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -544,11 +544,11 @@ def _blocking_connect() -> None: # see the documented SpanPanelConnectionError. raise SpanPanelConnectionError(f"Cannot connect to MQTT broker at {self._host}:{self._port}: {exc}") from exc _LOGGER.debug("BRIDGE: Executor connect returned, waiting for CONNACK...") - # A disconnect() while the executor held the client left it to the - # thread, and `_executor_returned` has closed it by now. - self._raise_if_abandoned(attempt) - # Wait for CONNACK, or for disconnect(), which sets the same event. + # Wait for CONNACK, or for disconnect(), which sets the same event. A + # disconnect() while the executor held the client has already set it -- + # and `_executor_returned` has closed the client -- so this returns at + # once and the check below reports the abandoned attempt. try: await asyncio.wait_for(connack.wait(), timeout=MQTT_CONNECT_TIMEOUT_S) except TimeoutError as exc: From 75a2c5fb6136c32105bd5fcb516d6022351fc619 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:01:06 -0800 Subject: [PATCH 22/33] test(mqtt): wait for the hand-back rather than counting loop turns Three cross-thread tests waited for a blocking call's hand-back with five sleep(0)s after the thread returned. They now wait until the bridge holds no client in an executor call, and then for the DISCONNECT the hand-back queued for a let-go client to be written. --- tests/test_one_subscribe_per_session.py | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 50c1c23..171c2e9 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -1292,9 +1292,8 @@ async def test_disconnect_during_a_blocking_reconnect_waits_for_the_thread_then_ await bridge.disconnect() await _let_the_loop_run() gate.set() - await _until(lambda: not broker.clients[-1].held_by_a_thread, "the reconnect to return") - for _ in range(5): - await asyncio.sleep(0) + await _until(lambda: not bridge._executor_clients, "the hand-back") + await _until(lambda: broker.pending == 0, "the let-go client's DISCONNECT write") assert broker.calls_while_held == [] assert [session.open for session in broker.sessions] == [False, False] @@ -1321,9 +1320,8 @@ async def test_disconnect_during_a_rebuilds_blocking_connect_waits_for_the_threa await bridge.disconnect() await _let_the_loop_run() gate.set() - await _until(lambda: not broker.clients[-1].held_by_a_thread, "the rebuild's connect to return") - for _ in range(5): - await asyncio.sleep(0) + await _until(lambda: not bridge._executor_clients, "the hand-back") + await _until(lambda: broker.pending == 0, "the let-go client's DISCONNECT write") assert len(broker.clients) == 2, "precondition: the rebuild built a client" assert broker.calls_while_held == [] @@ -1351,12 +1349,9 @@ async def test_a_blocking_reconnect_that_fails_after_disconnect_is_not_reported_ await bridge.disconnect() await _let_the_loop_run() gate.set() - await _until(lambda: not held.held_by_a_thread, "the reconnect to fail") - for _ in range(5): - await asyncio.sleep(0) + await _until(lambda: not bridge._executor_clients, "the hand-back") del held gc.collect() - await asyncio.sleep(0) assert errors == [] From 3ab3d15f93fa606729eb1edd742e4a770606d056 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:57:50 -0800 Subject: [PATCH 23/33] fix(mqtt): never unwatch a socket by a descriptor number it may no longer own A close paho made on the executor thread -- reconnect() replacing a socket still awaiting its CONNACK -- was replayed by the hand-back as remove_reader and remove_writer on the descriptor number recorded at the close. paho had closed that socket on the thread, so the number was free for the rest of the call, and anything else in the process could take it: the hand-back then stopped the loop reading the new owner. A second bridge kept is_connected and never heard from its broker again; an asyncio transport logged a RuntimeError. The loop now acts only on a socket object it knows to be open. _run_blocking stops watching the client's socket before the call is submitted, by the socket itself, and keeps what restores exactly those watchers. A close made inside the call records only the bridge's own bookkeeping, and a write-unregister records nothing, since no socket of the client is watched while the call runs. Socket closes paho makes on the loop unwatch by the socket while it is still open. If the call leaves the socket it was given open and still the client's -- the executor never ran it, or reconnect() refused its host before closing anything -- the hand-back watches it again as it was. --- src/span_panel_api/mqtt/connection.py | 118 +++++++++----- tests/test_one_subscribe_per_session.py | 201 +++++++++++++++++++++++- 2 files changed, 275 insertions(+), 44 deletions(-) diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index 89b78d6..d7294e0 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -59,6 +59,10 @@ _MQTT_MAX_STRING_BYTES = 65535 +def _nothing_to_restore() -> None: + """What `_stop_watching` returns for a client with no open socket to give back.""" + + def _check_topic_filter(topic: str) -> None: """Refuse what MQTT 3.1.1 does not accept as a topic filter (section 4.7). @@ -621,10 +625,21 @@ def _run_blocking( paho makes socket callbacks on whichever thread it is running on, the executor's inside this call: opening the new socket and queueing its - CONNECT, and -- in `reconnect()` -- closing the one it replaces. Each is - recorded rather than acted on, and `_executor_returned` replays them in - order once the call has returned, so every socket the call touched is - registered or released on the loop, after the thread is done. + CONNECT, and -- in `reconnect()` -- closing the one it replaces. An open + is recorded and replayed by `_executor_returned` once the call has + returned, so the loop starts watching the new socket after the thread is + done. A close needs nothing from the loop but the bridge's own + bookkeeping: the loop stopped watching this client's socket before the + call, while it was certainly still open, and watches none the call opens + until the hand-back. + + Nothing is ever keyed by a descriptor number. Once paho closes a socket + its number is free for anything else in the process -- another panel's + bridge, Home Assistant's own MQTT, a resolver -- so the loop acts only on + a socket object it knows to be open: the client's, unwatched before the + call; one the call opened, registered after it and only while it is + still open; and the client's again if the call left it open, watched + again exactly as it was. The loop takes the client back when the call returns, not when its caller resumes. Cancelling the caller does not stop the thread, so the @@ -644,15 +659,14 @@ def opened(opener: paho.Client, userdata: object, sock: SocketLike) -> None: def write_registered(writer: paho.Client, userdata: object, sock: SocketLike) -> None: events.append(partial(self._async_on_socket_register_write, writer, userdata, sock)) - def write_unregistered(writer: paho.Client, _userdata: object, sock: SocketLike) -> None: - # Read now: paho closes the socket as soon as the callbacks return. - events.append(partial(self._socket_write_unregistered, writer, sock.fileno())) + def write_unregistered(_writer: paho.Client, _userdata: object, _sock: SocketLike) -> None: + """Nothing to replay: no socket of this client is watched while the call runs.""" - def closed(closer: paho.Client, _userdata: object, sock: SocketLike) -> None: - events.append(partial(self._socket_closed, closer, sock.fileno())) + def closed(closer: paho.Client, _userdata: object, _sock: SocketLike) -> None: + events.append(partial(self._socket_gone, closer)) - watched = client.socket() - watched_fileno = watched.fileno() if watched is not None else -1 + # Before the call is submitted, so before the thread can close the socket. + watch_again = self._stop_watching(loop, client) client.on_socket_open = opened client.on_socket_register_write = write_registered client.on_socket_unregister_write = write_unregistered @@ -662,18 +676,41 @@ def closed(closer: paho.Client, _userdata: object, sock: SocketLike) -> None: except BaseException: # Refused before a thread took it: the client is still the loop's. self._give_loop_socket_callbacks(client) + watch_again() raise self._executor_clients.add(client) - if watched_fileno > -1: - loop.remove_reader(watched_fileno) - loop.remove_writer(watched_fileno) caller: asyncio.Future[object] = loop.create_future() - call_future.add_done_callback(partial(self._executor_returned, client, caller, events)) + call_future.add_done_callback(partial(self._executor_returned, client, watch_again, caller, events)) return caller + def _stop_watching(self, loop: asyncio.AbstractEventLoop, client: paho.Client) -> Callable[[], None]: + """Stop the loop reading and writing `client`'s socket, and return what gives the loop that socket back. + + By the socket object, while it is open: its descriptor is its own until + paho closes it. The returned call restores exactly the watchers this + took away, and only for that same socket while it is still open and + still the client's -- a call that closed or replaced it gets nothing back. + """ + sock = client.socket() + if sock is None or sock.fileno() < 0: + return _nothing_to_restore + reading = loop.remove_reader(sock) + writing = loop.remove_writer(sock) + + def watch_again() -> None: + if client.socket() is not sock or sock.fileno() < 0: + return + if reading: + loop.add_reader(sock, partial(self._async_reader_callback, client)) + if writing: + loop.add_writer(sock, partial(self._async_writer_callback, client)) + + return watch_again + def _executor_returned( self, client: AsyncMQTTClient, + watch_again: Callable[[], None], caller: asyncio.Future[object], events: list[Callable[[], None]], call: asyncio.Future[object], @@ -681,7 +718,10 @@ def _executor_returned( """Take `client` back on the loop once its blocking `call` has returned, then answer its `caller`. The loop's own socket callbacks again, and the socket events the call - made replayed through them, in order. A client this bridge let go of + made replayed through them, in order. The socket the call was given is + watched again if the call left it open -- an executor that never ran + the call, a `reconnect()` that refused its host before closing anything. + A client this bridge let go of while the thread held it -- disconnect() ran meanwhile -- is then disconnected here, closing whatever socket the call went on to open. Only then is `caller` given the call's outcome, so whoever awaits it @@ -696,6 +736,7 @@ def _executor_returned( event() except Exception: # pylint: disable=broad-exception-caught _LOGGER.warning("Replaying a socket event of a blocking paho call raised", exc_info=True) + watch_again() if client is not self._client: try: client.disconnect() @@ -1025,26 +1066,22 @@ def _async_on_socket_open(self, client: paho.Client, _userdata: object, sock: So self._async_reader_callback(client) def _async_on_socket_close(self, client: paho.Client, _userdata: object, sock: SocketLike) -> None: - """Handle socket close on the loop.""" - self._socket_closed(client, sock.fileno()) - - def _socket_closed(self, client: paho.Client, fileno: int) -> None: - """A socket of `client` closed: stop reading it, and end a connect still waiting on it. + """Handle socket close on the loop: paho calls this before it closes the socket, so the socket is still its own.""" + # The bookkeeping first, so a removal that raised could not leave it undone. + self._socket_gone(client) + loop = self._loop + if loop is not None and sock.fileno() > -1: + loop.remove_reader(sock) - Takes the descriptor rather than the socket because a close replayed - from a blocking call (see `_run_blocking`) arrives after paho has closed - the socket, which then has none. + def _socket_gone(self, client: paho.Client) -> None: + """A socket of `client` closed: end a connect still waiting on it, and stop the misc timer. - A client this bridge no longer holds only stops being read, as its - CONNACK and its disconnect change nothing (see `_on_connect`). Its - socket can close after the bridge has started connecting again -- an - abandoned connect's DISCONNECT written late -- and the connect waiting - now, and the misc timer the new socket started, are not its to end. + Only for the client this bridge holds, as its CONNACK and its disconnect + are heard only from it (see `_on_connect`). A let-go client's socket can + close after the bridge has started connecting again -- an abandoned + connect's DISCONNECT written late -- and the connect waiting now, and + the misc timer the new socket started, are not its to end. """ - if self._loop is None: - return - if fileno > -1: - self._loop.remove_reader(fileno) if client is not self._client: return # Ensure connect event is signaled if socket closes early @@ -1065,16 +1102,11 @@ def _async_on_socket_register_write(self, client: paho.Client, _userdata: object if fileno > -1: self._loop.add_writer(sock, partial(self._async_writer_callback, client)) - def _async_on_socket_unregister_write(self, client: paho.Client, _userdata: object, sock: SocketLike) -> None: - """Unregister the socket for writing, on the loop.""" - self._socket_write_unregistered(client, sock.fileno()) - - def _socket_write_unregistered(self, _client: paho.Client, fileno: int) -> None: - """Stop watching a socket for writing, by descriptor for the reason `_socket_closed` gives.""" - if self._loop is None: - return - if fileno > -1: - self._loop.remove_writer(fileno) + def _async_on_socket_unregister_write(self, _client: paho.Client, _userdata: object, sock: SocketLike) -> None: + """Unregister the socket for writing, on the loop, by the socket while it is still open.""" + loop = self._loop + if loop is not None and sock.fileno() > -1: + loop.remove_writer(sock) # -- MQTT callbacks (run directly on event loop) ------------------------ diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 171c2e9..6020112 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -101,6 +101,7 @@ class _FakeSocket: def __init__(self, real: bool) -> None: self._pair = socket.socketpair() if real else None + self.bytes_read = 0 def fileno(self) -> int: return self._pair[0].fileno() if self._pair is not None else -1 @@ -114,7 +115,7 @@ def drain(self) -> None: if self._pair is not None: self._pair[0].setblocking(False) try: - self._pair[0].recv(4096) + self.bytes_read += len(self._pair[0].recv(4096)) except BlockingIOError: pass @@ -159,6 +160,10 @@ def __init__(self, loop: asyncio.AbstractEventLoop, retained: dict[str, str]) -> executor's inside a blocking call; a loop-only handler there would touch the event loop from the wrong thread. """ + self.reconnect_fails_before_closing: Exception | None = None + """When set, the next blocking reconnect raises this before closing the socket it holds, as paho does on a bad host.""" + self.after_closing_in_reconnect: Callable[[], None] | None = None + """Called on the thread once a blocking reconnect has closed the old socket and before it opens the next.""" self.connect_fails_after_opening: OSError | None = None """When set, the next blocking connect opens its socket and then raises this, leaving the socket open.""" self.real_sockets = False @@ -323,9 +328,16 @@ def reconnect(self) -> MQTTErrorCode: gate = self._broker.reconnect_gate if gate is not None: assert gate.wait(timeout=5), "the test never released the blocking reconnect" + early = self._broker.reconnect_fails_before_closing + self._broker.reconnect_fails_before_closing = None + if early is not None: + raise early error = self.next_reconnect_error self.next_reconnect_error = None self._sock_close() + after_closing = self._broker.after_closing_in_reconnect + if after_closing is not None: + after_closing() if error is not None: raise error session = self._open() @@ -530,6 +542,47 @@ def _bridge() -> AsyncMqttBridge: ) +_LOOP_OPERATIONS = ( + "add_reader", + "remove_reader", + "add_writer", + "remove_writer", + "call_soon", + "call_at", + "call_later", + # What `TimerHandle.cancel()` calls: cancelling the misc timer off the loop. + "_timer_handle_cancelled", +) + + +@pytest.fixture(autouse=True) +async def _the_loop_is_driven_only_from_its_own_thread() -> AsyncIterator[None]: + """Every event-loop operation in these tests is made on the loop's thread. + + The thread-safe way in is `call_soon_threadsafe`, which is left alone. A + loop operation from the executor thread -- a socket callback acting there + rather than being recorded for the hand-back, whatever it is called -- is a + failure of the test that made it. + """ + loop = asyncio.get_running_loop() + loop_thread = threading.current_thread() + off_loop: list[str] = [] + with contextlib.ExitStack() as patches: + for name in _LOOP_OPERATIONS: + original: Callable[..., object] = getattr(loop, name) + + def guarded( + *args: object, _name: str = name, _original: Callable[..., object] = original, **kwargs: object + ) -> object: + if threading.current_thread() is not loop_thread: + off_loop.append(_name) + return _original(*args, **kwargs) + + patches.enter_context(patch.object(loop, name, guarded)) + yield + assert off_loop == [], f"event-loop operations made off the loop's thread: {off_loop}" + + @pytest.fixture(autouse=True) def _quick_reconnects(monkeypatch: pytest.MonkeyPatch) -> None: """Short enough that a refused reconnect is retried inside a test's patience.""" @@ -1605,3 +1658,149 @@ async def test_a_rebuild_whose_connect_fails_closes_what_that_connect_opened() - failed = broker.sessions[1] assert broker.clients[1].socket() is None and not failed.open, "the failed connect's socket was left open" + + +def _parked_after_closing( + broker: _Broker, +) -> tuple[threading.Event, threading.Event, list[tuple[socket.socket, socket.socket]]]: + """Park the next blocking reconnect after it closes the old socket, having opened a socket pair of its own meanwhile. + + The pair stands in for anything else in the process: the lowest free + descriptors are the ones the close just freed, so it takes them. + """ + closed = threading.Event() + resume = threading.Event() + taken: list[tuple[socket.socket, socket.socket]] = [] + + def after_closing() -> None: + taken.append(socket.socketpair()) + closed.set() + assert resume.wait(timeout=5), "the test never resumed the reconnect" + + broker.after_closing_in_reconnect = after_closing + return closed, resume, taken + + +@pytest.mark.asyncio +async def test_a_hand_back_never_unwatches_a_descriptor_someone_else_took_meanwhile(monkeypatch: pytest.MonkeyPatch) -> None: + """The reconnect closed the old socket on the thread; its number went to another socket before the hand-back. + + Unwatching by the remembered number would stop the loop reading that other + socket -- another panel's bridge, Home Assistant's own MQTT, a resolver -- + which would then never hear from its peer again. + """ + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.3) + loop = asyncio.get_running_loop() + broker = _Broker(loop, _FLAT_TREE) + broker.real_sockets = True + heard: list[bytes] = [] + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + await bridge.connect() + broker.holding_connacks = True + [client] = broker.clients + client.drop() + await _until(lambda: len(broker.sessions) == 2, "the first reconnect's CONNECT") + awaiting = client.socket() + assert awaiting is not None + freed = awaiting.fileno() + closed, resume, taken = _parked_after_closing(broker) + await _until(closed.is_set, "the second reconnect to close the awaiting socket") + [(other, peer)] = taken + assert other.fileno() == freed or peer.fileno() == freed, "precondition: the freed number was taken" + mine = other if other.fileno() == freed else peer + theirs = peer if mine is other else other + loop.add_reader(mine, lambda: heard.append(mine.recv(16))) + + resume.set() + await _until(lambda: not bridge._executor_clients, "the hand-back") + theirs.send(b"still here") + await _until(lambda: bool(heard), "the other socket to be read") + loop.remove_reader(mine) + broker.after_closing_in_reconnect = None + await bridge.disconnect() + other.close() + peer.close() + + assert heard == [b"still here"] + + +@pytest.mark.asyncio +async def test_a_blocking_reconnect_that_never_closes_its_socket_leaves_it_watched(monkeypatch: pytest.MonkeyPatch) -> None: + """paho refuses a bad host before closing the socket it holds; the hand-back gives the loop that socket back.""" + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.3) + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + broker.real_sockets = True + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + await bridge.connect() + broker.holding_connacks = True + [client] = broker.clients + client.drop() + await _until(lambda: len(broker.sessions) == 2, "the first reconnect's CONNECT") + awaiting = client.socket() + assert awaiting is not None + broker.reconnecting.clear() + broker.reconnect_fails_before_closing = ValueError("Invalid host.") + await _until(broker.reconnecting.is_set, "the second reconnect") + await _until(lambda: not bridge._executor_clients, "its hand-back") + assert client.socket() is awaiting, "precondition: the failed reconnect kept its socket" + + awaiting.make_readable() + await _until(lambda: awaiting.bytes_read > 0, "the loop to read that socket again") + await bridge.disconnect() + + +@pytest.mark.asyncio +async def test_a_reconnect_the_executor_refuses_gives_the_loop_its_socket_back(monkeypatch: pytest.MonkeyPatch) -> None: + """The loop stopped watching the client's open socket to hand it to a thread; refused, the call never ran, so it is watched again.""" + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.3) + loop = asyncio.get_running_loop() + broker = _Broker(loop, _FLAT_TREE) + broker.real_sockets = True + real_run_in_executor = loop.run_in_executor + refusals: list[int] = [] + + def refuse_once(executor: None, call: Callable[[], object]) -> asyncio.Future[object]: + if not refusals: + refusals.append(1) + raise RuntimeError("cannot schedule new futures after shutdown") + return real_run_in_executor(executor, call) + + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + await bridge.connect() + broker.holding_connacks = True + [client] = broker.clients + client.drop() + await _until(lambda: len(broker.sessions) == 2, "the first reconnect's CONNECT") + await _until(lambda: not bridge._executor_clients, "its hand-back") + awaiting = client.socket() + assert awaiting is not None + with patch.object(loop, "run_in_executor", side_effect=refuse_once): + await _until(lambda: bool(refusals), "the refused reconnect") + awaiting.make_readable() + await _until(lambda: awaiting.bytes_read > 0, "the loop to read that socket again") + await bridge.disconnect() + + +@pytest.mark.asyncio +async def test_a_socket_paho_closes_on_the_loop_is_no_longer_watched() -> None: + """A dropped connection's socket leaves no watcher behind for whatever takes its number next.""" + loop = asyncio.get_running_loop() + broker = _Broker(loop, _FLAT_TREE) + broker.real_sockets = True + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + await bridge.connect() + [client] = broker.clients + sock = client.socket() + assert sock is not None + number = sock.fileno() + + client.drop() + # Checked at once, before anything else can run and take the number. + still_watched = loop.remove_reader(number) + await bridge.disconnect() + + assert not still_watched, "the closed socket's descriptor was left watched" From c3f2af505985494078063221f072d73a0b892464 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:04:58 -0800 Subject: [PATCH 24/33] fix(mqtt): keep a stopped misc timer from reading as a running one A misc tick that stopped -- no client to tick for, or paho answering that the client had no socket -- returned without clearing _misc_timer, and the next socket opened then saw a handle set and started no timer. A bridge reused more than a second after an abandoned connect, or an old client reconnecting more than a second after a failed rebuild, ran its session without keepalives until the broker dropped it. Each tick now clears the handle before anything else, so it is set exactly while a tick is scheduled. The socket-close handler also keeps a failing removal of the socket's watcher from paho: raised there, it ended paho's close before paho reported the disconnect, and the bridge never heard. The bridge's own bookkeeping already ran first. --- src/span_panel_api/mqtt/connection.py | 19 +++++- tests/test_one_subscribe_per_session.py | 86 +++++++++++++++++++++++++ 2 files changed, 102 insertions(+), 3 deletions(-) diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index d7294e0..c811484 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -1033,12 +1033,20 @@ def _async_handle_loop_error(self, status: int) -> None: _LOGGER.debug("MQTT loop error: %s", paho.error_string(status)) def _async_start_misc_periodic(self) -> None: - """Start the periodic loop_misc() timer (1-second interval).""" + """Start the periodic loop_misc() timer (1-second interval). + + `_misc_timer` is set exactly while a tick is scheduled: each tick clears + it before anything else, and only rescheduling sets it again. A tick + that stops -- no client, or paho answering that the client has no + socket -- therefore leaves nothing behind that reads as a timer still + running, and the next socket opened starts a fresh one. + """ if self._loop is None: return loop = self._loop def _async_misc() -> None: + self._misc_timer = None client = self._client if client is None: return @@ -1067,11 +1075,16 @@ def _async_on_socket_open(self, client: paho.Client, _userdata: object, sock: So def _async_on_socket_close(self, client: paho.Client, _userdata: object, sock: SocketLike) -> None: """Handle socket close on the loop: paho calls this before it closes the socket, so the socket is still its own.""" - # The bookkeeping first, so a removal that raised could not leave it undone. + # The bookkeeping first, so a removal that raised could not leave it undone, + # and a removal that raised is kept from paho: it would end paho's close + # there, before it reports the disconnect, and the bridge would never hear. self._socket_gone(client) loop = self._loop if loop is not None and sock.fileno() > -1: - loop.remove_reader(sock) + try: + loop.remove_reader(sock) + except Exception: # pylint: disable=broad-exception-caught + _LOGGER.warning("Could not stop watching a closed MQTT socket", exc_info=True) def _socket_gone(self, client: paho.Client) -> None: """A socket of `client` closed: end a connect still waiting on it, and stop the misc timer. diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 6020112..f617ab0 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -271,6 +271,7 @@ def __init__(self, broker: _Broker) -> None: self.disconnect_calls = 0 self.loop_read_calls = 0 self.loop_misc_calls = 0 + self.loop_misc_without_socket = 0 self._holder: threading.Thread | None = None self._sock: _FakeSocket | None = None self._write_registered = False @@ -393,7 +394,11 @@ def loop_write(self) -> MQTTErrorCode: return MQTTErrorCode.MQTT_ERR_SUCCESS def loop_misc(self) -> MQTTErrorCode: + """paho answers MQTT_ERR_NO_CONN with no socket, and the bridge's misc timer then stops.""" self._record_if_held("loop_misc") + if self._sock is None: + self.loop_misc_without_socket += 1 + return MQTTErrorCode.MQTT_ERR_NO_CONN self.loop_misc_calls += 1 return MQTTErrorCode.MQTT_ERR_SUCCESS @@ -1804,3 +1809,84 @@ async def test_a_socket_paho_closes_on_the_loop_is_no_longer_watched() -> None: await bridge.disconnect() assert not still_watched, "the closed socket's descriptor was left watched" + + +async def _ticks(client: _FakePaho, what: str) -> None: + """Wait for `client`'s keepalive: the misc timer calling paho's loop_misc on it, once a second.""" + ticks = client.loop_misc_calls + await _until(lambda: client.loop_misc_calls > ticks, what, timeout=3.0) + + +@pytest.mark.asyncio +async def test_a_bridge_reused_after_an_abandoned_connect_keeps_its_live_session_alive() -> None: + """More than a second after the abandoned connect, the next session still gets its keepalives. + + The abandoned client's socket started the misc timer; with nobody to tick for + it stopped, and a handle left set read as a timer still running, so the next + socket started none and the broker dropped the session for its keepalive. + """ + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + gate = threading.Event() + broker.connect_gate = gate + await _disconnect_while_bridge_connects(broker, bridge, broker.connecting.is_set, gate.set) + broker.connect_gate = None + await asyncio.sleep(1.2) + + await bridge.connect() + await _ticks(broker.clients[-1], "the live session's keepalive") + await bridge.disconnect() + + +@pytest.mark.asyncio +async def test_a_failed_rebuild_leaves_the_old_client_its_keepalive_once_it_reconnects( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The failed rebuild's client started the misc timer; once the old client reconnects, the timer ticks for it. + + The reconnect comes more than a second later, so the timer has ticked once + for the old client while it had no socket and stopped. + """ + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 1.3) + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + await bridge.connect() + [old] = broker.clients + broker.connect_fails_after_opening = ConnectionResetError(54, "Connection reset by peer") + old.next_reconnect_error = ssl.SSLError("handshake failed") + old.drop() + await _until(lambda: len(broker.sessions) == 3 and bridge.is_connected(), "the old client's reconnect") + assert bridge._client is old, "precondition: the failed rebuild left the old client in place" + assert old.loop_misc_without_socket > 0, "precondition: the timer ticked while the old client had no socket" + + await _ticks(old, "the old client's keepalive") + await bridge.disconnect() + + +@pytest.mark.asyncio +async def test_a_socket_close_whose_unwatching_raises_still_reports_the_disconnect() -> None: + """paho reports the disconnect only after the socket-close callback returns; a removal that raised must not stop it.""" + loop = asyncio.get_running_loop() + broker = _Broker(loop, _FLAT_TREE) + broker.real_sockets = True + real_remove_reader = loop.remove_reader + raised: list[int] = [] + + def remove_reader_raising_once(fd: object) -> bool: + if not raised: + raised.append(1) + raise RuntimeError("File descriptor is used by transport") + return real_remove_reader(fd) + + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + await bridge.connect() + [client] = broker.clients + with patch.object(loop, "remove_reader", side_effect=remove_reader_raising_once): + client.drop() + await _until(lambda: len(broker.sessions) == 2 and bridge.is_connected(), "the reconnect") + await bridge.disconnect() + + assert raised == [1], "precondition: the unwatching raised" From ba9c7d4a8694cefc60f966d2acf03bd261d78acc Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:15:29 -0800 Subject: [PATCH 25/33] test(mqtt): pin the hand-back's event order, its callback swap and the timer's stop on close A reconnect that replaces a socket still awaiting its CONNACK closes one socket and opens another inside the same blocking call; taken back in reverse, the close would stop the timer the open had left running. An idle connected socket must not stay watched for writing, which only holds if the hand-back gives paho's unregister back to the loop. And the bridge's own close stops the misc timer, so nothing ticks into a client without a socket through an outage; that window is anchored on the first refused reconnect being handed back rather than on a fixed sleep. --- tests/test_one_subscribe_per_session.py | 91 +++++++++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index f617ab0..6e60726 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -22,6 +22,7 @@ import contextlib import gc from dataclasses import dataclass, field +import logging import socket import ssl import threading @@ -289,6 +290,11 @@ def __init__(self, broker: _Broker) -> None: def held_by_a_thread(self) -> bool: return self._holder is not None + @property + def wants_to_write(self) -> bool: + """Whether paho has asked the loop to watch this client's socket for writing and not yet withdrawn it.""" + return self._write_registered + def setup(self) -> None: """The lock swap `AsyncMQTTClient` does; nothing to swap here.""" @@ -1890,3 +1896,88 @@ def remove_reader_raising_once(fd: object) -> bool: await bridge.disconnect() assert raised == [1], "precondition: the unwatching raised" + + +@pytest.mark.asyncio +async def test_keepalive_survives_a_reconnect_that_replaced_a_socket_awaiting_its_connack( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The replaced socket's close and the new socket's open are taken back in the order paho made them. + + Taken in reverse, the close would stop the misc timer the open had just + left running, and the new session would get no keepalives. + """ + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.3) + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + await bridge.connect() + broker.holding_connacks = True + [client] = broker.clients + client.drop() + await _until(lambda: len(broker.sessions) == 2, "the first reconnect's CONNECT") + await _until(lambda: len(broker.sessions) == 3, "the reconnect replacing the socket awaiting its CONNACK") + broker.release_connacks() + await _until(bridge.is_connected, "the CONNACK") + + await _ticks(client, "the live session's keepalive") + await bridge.disconnect() + + +@pytest.mark.asyncio +async def test_an_idle_connected_socket_is_not_watched_for_writing() -> None: + """Once the CONNECT is written paho asks the loop to stop watching for writing, and the loop must hear it. + + Left watched, a socket that is always writable wakes the loop on every + turn: an idle connection spinning a core. + """ + loop = asyncio.get_running_loop() + broker = _Broker(loop, _FLAT_TREE) + broker.real_sockets = True + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + await bridge.connect() + [client] = broker.clients + sock = client.socket() + assert sock is not None + await _until(lambda: not client.wants_to_write, "the CONNECT to be written") + + watched_for_writing = loop.remove_writer(sock) + await bridge.disconnect() + + assert not watched_for_writing, "an idle socket was left watched for writing" + + +@pytest.mark.asyncio +async def test_the_misc_timer_does_not_tick_through_an_outage( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """With the socket gone the timer stops, rather than calling into a client that has nothing to keep alive. + + The window opens once the first refused reconnect has been handed back + and logged. Nothing holds the client from then until the next attempt, + half a minute away, so a tick still pending would call paho rather than + look again later. Every tick is scheduled one second ahead, and the loop + runs timers in the order they fall due, so the sleep after it ends only + once any tick pending when the window opened has run. + """ + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 30.0) + caplog.set_level(logging.WARNING, logger="span_panel_api.mqtt.connection") + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + bridge = _bridge() + await bridge.connect() + [client] = broker.clients + await _ticks(client, "the keepalive before the outage") + broker.refusing = True + client.drop() + await _until( + lambda: any(record.getMessage().startswith("Reconnect failed") for record in caplog.records), + "the first refused reconnect, handed back", + ) + await asyncio.sleep(1.01) + ticks_without_a_socket = client.loop_misc_without_socket + await bridge.disconnect() + + assert broker.clients == [client], "precondition: no rebuild inside the window" + assert ticks_without_a_socket == 0, "the misc timer ticked into a client with no socket" From 878f6826d52c9c30b1ce4266761acb895216d9e2 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:19:51 -0800 Subject: [PATCH 26/33] test(mqtt): type the raising remove_reader stand-in as the loop's own It took `object` where the loop takes a descriptor number or anything with a fileno(). The failed-rebuild test's precondition now reads the fake broker's record, that the rebuild built a client and the live session is the old client's, rather than the bridge's private client attribute. --- tests/test_one_subscribe_per_session.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 6e60726..475be33 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -26,6 +26,7 @@ import socket import ssl import threading +from typing import Protocol from unittest.mock import patch from paho.mqtt.client import ConnectFlags, DisconnectFlags, MQTTMessage, topic_matches_sub @@ -92,6 +93,12 @@ class _Session: SocketHandler = Callable[["_FakePaho", object, "_FakeSocket"], None] +class _HasFileno(Protocol): + """What the event loop's reader and writer methods take besides a bare descriptor number.""" + + def fileno(self) -> int: ... + + class _FakeSocket: """What paho hands its socket callbacks. @@ -1864,7 +1871,8 @@ async def test_a_failed_rebuild_leaves_the_old_client_its_keepalive_once_it_reco old.next_reconnect_error = ssl.SSLError("handshake failed") old.drop() await _until(lambda: len(broker.sessions) == 3 and bridge.is_connected(), "the old client's reconnect") - assert bridge._client is old, "precondition: the failed rebuild left the old client in place" + assert len(broker.clients) == 2, "precondition: the rebuild built a client" + assert old.session is broker.sessions[-1], "precondition: the failed rebuild left the old client in place" assert old.loop_misc_without_socket > 0, "precondition: the timer ticked while the old client had no socket" await _ticks(old, "the old client's keepalive") @@ -1880,7 +1888,7 @@ async def test_a_socket_close_whose_unwatching_raises_still_reports_the_disconne real_remove_reader = loop.remove_reader raised: list[int] = [] - def remove_reader_raising_once(fd: object) -> bool: + def remove_reader_raising_once(fd: int | _HasFileno) -> bool: if not raised: raised.append(1) raise RuntimeError("File descriptor is used by transport") From 250ec15130f7f201297471fa01bc50264c8e6a4b Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:32:12 -0800 Subject: [PATCH 27/33] test(mqtt): wait on conditions where the session tests counted loop turns The broker counts every packet it schedules where it schedules it, under a lock since a CONNACK is scheduled from the executor thread, so waiting for nothing pending leaves no CONNACK or SUBSCRIBE replay on its way. A close or disconnect made while a blocking call is held is followed by every task it cancelled running to its end, rather than five turns of the loop. A socket made readable is followed by a poll of the loop's selector, a keepalive expected by the tick it waits for, and the ready wait's end by that task. A late disconnect from a replaced client needs no wait at all: acting on it shows inside drop(). The windows left are timer deadlines, each commented. --- tests/test_one_subscribe_per_session.py | 140 ++++++++++++++++-------- 1 file changed, 94 insertions(+), 46 deletions(-) diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 475be33..1585015 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -18,10 +18,11 @@ from __future__ import annotations import asyncio -from collections.abc import AsyncIterator, Callable, Iterator +from collections.abc import AsyncIterator, Awaitable, Callable, Iterator import contextlib import gc from dataclasses import dataclass, field +from functools import partial import logging import socket import ssl @@ -179,22 +180,38 @@ def __init__(self, loop: asyncio.AbstractEventLoop, retained: dict[str, str]) -> self.holding_closes = False """While set, a DISCONNECT that `disconnect()` queued waits in `held_closes` for `release_closes`.""" self.held_closes: list[Callable[[], None]] = [] - self.pending = 0 - """Deliveries and DISCONNECT writes scheduled and not yet made.""" + self._pending = 0 + self._pending_lock = threading.Lock() - def defer(self, action: Callable[[], None]) -> None: - """Run `action` on the loop later, as paho writes a queued packet from the loop's write callback.""" - if self.holding_closes: - self.held_closes.append(action) - return - self.pending += 1 + @property + def pending(self) -> int: + """Packets scheduled on the loop and not yet made: deliveries, CONNACKs and DISCONNECT writes.""" + return self._pending + + def later(self, action: Callable[[], None]) -> None: + """Run `action` on the loop, from whichever thread schedules it, counted in `pending` until it has run. + + The count is taken where the packet is scheduled, so no packet on its + way can be missed by a test waiting for `pending` to reach nothing. A + CONNACK is scheduled from the executor thread, hence the lock. + """ + with self._pending_lock: + self._pending += 1 def run() -> None: - self.pending -= 1 + with self._pending_lock: + self._pending -= 1 action() self.loop.call_soon_threadsafe(run) + def defer(self, action: Callable[[], None]) -> None: + """Run `action` on the loop later, as paho writes a queued packet from the loop's write callback.""" + if self.holding_closes: + self.held_closes.append(action) + return + self.later(action) + def release_closes(self) -> None: self.holding_closes = False held, self.held_closes = self.held_closes, [] @@ -205,7 +222,7 @@ def release_connacks(self) -> None: self.holding_connacks = False held, self.held = self.held, [] for client, session in held: - self.loop.call_soon_threadsafe(client.connack, session) + self.later(partial(client.connack, session)) def client( self, *, callback_api_version: CallbackAPIVersion, transport: MqttTransport, reconnect_on_failure: bool @@ -251,11 +268,9 @@ def publish(self, topic: str, payload: str) -> None: self._schedule(client, session, topic, payload) def _schedule(self, client: _FakePaho, session: _Session, topic: str, payload: str) -> None: - self.pending += 1 - self.loop.call_soon_threadsafe(self._deliver, client, session, topic, payload) + self.later(partial(self._deliver, client, session, topic, payload)) def _deliver(self, client: _FakePaho, session: _Session, topic: str, payload: str) -> None: - self.pending -= 1 if not session.open or client.on_message is None: return session.delivered.append(topic) @@ -481,7 +496,7 @@ def _answer(self, session: _Session) -> None: if self._broker.holding_connacks: self._broker.held.append((self, session)) return - self._broker.loop.call_soon_threadsafe(self.connack, session) + self._broker.later(partial(self.connack, session)) def connack(self, session: _Session) -> None: """The broker's answer to the CONNECT that opened `session`, if that session is still this client's.""" @@ -490,14 +505,44 @@ def connack(self, session: _Session) -> None: self.on_connect(self, None, ConnectFlags(session_present=False), ReasonCode(PacketTypes.CONNACK, "Success"), None) -async def _let_the_loop_run() -> None: - """Run what the last call scheduled, while a gated executor call is still held. +async def _and_what_it_cancels(call: Awaitable[None]) -> list[str]: + """Await `call`, then every task it cancelled to its end, and name those tasks. - Released at once, a gated call could finish before anything the loop had - yet to run, and a call that reached the held client would go unrecorded. + For a close or disconnect made while a gated executor call is still held. A + cancelled task is only asked to stop, and runs its way out on later turns + of the loop; ended before the gate opens, anything it did on the way out + into the held client was done while the client was held, and recorded as + such. """ - for _ in range(5): - await asyncio.sleep(0) + running: set[asyncio.Task[object]] = asyncio.all_tasks() + await call + cancelled = [task for task in running if task.cancelling()] + await _until(lambda: all(task.done() for task in cancelled), "the tasks it cancelled to end") + return [task.get_name() for task in cancelled] + + +async def _after_a_poll() -> None: + """Return once the loop has polled its sockets since this was called. + + A watched socket that is readable now has had its reader called by then: + one poll reports every ready socket, and the loop calls all their readers + before the task awaiting this resumes. + """ + loop = asyncio.get_running_loop() + probe, poke = socket.socketpair() + polled: asyncio.Future[None] = loop.create_future() + + def heard() -> None: + loop.remove_reader(probe) + polled.set_result(None) + + with probe, poke: + loop.add_reader(probe, heard) + try: + poke.send(b"\0") + await polled + finally: + loop.remove_reader(probe) async def _until(condition: Callable[[], bool], what: str, timeout: float = 10.0) -> None: @@ -518,10 +563,14 @@ async def until(self, condition: Callable[[], bool], what: str, timeout: float = await _until(condition, what, timeout) async def quiesce(self) -> None: - """Wait until every delivery the broker scheduled has been made and handled.""" - await self.until(lambda: self.broker.pending == 0, "the broker's deliveries") - for _ in range(5): - await asyncio.sleep(0) + """Wait until every packet the broker scheduled has been made and handled. + + Each is handled where it is made, and anything handling one sends -- + the SUBSCRIBE a CONNACK brings, the replay a SUBSCRIBE brings -- is + counted inside that same callback, so the count never reads nothing + while a packet is still on its way. + """ + await self.until(lambda: self.broker.pending == 0, "the broker's packets") @contextlib.asynccontextmanager @@ -869,8 +918,7 @@ async def _close_while_connect_waits(panel: _Panel, waiting: Callable[[], bool], """ connecting = asyncio.create_task(panel.client.connect()) await panel.until(waiting, "connect() to suspend") - await panel.client.close() - await _let_the_loop_run() + await _and_what_it_cancels(panel.client.close()) resume() with pytest.raises(SpanPanelConnectionError, match="Closed while connecting"): await asyncio.wait_for(connecting, timeout=5) @@ -1185,14 +1233,11 @@ async def _disconnect_while_bridge_connects( """Start the bridge's connect(), disconnect it once `waiting` says connect() is suspended, then let it resume.""" connecting = asyncio.create_task(bridge.connect()) await _until(waiting, "the bridge's connect() to suspend") - await bridge.disconnect() - await _let_the_loop_run() + await _and_what_it_cancels(bridge.disconnect()) resume() with pytest.raises(SpanPanelConnectionError, match="disconnect"): await asyncio.wait_for(connecting, timeout=5) await _until(lambda: broker.pending == 0, "the broker's deliveries") - for _ in range(5): - await asyncio.sleep(0) @pytest.mark.asyncio @@ -1277,8 +1322,9 @@ async def test_a_replaced_clients_late_disconnect_does_not_end_the_rebuilt_sessi await panel.quiesce() assert edges == [True, False, True], "precondition: rebuilt and announced" + # Acting on it would show at once: the False edge and the bridge marked + # disconnected are both made inside drop(). old.drop() - await asyncio.sleep(0.1) await panel.quiesce() assert edges == [True, False, True] @@ -1360,8 +1406,8 @@ async def test_disconnect_during_a_blocking_reconnect_waits_for_the_thread_then_ broker.clients[-1].drop() await _until(broker.reconnecting.is_set, "the blocking reconnect") - await bridge.disconnect() - await _let_the_loop_run() + cancelled = await _and_what_it_cancels(bridge.disconnect()) + assert "span_mqtt_reconnect" in cancelled, "precondition: disconnect() cancelled the reconnect loop" gate.set() await _until(lambda: not bridge._executor_clients, "the hand-back") await _until(lambda: broker.pending == 0, "the let-go client's DISCONNECT write") @@ -1388,8 +1434,8 @@ async def test_disconnect_during_a_rebuilds_blocking_connect_waits_for_the_threa old.drop() await _until(broker.connecting.is_set, "the rebuilt client's blocking connect") - await bridge.disconnect() - await _let_the_loop_run() + cancelled = await _and_what_it_cancels(bridge.disconnect()) + assert "span_mqtt_reconnect" in cancelled, "precondition: disconnect() cancelled the reconnect loop" gate.set() await _until(lambda: not bridge._executor_clients, "the hand-back") await _until(lambda: broker.pending == 0, "the let-go client's DISCONNECT write") @@ -1417,8 +1463,8 @@ async def test_a_blocking_reconnect_that_fails_after_disconnect_is_not_reported_ held.drop() await _until(broker.reconnecting.is_set, "the blocking reconnect") - await bridge.disconnect() - await _let_the_loop_run() + cancelled = await _and_what_it_cancels(bridge.disconnect()) + assert "span_mqtt_reconnect" in cancelled, "precondition: disconnect() cancelled the reconnect loop" gate.set() await _until(lambda: not bridge._executor_clients, "the hand-back") del held @@ -1453,6 +1499,9 @@ async def test_a_reconnect_replacing_a_socket_still_awaiting_its_connack_leaves_ broker.reconnect_gate = gate await _until(broker.reconnecting.is_set, "the second reconnect, replacing the socket awaiting its CONNACK") + # The misc timer was started by the first reconnect's socket, before this + # hold began, and ticks a second after it was last scheduled; the loop runs + # timers in the order they fall due, so this outlasts a tick. await asyncio.sleep(1.2) gate.set() await _until(lambda: len(broker.sessions) == 3, "the second reconnect's CONNECT") @@ -1516,7 +1565,7 @@ async def test_the_loop_stops_reading_a_clients_socket_while_a_thread_is_inside_ await _until(broker.reconnecting.is_set, "the second reconnect") awaiting.make_readable() - await asyncio.sleep(0.05) + await _after_a_poll() gate.set() await _until(lambda: not bridge._executor_clients, "the hand-back") broker.reconnect_gate = None @@ -1570,16 +1619,12 @@ async def test_a_let_go_clients_socket_closing_late_leaves_the_bridges_next_conn await _until(lambda: broker.pending == 0, "the abandoned client's DISCONNECT write") broker.release_connacks() await asyncio.wait_for(connecting, timeout=5) - live = broker.clients[-1] - misc = live.loop_misc_calls - await asyncio.sleep(1.2) - ticked = live.loop_misc_calls > misc + await _ticks(broker.clients[-1], "the live session's keepalive, which the late close must leave running") await bridge.disconnect() await _until(lambda: broker.pending == 0, "the live client's DISCONNECT write") assert [session.open for session in broker.sessions] == [False, False] assert broker.sessions[1].subscribed == [_FLAT_FILTER] - assert ticked, "the late close cancelled the live session's misc timer" @pytest.mark.asyncio @@ -1648,13 +1693,13 @@ def ready_waits() -> list[asyncio.Task[object]]: async with _serving(never_ready, flat_schema()) as panel: connecting = asyncio.create_task(panel.client.connect()) await panel.until(lambda: bool(ready_waits()), "connect() to wait for a ready tree") + [ready] = ready_waits() connecting.cancel() with pytest.raises(asyncio.CancelledError): await connecting - await asyncio.sleep(0) - assert ready_waits() == [] + await panel.until(ready.done, "the ready wait to end with connect()") @pytest.mark.asyncio @@ -1845,6 +1890,9 @@ async def test_a_bridge_reused_after_an_abandoned_connect_keeps_its_live_session broker.connect_gate = gate await _disconnect_while_bridge_connects(broker, bridge, broker.connecting.is_set, gate.set) broker.connect_gate = None + # The abandoned socket started the misc timer when it was handed back, + # before the helper returned, and its tick falls due within a second of + # that; the loop runs timers in the order they fall due. await asyncio.sleep(1.2) await bridge.connect() From 62a9b2f34038f3cc6d92cc0c9e35e62ef4e84356 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:33:57 -0800 Subject: [PATCH 28/33] style(mqtt): rewrap the hand-back's docstring --- src/span_panel_api/mqtt/connection.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index c811484..4d9e410 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -721,13 +721,12 @@ def _executor_returned( made replayed through them, in order. The socket the call was given is watched again if the call left it open -- an executor that never ran the call, a `reconnect()` that refused its host before closing anything. - A client this bridge let go of - while the thread held it -- disconnect() ran meanwhile -- is then - disconnected here, closing whatever socket the call went on to open. - Only then is `caller` given the call's outcome, so whoever awaits it - resumes with the client already back. A caller that was cancelled is - told nothing: the outcome is retrieved here, so a failure nobody is - waiting for is not reported as never retrieved. + A client this bridge let go of while the thread held it -- disconnect() + ran meanwhile -- is then disconnected here, closing whatever socket the + call went on to open. Only then is `caller` given the call's outcome, so + whoever awaits it resumes with the client already back. A caller that + was cancelled is told nothing: the outcome is retrieved here, so a + failure nobody is waiting for is not reported as never retrieved. """ self._executor_clients.discard(client) self._give_loop_socket_callbacks(client) From e4364e11b4e13ed55effbdc9ca5e0f02a133f303 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:46:10 -0800 Subject: [PATCH 29/33] test(mqtt): hold the real-socket reconnects to a clean hand-back, and wait for tasks a call started A hand-back that raised after a reconnect had closed its real socket left the reconnect loop waiting on an answer that never came, and the tests on that path passed because none of them looked at the loop's exception handler; they do now, and a new one has two reconnects replace sockets before any CONNACK, so a loop left waiting never tries again, then drops the session a second time. The helper that waits out what a close or disconnect cancelled also takes the tasks still running after the call, so a task the call both started and cancelled is waited for too. --- tests/test_one_subscribe_per_session.py | 62 +++++++++++++++++++++---- 1 file changed, 54 insertions(+), 8 deletions(-) diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 1585015..62d0beb 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -512,11 +512,14 @@ async def _and_what_it_cancels(call: Awaitable[None]) -> list[str]: cancelled task is only asked to stop, and runs its way out on later turns of the loop; ended before the gate opens, anything it did on the way out into the held client was done while the client was held, and recorded as - such. + such. The tasks looked at are those running before the call and those + still running after it, so a task the call both started and cancelled is + waited for too. """ running: set[asyncio.Task[object]] = asyncio.all_tasks() await call - cancelled = [task for task in running if task.cancelling()] + still_running: set[asyncio.Task[object]] = asyncio.all_tasks() + cancelled = [task for task in running | still_running if task.cancelling()] await _until(lambda: all(task.done() for task in cancelled), "the tasks it cancelled to end") return [task.get_name() for task in cancelled] @@ -1550,7 +1553,7 @@ async def test_the_loop_stops_reading_a_clients_socket_while_a_thread_is_inside_ monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.3) broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) broker.real_sockets = True - with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client), _unobserved_loop_errors() as errors: bridge = _bridge() await bridge.connect() broker.holding_connacks = True @@ -1572,6 +1575,7 @@ async def test_the_loop_stops_reading_a_clients_socket_while_a_thread_is_inside_ await bridge.disconnect() assert broker.calls_while_held == [], "the loop read a client the executor thread was inside" + assert errors == [], "a step of the bridge raised into the event loop" @pytest.mark.asyncio @@ -1757,7 +1761,7 @@ async def test_a_hand_back_never_unwatches_a_descriptor_someone_else_took_meanwh broker = _Broker(loop, _FLAT_TREE) broker.real_sockets = True heard: list[bytes] = [] - with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client), _unobserved_loop_errors() as errors: bridge = _bridge() await bridge.connect() broker.holding_connacks = True @@ -1786,6 +1790,7 @@ async def test_a_hand_back_never_unwatches_a_descriptor_someone_else_took_meanwh peer.close() assert heard == [b"still here"] + assert errors == [], "a step of the bridge raised into the event loop" @pytest.mark.asyncio @@ -1794,7 +1799,7 @@ async def test_a_blocking_reconnect_that_never_closes_its_socket_leaves_it_watch monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.3) broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) broker.real_sockets = True - with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client), _unobserved_loop_errors() as errors: bridge = _bridge() await bridge.connect() broker.holding_connacks = True @@ -1813,6 +1818,8 @@ async def test_a_blocking_reconnect_that_never_closes_its_socket_leaves_it_watch await _until(lambda: awaiting.bytes_read > 0, "the loop to read that socket again") await bridge.disconnect() + assert errors == [], "a step of the bridge raised into the event loop" + @pytest.mark.asyncio async def test_a_reconnect_the_executor_refuses_gives_the_loop_its_socket_back(monkeypatch: pytest.MonkeyPatch) -> None: @@ -1830,7 +1837,7 @@ def refuse_once(executor: None, call: Callable[[], object]) -> asyncio.Future[ob raise RuntimeError("cannot schedule new futures after shutdown") return real_run_in_executor(executor, call) - with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client), _unobserved_loop_errors() as errors: bridge = _bridge() await bridge.connect() broker.holding_connacks = True @@ -1846,6 +1853,8 @@ def refuse_once(executor: None, call: Callable[[], object]) -> asyncio.Future[ob await _until(lambda: awaiting.bytes_read > 0, "the loop to read that socket again") await bridge.disconnect() + assert errors == [], "a step of the bridge raised into the event loop" + @pytest.mark.asyncio async def test_a_socket_paho_closes_on_the_loop_is_no_longer_watched() -> None: @@ -1853,7 +1862,7 @@ async def test_a_socket_paho_closes_on_the_loop_is_no_longer_watched() -> None: loop = asyncio.get_running_loop() broker = _Broker(loop, _FLAT_TREE) broker.real_sockets = True - with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client), _unobserved_loop_errors() as errors: bridge = _bridge() await bridge.connect() [client] = broker.clients @@ -1867,6 +1876,7 @@ async def test_a_socket_paho_closes_on_the_loop_is_no_longer_watched() -> None: await bridge.disconnect() assert not still_watched, "the closed socket's descriptor was left watched" + assert errors == [], "a step of the bridge raised into the event loop" async def _ticks(client: _FakePaho, what: str) -> None: @@ -1942,7 +1952,7 @@ def remove_reader_raising_once(fd: int | _HasFileno) -> bool: raise RuntimeError("File descriptor is used by transport") return real_remove_reader(fd) - with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client): + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client), _unobserved_loop_errors() as errors: bridge = _bridge() await bridge.connect() [client] = broker.clients @@ -1952,6 +1962,42 @@ def remove_reader_raising_once(fd: int | _HasFileno) -> bool: await bridge.disconnect() assert raised == [1], "precondition: the unwatching raised" + assert errors == [], "a step of the bridge raised into the event loop" + + +@pytest.mark.asyncio +async def test_reconnects_that_replace_real_sockets_leave_the_bridge_reconnecting( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """Each reconnect closes the socket it was given on the thread, and its hand-back must still finish. + + Ended early, the hand-back left its caller -- the reconnect loop -- waiting + for ever: with the session it had opened never answered, nothing tried + again. Here no CONNACK comes until two reconnects have replaced sockets, + then a second drop must be reconnected as the first was. + """ + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.3) + caplog.set_level(logging.WARNING, logger="span_panel_api.mqtt.connection") + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + broker.real_sockets = True + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client), _unobserved_loop_errors() as errors: + bridge = _bridge() + await bridge.connect() + [client] = broker.clients + broker.holding_connacks = True + client.drop() + await _until(lambda: len(broker.sessions) == 4, "two reconnects, each replacing a socket awaiting its CONNACK") + await _until(lambda: not bridge._executor_clients, "the last one's hand-back") + broker.release_connacks() + await _until(bridge.is_connected, "the CONNACK") + + client.drop() + await _until(lambda: len(broker.sessions) == 5 and bridge.is_connected(), "the reconnect after the second drop") + await bridge.disconnect() + + assert errors == [], "a step of the hand-back raised into the event loop" + failed = [record.getMessage() for record in caplog.records if record.exc_info] + assert failed == [], "a reconnect that replaced its socket was reported as failing" @pytest.mark.asyncio From 9dff638ad23d1946f95af7e9ba1c8e2a8f0a3db1 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:51:13 -0800 Subject: [PATCH 30/33] fix(mqtt): answer a blocking call's caller however its hand-back goes The hand-back answered its caller only if every step before the answer succeeded. A step that raised -- giving the loop back a socket the call had kept, say -- ended it there, and the reconnect loop waiting on that answer waited for ever; with the kept socket unwatched no CONNACK could reach it either, so the bridge never connected again. Each step is now taken whether or not one before it raised, and the caller is answered in a finally. A call that succeeded hands its caller the hand-back's first failure, so the reconnect loop counts and retries the attempt as it does any other failure, and connect() reports it as its connection error; a failure the caller is not given is logged with its traceback. A let-go client's failed disconnect is logged as a warning, where it was a debug line, and never given to its abandoned caller. --- src/span_panel_api/mqtt/connection.py | 87 +++++++++----- tests/test_one_subscribe_per_session.py | 144 ++++++++++++++++++++++++ 2 files changed, 204 insertions(+), 27 deletions(-) diff --git a/src/span_panel_api/mqtt/connection.py b/src/span_panel_api/mqtt/connection.py index 4d9e410..8ba3316 100644 --- a/src/span_panel_api/mqtt/connection.py +++ b/src/span_panel_api/mqtt/connection.py @@ -63,6 +63,44 @@ def _nothing_to_restore() -> None: """What `_stop_watching` returns for a client with no open socket to give back.""" +def _attempt(failures: list[Exception], step: Callable[[], object]) -> None: + """Take one step of a hand-back, keeping what it raised in `failures` rather than letting it end the rest.""" + try: + step() + except Exception as exc: # pylint: disable=broad-exception-caught + failures.append(exc) + + +def _answer(caller: asyncio.Future[object], call: asyncio.Future[object], failures: list[Exception]) -> None: + """Give `caller` the outcome of its blocking `call`, taking into account what the hand-back's `failures` were. + + A call that failed or was cancelled gives the caller that outcome. A call + that succeeded gives it the hand-back's first failure, if there was one: + the client is not fully back on the loop, and the caller's own failure + handling -- the reconnect loop's retry, connect()'s error -- is what deals + with that. A caller already done is told nothing, but the call's outcome + is retrieved, so a failure nobody is waiting for is not reported as never + retrieved. Every failure the caller is not given is logged here, as no + one else will see it. + """ + unheard = failures + if call.cancelled(): + if not caller.done(): + caller.cancel() + else: + failure = call.exception() + if not caller.done(): + if failure is not None: + caller.set_exception(failure) + elif failures: + caller.set_exception(failures[0]) + unheard = failures[1:] + else: + caller.set_result(call.result()) + for exc in unheard: + _LOGGER.warning("Handing a paho client back to the event loop raised", exc_info=exc) + + def _check_topic_filter(topic: str) -> None: """Refuse what MQTT 3.1.1 does not accept as a topic filter (section 4.7). @@ -723,35 +761,30 @@ def _executor_returned( the call, a `reconnect()` that refused its host before closing anything. A client this bridge let go of while the thread held it -- disconnect() ran meanwhile -- is then disconnected here, closing whatever socket the - call went on to open. Only then is `caller` given the call's outcome, so - whoever awaits it resumes with the client already back. A caller that - was cancelled is told nothing: the outcome is retrieved here, so a - failure nobody is waiting for is not reported as never retrieved. + call went on to open. Only then is `caller` answered (see `_answer`), so + whoever awaits it resumes with the client already back. + + Each step is taken whether or not one before it raised, and the caller + is answered however they went: a caller left waiting is a reconnect loop + waiting for ever on an attempt long over, which tries nothing again. + What a step raised goes to the caller, or to the log. A let-go client's + failed disconnect is logged, never given to its caller: that caller is + an abandoned attempt, which reports its abandonment, not this. """ self._executor_clients.discard(client) - self._give_loop_socket_callbacks(client) - for event in events: - try: - event() - except Exception: # pylint: disable=broad-exception-caught - _LOGGER.warning("Replaying a socket event of a blocking paho call raised", exc_info=True) - watch_again() - if client is not self._client: - try: - client.disconnect() - except Exception: # pylint: disable=broad-exception-caught - _LOGGER.debug("Disconnecting a let-go paho client raised", exc_info=True) - if call.cancelled(): - if not caller.done(): - caller.cancel() - return - failure = call.exception() - if caller.done(): - return - if failure is not None: - caller.set_exception(failure) - else: - caller.set_result(call.result()) + failures: list[Exception] = [] + try: + _attempt(failures, partial(self._give_loop_socket_callbacks, client)) + for event in events: + _attempt(failures, event) + _attempt(failures, watch_again) + if client is not self._client: + try: + client.disconnect() + except Exception: # pylint: disable=broad-exception-caught + _LOGGER.warning("Disconnecting a paho client this bridge let go of raised", exc_info=True) + finally: + _answer(caller, call, failures) def _give_loop_socket_callbacks(self, client: paho.Client) -> None: """Hand `client` the loop's own socket callbacks, for paho to call on the loop.""" diff --git a/tests/test_one_subscribe_per_session.py b/tests/test_one_subscribe_per_session.py index 62d0beb..0e5cee1 100644 --- a/tests/test_one_subscribe_per_session.py +++ b/tests/test_one_subscribe_per_session.py @@ -2083,3 +2083,147 @@ async def test_the_misc_timer_does_not_tick_through_an_outage( assert broker.clients == [client], "precondition: no rebuild inside the window" assert ticks_without_a_socket == 0, "the misc timer ticked into a client with no socket" + + +@pytest.mark.asyncio +async def test_a_hand_back_whose_rearm_raises_still_answers_the_reconnect_loop( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """The reconnect refused its host and kept its socket; giving the loop that socket back raised. + + The hand-back stopped there and never answered its caller, so the + reconnect loop waited for ever on an attempt long over, and with the kept + socket unwatched no CONNACK could reach it either: the bridge never + connected again. The caller is given the attempt's own failure, and the + re-arm's is logged. + """ + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.3) + caplog.set_level(logging.WARNING, logger="span_panel_api.mqtt.connection") + loop = asyncio.get_running_loop() + broker = _Broker(loop, _FLAT_TREE) + broker.real_sockets = True + real_add_reader = loop.add_reader + refusal = RuntimeError("File descriptor is used by transport") + refused: list[int] = [] + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client), _unobserved_loop_errors() as errors: + bridge = _bridge() + await bridge.connect() + broker.holding_connacks = True + [client] = broker.clients + client.drop() + await _until(lambda: len(broker.sessions) == 2, "the first reconnect's CONNECT") + await _until(lambda: not bridge._executor_clients, "its hand-back") + awaiting = client.socket() + assert awaiting is not None + gate = threading.Event() + broker.reconnecting.clear() + broker.reconnect_gate = gate + broker.reconnect_fails_before_closing = ValueError("Invalid host.") + await _until(broker.reconnecting.is_set, "the second reconnect") + + def add_reader_refusing_the_rearm(fd: int | _HasFileno, callback: Callable[..., object], *args: object) -> None: + if fd is awaiting and not refused: + refused.append(1) + raise refusal + real_add_reader(fd, callback, *args) + + with patch.object(loop, "add_reader", side_effect=add_reader_refusing_the_rearm): + broker.reconnect_gate = None + gate.set() + await _until(lambda: not bridge._executor_clients, "the second reconnect's hand-back") + assert refused == [1], "precondition: giving the loop the kept socket back raised" + + await _until(lambda: len(broker.sessions) == 3, "the reconnect loop's next attempt") + broker.release_connacks() + await _until(bridge.is_connected, "the CONNACK") + await bridge.disconnect() + + assert errors == [], "the hand-back's failure reached the event loop instead of the bridge's log" + assert any(record.exc_info is not None and record.exc_info[1] is refusal for record in caplog.records) + + +@pytest.mark.asyncio +async def test_a_hand_back_whose_replay_raises_is_a_failed_attempt_to_the_reconnect_loop( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """The reconnect succeeded, but the loop could not take its new socket: the reconnect loop hears that as the attempt failing. + + Told the attempt succeeded, the loop counted a reconnect whose socket + nothing was reading as a good one, and reset the count of failures that + leads it to rebuild the client. + """ + monkeypatch.setattr("span_panel_api.mqtt.connection.MQTT_RECONNECT_MIN_DELAY_S", 0.3) + caplog.set_level(logging.WARNING, logger="span_panel_api.mqtt.connection") + loop = asyncio.get_running_loop() + broker = _Broker(loop, _FLAT_TREE) + broker.real_sockets = True + real_add_reader = loop.add_reader + refusal = RuntimeError("File descriptor is used by transport") + refused: list[int] = [] + + def add_reader_refusing_once(fd: int | _HasFileno, callback: Callable[..., object], *args: object) -> None: + if not refused: + refused.append(1) + raise refusal + real_add_reader(fd, callback, *args) + + def heard_as_a_failed_attempt() -> bool: + return any( + record.getMessage().startswith("Reconnect failed") + and record.exc_info is not None + and record.exc_info[1] is refusal + for record in caplog.records + ) + + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client), _unobserved_loop_errors() as errors: + bridge = _bridge() + await bridge.connect() + # Held, so the hand-back answers the loop before any CONNACK could end its wait. + broker.holding_connacks = True + [client] = broker.clients + with patch.object(loop, "add_reader", side_effect=add_reader_refusing_once): + client.drop() + await _until(heard_as_a_failed_attempt, "the reconnect loop to hear the hand-back's failure") + await bridge.disconnect() + + assert refused == [1], "precondition: replaying the new socket's open raised" + assert errors == [], "the hand-back's failure reached the event loop instead of its caller" + + +@pytest.mark.asyncio +async def test_a_let_go_client_whose_disconnect_raises_is_reported( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """The hand-back closes a client disconnect() let go of while a thread held it; that raising is a warning, with its traceback. + + Its caller is an abandoned attempt, given its own outcome, so the failure + is the bridge's to report: a client it could not close may keep its socket + open. + """ + caplog.set_level(logging.WARNING, logger="span_panel_api.mqtt.connection") + broker = _Broker(asyncio.get_running_loop(), _FLAT_TREE) + refusal = OSError(9, "Bad file descriptor") + + def disconnect_refusing() -> MQTTErrorCode: + raise refusal + + with patch("span_panel_api.mqtt.connection.AsyncMQTTClient", broker.client), _unobserved_loop_errors() as errors: + bridge = _bridge() + await bridge.connect() + gate = threading.Event() + broker.reconnect_gate = gate + held = broker.clients[-1] + held.drop() + await _until(broker.reconnecting.is_set, "the blocking reconnect") + cancelled = await _and_what_it_cancels(bridge.disconnect()) + assert "span_mqtt_reconnect" in cancelled, "precondition: disconnect() cancelled the reconnect loop" + monkeypatch.setattr(held, "disconnect", disconnect_refusing) + + gate.set() + await _until(lambda: not bridge._executor_clients, "the hand-back") + + assert errors == [], "the failed disconnect reached the event loop instead of the bridge's log" + assert any( + record.levelno >= logging.WARNING and record.exc_info is not None and record.exc_info[1] is refusal + for record in caplog.records + ), "the let-go client's failed disconnect was not reported" From d066d8332c73b1a5a45f02e2245afc580176770e Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:46:32 -0800 Subject: [PATCH 31/33] docs(changelog): record that subscribe() sends once per topic, and set_subscriptions() --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9edff76..f0a0bb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,11 @@ beta corrected in an earlier beta does not appear at all: from the point of view - **`SpanCircuitSnapshot.breaker_rating_declared`** says whether a circuit declares a breaker rating, so a consumer can tell a rating the panel does not publish from one that has not arrived yet; `None` where the adapter does not say. - **`SpanPanelSnapshot.publishes_shared_meters`** says whether any circuit declares `meter/shared-with-device-ids`, so a consumer can tell a panel that describes its multi-load breakers from one, such as MAIN 32, that publishes each as a single circuit; `None` where the adapter does not say, as with `span-panel-api-schema-0` or a `span-panel-api-schema-1` older than 1.5.0. +- **`AsyncMqttBridge.set_subscriptions()` sets the topics every connection the bridge opens is subscribed to**, replacing what it set before and never dropping a topic `subscribe()` added. + +### Changed + +- **`AsyncMqttBridge.subscribe()` sends nothing for a topic the bridge already holds at that QoS or higher**, where every call sent a SUBSCRIBE and the broker replayed the topic's retained messages each time. ### Fixed From 7d6fff1136c6331025e880bb8dbcc2c0b4f33335 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:08:55 -0800 Subject: [PATCH 32/33] chore(release): span-panel-api 3.9.0b2 span-panel-api 3.9.0b2 subscribes each broker session once. schema-0 stays at 1.3.0 and schema-1 at 1.5.0b1, neither changed: schema-1 keeps its span-panel-api>=3.9.0b1 floor, which 3.9.0b2 satisfies, and the core extras keep their stable floors. The changelog carries the public version, 3.9.0. --- pyproject.toml | 2 +- uv.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 7d4a0a1..397f684 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "span-panel-api" -version = "3.9.0b1" +version = "3.9.0b2" description = "A client library for SPAN Panel API" authors = [ {name = "SpanPanel"} diff --git a/uv.lock b/uv.lock index 850e567..b124008 100644 --- a/uv.lock +++ b/uv.lock @@ -974,7 +974,7 @@ wheels = [ [[package]] name = "span-panel-api" -version = "3.9.0b1" +version = "3.9.0b2" source = { editable = "." } dependencies = [ { name = "httpx" }, From 6ec6c2f7ab12bc98eb657bb6422458efba5de826 Mon Sep 17 00:00:00 2001 From: cayossarian <23534755+cayossarian@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:47:33 -0800 Subject: [PATCH 33/33] chore(release): span-panel-api 3.9.0 and schema-1 1.5.0 Finals of 3.9.0b2 and 1.5.0b1, with the same code. The schema-1 extra floors on span-panel-api-schema-1 1.5.0, the adapter that fills breaker_rating_declared and publishes_shared_meters, and schema-1 floors on span-panel-api 3.9.0, a stable floor again in place of the beta's. schema-0 stays at 1.3.0, unchanged, and the schema-0 extra keeps its 1.3.0 floor. The 3.9.0 changelog entry gains its summary line and the schema-1 extra's floor, and the 1.5.0 entry says its floor carries both fields the parser fills. --- CHANGELOG.md | 3 +++ packages/schema-1/CHANGELOG.md | 2 +- packages/schema-1/pyproject.toml | 11 ++++++----- pyproject.toml | 7 +++++-- uv.lock | 4 ++-- 5 files changed, 17 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f0a0bb2..b03b71b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ beta corrected in an earlier beta does not appear at all: from the point of view ## [3.9.0] +Snapshots say whether a circuit declares a breaker rating and whether a panel publishes shared meters, and each broker connection subscribes once. + ### Added - **`SpanCircuitSnapshot.breaker_rating_declared`** says whether a circuit declares a breaker rating, so a consumer can tell a rating the panel does not publish from one that has not arrived yet; `None` where the adapter does not say. @@ -19,6 +21,7 @@ beta corrected in an earlier beta does not appear at all: from the point of view ### Changed - **`AsyncMqttBridge.subscribe()` sends nothing for a topic the bridge already holds at that QoS or higher**, where every call sent a SUBSCRIBE and the broker replayed the topic's retained messages each time. +- **The `schema-1` extra requires `span-panel-api-schema-1` 1.5.0 or newer**, the adapter that fills `breaker_rating_declared` and `publishes_shared_meters`. ### Fixed diff --git a/packages/schema-1/CHANGELOG.md b/packages/schema-1/CHANGELOG.md index cd7dd1c..ca91135 100644 --- a/packages/schema-1/CHANGELOG.md +++ b/packages/schema-1/CHANGELOG.md @@ -11,7 +11,7 @@ Pre-releases are not listed separately. A beta is a step towards the next public ## [1.5.0] -Requires `span-panel-api` **3.9.0 or newer**, whose circuit snapshot carries the field this parser now fills. +Requires `span-panel-api` **3.9.0 or newer**, whose snapshots carry the fields this parser now fills. ### Added diff --git a/packages/schema-1/pyproject.toml b/packages/schema-1/pyproject.toml index 6064288..c7366a9 100644 --- a/packages/schema-1/pyproject.toml +++ b/packages/schema-1/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "span-panel-api-schema-1" -version = "1.5.0b1" +version = "1.5.0" description = "Parent/child schema (data-model-version 1.x) parser for span-panel-api" authors = [ {name = "SpanPanel"} @@ -34,10 +34,11 @@ dependencies = [ # it, imports `device_id_order` from its models, implements the masked-tree # protocol and types new in it, and relies on its client reading a cleared # value as unpublished. - # Raised to 3.9.0b1: this parser fills `SpanCircuitSnapshot.breaker_rating_declared`, - # which that release adds. A beta floor while this is a beta; the final - # restores a stable one (RELEASE.md, "Pre-releases"). - "span-panel-api>=3.9.0b1,<4.0", + # Raised to 3.9.0, the first bootstrap whose snapshots carry + # `SpanCircuitSnapshot.breaker_rating_declared` and + # `SpanPanelSnapshot.publishes_shared_meters`, which this parser fills. + # Against an earlier one, building a snapshot fails on those arguments. + "span-panel-api>=3.9.0,<4.0", # Only this distribution depends on the eBus SDK. The bootstrap and # schema-0 stay clean, so a flat-panel install never pulls it in — which is # what bounds the release coupling this dependency introduces to panels on diff --git a/pyproject.toml b/pyproject.toml index 397f684..467be02 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "span-panel-api" -version = "3.9.0b2" +version = "3.9.0" description = "A client library for SPAN Panel API" authors = [ {name = "SpanPanel"} @@ -71,7 +71,10 @@ schema-0 = ["span-panel-api-schema-0>=1.3.0"] # Raised to 1.4.0 for 3.8.0: for the same reason as schema-0's, and because that # adapter fills the snapshot fields this bootstrap adds and exports the masked # device tree. -schema-1 = ["span-panel-api-schema-1>=1.4.0"] +# Raised to 1.5.0 for 3.9.0: a 1.4.x adapter is still accepted, but it leaves +# `breaker_rating_declared` and `publishes_shared_meters` unknown, and 1.5.0 is +# the adapter that fills them. +schema-1 = ["span-panel-api-schema-1>=1.5.0"] [project.urls] Homepage = "https://github.com/SpanPanel/span-panel-api" diff --git a/uv.lock b/uv.lock index b124008..216b125 100644 --- a/uv.lock +++ b/uv.lock @@ -974,7 +974,7 @@ wheels = [ [[package]] name = "span-panel-api" -version = "3.9.0b2" +version = "3.9.0" source = { editable = "." } dependencies = [ { name = "httpx" }, @@ -1057,7 +1057,7 @@ requires-dist = [{ name = "span-panel-api", editable = "." }] [[package]] name = "span-panel-api-schema-1" -version = "1.5.0b1" +version = "1.5.0" source = { editable = "packages/schema-1" } dependencies = [ { name = "ebus-sdk" },