Skip to content

format_*_message serializes into std::string on the internal heap: a failed allocation aborts under -fno-exceptions (decoded backtrace) #220

Closed

Description

@scurran75

Summary

format_*_message() serializes into a std::string, so the serialized output always
lands on the internal heap via operator new — even though the library already
places the JsonDocument in a PSRAM-preferring arena. Under -fno-exceptions (ESP-IDF's
default, and what ESPHome ships) a failed allocation there is an unrecoverable
abort()
, not an error the caller can handle.

We have this happening in the field on ESP32-S3 + W5500 Ethernet. Below is a decoded
backtrace from a real abort.

Decoded backtrace (ESP32-S3, IDF v5.5.5, sendspin-cpp 0.7.0)

abort                              panic.c:477
__wrap___cxa_allocate_exception    cxx_exception_stubs.cpp:184
operator new(unsigned int)         new_op.cc:54
std::string::_M_mutate             basic_string.tcc:332
std::string::push_back             basic_string.h:1576
  (inlined) ArduinoJson Writer<std::string>::write(unsigned char)
  (inlined) ArduinoJson serializeJson
sendspin::format_client_hello_message      src/protocol.cpp:901
sendspin::SendspinClient::build_hello_message       src/client.cpp:659
sendspin::ConnectionManager::send_hello_message     src/connection_manager.cpp:632

The code:

// src/protocol.cpp:900-902
std::string output;
serializeJson(doc, output);
return output;

Two properties that make this worse than a single failed allocation

1. It grows one character at a time. ArduinoJson's Writer<std::string> calls
push_back per byte, so a few-hundred-byte hello reallocates ~10 times, and each
reallocation needs a new contiguous block while the old one is still held — peak
demand of roughly 1.5× the final size, spread over ten separate chances to fail.

2. The failure is unconditionally fatal. operator new throws, exceptions are
stubbed, __cxa_allocate_exception aborts. The caller cannot see it, cannot close the
connection, cannot retry.

Why it bites exactly at reconnect

Our ESP32-S3 boards run Ethernet (W5500). Under load the driver intermittently fails to
allocate a receive buffer:

E w5500.mac: no mem for receive buffer      (×3, within ~3 s)
E sendspin.server_connection: httpd_ws_recv_frame failed with -1
I sendspin.conn_mgr: Current connection lost
D sendspin.ws_server: New client connection on socket 55
abort() was called at PC 0x420a53ca on core 1

So the internal heap is briefly exhausted → the websocket read fails → the connection
drops → the reconnect immediately serializes a hello into that same exhausted heap
and aborts. The transient is short: we instrumented the allocator and measured the
failing requests as size=1490, caps=MALLOC_CAP_DEFAULT|MALLOC_CAP_INTERNAL, in bursts
of a few seconds with minutes of quiet between.

⭐ It is probabilistic, which shows the fix is worthwhile. Four minutes before the
abort above, the identical sequence occurred on the same board and it survived —
reconnected and resumed playing. Across our logs, roughly 6 % of post-burst reconnects
abort
; the rest get through. Fewer and smaller allocations on this path should convert
most of the remainder into a recoverable failed reconnect.

Suggested fix

The library already has both the mechanism and the policy — they just are not applied to
the serialized output:

  • src/platform/json_arena.h — "Bounded internal-RAM bump-arena ArduinoJson allocator
    with PSRAM fallback"
    , already used for the JsonDocument (src/client.cpp:680).
  • src/platform/memory.h:150 — PlatformBuffer::allocate(size, MemoryLocation location = MemoryLocation::PREFER_EXTERNAL), i.e. SPIRAM-first by default, and it
    returns bool rather than throwing.
  • src/platform/types.h:34 — SsErr::NO_MEM = 0x101 already exists.

So:

  1. Size the output with measureJson(doc) and allocate once into a PlatformBuffer
    (or a std::basic_string with a PSRAM-preferring allocator) instead of growing a
    std::string byte by byte.
  2. Return SsErr::NO_MEM on failure and let the caller close the connection.

That removes ~10 internal-heap allocations per reconnect, takes a ~1 KB hello off
internal RAM entirely, and makes exhaustion survivable rather than fatal.

📌 The same std::string output; serializeJson(doc, output); pattern appears 5 times
in src/protocol.cpp, so this is a shape rather than one call site.

Notes

  • Not proposing CONFIG_COMPILER_CXX_EXCEPTIONS — it turns abort() into an uncaught
    std::bad_alloc → std::terminate, which is also an abort, and costs flash and IRAM.
  • We are separately capping our lwIP receive window to reduce the pressure, but that
    lowers the probability rather than removing the failure mode.

Environment: ESP32-S3 (chip rev v0.2), ESP-IDF v5.5.5, ESPHome 2026.7.4,
sendspin-cpp 0.7.0 (254603c283bc137aa2f748ff5b2c99a39c56faf2),
ArduinoJson V743HB22, W5500 Ethernet, FLAC 48 kHz/16-bit stereo.

Happy to test a patch — we have boards reproducing this within hours under load, with
the allocator instrumented.

Activity

  1. kahrendt commented on Nov 2, 2026

    @kahrendt
    Contributor

    There are still heap allocations happening at runtime, but #222 should fix the one you ran into. I am working to eliminate any internal heap allocations during connection/pairing/re-connecting. Hopefully by the end of the refactor, only the heap allocations needed for the public API; e.g., things like the std::string metadata values remain.

  2. scurran75 commented on Nov 3, 2026

    @scurran75
    Author

    5. There are still heap allocations happening at runtime, but #222 should fix the one you ran into. I am working to eliminate any internal heap allocations during connection/pairing/re-connecting. Hopefully by the end of the refactor, only the heap allocations needed for the public API; e.g., things like the std::string metadata values remain.

    thanks, appreciate speedy the follow up on this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions