Skip to content

Support paho-mqtt 1.x and 2.x in the MQTT discovery monitor - #2958

Merged
J. Nick Koston (bdraco) merged 2 commits into
mainfrom
mqtt-paho-dual-support
Oct 21, 2026
Merged

J. Nick Koston (bdraco) merged 2 commits into
mainfrom
mqtt-paho-dual-support

Conversation

@bdraco

Copy link
Copy Markdown
Member

What does this implement/fix?

The MQTT discovery monitor now runs on both paho-mqtt 1.x and 2.x, so the dashboard keeps working whichever esphome release it is installed next to.

# before
client = paho_mqtt.Client(client_id=client_id, clean_session=True)

# after
api_version = getattr(paho_mqtt, "CallbackAPIVersion", None)
client: Any = (
    paho_mqtt.Client(api_version.VERSION2, client_id=client_id, clean_session=True)
    if api_version is not None
    else paho_mqtt.Client(client_id=client_id, clean_session=True)
)
  • Dual support: the client is built on callback API v2 when the installed paho offers it, and the CONNACK and SUBACK callbacks accept either major's argument shape; no new pin in pyproject, esphome keeps owning the paho pin.
  • CI: the mosquitto e2e job becomes a two leg matrix, one on the esphome pin and one with paho-mqtt 2.1.0 installed on top, so both majors stay covered while releases carry either one.
  • Clears the way for [core] Update paho-mqtt to v2.1.0 esphome#18402, which moves esphome's pin from 1.6.1 to 2.1.0; this PR needs to merge first.
Mechanism

paho 2 with CallbackAPIVersion.VERSION2 passes on_connect(client, userdata, flags, reason_code, properties) and on_subscribe(client, userdata, mid, reason_codes, properties), where the codes are ReasonCode objects: value 0 is success, values at or above 0x80 are failures, and a v3 CONNACK rc 4 arrives as 134 "Bad user name or password". paho 1 passes four arguments with plain ints. The monitor's two callbacks take *_ for the extra argument and compare through _code_value, which reads .value when present and the int otherwise. Every other call the monitor makes (tls_set_context, tls_insecure_set, username_pw_set, connect, loop_start, loop_stop, disconnect, publish().rc) is unchanged between the majors.

Constructing without a CallbackAPIVersion on paho 2 still works but raises a DeprecationWarning on every session and stays on the v1 path that paho plans to remove, which is why the switch is explicit.

The client local is typed Any on purpose: paho 2 ships py.typed, and its subscribe and publish signatures do not structurally match the narrow SubscribeClient and PublishClient protocols, so a typed local would fail mypy the day the pin moves.

Verification
  • pytest tests/test_mqtt_monitor.py tests/e2e/slow/mqtt -W error::DeprecationWarning against a real mosquitto: 147 passed on paho 1.6.1 (the project venv) and 147 passed on paho 2.1.0 (a scratch venv built from the same constraints with paho overridden).
  • mypy on the monitor and coordinator passes in both venvs, including against paho 2's typed surface.
  • New unit tests drive the v2 path with a CallbackAPIVersion bearing stand-in: the client is built with VERSION2, a failing CONNACK reason code rejects by name, a SUBACK reason code at or above 0x80 fails the session, and _code_value is pinned for ints and reason codes. The existing paho 1 shaped tests are untouched.
  • The e2e fakes build their clients the same way and use lambda c, *_: for on_connect, so they run on either major.

Related issue or feature (if applicable):

Types of changes

  • Bugfix (non-breaking change which fixes an issue) — bugfix
  • New feature (non-breaking change which adds functionality) — new-feature
  • Enhancement to an existing feature — enhancement
  • Breaking change (fix or feature that would cause existing functionality to not work as expected) — breaking-change
  • Refactor (no behaviour change) — refactor
  • Documentation only — docs
  • Maintenance / chore — maintenance
  • CI / workflow change — ci
  • Dependencies bump — dependencies

Frontend coordination

  • No frontend change needed
  • Companion frontend PR: esphome/device-builder-frontend#

