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
@@ -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";