fix(MQTTDriver,MQTTTransport): free-heap guard prevents heap-exhaustion abort() under command bursts

Decoded a new crash via addr2line against the exact flashed ELF:
console reported faulting task "async_tcp", cause 29, vaddr 0. Full
backtrace traced through AsyncTCP's _async_service_task ->
AsyncMqttClient::_onData -> MQTTTransport::onMessage ->
CommandBus::dispatch -> the reply path -> MQTTDriver::publish ->
AsyncMqttClient::publish -> PublishOutPacket's vector::reserve ->
operator new failing -> unhandled C++ exception -> abort().

Root cause is heap fragmentation, not a single bad allocation: rapid
relay.test_bell commands with Verbose/Debug logging meant every
command triggered ~4-5 JsonDocument/String allocations (RX log,
dispatch log, handler log, MQTT log-channel copies, reply publish),
all on AsyncTCP's own task, faster than the allocator could coalesce
freed blocks between cycles. Two "JSON parse error: NoMemory"
warnings preceded the abort by seconds - an early symptom of the same
fragmentation.

Checked why this can't be a catchable exception: this SDK build has
CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0, so when the heap is
too fragmented to even allocate the object needed to throw
std::bad_alloc, it aborts instead of throwing. That's baked into the
precompiled Arduino-ESP32 core; fixing it means rebuilding the whole
ESP-IDF core from source, judged out of scope. Chose prevention over
a catchable-exception fix.

Adds MQTTDriver::hasHeapForPublish() (20KB threshold, chosen with
margin above the ~62KB-free-but-already-fragmented state seen at
crash time) and applies it before every allocation-heavy publish path
(publish, publishDirect, publishHeartbeat) and before MQTTTransport::
onMessage() does its own incoming-command deserialization. Skip
warnings use Serial.printf directly, not LOG_*, to avoid recursing
into the same low-heap condition via MQTT-channel logging.

Also corrects how coredump crash detail should be read for abort()-
reached crashes (vs. true hardware exceptions like the F-051 stack
canary trip): pc/exc_cause/exc_vaddr describe abort() internals in
this case, not the original fault site - only the task name is
reliably the "real" crash location. Documented for console/dashboard
consumers in feature-catalog.md F-055.

A full fix (queueing incoming commands off AsyncTCP's task, mirroring
the F-051 logging-queue redesign) is scoped out as a documented
future improvement, not rushed into this change.

Verified: pio run on vesper-std-v1 and agnus-v1.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-16 18:47:39 +03:00
co-authored by Claude Sonnet 5
parent 8546604490
commit 9cd6b142ef
6 changed files with 73 additions and 4 deletions
+32
View File
@@ -64,6 +64,7 @@ Every feature — user-facing or significant internal mechanism — is listed he
| F-052 | Consolidated lifetime boot counter + coredump crash detail, published automatically over MQTT | v2.1.3 | Stable |
| F-053 | `telemetry.get_boot_history` command + fixed boot-log counter drift + crash detail in SD history | v2.1.3 | Stable |
| F-054 | Console Health tab support — `free_heap` on heartbeat + `ping` round-trip timestamp echo | v2.1.4 | Stable |
| F-055 | Fix: heap-exhaustion abort() under rapid MQTT command bursts — free-heap guard on publish + command intake | v2.1.4 | Stable |
---
@@ -822,3 +823,34 @@ Response:
Verified: `pio run` on `vesper-std-v1` (has `ping`) and `agnus-v1` (compiles clean with `SystemHandler.cpp` excluded via `#if HAS_RTC`, confirming the scoping wasn't disturbed).
Subsystem: `src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp`, `src/Communication/Handlers/SystemHandler/SystemHandler.cpp`
---
### F-055 — Fix: heap-exhaustion `abort()` under rapid MQTT command bursts
**Incident.** After the F-051 stack-overflow fix held for a 4-hour idle test, the device crashed again when spammed with `relay.test_bell` MQTT commands for ~20 seconds with Serial/SD logging at Verbose and MQTT logging at Debug. F-052's coredump capture correctly reported the crash as: faulting task `async_tcp`, PC `0x40083ed5`, exception cause `29` (`EXCCAUSE_STORE_PROHIBITED`), faulting address `0x0`.
**Diagnosis method (reusable for future crashes).** The coredump summary's PC and backtrace are addresses into the exact firmware binary that was running — decode them with the toolchain's `addr2line` against the matching build's `.elf` (not `.bin` — the `.elf` retains debug symbols):
```
xtensa-esp32-elf-addr2line.exe -pfiaC -e .pio/build/vesper-std-v1/firmware.elf 0x40083ed5 <more addresses...>
```
(`xtensa-esp32-elf-addr2line.exe` ships with PlatformIO's toolchain package, e.g. `~/.platformio/packages/toolchain-xtensa-esp32/bin/`.) This requires the `.elf` to be the *exact* build that was flashed — check `git status` is clean and the checked-out commit matches what was flashed before trusting the decode. The full serial backtrace (not just the top `abort()` frame) is needed — decode every address in the `Backtrace:` line, since the top frames are almost always inside `abort()`/`std::terminate()` internals, not the original call site.
**What the decode revealed:** the real call chain was `_async_service_task` (AsyncTCP's own task — this is the `async_tcp` the console reported) → `AsyncClient::_recv` → `AsyncMqttClient::_onData` → `MQTTTransport::onMessage()` → `CommandBus::dispatch()` → the reply path → `MQTTDriver::publish()` → `AsyncMqttClient::publish()` → `AsyncMqttClientInternals::PublishOutPacket`'s constructor → `std::vector::reserve()` → `operator new` → **allocation failed** → unhandled C++ exception → `std::terminate()` → `abort()`.
**Important correction to the console's crash-detail semantics (relevant to F-052's `boot_report.crash` fields and `telemetry.get_boot_history`'s per-entry `crash` object):** for a crash reached via an unhandled C++ exception (as opposed to a direct hardware fault like F-051's stack-canary trip), the coredump's `pc`/`exc_cause`/`exc_vaddr` describe the state at the point `abort()`'s internal `panic_abort()` ran — i.e. the *abort mechanics* — not the original fault site. Cause 29 / vaddr 0 here does not mean "null pointer dereference at address 0"; it's an artifact of how this SDK's `std::terminate()` path reaches `abort()`. **The `task` field remains accurate and is the most actionable piece** — it correctly named `async_tcp`, which is what led straight to the real cause. Console/dashboard builders should treat `pc`/`exc_cause`/`exc_vaddr` as "useful forensic detail, decode with `addr2line` for confirmation" rather than literal ground truth when the reset reason is a plain `PANIC` from an `abort()` call (vs. a true Xtensa hardware exception).
**Root cause:** heap fragmentation, not a single bad allocation. Every incoming MQTT command allocates a `JsonDocument` (ArduinoJson v7's `JsonDocument` always heap-allocates via `DefaultAllocator` — this codebase has no fixed-capacity `StaticJsonDocument` on this path), and every reply/log line allocates its own `JsonDocument`/`String`/`AsyncMqttClientInternals::PublishOutPacket` vector — all on `_async_service_task`, back-to-back, with logging at Verbose/Debug multiplying the allocation count per command roughly 4-5x (RX log, dispatch log, handler log, reply publish, plus each of those again on the `/logs` MQTT channel via F-051's `LoggingTask` queue). Sustained rapid-fire commands don't give the allocator time to coalesce freed blocks between cycles. The log immediately before the crash showed `Free heap: 63864 bytes` but `Largest block: 40948` — measurable fragmentation already present before the fatal allocation. Two `"JSON parse error: NoMemory"` warnings (ArduinoJson failing to allocate for *incoming* command deserialization) appeared seconds before the abort — an early symptom of the same fragmentation, not the crash itself.
**Why this can't be made a catchable exception:** checked this SDK build's `sdkconfig` — `CONFIG_COMPILER_CXX_EXCEPTIONS=y` (exceptions are enabled) but `CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0`. When the heap is too fragmented to allocate even the small object needed to *throw* `std::bad_alloc`, ESP-IDF's C++ runtime normally falls back to a small reserved "emergency pool" to make the throw possible — with that pool sized 0, there's nothing to fall back to, so it aborts instead. This value is baked into the precompiled Arduino-ESP32 framework binary PlatformIO uses; changing it requires rebuilding the entire ESP-IDF core from source with a custom `sdkconfig` (hours of toolchain setup), which was judged out of scope for this fix. **Prevention was chosen over a catchable-exception fix.**
**Fix applied — free-heap guard before allocation-heavy MQTT work:**
- `MQTTDriver::hasHeapForPublish()` (public, so `MQTTTransport` can reuse the same threshold) checks `ESP.getFreeHeap() >= MIN_FREE_HEAP_FOR_PUBLISH` (20480 bytes / 20KB — chosen with real margin above the ~62KB-free-but-already-fragmented state observed at crash time). On failure it logs via `Serial.printf()` directly, **not** `LOG_*` — an MQTT-channel log call here would itself attempt a publish, recursing straight back into the low-heap condition being guarded against (same reasoning as the pre-existing "don't log here" comment on the disconnected-check in the same function).
- Applied at three call sites: `MQTTDriver::publish()`, `MQTTDriver::publishDirect()` (both wrap the same underlying `AsyncMqttClient::publish()` that failed in this incident), and `MQTTDriver::publishHeartbeat()` (checked *before* building its `JsonDocument`, not just before the final publish, since that construction is itself part of the churn).
- `MQTTTransport::onMessage()` also checks `_mqtt.hasHeapForPublish()` **first thing**, before even constructing the incoming `JsonDocument doc` for deserialization — under critical heap pressure, incoming commands are dropped silently rather than attempting to process them and risk being the allocation that finally fails. A dropped command under this condition means the caller gets no reply (indistinguishable from a lost network message) — no error response is sent, since building one would itself risk the same allocation failure.
**What this does NOT fix:** the underlying churn (every command still allocates a `JsonDocument`, `String`s, and does 4-5 heap alloc/free cycles under verbose logging) is unchanged — the guard prevents the crash by refusing to attempt risky work below the threshold, it doesn't reduce how much allocation happens above it. A **command-processing queue** (mirroring F-051's logging-queue redesign — move `MQTTTransport::onMessage()`'s deserialize/dispatch/reply work off `_async_service_task` onto a dedicated task with its own stack, so AsyncTCP's task only ever does a fast, non-allocating handoff) was considered but scoped out as a separate, larger follow-up rather than rushed into this fix. Documented here so it isn't lost as a vague TODO — same rationale as F-051's own deferred-queue redesign.
Verified: `pio run` on both `vesper-std-v1` and `agnus-v1`.
Subsystem: `src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp`, `src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp`, `src/Communication/Transport/MQTTTransport/MQTTTransport.cpp`
@@ -149,12 +149,24 @@ void MQTTDriver::disconnect() {
LOG_INFO(TAG, "Disconnected from MQTT broker");
}
bool MQTTDriver::hasHeapForPublish() const {
if (ESP.getFreeHeap() >= MIN_FREE_HEAP_FOR_PUBLISH) return true;
// Serial.printf directly, not LOG_* — MQTT-channel logging would try to publish
// this very warning, recursing straight back into the low-heap condition we're
// trying to avoid. Same reasoning as the disconnected-check below.
Serial.printf("[MQTTClient] Skipping publish - free heap %u below %u byte threshold\n",
(unsigned)ESP.getFreeHeap(), (unsigned)MIN_FREE_HEAP_FOR_PUBLISH);
return false;
}
uint16_t MQTTDriver::publish(const String& topic, const String& payload, int qos, bool retain) {
// Check if connected before attempting to publish
if (!_mqttClient.connected()) {
// Don't log error here - would cause infinite loop with MQTT logging
return 0;
}
if (!hasHeapForPublish()) return 0;
// Build full topic (if relative)
String fullTopic = topic.startsWith("vesper/") ? topic : _dataTopic;
@@ -173,6 +185,8 @@ uint16_t MQTTDriver::publishDirect(const String& fullTopic, const String& payloa
if (!_mqttClient.connected()) {
return 0;
}
if (!hasHeapForPublish()) return 0;
uint16_t packetId = _mqttClient.publish(fullTopic.c_str(), qos, retain, payload.c_str());
if (packetId > 0) {
LOG_DEBUG(TAG, "Published to %s (packetId=%d)", fullTopic.c_str(), packetId);
@@ -378,6 +392,7 @@ void MQTTDriver::publishHeartbeat() {
LOG_WARNING(TAG, "⚠️ Cannot publish heartbeat - MQTT not connected");
return;
}
if (!hasHeapForPublish()) return; // skip building the JsonDocument too, not just the publish
// Build heartbeat JSON message
JsonDocument doc;
@@ -99,6 +99,18 @@ public:
*/
void onNetworkDisconnected();
// Minimum free heap (bytes) required before attempting a publish. Below this,
// AsyncMqttClient's internal packet-buffer allocation risks failing outright —
// this SDK build has CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0, so a failed
// allocation that can't even throw std::bad_alloc calls abort() instead of being
// catchable. Skipping the publish (or, from MQTTTransport, skipping incoming
// command processing) is far cheaper than crashing the device. Public so
// MQTTTransport can apply the same threshold before doing its own allocation-
// heavy work (JSON deserialization) without duplicating the constant.
// See docs/features/feature-catalog.md for the incident this guards against.
static constexpr uint32_t MIN_FREE_HEAP_FOR_PUBLISH = 20480; // 20KB
bool hasHeapForPublish() const;
private:
ConfigManager& _configManager;
Networking& _networking;
@@ -21,8 +21,9 @@ Topics:
| `void begin()` | Caches topic strings, registers AsyncMqttClient event handlers, configures broker host/port/credentials/keepalive. Does not connect. |
| `void connect()` | Calls `AsyncMqttClient::connect()`. No-op if MQTT is disabled in config or already connected. |
| `void disconnect()` | Disconnects cleanly. |
| `uint16_t publish(const String& topic, const String& payload, int qos, bool retain)` | Publishes to `topic`. If `topic` does not start with `"vesper/"`, it is treated as relative and the full data topic is used instead. Returns packet ID or 0 on failure. |
| `uint16_t publishDirect(const String& fullTopic, const String& payload, int qos, bool retain)` | Publishes to an absolute, fully-qualified topic — no prefix is applied. Used by `CommunicationRouter` to target `status/alerts` and `status/info` topics directly. |
| `uint16_t publish(const String& topic, const String& payload, int qos, bool retain)` | Publishes to `topic`. If `topic` does not start with `"vesper/"`, it is treated as relative and the full data topic is used instead. Returns packet ID, or 0 on failure (not connected, or free heap below `hasHeapForPublish()`'s threshold). |
| `uint16_t publishDirect(const String& fullTopic, const String& payload, int qos, bool retain)` | Publishes to an absolute, fully-qualified topic — no prefix is applied. Used by `CommunicationRouter` to target `status/alerts` and `status/info` topics directly. Same heap guard as `publish()`. |
| `bool hasHeapForPublish() const` | Returns `true` if `ESP.getFreeHeap() >= MIN_FREE_HEAP_FOR_PUBLISH` (20KB). Public so `MQTTTransport` can apply the same threshold before its own allocation-heavy work (JSON deserialization of incoming commands) without duplicating the constant. See [Gotchas](#gotchas--notes) below for why this exists. |
| `const String& getAlertsTopic() const` | Returns the cached `vesper/{uid}/status/alerts` topic string. Available after `begin()`. |
| `const String& getInfoTopic() const` | Returns the cached `vesper/{uid}/status/info` topic string. Available after `begin()`. |
| `void setCallback(MessageCallback callback)` | Registers the message-received callback. Called by `MQTTTransport::begin()`. |
@@ -82,6 +83,7 @@ Once connected, a heartbeat is published immediately and then every 30 seconds t
- **Timer callbacks defer to tasks.** Timer callbacks run in the FreeRTOS Timer Service task (Tmr Svc, default 2 KB stack). Any callback that calls `LOG_*` macros, `connect()`, or JSON serialisation would overflow this stack. All three callbacks (`mqttReconnectTimerCallback`, `networkStabilizationTimerCallback`, `heartbeatTimerCallback`) spawn a 3 KB task and return immediately.
- **Heartbeat task guard.** If the previous heartbeat task has not yet exited when the next timer fires, the new task is not spawned. This prevents task accumulation under slow broker connections.
- **Error logging is suppressed on publish failure.** `publish()` does not log an error when `_mqttClient.publish()` returns 0 (packet ID failure), because `publish()` is also called from the MQTT log channel and logging an error there would recurse infinitely.
- **Free-heap guard before publishing (`hasHeapForPublish()`).** Below `MIN_FREE_HEAP_FOR_PUBLISH` (20KB), `publish()`, `publishDirect()`, and `publishHeartbeat()` skip the operation entirely rather than risk `AsyncMqttClient::publish()`'s internal packet-buffer allocation failing. This SDK build has `CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0` — a failed allocation under heavy fragmentation can't even throw a catchable `std::bad_alloc`, it calls `abort()` directly. This guard exists because exactly that happened in production under a rapid MQTT command burst with verbose logging (see `docs/features/feature-catalog.md` F-055 for the full `addr2line`-decoded diagnosis). The skip is logged via `Serial.printf()` directly, not `LOG_*` — logging the skip over MQTT would itself attempt a publish, recursing into the same low-heap condition.
- **Credentials from NVS.** The broker username and password are read from `ConfigManager`, which loads them from NVS at boot. The password is a 32-character HMAC-SHA256 hex digest derived from the device UID and `MQTT_SECRET` (compiled in via `-DMQTT_SECRET`).
- **`begin()` must be called before `connect()`.** `begin()` registers AsyncMqttClient event handlers and configures the server. Calling `connect()` before `begin()` will silently do nothing useful.
- **`onConnect` callback fires on every connect, not just the first.** `setOnConnectCallback` fires on every successful connection, including reconnects after a drop — callers that want "once per boot" semantics (like `CommunicationRouter::reportBootReasonOnce()`) must track that themselves.
- **`onConnect` callback fires on every connect, not just the first.** `setOnConnectCallback` fires on every successful connection, including reconnects after a drop — callers that want "once per boot" semantics (like `CommunicationRouter::reportBootOnce()`) must track that themselves.
@@ -45,6 +45,13 @@ void MQTTTransport::onNetworkDisconnected() {
// ---------------------------------------------------------------------------
void MQTTTransport::onMessage(const String& topic, const String& payload) {
// Skip entirely under critical heap pressure — deserializing, dispatching, and
// replying all allocate, and this runs inline on AsyncTCP's own task. Letting a
// burst of incoming commands compound an already-low-heap condition is what led
// to an unrecoverable abort() in production (this SDK build can't even throw
// std::bad_alloc when allocation fails — see MQTTDriver::hasHeapForPublish()).
if (!_mqtt.hasHeapForPublish()) return;
LOG_DEBUG(TAG, "RX [%s]: %s", topic.c_str(), payload.c_str());
JsonDocument doc;
@@ -59,3 +59,4 @@ Responses are published to the data topic:
- **MQTT must be enabled in config.** `MQTTDriver::connect()` is a no-op if `mqttConfig.enabled` is false. Toggle with `mqtt.enable` / `mqtt.disable` commands.
- **No per-message QoS.** Command replies and broadcasts are published at QoS 0. Heartbeats use QoS 1 with `retain = true`.
- **JSON parse errors drop the message silently** (with a `LOG_WARNING`). The client receives no error response.
- **Incoming commands are dropped under critical heap pressure.** `onMessage()` checks `MQTTDriver::hasHeapForPublish()` (free heap ≥ 20KB) before even constructing the `JsonDocument` used to deserialize the incoming payload. Below that threshold, the message is dropped with no reply and no error response — indistinguishable from a lost network message to the caller. This exists because a rapid burst of commands (each involving deserialize + dispatch + reply, all allocation-heavy, all running inline on AsyncTCP's own task) previously fragmented the heap enough to crash the device with an unrecoverable `abort()` — see `docs/features/feature-catalog.md` F-055. A full fix (queueing incoming commands to a dedicated task, so this work never runs on AsyncTCP's task at all) is a scoped future improvement, not yet implemented.