Checklist

  • The code change is tested and works locally.
  • Pre-commit hooks pass (ruff, codespell, yaml/json/python checks).
  • Tests have been added or updated under tests/ where applicable.
  • components.index.json / definitions/components/*.json have not been hand-edited (regenerate via script/sync_components.py if a sync is needed).
  • Architecture-level changes are reflected in docs/ARCHITECTURE.md and/or docs/API.md.

@bdraco J. Nick Koston (bdraco) added the enhancement Improvement to an existing feature label Oct 21, 2026
@bdraco

Copy link
Copy Markdown
Member Author

ESPHome Bot (@esphbot) review

@codspeed

codspeed Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 28 untouched benchmarks
⏩ 1 skipped benchmark1


Comparing mqtt-paho-dual-support (5f7ee79) with main (d0f0da0)

Open in CodSpeed

Footnotes

  1. 1 benchmark was skipped, so the baseline result was used instead. If it was deleted from the codebase, click here and archive it to remove it from the performance reports. ↩

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

The focused compatibility changes have supporting unit and integration coverage, with no unresolved findings.

No open issues 🎉

What changed in this PR

Adds paho-mqtt 1.x and 2.x compatibility to MQTT discovery without changing dependency ownership.

Changes:

  • Selects callback API v2 when available and handles both callback formats.
  • Adds compatibility tests and updates MQTT test clients.
  • Adds a paho 2.1.0 CI leg and documents dual-version support.
File Description
tests/​test_mqtt_monitor.py Tests v2 construction and callback result handling.
tests/​e2e/​slow/​mqtt/​conftest.py Supports both paho versions in test clients.
esphome_device_builder/​controllers/​_device_mqtt_monitor.py Adapts client construction and callbacks.
docs/​ARCHITECTURE.md Documents dual-version compatibility.
.github/​workflows/​test.yml Tests the ESPHome pin and paho 2.1.0.

Review effort: Balanced

@esphbot

ESPHome Bot (esphbot) commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@esphbot ESPHome Bot (esphbot) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

No blocking issues found — ready to merge.

@bdraco

Copy link
Copy Markdown
Member Author

ESPHome Bot (@esphbot) review

Applied in 5f7ee79: dropped the unused is_failure property from _FakeReasonCode; the monitor only reads .value.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

The focused compatibility changes preserve existing behavior and include regression coverage, with no identified blocking defects.

No open issues 🎉

Review effort: Balanced

@codecov

codecov Bot commented Oct 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.76%. Comparing base (d0f0da0) to head (5f7ee79).

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main    #2958   +/-   ##
=======================================
  Coverage   99.76%   99.76%           
=======================================
  Files         300      300           
  Lines       26425    26429    +4     
=======================================
+ Hits        26363    26367    +4     
  Misses         62       62           
Flag Coverage Δ
py3.12 99.72% <100.00%> (-0.01%) ⬇️
py3.14 99.61% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...device_builder/controllers/_device_mqtt_monitor.py 100.00% <100.00%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@esphbot

Copy link
Copy Markdown
Contributor

J. Nick Koston (@bdraco): ESPHome Bot (@esphbot) review

Confirmed. is_failure gone from head. Monitor reads only .value via _code_value. No remaining findings.

@esphbot

Copy link
Copy Markdown
Contributor

PR Review — Support paho-mqtt 1.x and 2.x in the MQTT discovery monitor

Ready to merge. The one earlier finding is fixed, and I found nothing new.

What the PR does well:

  • The client is built with callback API v2 when it is available. It checks this each session through getattr(paho_mqtt, "CallbackAPIVersion", None), so tests that swap in a fake module keep working.
  • The *_ tail and _code_value let one callback per event handle both paho majors without branching on the version.
  • The SUBACK check is now >= 0x80. This catches paho 2 reason codes such as 0x87, and it still catches the v3 0x80.
  • When a CONNACK is rejected, the error message names the reason, because ReasonCode.__str__ prints its name.
  • The CI matrix covers both majors without contaminating the cached venv.
  • The new unit tests cover building with VERSION2, a CONNACK rejection, a SUBACK denial at 0x87, and _code_value for both ints and reason codes.

Prior finding:

  • Fixed in 5f7ee79: _FakeReasonCode.is_failure is gone. A search confirms nothing references it any more.


Checklist

  • No hardcoded secrets
  • Callback signatures valid for both paho majors
  • CI matrix doesn't contaminate the cached venv
  • New branches covered by tests
  • Prior finding resolved

Automated review by Kōan (Claude) HEAD=5f7ee79 20s

@esphbot ESPHome Bot (esphbot) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

No blocking issues found — ready to merge.

@bdraco
J. Nick Koston (bdraco) marked this pull request as ready for review October 21, 2026 19:26
@bdraco
J. Nick Koston (bdraco) merged commit 80b8d1b into main Oct 21, 2026
26 checks passed
@bdraco
J. Nick Koston (bdraco) deleted the mqtt-paho-dual-support branch October 21, 2026 19:26
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 23, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

enhancement Improvement to an existing feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants