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:
+13
-5
@@ -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.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user