Skip to content

Re-arm the MQTT reconnect log gate on a granted SUBACK, not on CONNACK - #2960

Merged
J. Nick Koston (bdraco) merged 3 commits into
mainfrom
mqtt-suback-denial-log-gate
Oct 21, 2026
Merged

J. Nick Koston (bdraco) merged 3 commits into
mainfrom
mqtt-suback-denial-log-gate

Conversation

@bdraco

@bdraco J. Nick Koston (bdraco) commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

What does this implement/fix?

A broker that accepts the connection but denies the esphome/discover/# subscription made the monitor log the same WARNING on every 5 second reconnect forever, because the quiet-log gate was re-armed by the CONNACK that preceded each denial; the gate now re-arms only on a granted SUBACK, so a persistent denial warns once and then collapses to DEBUG like a rejected CONNACK already does.

# before: set right after CONNACK in _connect_and_listen
_LOGGER.info("MQTT connected to %s:%s", ...)
self._connected_this_session = True
self._set_connected(value=True)

# after: set once the discovery SUBACK is granted, in require_suback
async with asyncio.timeout(_CONNECT_TIMEOUT):
    await signals.subscribed.wait()
self._subscribed_this_session = True
  • A denied subscription now logs one MQTT broker ... unreachable (subscription denied ...) WARNING per streak, with the repeats at DEBUG; a real outage after a working session still re-warns, since a granted SUBACK re-arms the gate exactly as the CONNACK used to.
  • Monitor and its unit tests only; the flag is renamed to say what it now means, and two tests pin the new behaviour (a healthy session arms the reset, a persistently denied one warns once).
  • Surfaced by live testing of Support paho-mqtt 1.x and 2.x in the MQTT discovery monitor #2958 against a stub broker that returns SUBACK 0x80; the behaviour predates that PR and is the same on paho 1.x and 2.x.
Mechanism

_run loops _connect_and_listen and calls _log_reconnect_failure on every failure. That method logs loudly only while _connect_error_logged is clear, and clears it when the failed iteration had set the "this session connected" flag. The flag was set immediately after a successful CONNACK, before the SUBACK verdict. A denial therefore ran: CONNACK ok (flag set) → SUBACK 0x80 → ConnectionError("subscription denied ...") → gate re-armed → WARNING, every _RECONNECT_DELAY. A rejected CONNACK never set the flag, which is why that case already collapsed to DEBUG.

Moving the set into require_suback, after signals.subscribed fires, keeps every other property: the re-arm still happens inside the iteration (not on a clean return, which production rarely sees because the TaskGroup parks), and it happens once per granted handshake, including paho's own auto-reconnect SUBACKs, so the down → up → down case still warns twice (test_run_resets_log_gate_after_granted_suback, formerly ..._after_successful_connect).

The MQTT connected to ... INFO line still appears on each reconnect in the denial loop; it is accurate (the broker did accept the connection) and matches what a flapping broker logs, so it is left alone.

Verification
  • pytest tests/test_mqtt_monitor.py: 145 passed; pytest tests/e2e/slow/mqtt (real mosquitto): 4 passed; mypy clean on the monitor; pre-commit clean.
  • Live run of the real dashboard process against mosquitto plus a stub broker that answers SUBACK 0x80, once on paho 1.6.1 and once on paho 2.1.0 (~2.5 minutes each, with a broker outage in the middle): on both, the denial produced 1 WARNING and 30 DEBUG lines, where main produced a WARNING on every iteration. Good devices still came ONLINE via MQTT, the CONNACK 4 / 5 and TLS misconfiguration cases still logged their single WARNING, and nothing flipped OFFLINE during the outage.

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

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-suback-denial-log-gate (c3302db) with main (3c52ef5)

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. ↩

@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 (80b8d1b) to head (c3302db).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main    #2960   +/-   ##
=======================================
  Coverage   99.76%   99.76%           
=======================================
  Files         300      300           
  Lines       26429    26429           
=======================================
  Hits        26367    26367           
  Misses         62       62           
Flag Coverage Δ
py3.12 99.73% <100.00%> (ø)
py3.14 99.61% <100.00%> (ø)

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

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.

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.

🟡 Changes recommended

The persistent-denial regression test bypasses the original faulty reset point and would still pass if that bug were restored.

1 open issue
What changed in this PR

This PR adjusts the MQTT discovery monitor’s reconnect logging so persistent subscription denials warn once, while a working subscription re-arms warnings for a later outage.

