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