fix(Logging): defer MQTT/SD publish off the caller's stack via dedicated task+queue

Logging::log() previously ran AsyncMqttClient::publish() and SD file
writes synchronously on whatever task called LOG_*. Both are
variable-depth, stack-hungry operations, and this is what let
TelemetryTask's 4096B stack silently absorb enough nested cost to
overflow its canary (see feature-catalog.md F-051).

Serial output stays synchronous (cheap, and must reflect true event
order for crash debugging). MQTT/SD-bound messages are now copied
into a fixed-size LogQueueItem (256-byte message cap, audited against
real LOG_* call sites — worst case ~150-180 chars, comfortable
margin) and handed via non-blocking xQueueSend to a lazily-created
LoggingTask, which performs the actual publish/write on its own
4096B stack. A full queue drops the line rather than blocking the
caller. Queue+task creation is spinlock-guarded against concurrent
first-callers.

This removes the stack-nesting risk for every current and future
task that logs, not just Telemetry/HealthMonitor — closing the
broader risk flagged in F-051 for OutputManager, TimeKeeper,
MQTTDriver's own tasks, and Networking's netRecon.

Verified via pio run: RAM impact negligible (62980 vs 62956 bytes).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-16 09:39:57 +03:00
co-authored by Claude Sonnet 5
parent 838e206a82
commit 381465cfe4
4 changed files with 121 additions and 25 deletions
+14 -12
View File
@@ -60,7 +60,7 @@ Every feature — user-facing or significant internal mechanism — is listed he
| F-048 | SD log retrieval commands (`logs.list` / `logs.download`) | v2.1.2 | Stable |
| F-049 | `firmware.status` rollback safety-net diagnostics (retry/failure counts, backup partition) | v2.1.2 | Stable |
| F-050 | SD log lines prefixed with wall-clock date/time + uptime | v2.1.2 | Stable |
| F-051 | Fix: TelemetryTask/HealthMonitor stack overflow on SD+MQTT-nested logging | v2.0.3 | Stable |
| F-051 | Fix: TelemetryTask/HealthMonitor stack overflow — stack bump + deferred MQTT/SD logging queue | v2.0.3 | Stable |
---
@@ -698,20 +698,22 @@ Device rebooted every ~10 minutes with `Guru Meditation Error: ... Stack canary
**Fix applied:** Bumped `TelemetryTask` to 8192 bytes ([Telemetry.cpp](../../src/Telemetry/Telemetry.cpp)) and `HealthMonitor`'s monitoring task to 6144 bytes ([HealthMonitor.cpp](../../src/HealthMonitor/HealthMonitor.cpp)) — `HealthMonitor::performFullHealthCheck()` logs once per subsystem (11 `LOG_*` calls per pass) through the same nested nesting pattern and was judged the next most likely to trip. Verified via `pio run` — RAM usage after the bump is 19.2% (63KB/320KB), so the +6KB combined stack cost is not a concern.
**Not yet fixed — same risk remains in:** `OutputManager` (`OutputDuration`, 4096B), `TimeKeeper` (`TimeKeeper`, 4096B), `MQTTDriver`'s `mqttRecon`/`mqttHB`/`mqttConnect` (4096B each — their job *is* the MQTT publish, so no extra JSON/SD nesting, but no extra margin either), and `Networking`'s `netRecon` (3072B, the tightest of all). None have tripped yet, but all share the same structural fragility: any `LOG_*` call adds `Logging::log()`'s 512-byte buffer plus, if MQTT-enabled for that tag, `publishToMqtt()`'s 600-byte `String` and a synchronous `AsyncMqttClient::publish()` call onto whatever stack the calling task happens to have.
**Broader risk identified at the time:** `OutputManager` (`OutputDuration`, 4096B), `TimeKeeper` (`TimeKeeper`, 4096B), `MQTTDriver`'s `mqttRecon`/`mqttHB`/`mqttConnect` (4096B each), and `Networking`'s `netRecon` (3072B, the tightest of all) all called `LOG_*` directly on small task stacks, sharing the same structural fragility: any `LOG_*` call that fanned out to MQTT or SD added `Logging::log()`'s 512-byte buffer plus `publishToMqtt()`'s 600-byte `String` and a synchronous `AsyncMqttClient::publish()`/SD-write call onto whatever stack the calling task happened to have. This is fixed at the root by the logging redesign below — those tasks no longer pay that cost regardless of their own stack size.
**Proper fix (not yet implemented) — move logging output off the caller's stack:**
**Proper fix — deferred MQTT/SD logging via a dedicated queue + task:**
The root architectural problem is that `Logging::log()` does all formatting *and* all I/O (Serial/MQTT/SD) synchronously, on whatever task called `LOG_*`. A task that already has other stack-heavy work nested (JSON serialization, SD I/O) has no way to know it's borrowing stack for the logger too.
The root architectural problem was that `Logging::log()` did all formatting *and* all I/O (Serial/MQTT/SD) synchronously, on whatever task called `LOG_*`. A task with other stack-heavy work nested (JSON serialization, SD I/O) had no way to know it was borrowing stack for the logger too.
Planned design:
1. Add a small dedicated `LoggingTask` (its own generously-sized stack, e.g. 4096B, since it only formats + ships bytes) fed by a FreeRTOS queue.
2. `Logging::log()` still does `vsnprintf` into its local buffer (cheap, fixed-size, stays on the caller's stack — this part is fine), but instead of calling `publishToMqtt()`/`writeToSd()` directly, it copies the formatted line (tag, level, message, timestamp) into a fixed-size queue item and calls `xQueueSend()` (non-blocking or short-timeout, so a full queue drops rather than blocks the caller).
3. `LoggingTask` drains the queue and performs the actual `AsyncMqttClient::publish()` and SD write — these expensive, variable-depth operations now only ever nest on the logging task's own stack, never on the caller's.
4. Serial output can stay synchronous in `Logging::log()` — `Serial.printf()` is cheap and doesn't need to move.
Implemented in `src/Logging/Logging.hpp` / `Logging.cpp`:
1. A dedicated `LoggingTask` (4096B stack, Core 0, priority 1), lazily created on the first log call that needs MQTT or SD output — `ensureLoggingTaskStarted()` is guarded by a spinlock (`_logQueueInitSpinlock`) so concurrent first-callers can't race and create two queues/tasks.
2. `Logging::log()` still does `vsnprintf` into its local 512-byte buffer (cheap, fixed-size, stays on the caller's stack — unchanged). If the message is MQTT- or SD-enabled for that tag, it's copied into a fixed-size `LogQueueItem` (`tag[24]`, `levelStr[6]`, `message[256]`, plus the `LogLevel` enum and `toMqtt`/`toSd` flags) and sent via `xQueueSend(..., 0)` — non-blocking, so a full queue (depth 16) drops the line rather than stalling the caller.
3. `LoggingTask` drains the queue and calls the existing `publishToMqtt()` / `writeToSd()` unchanged — those functions, and the expensive/variable-depth `AsyncMqttClient::publish()` and SD file write calls inside them, now only ever nest on the logging task's own stack, never on the caller's.
4. Serial output stays synchronous in `Logging::log()` — cheap, and keeps the USB serial monitor showing the true, immediate order of events (important when debugging a crash, as opposed to a queue-drained/reordered view).
This fixes the *class* of bug for every current and future task that calls `LOG_*`, not just Telemetry/HealthMonitor. It does **not** fix stack pressure from non-logging causes (e.g. `FileManager::writeJsonFile()`'s own ArduinoJson/SD usage) — those still consume whatever they consume on the calling task's stack; only the logging fan-out moves.
**Message length cap:** queued MQTT/SD messages are capped at 256 bytes (vs. 512 for the Serial/vsnprintf buffer). Audited via grep across all `LOG_*` call sites in the codebase — the longest literal format strings are ~110 characters; with realistic `%s`/`%d` substitutions (hostnames, paths, `ArduinoJson::DeserializationError::c_str()`, which is always a short fixed string like `"InvalidInput"`), worst-case realistic messages land around 150–180 characters. 256 bytes leaves comfortable margin with no observed truncation risk.
Subsystem: `src/Telemetry/Telemetry.cpp`, `src/HealthMonitor/HealthMonitor.cpp`, `src/Logging/Logging.cpp`, `src/FileManager/FileManager.cpp`
**What this does NOT fix:** stack pressure from non-logging causes. `FileManager::writeJsonFile()`'s own ArduinoJson serialization and SD I/O still run synchronously on whatever task calls it — only the logging fan-out (the part that made TelemetryTask's overflow possible in the first place) was moved off the caller's stack.
Subsystem: `src/Logging/Logging.cpp`
RAM impact verified negligible via `pio run` (62980 vs. 62956 bytes static RAM; the 4096B task stack is allocated at runtime only if MQTT or SD logging is actually enabled).
Subsystem: `src/Logging/Logging.hpp`, `src/Logging/Logging.cpp`
+57 -7
View File
@@ -1,5 +1,6 @@
#include "Logging.hpp"
#include <time.h>
#include <cstring>
// ═══════════════════════════════════════════════════════════════════════════════════
// STATIC MEMBER INITIALIZATION
@@ -19,6 +20,10 @@ String Logging::_mqttLogTopic = "";
std::map<String, Logging::MqttRateState> Logging::_mqttRateStates;
QueueHandle_t Logging::_logQueue = nullptr;
TaskHandle_t Logging::_loggingTaskHandle = nullptr;
portMUX_TYPE Logging::_logQueueInitSpinlock = portMUX_INITIALIZER_UNLOCKED;
// ═══════════════════════════════════════════════════════════════════════════════════
// GLOBAL CHANNEL LEVEL SETTERS / GETTERS
// ═══════════════════════════════════════════════════════════════════════════════════
@@ -167,7 +172,8 @@ void Logging::log(LogLevel level, const char* levelStr, const char* tag, const c
char buffer[512];
vsnprintf(buffer, sizeof(buffer), format, args);
// Serial output
// Serial output — stays synchronous (cheap, and must reflect true event order
// for crash debugging), unlike MQTT/SD which are deferred below.
if (serialEnabled) {
const char* icon = (level == ERROR) ? "🔴" :
(level == WARNING) ? "🟡" :
@@ -176,14 +182,58 @@ void Logging::log(LogLevel level, const char* levelStr, const char* tag, const c
Serial.printf("%s [%s][%s] %s\n", icon, levelStr, tag, buffer);
}
// MQTT output
if (mqttEnabled) {
publishToMqtt(level, levelStr, tag, buffer);
// MQTT/SD output — deferred to LoggingTask so the variable-depth I/O
// (AsyncMqttClient::publish(), SD file writes) never nests on the calling
// task's own stack. See F-051.
if (mqttEnabled || sdEnabled) {
ensureLoggingTaskStarted();
LogQueueItem item;
item.level = level;
strncpy(item.tag, tag, sizeof(item.tag) - 1);
item.tag[sizeof(item.tag) - 1] = '\0';
strncpy(item.levelStr, levelStr, sizeof(item.levelStr) - 1);
item.levelStr[sizeof(item.levelStr) - 1] = '\0';
strncpy(item.message, buffer, sizeof(item.message) - 1);
item.message[sizeof(item.message) - 1] = '\0';
item.toMqtt = mqttEnabled;
item.toSd = sdEnabled;
// Non-blocking: a full queue drops the line rather than stalling the
// caller. Losing a log line under extreme burst beats risking the
// same stack-nesting problem this redesign exists to remove.
if (_logQueue != nullptr) {
xQueueSend(_logQueue, &item, 0);
}
}
}
// SD output
if (sdEnabled) {
writeToSd(level, levelStr, tag, buffer);
// ═══════════════════════════════════════════════════════════════════════════════════
// PRIVATE: DEFERRED OUTPUT TASK
// ═══════════════════════════════════════════════════════════════════════════════════
void Logging::ensureLoggingTaskStarted() {
if (_logQueue != nullptr) return; // fast path — avoid the spinlock once started
portENTER_CRITICAL(&_logQueueInitSpinlock);
if (_logQueue == nullptr) {
_logQueue = xQueueCreate(LOG_QUEUE_DEPTH, sizeof(LogQueueItem));
xTaskCreatePinnedToCore(loggingTask, "LoggingTask", 4096, nullptr, 1, &_loggingTaskHandle, 0);
}
portEXIT_CRITICAL(&_logQueueInitSpinlock);
}
void Logging::loggingTask(void* parameter) {
LogQueueItem item;
while (true) {
if (xQueueReceive(_logQueue, &item, portMAX_DELAY) == pdTRUE) {
if (item.toMqtt) {
publishToMqtt(item.level, item.levelStr, item.tag, item.message);
}
if (item.toSd) {
writeToSd(item.level, item.levelStr, item.tag, item.message);
}
}
}
}
+36
View File
@@ -34,6 +34,8 @@
#include <Arduino.h>
#include <map>
#include <functional>
#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
class Logging {
public:
@@ -130,6 +132,40 @@ private:
// Resolve effective level for a tag on a channel
static LogLevel resolveLevel(const char* tag, LogLevel globalLevel, const std::map<String, LogLevel>& overrides);
// ═══════════════════════════════════════════════════════════════════════════════
// DEFERRED OUTPUT (MQTT publish + SD write)
// Both channels do variable-depth, stack-hungry I/O (AsyncMqttClient::publish(),
// SD file writes). Running them synchronously on whatever task called LOG_*
// let a small task's stack silently absorb that cost — this is what overflowed
// TelemetryTask's 4096B stack in production (see feature-catalog.md F-051).
// Instead, log() copies the formatted message into a fixed-size queue item and
// a dedicated LoggingTask (its own stack) performs the actual MQTT/SD I/O.
// Serial output is NOT deferred — it's cheap and stays synchronous so what you
// see over USB reflects the true, immediate order of events (important when
// debugging a crash).
// ═══════════════════════════════════════════════════════════════════════════════
static constexpr size_t LOG_QUEUE_MESSAGE_MAX = 256; // truncates longer messages; see F-051 audit
static constexpr UBaseType_t LOG_QUEUE_DEPTH = 16;
struct LogQueueItem {
LogLevel level;
char tag[24];
char levelStr[6];
char message[LOG_QUEUE_MESSAGE_MAX];
bool toMqtt;
bool toSd;
};
static QueueHandle_t _logQueue;
static TaskHandle_t _loggingTaskHandle;
static portMUX_TYPE _logQueueInitSpinlock;
// Lazily created on first deferred item — MQTT/SD callbacks are registered
// well after boot (CommunicationRouter::begin()), so there's nothing to
// drain before then.
static void ensureLoggingTaskStarted();
static void loggingTask(void* parameter);
// ═══════════════════════════════════════════════════════════════════════════════
// MQTT RATE LIMITING
// Per-subsystem token bucket. Protects the broker/airtime from a chatty or
+13 -5
View File
@@ -18,7 +18,7 @@ Each `.cpp` file defines `#define TAG "SubsystemName"` at the top and calls the
| `LOG_DEBUG(tag, fmt, ...)` / `Logging::debug(tag, fmt, ...)` | Emit at DEBUG level |
| `LOG_VERBOSE(tag, fmt, ...)` / `Logging::verbose(tag, fmt, ...)` | Emit at VERBOSE level |
`fmt` is a `printf`-style format string. The formatted message is capped at 512 bytes internally.
`fmt` is a `printf`-style format string. The formatted message is capped at 512 bytes internally for Serial output. Messages routed to MQTT and/or SD are additionally capped at 256 bytes when copied into the deferred-output queue — see [Deferred MQTT/SD output](#deferred-mqttsd-output) below.
### Global channel levels
@@ -54,6 +54,14 @@ Pass `Logging::NONE` to fully suppress a tag on a channel. The override map is k
Both channels start disabled (callbacks are `nullptr`). Output on a channel is silenced until the relevant callback is registered.
### Deferred MQTT/SD output
MQTT and SD are not written synchronously from the calling task. `Logging::log()` formats the Serial line as before, but if the message is also enabled for MQTT and/or SD, it copies the tag/level/message into a fixed-size `LogQueueItem` (`message` capped at 256 bytes) and hands it to a dedicated `LoggingTask` via a FreeRTOS queue (depth 16, non-blocking send — a full queue drops the line rather than stalling the caller). `LoggingTask` is created lazily, on the first message that needs MQTT or SD output, and runs the existing `publishToMqtt()`/`writeToSd()` logic on its own 4096-byte stack.
This exists because `AsyncMqttClient::publish()` and SD file writes are variable-depth, stack-hungry operations. Running them synchronously on whatever task called `LOG_*` meant a small-stack task doing other stack-heavy work (JSON serialization, SD I/O) could silently overflow — this is exactly what happened to `TelemetryTask` (see `docs/features/feature-catalog.md` F-051). Deferring MQTT/SD to their own task means no caller's stack ever has to absorb that cost.
Serial output is deliberately **not** deferred — it stays synchronous so the USB serial monitor reflects the true, immediate order of events, which matters most when debugging a crash.
### MQTT rate limiting
Each subsystem tag has its own token bucket on the MQTT channel: a burst of 10 messages, refilling at 1/second. Once a tag's bucket is empty, further messages from that tag are dropped (not queued) until it refills. This protects the broker/airtime from a chatty or misconfigured subsystem — e.g. a per-subsystem override left at `VERBOSE` in the field.
@@ -157,21 +165,21 @@ Command example:
| `FileManager` | Provides `appendLine()` used by the SD callback |
| `std::map<String, LogLevel>` | Per-subsystem override storage |
`Logging.hpp` includes `<map>` and `<functional>` directly. No FreeRTOS headers are included; the class does not create any tasks or timers.
`Logging.hpp` includes `<map>`, `<functional>`, and `<freertos/FreeRTOS.h>`/`<freertos/queue.h>`. The class lazily creates one dedicated `LoggingTask` (and its backing queue) the first time a message needs MQTT or SD output.
---
## Gotchas / Notes
**Thread safety.** The class has no mutex protection. The per-channel re-entrancy guards (`isPublishing`, `isWriting`) are `static bool` flags, not atomics. These prevent log-of-a-log recursion within a single call path but are not safe across concurrent FreeRTOS tasks. In practice, Serial output is the only channel exercised from multiple tasks simultaneously (e.g. BellEngine on Core 1, MQTT task on Core 0). Serial's hardware FIFO makes this tolerable in practice, but strictly speaking concurrent calls are a data race.
**Thread safety.** The class has no general mutex protection. The per-channel re-entrancy guards (`isPublishing`, `isWriting`) are `static bool` flags, not atomics — harmless now that `publishToMqtt()`/`writeToSd()` only ever run from `LoggingTask` (a single task, so no concurrent entry), but not a general-purpose safety mechanism. The one spot that is protected is `LoggingTask`/queue creation itself (`ensureLoggingTaskStarted()`), guarded by a spinlock so two tasks racing to log for the first time can't both create a queue+task. Serial output is still called directly from whatever task logs; its hardware FIFO makes concurrent calls tolerable in practice, but strictly speaking interleaved `Serial.printf()` calls from multiple tasks are a data race.
**MQTT feedback loop.** Any subsystem whose logs are emitted on the MQTT channel must not call `Logging` from within the MQTT publish path. `MQTTClient` and `CommRouter` are silenced on MQTT by default for this reason. The `isPublishing` guard is a secondary safeguard.
**SD writes are synchronous, on whatever task logged.** `setSdWriteCallback` delegates to `FileManager::appendLogLine`, which runs on the calling task's own stack — there is no dedicated logging task. Calling `LOG_*` at high frequency with SD enabled stalls the calling task for the duration of the write, and every 50th write additionally does a full `/logs` directory scan (see [FileManager's log rotation notes](../FileManager/README.md#log-file-rotation)). Tasks with small stacks that may log at an SD-enabled level need enough headroom for this — the MQTT driver's connect/reconnect/heartbeat tasks were bumped to 4096 bytes after a stack-canary panic surfaced this.
**MQTT/SD output is deferred to `LoggingTask`, not run on the calling task.** See [Deferred MQTT/SD output](#deferred-mqttsd-output) above. `FileManager::appendLogLine`'s directory scan (every 50th write — see [FileManager's log rotation notes](../FileManager/README.md#log-file-rotation)) and `AsyncMqttClient::publish()` now only ever run on `LoggingTask`'s own stack. Calling tasks pay only a `vsnprintf` into a 512-byte local buffer plus a non-blocking queue send — cheap and fixed-cost regardless of MQTT/SD load.
**`isLevelEnabled` checks Serial only.** If you need to guard an expensive log-string build (e.g. formatting a large buffer before calling `LOG_DEBUG`), use `Logging::isLevelEnabled(Logging::DEBUG)`. Be aware this ignores MQTT and SD levels.
**Message truncation.** The internal format buffer is 512 bytes. Messages longer than 511 characters are silently truncated by `vsnprintf`.
**Message truncation.** The Serial format buffer is 512 bytes; messages longer than 511 characters are silently truncated by `vsnprintf`. Messages also routed to MQTT/SD are truncated again to 255 characters when copied into the queue item. Audited against actual `LOG_*` call sites in the codebase (longest literal format strings ~110 chars; worst realistic case with substitutions ~150–180 chars) — 256 bytes has comfortable margin.
**No timestamps beyond `millis()`.** MQTT and SD payloads use `millis()` (ms since boot). Wall-clock timestamps are not included; correlate with NTP-synced log entries from the backend if absolute time is needed.