Changes:

  • Move log-gate re-arming from connection acceptance to a granted discovery subscription.
  • Rename the session flag to reflect subscription success.
  • Add and update tests for subscription denial and warning-reset behavior.
File Description
tests/​test_mqtt_monitor.py Adds subscription log-gate tests and updates outage-reset coverage.
esphome_device_builder/​controllers/​_device_mqtt_monitor.py Re-arms reconnect warnings only after a granted SUBACK.

Review effort: Balanced

Comment thread tests/test_mqtt_monitor.py Resolved
@bdraco

Copy link
Copy Markdown
Member Author

ESPHome Bot (@esphbot) review

Applied in 901f6e7: the denial test now leaves subscribe() silent and fires the SUBACK 0x80 from the fake's first publish, which only runs once the session has passed the CONNACK verdict (it also asserts the MQTT connected line for every iteration). With main's monitor swapped in, the test fails with three WARNINGs; on the branch it passes. The require_suback comment and the gate test docstring are cut back to the contract.

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 narrow change preserves outage warnings while suppressing repeated subscription-denial warnings, with focused regression coverage and no unresolved findings.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@esphbot

Copy link
Copy Markdown
Contributor

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

Confirmed resolved. SUBACK denial now fires from publish, after the CONNACK check. The MQTT connected assertion proves that path runs. The trimmed comments match the contract rule. No further findings.

@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

c3302db fixes the Pytest (ubuntu / 3.12) timeout on the previous head: with a zero reconnect delay the fake kept the session failing in a tight loop, and the cancel from running_task could land while the TaskGroup was still propagating a child failure, so the drain never finished. The fake now denies three sessions and leaves the fourth parked; the test waits for that fourth session's first broadcast before exiting, so teardown always finds a quiet task. 25 consecutive runs each on 3.12 and 3.13 locally, no failures; the full monitor file passes on both.

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 narrow logging fix preserves reconnect behavior and includes regression coverage for persistent denials and recovery.

No open issues 🎉

Review effort: Balanced

@bdraco
J. Nick Koston (bdraco) marked this pull request as ready for review October 21, 2026 22:56
@esphbot

Copy link
Copy Markdown
Contributor

PR Review — Re-arm the MQTT reconnect log gate on a granted SUBACK, not on CONNACK

Ready to merge. The flake fix in c3302db is sound, and I found no new issues.

  • The gate fix is correct. The re-arm now happens after signals.subscribed.wait() inside require_suback (_device_mqtt_monitor.py:445-447). on_subscribe sets subscribed only when no granted QoS is 0x80 or above. So a denied SUBACK can never re-arm the gate, but a granted SUBACK after one of paho's own reconnects still does. That means a broker that goes down, comes back, then goes down again still warns twice.
  • The teardown race is fixed. The fake denies sessions 1-3 from publish and leaves session 4 parked. The test waits on fourth_session_parked before leaving running_task, so the cancel lands while the TaskGroup is idle in require_suback/_listen. It can no longer land while a child failure is still being propagated. That race is what caused the ubuntu/3.12 timeout.
  • The parked session cannot fail before the test ends. It is waiting on the SUBACK, bounded by _CONNECT_TIMEOUT, which is far longer than the moment between its first broadcast and the test exiting. The final _subscribed_this_session is False assertion is also correct, because no session was ever granted.
  • The test still covers the original bug. The denial is still delivered after the CONNACK check, and the MQTT connected assertion confirms every iteration takes that path. Restoring main's CONNACK-based reset would make the WARNING/DEBUG/DEBUG assertion fail.
  • The PR description matches the diff. The change is limited to the monitor and its tests, and the new comments follow the one-line-contract convention.

I couldn't run pytest in this review shell. The 25-run stability claim and the claim that the test fails on main are the author's own results; reading the code supports both.



Checklist

  • Gate re-arm only on granted SUBACK, per handshake
  • Regression test exercises post-CONNACK denial path
  • Test teardown free of TaskGroup-failure race
  • Docstrings/comments follow one-line contract convention
  • PR description matches diff
  • No security or resource-leak concerns

Automated review by Kōan (Claude) HEAD=c3302db 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) merged commit 61ae472 into main Oct 21, 2026
26 checks passed
@bdraco
J. Nick Koston (bdraco) deleted the mqtt-suback-denial-log-gate branch October 21, 2026 23:00
@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

bugfix Bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants