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:
@@ -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`
|
||||
|
||||
Reference in New Issue
Block a user