Skip to content

Count the library's allocations from accept to admission - #225

Merged
kahrendt merged 2 commits into
mainfrom
alloc-1-counter
Nov 3, 2026
Merged

kahrendt merged 2 commits into
mainfrom
alloc-1-counter

Conversation

@kahrendt

@kahrendt kahrendt commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Layer 1 of 7 (base: main).

Summary

On ESPHome operator new uses internal RAM only and aborts under -fno-exceptions, so every heap allocation a connection makes on its way to admission is a crash risk during a reconnect (the class of bug in #220). This layer measures them; the six above it remove most.

Changes

  • New test binary sendspin_alloc_tests replaces the global operator new and records the size and stack of every allocation inside a window. It is separate so sendspin_tests keeps the sanitizers' own allocator; building sendspin_tests builds it too.
  • One loopback connection is measured over three windows: from the fake server's connect through the Noise handshake, hello, server/activate and the first client/state; one client/state publish; and one time burst.
  • Each allocation is attributed to the library, the host transport or the test by its stack. The library's count is asserted exactly per standard library, and no allocation may go unattributed. Accept to admission: 57 under libc++, 63 under libstdc++, whose 15-character inline strings match ESP-IDF's. One client/state publish: 3. One time burst: 0. SENDSPIN_ALLOC_REPORT=1 prints the allocations grouped by call site.
  • Only operator new is counted. platform_malloc buffers return null instead of aborting, so they are not.

Testing

  • The libstdc++ figures were measured with Homebrew GCC on macOS. CI's three Linux GCC jobs (unit tests, no-Opus, TSan) are their first runs on Linux, and no local build measured the no-Opus configuration.

Every layer above lowers the asserted counts in the commit that removes the allocations.

A new test binary, sendspin_alloc_tests, replaces the global operator new
and records the size and stack of every allocation inside a window. One
loopback connection is measured from the fake server's connect through the
Noise handshake, hello, server/activate and the first client/state, then
over one client/state publish and one time burst. Stacks attribute each
allocation to the library, the host transport or the test; the library's
count is asserted exactly (57 under libc++, 63 under libstdc++, whose
15-character inline strings match ESP-IDF's) and SENDSPIN_ALLOC_REPORT=1
prints it grouped by call site.

The binary is separate so sendspin_tests keeps the sanitizers' own
operator new; building sendspin_tests builds it too.
@kahrendt
kahrendt added this pull request to stack #232 November 3, 2026 14:10
@kahrendt
kahrendt marked this pull request as ready for review November 3, 2026 14:15
@kahrendt
kahrendt requested a balanced review from Copilot November 3, 2026 14:15

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 allocation test target can fail to link on Linux without ${CMAKE_DL_LIBS}, and its measurement window is not synchronized to completed protocol bursts.

2 open issues
What changed in this PR

Adds a host-side allocation baseline for the reconnect crash risks described in #220. This first layer measures allocations; later layers will reduce them.

Changes:

  • Adds a separate allocation-counting executable covering admission, state publishing, and time bursts.
  • Classifies allocations by owner, asserts library counts, and provides optional call-site reports.
  • Integrates the executable into the existing test build and CTest workflow.
File Description
tests/​test_allocations.cpp Adds allocation hooks, stack attribution, reports, and measurement windows.
tests/​README.md Documents the allocation test and report option.
tests/​lifecycle_test_fixtures.h Adds a received time-message counter for measurement boundaries.
tests/​CMakeLists.txt Builds and registers the separate allocation test executable.

Review effort: Balanced

Comment thread tests/CMakeLists.txt Resolved
Comment thread tests/test_allocations.cpp Resolved
The burst window opened and closed on the fake server's count of
client/time messages, which it bumps before replying. The client's
handling of the burst's last reply and the burst's completion then fell
outside the window, or inside it, depending on timing. It now opens and
closes on on_time_sync_updated(), which the main loop delivers only
after both, so the window holds one whole burst. The fixture's
client/time counter had no other user and goes.

sendspin_alloc_tests calls dladdr(), which lives in libdl before glibc
2.34, so it links CMAKE_DL_LIBS.
@kahrendt
kahrendt merged commit 04fb6de into main Nov 3, 2026
16 checks passed
@kahrendt
kahrendt deleted the alloc-1-counter branch November 3, 2026 16:01
kahrendt added a commit that referenced this pull request Nov 3, 2026
## Summary

A coherence review of the allocation series (#225-#234) found the
migrated pieces consistent with each other, plus a set of small
inconsistencies at their edges. This PR fixes those. No behavior change.

## Change

- **Caps:** `MAX_SERVER_INIT_BYTES` moves from `noise_handshake.h` to
`crypto/constants.h`, beside `MAX_HANDSHAKE_MESSAGE_BYTES`; each comment
names the other.
- **Inline text:**
- `InlineText::assign()` is `[[nodiscard]]`; each caller checks it, or
casts to `(void)` with the reason its text fits (or, for the last-played
id, that clearing is the documented behavior).
- `set_noise_handshake_result()` and `run_rehandshake_msg1()` take
`const IdText&` instead of re-assigning views. `last_played_server_id()`
returns `const IdText&`, like `get_server_id()`.
- `ResolvedPsk::counterparty_id` is a plain `IdText`, empty for a PSK
bound to no server, instead of `std::optional<IdText>`.
- `SENTINEL_PSK_ID` is a `constexpr std::string_view` literal instead of
a global `std::string` built during static initialization.
- The connection's id and name members sit in its "String fields" group.
- **`ParsedJsonMessage::extract()`** static_asserts that an extractor
does not return a pointer, a `std::string_view`, or a
`JsonVariant`/`JsonObject`/`JsonArray`/`JsonString` (alone or in
`std::optional`), since the document is released before the caller reads
it.
- **Comments:** the stale "hub" comments name the real callers (protocol
task, `ConnectionManager`, transport threads); the ESP `start()` comment
describes when the connection is delivered.
- **Naming:** the activation check left over from `ConnectionTrust` is
"the admissibility check" in src, docs and tests, matching
`admissible()` and `inadmissible_reject_reason()`.

## Tests

- Tests build ids through a new `id_text()` helper in
`tests/record_test_helpers.h`, which fails a test whose id would not
fit.
- `CryptoConstants.SentinelPskIdMatchesSpecConstant` now checks that
`psk_id_for(SENTINEL_PSK)` derives the literal, so it fails if either
drifts.
- The `extract()` guard was checked with a probe: an extractor returning
a `std::string_view` fails to compile with the new message, one
returning an `int` compiles.
kahrendt added a commit that referenced this pull request Nov 4, 2026
## Summary

The allocation series (#225-#236) enforced a rule that was written down
only in `tests/test_allocations.cpp`'s header and in PR bodies.
ESPHome's `operator new` draws only on internal RAM and aborts on
failure, so after `start()` connection setup and message handling
allocate through the fallible `platform_malloc` family, and bounded
values are held inline. This PR states that rule and records where the
code still allocates with `operator new`. Docs only.

## Change

- **`docs/conventions.md`:** "Embedded resource discipline" gains the
rule: `operator new` at construction, `add_*()` and `start()` only;
afterwards `platform_malloc`, whose failure refuses or closes the
connection or drops the message; bounded values inline (`InlineText`,
`InlineVector`, `EnumSet`, `std::array`); peer text bounded where it is
parsed; public `std::string`/`std::vector` types built on the thread
that hands them to the consumer. The Documentation bullet lists the
allocation model among `internals.md`'s contents.
- **`docs/internals.md`:** a new "Memory" section: the three allocators
(`operator new`, `platform_malloc`, noise-c's `calloc`) and how each
fails, what is held inline, a table of the `operator new` allocations
that remain after `start()` with when and on which thread each runs, and
the one-pointer capture the `std::function`s built after `start()` rely
on.
- **`CLAUDE.md`:** the Memory convention names the inline types and
points at the new section; the test build note says what
`sendspin_alloc_tests` counts; both descriptions of `internals.md`
mention memory.
- **`.claude/skills/embedded-review/SKILL.md`:** a new `operator new`
after `start()` is listed in "Memory" or reported as a finding.

## Tests

Docs only. Each claim in the Memory section was checked against the
code; the table is the checklist the remaining allocation groups
(tracked in Sendspin/backlog#92) remove rows from.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants