Skip to content

fix(socket, rtps): no heap allocation per received datagram or event; RTPS_RECEIVE_BUFFER_SIZE (#969) - #970

Merged
finger563 merged 10 commits into
mainfrom
fix/udp-receive-buffer
Dec 3, 2026
Merged

finger563 merged 10 commits into
mainfrom
fix/udp-receive-buffer

Conversation

@finger563

@finger563 finger563 commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #969.

Problem

Each received UDP datagram allocated and zero-filled a fresh max-size buffer (8 KB in the RTPS transport), then copied the data into a second vector. On an ESP32-S3 with a fragmented internal heap, that allocation failed during RTPS participant rebuilds. With C++ exceptions off, a failed new aborts, which took down both boards in the report.

Measuring the whole receive path turned up more allocations than the buffer alone:

Path Allocations per datagram / event (before) After
UdpSocket::receive into a reused vector 1 0
SocketReactor UDP receiver (reactor loop + pool dispatch + receive) 5 0
SocketReactor TCP stream 5 0
UdpSocket::start_receiving task 3 0
any espp::Task loop iteration (callback larger than std::function's small buffer) 1 0

Changes

Socket and reactor (fix(socket))

  • Receive functions: UdpSocket::receive and TcpSocket::receive(vector) receive straight into the caller's vector and shrink it to what arrived. There's no separate buffer and no copy, and a reused vector keeps its capacity. The per-call "Receiving up to" logs are now debug, and the error string is only built when it would be printed.
  • Reactor receive buffers: SocketReactor's UDP and TCP handlers read into receive buffers the reactor pools. A buffer is checked out for one handler run and returned afterwards, so the pool holds about one per pool worker, and capacity only grows. The buffers are sized at registration, not in a worker in the middle of traffic. Memory is therefore workers × buffer_size, the same as the old peak, rather than one buffer per registration (RTPS opens up to 10 sockets on ESP).
  • Reactor dispatch and loop:
    • dispatch() shares the handler through a shared_ptr instead of copying the std::function.
    • The loop reuses its ready list and sorts it with std::sort. Entries are ordered by id, so (band, id) is exactly the order the old stable_sort produced.
  • UdpSocket receive task: reuses member buffers.
  • espp::Task: calls its callback by reference. It copied the std::function on every loop iteration, which allocated in every Task and Timer loop whose captures outgrow the small buffer.
  • ThreadPool: each band's FIFO is now a ring buffer that grows and never shrinks. std::deque frees and re-allocates its blocks as jobs pass through; on MSVC that happens on every push.
  • Socket::socket_ is atomic, and cleanup() claims the descriptor with exchange().
    • stop_receiving() closes the socket from another thread to unblock receive(). The new test made TSan report that as a data race.
    • Two concurrent cleanup()s can no longer close the same descriptor twice.
  • stop_receiving() order: it now stops the receive task before closing the socket. Linux CI's TSan also flags closing a descriptor that another thread is blocked on, since the number can be handed to the next socket opened.
    • The task now waits for data in 100 ms select() slices, and start_receiving() bounds the receive itself to 1 s, so stop_receiving() returns within about 100 ms instead of instantly.

RTPS (feat(rtps))

  • RTPS_RECEIVE_BUFFER_SIZE (Kconfig, 0 = automatic):

    • 64 KB with fragmentation;
    • 1472 when lwIP IPv4 reassembly is off (the largest datagram an MTU-1500 link delivers unfragmented);
    • 8 KB otherwise, as before.

    It reaches the transport as rtps::Config::RECEIVE_BUFFER_SIZE, and the host profiles are unchanged. A build of the RTPS example with LWIP_IP4_REASSEMBLY=n gets RTPS_CFG_RECEIVE_BUFFER_SIZE=1472 in every RTPS compile unit.

  • Truncation is detected: the transport reads one spare byte. A datagram longer than the buffer is dropped with a warning that names the option, on the first and every 100th, instead of being parsed cut off. This can happen with another participant on the same chip, because lwIP loops those datagrams back before fragmenting them.

  • Memory on ESP: with the defaults (fragmentation off, no IPv4 reassembly), RTPS receive now holds one 1473-byte buffer per receive worker, about 3 KB for two workers. Before, each in-flight datagram took a transient 8 KB allocation plus its copy, about 16 KB at peak across two workers.

Tests and CI (test(socket))

  • New pc/tests/socket_receive.cpp: it counts every operator new, with the traffic-generating threads exempt, and requires zero allocations over 100 datagrams or events on each path in the table. Payloads are checked in place. On main it fails with the counts in the table.
  • pc/tests/thread_pool.cpp: the ring keeps FIFO order across wrap-around and growth, releases a finished job's captures, and drops and counts jobs still queued at stop().
  • More CI coverage:
    • socket_reactor and socket_receive use unicast loopback only, so they're now plain unit tests. They run in the Linux, macOS and Windows library jobs, which exclude network; on main, socket_reactor only ran in the Linux sanitizer job.
    • socket_receive is added to the sanitizer job's triggers.

Local results (macOS):

  • All 67 pc unit tests pass, plain, under TSan, and under ASan + UBSan.
  • socket_receive passed 5 extra TSan runs with no races.
  • The ESP-IDF RTPS example builds with both lwIP settings.

Behavior notes

  • A reactor UDP or TCP callback now gets the pooled buffer. Copy what must outlive the callback; moving out of it still works, but the buffer then has to grow again. RTPS processes each datagram synchronously and never keeps it.
  • UdpSocket::receive and TcpSocket::receive(vector) leave the vector's capacity at max_num_bytes, and clear it on failure.
  • UdpSocket::start_receiving() sets a 1 s receive timeout on the socket.
  • Builds with fragmentation enabled now hold one 64 KB buffer per receive worker instead of allocating it per datagram. The QEMU memory report will show this for the interop app, which enables fragmentation.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU

finger563 and others added 3 commits December 2, 2026 19:08
#969)

Every received datagram allocated (and zero-filled) a max-size buffer, then
copied into a second vector; on a fragmented ESP32 heap that allocation
failed during RTPS participant rebuilds and, with exceptions off, aborted.
Steady-state receive now allocates nothing at all:

- UdpSocket::receive / TcpSocket::receive(vector) receive straight into
  the caller's vector and shrink it to what arrived: no separate buffer, no
  copy, and a reused vector keeps its capacity. The per-call "Receiving up
  to" logs are debug, and the error string is only built when printed.
- SocketReactor: UDP / TCP handlers read into receive buffers the reactor
  pools (one checked out per running handler, about one per pool worker,
  capacity only grows; sized at registration, not in a worker mid-traffic),
  so memory is workers x buffer_size, not registrations x buffer_size.
  dispatch() shares the handler through a shared_ptr instead of copying the
  std::function, and the loop reuses its ready list and sorts it with
  std::sort (same band / id order as the stable_sort it replaces).
- UdpSocket's receive task reuses member buffers for every datagram.
- Task calls its callback by reference: copying the std::function every
  loop iteration allocated whenever the captures outgrew its small buffer,
  in every Task / Timer loop.
- ThreadPool: each band's FIFO is a ring buffer that grows and never
  shrinks (std::deque frees and re-allocates blocks as jobs pass through,
  on MSVC every push).
- Socket::socket_ is atomic, and cleanup() claims the descriptor with
  exchange(): stop_receiving() closes the socket from another thread to
  unblock receive() (a data race TSan reports), and two concurrent
  cleanup()s no longer close the same descriptor twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
…v4 reassembly (#969)

The transport read every datagram into an 8 KB buffer (64 KB with
fragmentation) with no option to change it. Without lwIP IPv4 reassembly no
datagram longer than one MTU-1500 frame (1472 bytes of UDP payload) can
arrive from the network, so most of that buffer could never be used, and the
socket reactor now keeps one such buffer per receive worker.

- Kconfig RTPS_RECEIVE_BUFFER_SIZE (0 = automatic): 64 KB with
  fragmentation, 1472 when LWIP_IP4_REASSEMBLY is off, 8 KB otherwise;
  rtps::Config::RECEIVE_BUFFER_SIZE (RTPS_CFG_RECEIVE_BUFFER_SIZE) carries
  it to the transport, the profile defaults are unchanged on the host.
- The transport reads one spare byte, so a datagram longer than the buffer
  (truncated) is detected and dropped, with a warning naming the option on
  the first and every 100th, instead of being parsed cut off. (Another
  participant on the same chip can deliver one: lwIP loops those back
  without fragmenting.)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
…y OS and under the sanitizers (#969)

- pc/tests/socket_receive.cpp counts every operator new (traffic-generating
  threads exempt) and requires zero allocations over 100 datagrams / events
  for UdpSocket::receive, the SocketReactor UDP and TCP paths, UdpSocket's
  receive task and an espp::Task loop, with payloads checked in place.
  Before the fix: 1, 5, 5, 3 and 1 allocation(s) per datagram / iteration.
- pc/tests/thread_pool.cpp: the band queue ring keeps FIFO order across
  wrap-around and growth, releases a finished job's captures, and drops
  (and counts) jobs still queued at stop().
- socket_reactor and socket_receive use unicast loopback only, so they are
  plain `unit` tests: they now also run in the Linux / macOS / Windows
  library jobs (which exclude `network`), not only in the Linux sanitizer
  job; socket_receive is added to that job's triggers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
Copilot AI balanced review requested due to automatic review settings December 3, 2026 01:10
finger563 and others added 2 commits December 2, 2026 19:26
… race)

stop_receiving() closed the socket to wake the task out of a blocking
recvfrom, which Linux ThreadSanitizer reports as a race on the descriptor:
closing a descriptor another thread is blocked on can hand its number to the
next socket opened. The task now waits for data in bounded select() slices
(100 ms) before receiving, and start_receiving() bounds the receive itself
(1 s) for a spurious readiness, so stop_receiving() stops the task first and
only then closes the socket. Steady-state receive still allocates nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
…gs and stubs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU

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.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Copilot review overview

5 open issues
What changed in this PR

This PR removes steady-state heap allocations from the socket receive path (UDP/TCP, reactor dispatch, Task loop, and ThreadPool queues) and adds tests to enforce “0 allocations per datagram/event”, plus introduces an RTPS receive-buffer-size configuration to avoid truncation and heap fragmentation failures (#969).

Changes:

  • Refactors UDP/TCP receive and SocketReactor dispatch to reuse caller/pool buffers and avoid per-event allocations.
  • Reworks ThreadPool per-band FIFO into a grow-only ring buffer and avoids std::function copies in Task.
  • Adds allocation-counting host tests and updates CI/test labeling; adds configurable RTPS receive buffer size + truncation detection.
File Description
pc/​tests/​thread_pool.cpp Adds tests validating the new ThreadPool ring-buffer behavior (FIFO, growth, capture release, drop-on-stop).
pc/​tests/​socket_receive.cpp New allocation-counting test covering UDP/TCP receive paths, reactor dispatch, and Task loop.
pc/​CMakeLists.txt Updates test labeling so socket tests run as unit everywhere (unicast loopback only).
components/​thread_pool/​include/​thread_pool.hpp Replaces per-band std::deque with a grow-only ring buffer to avoid steady-state allocations.
components/​task/​src/​task.cpp Avoids copying std::function every loop iteration by calling callbacks by reference.
components/​socket/​src/​udp_socket.cpp Receives directly into caller-provided vector; reuses member buffers for receive task.
components/​socket/​src/​tcp_socket.cpp Receives directly into caller-provided vector; reduces logging/allocation on error.
components/​socket/​src/​socket_reactor.cpp Pools receive buffers, shares handlers via shared_ptr, reuses ready list, switches to std::sort.
components/​socket/​src/​socket.cpp Makes socket descriptor atomic and uses exchange() to prevent double-close/data races.
components/​socket/​include/​udp_socket.hpp Documents new “receive into caller vector” semantics; adds reused task buffers.
components/​socket/​include/​tcp_socket.hpp Documents new “receive into caller vector” semantics.
components/​socket/​include/​socket_reactor.hpp Documents pooled-buffer semantics; stores handler as shared_ptr; adds buffer pool members.
components/​socket/​include/​socket.hpp Changes socket descriptor to std::atomic<sock_type_t> and documents cross-thread close rationale.
components/​rtps/​src/​communication/​EsppTransport.cpp Uses configurable receive buffer (+1 spare byte) and drops oversized datagrams with warning.
components/​rtps/​include/​rtps/​config.hpp Introduces RTPS_CFG_RECEIVE_BUFFER_SIZE / Config::RECEIVE_BUFFER_SIZE with bounds check.
components/​rtps/​include/​rtps/​communication/​EsppTransport.hpp Adds counter for dropped/truncated datagrams.
components/​rtps/​README.md Documents RTPS_RECEIVE_BUFFER_SIZE behavior and memory implications.
components/​rtps/​Kconfig Adds RTPS_RECEIVE_BUFFER_SIZE knob with “0 = automatic” behavior description.
components/​rtps/​CMakeLists.txt Propagates Kconfig receive buffer size and sets automatic 1472 when IPv4 reassembly is off.
.github/​workflows/​host_sanitizers.yml Runs the new socket_receive unit test under sanitizers.

Review effort: Lite

Comment thread components/rtps/CMakeLists.txt Resolved
Comment thread components/rtps/include/rtps/config.hpp Resolved
Comment thread components/socket/src/udp_socket.cpp Resolved
Comment thread pc/tests/socket_receive.cpp Resolved
…icit ring mask, aligned new counted

- RTPS_RECEIVE_BUFFER_SIZE tops out at 65507 (the largest IPv4 UDP payload),
  which is also the automatic size with fragmentation (was 64 KiB).
- UdpSocket::receive / TcpSocket::receive load the atomic descriptor once
  (relaxed) for the syscall.
- ThreadPool ring: the power-of-two invariant is explicit (mask_ set only
  when the ring grows, asserted).
- socket_receive also counts the aligned operator new / delete forms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
@github-actions

github-actions Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

rtps memory footprint (QEMU, esp32)

Deltas in parentheses are against main @ 06c36f5 (run 46763658514): a bigger size or a smaller free heap than the baseline's is a cost of this change.

librtps.a in the image (bytes, idf.py size-components)

embedded host host_large
flash code 161,898 (-229) 163,244 (-241) 163,677 (-220)
flash data 1,272 (+0) 1,272 (+0) 1,272 (+0)
DRAM (.data + .bss) 126 (+0) 126 (+0) 126 (+0)
IRAM 0 (+0) 0 (+0) 0 (+0)

engine objects, sizeof (bytes; the Domain is allocated from the heap at start())

object embedded host host_large
rtps::Domain (holds every pool below) 99,208 (+0) 569,968 (+0) 3,156,208 (+0)
rtps::Participant 34,304 (+0) 42,736 (+0) 52,720 (+0)
rtps::StatefulWriter 2,528 (+0) 2,960 (+0) 6,416 (+0)
rtps::StatelessWriter 1,872 (+0) 2,256 (+0) 3,792 (+0)
rtps::StatefulReader 1,968 (+0) 2,008 (+0) 2,104 (+0)
rtps::StatelessReader 1,960 (+0) 2,000 (+0) 2,096 (+0)
espp::RtpsParticipant 608 (+0) 608 (+0) 608 (+0)

embedded: heap by stage (free bytes; a cost is a negative delta)

stage internal delta internal low-water mark largest internal block PSRAM delta
boot 220,279 (+0) 219,552 (+0) 131,072 4,191,440 (+0)
started 161,483 (+1,428) -58,796 160,852 (+1,564) 77,824 3,959,128 (-131,068) -232,312
endpoints 143,043 (+3,532) -18,440 141,668 (+3,532) 69,632 3,959,128 (-131,068) +0

embedded: heap after each host-driven step (free bytes; deltas against the previous row; the pools are preallocated, so a peer costs little heap - the low-water mark shows the transients)

step internal delta internal low-water mark largest internal block PSRAM delta
baseline 136,819 (+3,556) 135,956 (+3,780) 69,632 3,959,140 (-131,076)
+1 remote participant (no match) 136,695 (+3,556) -124 135,336 (+4,904) 69,632 3,959,140 (-131,076) +0
+1 more remote participant (no match) 136,691 (+3,584) -4 135,336 (+4,904) 69,632 3,959,140 (-131,076) +0
+1 remote participant with a matched publisher 136,667 (+3,572) -24 135,336 (+4,904) 69,632 3,959,140 (-131,076) +0
after a service call 136,647 (+3,576) -20 135,336 (+4,904) 69,632 3,959,140 (-131,076) +0
after an action goal 135,271 (+3,392) -1,376 134,140 (+3,932) 69,632 3,959,140 (-131,076) +0
after one 30 KB sample 135,267 (+3,388) -4 133,956 (+4,100) 69,632 3,928,928 (-131,076) -30,212
all peers gone 135,267 (+3,384) +0 133,956 (+4,100) 69,632 3,928,928 (-131,076) +0

host: heap by stage (free bytes; a cost is a negative delta)

stage internal delta internal low-water mark largest internal block PSRAM delta
boot 219,047 (+0) 218,320 (+0) 131,072 4,191,440 (+0)
started 132,039 (+1,760) -87,008 131,424 (+1,716) 69,632 3,486,040 (-131,080) -705,400
endpoints 113,339 (+3,552) -18,700 111,964 (+3,552) 69,632 3,486,040 (-131,080) +0

host_large: the participant did not start on this target - the profile does not fit (panicked while the engine was being built - internal RAM exhausted building the Domain's mutexes (the first error logged: [RtpsTransport/E][2.632]: Failed to create valid UDP socket for port 7401)); its sizeof is in the table above, the boot heap below

host_large: heap by stage (free bytes; a cost is a negative delta)

stage internal delta internal low-water mark largest internal block PSRAM delta
boot 219,047 (+0) 218,320 (+0) 131,072 4,191,440 (+0)
started n/a
endpoints n/a

The QEMU memory suite on 19c99f5 (run); the full numbers are the run's rtps-memory artifact.

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 receive loop risks memory corruption for high-numbered descriptors and shutdown hangs if timeout setup fails, while the thread-pool test relies on unreliable timing.

2 open issues
1 previously missed issue

In code that hasn't changed since last review

Medium severity Make the pool rejection test deterministic

pc/​tests/​thread_pool.cpp:907

The 50 ms sleep does not guarantee stop() starts before the worker is released. If the main thread is descheduled after creating opener, the worker can execute the ten queued jobs first, making the rejection-count assertion fail for a correct pool. Run stop() on a helper thread and wait until it has counted the dropped jobs before opening the gate.

5 resolved since last review

Review effort: Balanced

Comment thread components/socket/src/udp_socket.cpp Resolved
Comment thread components/socket/src/udp_socket.cpp Resolved
finger563 and others added 3 commits December 2, 2026 20:12
…s its receive timeout

- The receive task's bounded wait used Socket::select(), whose FD_SET writes
  outside its fd_set for a valid POSIX descriptor >= FD_SETSIZE (which the
  old recvfrom-only loop handled). It now waits with poll() on POSIX hosts,
  and with select() only on Windows (an fd_set holds socket handles) and
  ESP-IDF (lwIP descriptors are always below its FD_SETSIZE).
- start_receiving() refuses to start when the 1 s receive timeout cannot be
  set: without it a spurious readiness could block the task in recvfrom,
  and stop_receiving() (which now stops the task before closing the socket)
  would hang. SocketReactor::add_udp_receiver() already refuses this case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
…rashes

On Windows both socket tests (socket_reactor runs there for the first time
in this PR) end with 0xc0000409 and no output: ctest pipes the output, the
C runtime buffers it fully, and a fail-fast abort ends the process before
the buffer is flushed. crash_diagnostics.hpp makes stdout / stderr
unbuffered and reports an uncaught exception reaching std::terminate, an
abort(), or a CRT invalid-parameter failure.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
…hed on Windows)

On Windows write() is the C runtime's file-descriptor write: handed a
Winsock SOCKET it fails its invalid-parameter check and aborts the process
(0xc0000409). TCP transmit had never run on Windows until this PR made the
socket tests run there; the crash diagnostics pinpointed it. send() is the
socket call on every platform.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU
@finger563
finger563 requested a balanced review from Copilot December 3, 2026 02:56
…indows)

The reactor creates its wakeup socket with a raw ::socket(), and on Windows
Winsock is only started by espp::Socket's constructor: a reactor started
before any Socket existed could not create it ("Could not create wakeup
socket") and refused to start. Seen once socket_reactor ran on Windows.
WSAStartup is reference-counted, so the reactor now calls it once itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU

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

The test relies on a 50 ms sleep for ordering, so scheduling delays can let all jobs execute before stop counts them, causing a false failure.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Replace timing-based sleep with synchronization in stop test

pc/​tests/​thread_pool.cpp:907

The 50 ms sleep does not guarantee that pool.stop() runs before open_gate(3). If the test thread is descheduled, the opener can release the worker and all ten jobs can execute before stop counts them, failing the test despite a correct pool. Run stop on a helper thread, wait until it has counted the queued jobs as rejected, then release the gate and join.

2 resolved since last review

Review effort: Balanced

@finger563
finger563 merged commit 0bb7b00 into main Dec 3, 2026
208 checks passed
@finger563
finger563 deleted the fix/udp-receive-buffer branch December 3, 2026 04:06
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.

rtps/socket: every received datagram allocates and zero-fills an 8 KB buffer; on a tight heap the failed new aborts the chip

2 participants