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:
@@ -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,7 +392,8 @@ 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;
|
||||
doc["status"] = "INFO";
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user