From e99d19dedf9056a5cdc4eaca1724235996c68a2e Mon Sep 17 00:00:00 2001 From: Jason Huebert Date: Fri, 16 Oct 2026 21:01:06 -0500 Subject: [PATCH] feat: defer observer broker connects without internal-heap headroom A second TLS client started on a fragmented internal heap aborts a non-PSRAM ESP32. Gate connect() on free/largest internal-heap bytes (secure slots need much more than plaintext), deferring and retrying every 30 s instead of crashing. The decision is a pure policy function so the host suite covers it; the deferral is never a terminal state, so a broker missed during a heap squeeze is still retried after a long outage. --- MQTT_OBSERVER.md | 7 ++++++ examples/mqtt_observer/MQTTObserver.cpp | 23 +++++++++++++++---- examples/mqtt_observer/MQTTObserver.h | 1 + examples/mqtt_observer/MQTTObserverPolicy.h | 17 ++++++++++++++ .../test_mqtt_observer/test_mqtt_observer.cpp | 17 ++++++++++++++ 5 files changed, 61 insertions(+), 4 deletions(-) diff --git a/MQTT_OBSERVER.md b/MQTT_OBSERVER.md index 74cc1449..73e94108 100644 --- a/MQTT_OBSERVER.md +++ b/MQTT_OBSERVER.md @@ -197,6 +197,13 @@ no connected broker. No packet event, queue entry, or offline history is written to flash or replayed after reboot. Waiting for valid time also expires queued events, and a flush starts a fresh expiry window for newly captured events. Publish work, TLS, NTP, and reconnects run outside the receive and forwarding path. +Before opening a broker connection the worker checks internal-heap headroom +(free and largest contiguous block); a secure slot needs considerably more than +a plaintext one. When the heap is too fragmented to start a client the connect +is deferred and retried every 30 seconds, so a second TLS slot on a low-memory +board waits for room instead of aborting the device. This check is never +terminal: a broker that could not be reached during a heap squeeze is retried +indefinitely, including after a long outage. Both connected slots are offered each queued event. Following the reference observer's queue policy, the event is considered delivered when any connected diff --git a/examples/mqtt_observer/MQTTObserver.cpp b/examples/mqtt_observer/MQTTObserver.cpp index 8c854831..3ee7e7d4 100644 --- a/examples/mqtt_observer/MQTTObserver.cpp +++ b/examples/mqtt_observer/MQTTObserver.cpp @@ -6,6 +6,7 @@ #include "../simple_repeater/CliUtil.h" #include #include +#include #include #include #if defined(BOARD_HAS_PSRAM) @@ -206,6 +207,12 @@ bool MQTTObserver::ready(const MQTTObserverConfig& config, size_t slot) const { MQTTObserverConfigCodec::valid(config); } +bool MQTTObserver::hasConnectHeadroom(bool secure) const { + return MQTTObserverConnectionPolicy::hasConnectHeadroom( + secure, heap_caps_get_free_size(MALLOC_CAP_INTERNAL), + heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)); +} + bool MQTTObserver::readRecord(File& file, MQTTObserverConfig& config) { if (file.size() != MQTTObserverRecord::kRecordSize) return false; if (file.read(_load_record, sizeof(_load_record)) != sizeof(_load_record)) return false; @@ -643,10 +650,18 @@ void MQTTObserver::worker() { runtime.state.store(STATE_RETRY, std::memory_order_relaxed); } if (!runtime.client_started && static_cast(now - runtime.next_connect_ms) >= 0) { - runtime.client->connect(); - runtime.client_started = true; - runtime.attempt_started = now; - runtime.state.store(STATE_CONNECTING, std::memory_order_relaxed); + if (hasConnectHeadroom(secureUri(runtime.server_uri))) { + runtime.client->connect(); + runtime.client_started = true; + runtime.attempt_started = now; + runtime.state.store(STATE_CONNECTING, std::memory_order_relaxed); + } else { + // A second TLS client started without a contiguous internal-heap + // allocation can abort the device. Defer and retry indefinitely + // (never a terminal state) until the heap recovers. + runtime.next_connect_ms = now + 30000; + runtime.state.store(STATE_RETRY, std::memory_order_relaxed); + } } State state = runtime.state.load(std::memory_order_relaxed); any_connecting = any_connecting || state == STATE_CONNECTING || state == STATE_RETRY; diff --git a/examples/mqtt_observer/MQTTObserver.h b/examples/mqtt_observer/MQTTObserver.h index 5b4564ed..18e5ea6b 100644 --- a/examples/mqtt_observer/MQTTObserver.h +++ b/examples/mqtt_observer/MQTTObserver.h @@ -98,6 +98,7 @@ class MQTTObserver { void worker(); void copyConfig(MQTTObserverConfig& config); bool ready(const MQTTObserverConfig& config, size_t slot) const; + bool hasConnectHeadroom(bool secure) const; bool configureClient(size_t slot, const MQTTObserverBrokerConfig& config); bool createJwt(size_t slot, const MQTTObserverBrokerConfig& config, uint32_t& expires_at); bool publishEvent(const Event& event, const MQTTObserverConfig& config); diff --git a/examples/mqtt_observer/MQTTObserverPolicy.h b/examples/mqtt_observer/MQTTObserverPolicy.h index 1858e74c..b5339bcd 100644 --- a/examples/mqtt_observer/MQTTObserverPolicy.h +++ b/examples/mqtt_observer/MQTTObserverPolicy.h @@ -47,6 +47,23 @@ inline bool jwtNeedsRenewal(int64_t epoch, uint32_t expiry) { return expiry != 0 && epoch + 300 >= expiry; } +// A TLS client needs a contiguous mbedTLS allocation on the internal heap; +// starting one without headroom aborts a non-PSRAM device, so connect() waits +// for the heap to recover instead of crashing. The secure thresholds follow +// the reference observers (roughly 60 KB free and one ~17 KB TLS record); +// plaintext brokers need far less. Keeping the decision pure lets the host +// suite cover it. +static const size_t kSecureFreeInternalBytes = 64u * 1024u; +static const size_t kSecureLargestInternalBytes = 18u * 1024u; +static const size_t kPlainFreeInternalBytes = 24u * 1024u; +static const size_t kPlainLargestInternalBytes = 8u * 1024u; + +inline bool hasConnectHeadroom(bool secure, size_t free_internal, size_t largest_internal) { + const size_t free_needed = secure ? kSecureFreeInternalBytes : kPlainFreeInternalBytes; + const size_t block_needed = secure ? kSecureLargestInternalBytes : kPlainLargestInternalBytes; + return free_internal >= free_needed && largest_internal >= block_needed; +} + } // namespace MQTTObserverConnectionPolicy namespace MQTTObserverQueuePolicy { diff --git a/test/test_mqtt_observer/test_mqtt_observer.cpp b/test/test_mqtt_observer/test_mqtt_observer.cpp index 0e515616..06fb3133 100644 --- a/test/test_mqtt_observer/test_mqtt_observer.cpp +++ b/test/test_mqtt_observer/test_mqtt_observer.cpp @@ -199,6 +199,23 @@ TEST(MQTTObserverConnectionPolicy, RenewsBeforeReconnectAsWellAsWhileConnected) EXPECT_TRUE(MQTTObserverConnectionPolicy::jwtNeedsRenewal(2000, 1300)); } +TEST(MQTTObserverConnectionPolicy, RequiresInternalHeapHeadroomToConnect) { + using namespace MQTTObserverConnectionPolicy; + // Exactly at both secure thresholds is allowed. + EXPECT_TRUE(hasConnectHeadroom(true, kSecureFreeInternalBytes, kSecureLargestInternalBytes)); + // One byte short of either secure threshold defers the connect. + EXPECT_FALSE(hasConnectHeadroom(true, kSecureFreeInternalBytes - 1, kSecureLargestInternalBytes)); + EXPECT_FALSE(hasConnectHeadroom(true, kSecureFreeInternalBytes, kSecureLargestInternalBytes - 1)); + // Plaintext brokers need less: the secure floor clears the plain thresholds. + EXPECT_TRUE(hasConnectHeadroom(false, kSecureFreeInternalBytes, kSecureLargestInternalBytes)); + EXPECT_TRUE(hasConnectHeadroom(false, kPlainFreeInternalBytes, kPlainLargestInternalBytes)); + EXPECT_FALSE(hasConnectHeadroom(false, kPlainFreeInternalBytes - 1, kPlainLargestInternalBytes)); + EXPECT_FALSE(hasConnectHeadroom(false, kPlainFreeInternalBytes, kPlainLargestInternalBytes - 1)); + // An empty heap never admits a client. + EXPECT_FALSE(hasConnectHeadroom(true, 0, 0)); + EXPECT_FALSE(hasConnectHeadroom(false, 0, 0)); +} + TEST(MQTTObserverQueuePolicy, RestartsStaleWindowAfterFlushAndHandlesWrap) { uint32_t since = 0; EXPECT_FALSE(MQTTObserverQueuePolicy::trackDisconnected(100, false, since));