Skip to content

Serialize outbound JSON straight into the Noise send buffer - #222

Merged
kahrendt merged 5 commits into
mainfrom
serialize-into-send-buffer
Nov 2, 2026
Merged

kahrendt merged 5 commits into
mainfrom
serialize-into-send-buffer

Conversation

@kahrendt

@kahrendt kahrendt commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #220. Every outbound JSON message was serialized into a std::string that grew a byte at a time. On ESPHome operator new only uses internal RAM and aborts under -fno-exceptions, so a reconnect right after the internal heap ran out crashed in format_client_hello_message(). Outbound JSON now goes straight into the transport's existing send buffer (PSRAM-preferring, kept across messages), with no heap string on the way.

Changes

  • format_*_message() -> build_*_message(), filling a caller-owned JsonDocument made from the JSON arena (the output-parameter shape the process_*() parsers use; returning documents by value trips clang-analyzer's StackAddressEscape on ArduinoJson's self-referencing pool list).
  • SendspinConnection::send_json(doc) is the one send path: it serializes the document, sized by measureJson(), into the send buffer (NoiseTransport::stage_json()), then encrypts it in place (send_staged_json()) or, before the handshake, sends it from there as a cleartext text frame. client/time formats into the same buffer; the re-handshake msg2 is staged there before send_msg2_and_swap(). client/init still goes out from the text the handshake keeps for its prologue.
  • A document that overflowed its allocator (the arena's heap fallback failed) or one longer than one frame is refused with NO_MEM, instead of sent truncated or fragmented; the hello path already drops the connection on any error.
  • A refused or failed send wipes the staged text; a successful one encrypts over it. This replaces the caller-side wipe of the pair-finalize string.
  • Outbound fragmentation is removed. With JSON and lent binary both refused above one frame, NoiseTransport::send_binary() had no production caller, so it and fragment_and_send(), the only allocation of a ~64 KB frame buffer, are gone. Inbound reassembly stays, since servers still fragment large messages.
  • send_text_message() takes (const char*, size_t) on every transport. build_client_hello() returns the hello fields, so client.h needs no ArduinoJson.

Testing

  • New table rows: an oversized and an overflowed document are refused before the encrypt; refusals and a failed encrypt wipe the staged text. Mutants removing the wipe, the overflow check or the one-frame check, or wiping only without a session, each fail a test.
  • tools/stack_usage: edges.json re-keyed from the removed send_app_json to send_json(), whose stale entry had dropped the cleartext send edges. Re-measured: the protocol task's bound is 6,560 / 6,624 B (-Os / -Og, was 6,560 / 6,832) and its reachable chain 5,936 / 6,368 B (was 6,352 / 6,576), so the 7,168 default stays; README updated.
  • ESPHome build against this tree: playback works.

Not covered: the reporter's reproduction under heap exhaustion; a failed msg2 staging during a re-handshake. The hello struct's own strings and the handshake's base64 strings still allocate internally.

Every outbound JSON message was serialized into a std::string that grew
a byte at a time. On ESPHome, operator new only uses internal RAM and
aborts under -fno-exceptions when an allocation fails, which crashed a
reconnect after the internal heap ran out (#220).

The format_*_message() builders now return a JsonDocument from the
JSON arena, and SendspinConnection::send_json() serializes it, sized by
measureJson(), into the transport's reused send buffer
(NoiseTransport::stage_json()). From there it is encrypted in place
(send_staged_json()) or, before the handshake, sent as a cleartext text
frame. client/time is formatted into the same buffer, and the
re-handshake msg2 is staged there before send_msg2_and_swap().
client/init still goes out from the text the handshake keeps for its
prologue.

A document that overflowed its allocator, or one longer than one frame,
is refused with NO_MEM instead of sent truncated or fragmented; outbound
JSON no longer fragments. A refused or failed send wipes the staged
text, replacing the caller-side wipe of the pair-finalize string.
send_text_message() takes (const char*, size_t), and
build_client_hello() returns the hello fields so the public header needs
no ArduinoJson.
clang-tidy's clang-analyzer-core.StackAddressEscape flagged every
function returning a JsonDocument by value: ArduinoJson's pool list
points into its own inline storage, which the analyzer reads as a stack
address escaping, though the move constructor re-points it.

The build_*_message() builders now fill a document the caller makes
with make_json_document(), the output-parameter shape the process_*()
parsers already use, and a re-handshake result carries msg2's Noise
bytes for the connection to wrap (build_noise_handshake_message()).
@kahrendt
kahrendt marked this pull request as ready for review November 2, 2026 15:56
@kahrendt
kahrendt requested a balanced review from Copilot November 2, 2026 15:56

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The pairing failure path exceeds the JSON arena and forces an unnecessary heap allocation, while later-fragment failure coverage is missing and stack-analysis mappings remain stale.

3 open issues
What changed in this PR

This PR addresses #220 by serializing outbound JSON directly into the reusable Noise send buffer, avoiding temporary heap strings that could abort ESP32 reconnects under memory pressure.

Changes:

  • Converts message formatters into builders that fill caller-owned JSON documents.
  • Centralizes JSON staging and sending, rejects overflowed or oversized documents, and wipes staged plaintext on encrypted-send failures.
  • Updates transport interfaces, tests, and documentation for the new send path.
File Description
tests/​test_util.h Adds helpers for testing document builders.
tests/​test_protocol.cpp Migrates message-format tests to builders.
tests/​test_player_role.cpp Updates the fake text-send signature.
tests/​test_pairing_state_machine.cpp Adapts pairing fixtures and hello inspection.
tests/​test_noise_transport.cpp Tests staged sends, rejection, and plaintext wiping.
tests/​test_noise_rehandshake.cpp Consumes raw msg2 bytes in handshake tests.
tests/​test_message_trace.cpp Uses builders for secret-redaction fixtures.
tests/​test_json_arena.cpp Adapts arena-lifetime tests to caller-owned documents.
tests/​test_encrypted_lifecycle.cpp Updates send fakes and arena tests.
tests/​test_dynamic_pairing_code.cpp Migrates pairing-message tests to builders.
tests/​test_client_lifecycle.cpp Updates lifecycle send fakes.
tests/​test_artwork_role.cpp Builds the hello document for assertions.
tests/​loopback_connection.h Adapts shared transport and handshake helpers.
tests/​lifecycle_test_fixtures.h Updates a send-path comment.
tests/​CMakeLists.txt Documents private access used by wipe tests.
src/​source_role.cpp Sends stream lifecycle messages through documents.
src/​protocol.cpp Replaces string formatters with document builders.
src/​protocol_messages.h Declares builders and their ownership contract.
src/​pairing_offers.h Updates the hello-builder reference in comments.
src/​noise_transport.h Declares JSON staging and staged-send interfaces.
src/​noise_transport.cpp Stages and encrypts JSON in the reusable buffer.
src/​noise_handshake.h Updates handshake callbacks and result types.
src/​noise_handshake.cpp Builds msg2 documents and reuses retained init text.
src/​host/​server_connection.h Declares pointer-and-length text sends.
src/​host/​server_connection.cpp Implements pointer-and-length text sends.
src/​host/​client_connection.h Declares pointer-and-length text sends.
src/​host/​client_connection.cpp Implements pointer-and-length text sends.
src/​esp/​server_connection.h Updates the asynchronous text-send declaration.
src/​esp/​server_connection.cpp Queues text from pointer-and-length inputs.
src/​esp/​client_connection.h Updates the synchronous text-send declaration.
src/​esp/​client_connection.cpp Passes text buffers directly to WebSocket sends.
src/​connection.h Defines the document-send and staging contracts.
src/​connection.cpp Routes JSON, time messages, and msg2 through staging.
src/​connection_manager.cpp Uses document builders for management messages.
src/​connection_manager_pairing.cpp Migrates pairing sends to caller-owned documents.
src/​client.cpp Returns hello fields and builds state documents.
src/​client_dispatch.cpp Builds command documents and clarifies arena lifetime.
include/​sendspin/​config.h Documents outbound send-buffer placement.
include/​sendspin/​client.h Updates the private hello-builder declaration.
docs/​playback-sync.md Documents the staged time-message write hook.
docs/​internals.md Describes direct serialization and JSON size limits.
docs/​integration-guide.md Clarifies send-buffer memory placement.

Review effort: Balanced

Comment thread src/connection_manager_pairing.cpp Resolved
Comment thread tests/test_noise_transport.cpp Resolved
Comment thread src/connection.cpp Resolved
The static-code client/pair-init document stayed alive through
start_pake_round(), whose CPace failure path builds a pair/abort, so
two documents shared the arena. It is now released before CPace
starts, as in the Pairing-PSK flow.

edges.json still keyed the connection's virtual sends on the removed
send_app_json(const char*), and sent the handshake callback straight to
the text transports. send_json() now carries those edges, including the
cleartext send_text_message() targets, and the handshake callback
reaches its std::function invoker. Re-measured at -Os and -Og: the
protocol task's reachable chain is 5,936 / 6,368 bytes, so the default
stays 7,168.
Every message the client sends now fits one Noise frame: JSON through
stage_json(), and binary through send_binary_lent(), both refusing
anything longer. That left NoiseTransport::send_binary() with no
production caller and fragment_and_send(), its only user and the one
allocation of a ~64 KB frame buffer, unreachable. Both are gone, with
the tests that drove only them; inbound reassembly stays, since servers
still fragment large messages. Docs, the noise_buffer_location comments
and the stack-analysis edges no longer mention the fragmentation buffer.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Target-device validation is needed because the ESP32 heap-exhaustion reconnect and allocation failure while staging re-handshake msg2 remain untested, leaving low-memory recoverability unverified.

No open issues 🎉

3 resolved since last review

Review effort: Balanced

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

2 participants