From bb43b7f9401b333663d7c123f95a8d7c7830b9d8 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sat, 14 Nov 2026 13:08:13 -0600 Subject: [PATCH 1/6] fix(rtps): a late joiner gets in ahead of re-announcing evictees on an oversubscribed domain On a domain that stays bigger than the remote-participant pool, the eviction of unused participants starved the one participant the device needed: with one eviction per announcement period for anyone, the crowd's rejected members re-announce every period and take turns displacing each other at the eviction rate, and a participant never seen before competes with all of them for that one slot per period. In the QEMU suite the late /qemu_rx publisher went unmatched for 90 s (31 evictions, every victim "56 s since discovery") once the whole crowd of 28 was up against 20 usable slots; the passing runs had started the publisher while the crowd was still coming up. RecentEvictions, a ring of the participants evicted lately (one entry per pool slot, no allocation), decides whether an announcing participant may have one evicted for it: evicted less than SPDP_EVICT_READMIT_HOLDOFF_MS ago (default 5 x SPDP_RESEND_PERIOD_MS) -> held off, nothing evicted for it (it still takes a free slot at once); a former evictee past its hold-off -> the cooldown of one eviction per period, as before; never evicted -> served at once, cooldown or not (it is new only once, so the churn stays bounded). The victim selection is unchanged. Kconfig RTPS_SPDP_EVICT_READMIT_HOLDOFF_MS + the CMake knob pass-through; a host test pins the rule and the ring. The QEMU case lets the crowd settle 20 s after the first eviction before the publisher starts, so it meets a domain that STAYS bigger than the pool. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/CMakeLists.txt | 1 + components/rtps/Kconfig | 28 +++- .../rtps/include/rtps/config_desktop.hpp | 13 ++ components/rtps/include/rtps/config_esp32.hpp | 13 ++ .../rtps/include/rtps/config_host_large.hpp | 13 ++ .../rtps/discovery/RecentEvictions.hpp | 121 ++++++++++++++++ .../include/rtps/entities/Participant.hpp | 22 ++- components/rtps/interop/README.md | 2 +- components/rtps/interop/run_qemu_interop.sh | 11 +- components/rtps/src/discovery/SPDPAgent.cpp | 9 +- components/rtps/src/entities/Participant.cpp | 30 +++- pc/tests/rtps_recent_evictions.cpp | 129 ++++++++++++++++++ 12 files changed, 369 insertions(+), 23 deletions(-) create mode 100644 components/rtps/include/rtps/discovery/RecentEvictions.hpp create mode 100644 pc/tests/rtps_recent_evictions.cpp diff --git a/components/rtps/CMakeLists.txt b/components/rtps/CMakeLists.txt index 0a8f1c662e..68b933aac7 100644 --- a/components/rtps/CMakeLists.txt +++ b/components/rtps/CMakeLists.txt @@ -111,6 +111,7 @@ set(RTPS_TUNING_KNOBS SPDP_DEFAULT_REMOTE_LEASE_DURATION_S SPDP_MAX_REMOTE_LEASE_DURATION_S SPDP_EVICT_MIN_AGE_MS + SPDP_EVICT_READMIT_HOLDOFF_MS ) foreach(knob ${RTPS_TUNING_KNOBS}) if(DEFINED CONFIG_RTPS_${knob} AND NOT "${CONFIG_RTPS_${knob}}" STREQUAL "" AND NOT "${CONFIG_RTPS_${knob}}" STREQUAL "0") diff --git a/components/rtps/Kconfig b/components/rtps/Kconfig index dd78232391..bcbb167c95 100644 --- a/components/rtps/Kconfig +++ b/components/rtps/Kconfig @@ -318,11 +318,13 @@ menu "RTPS" participant takes the slot of the oldest one none of this participant's user endpoints match (an expired one first), so a peer you need can still be - discovered on a domain crowded with peers you do not. At most - one eviction per SPDP_RESEND_PERIOD_MS, never of a participant - discovered less than SPDP_EVICT_MIN_AGE_MS ago, each logged as - a warning. Off: a participant beyond the pool is ignored until - a lease frees a slot (the previous behaviour). + discovered on a domain crowded with peers you do not. Never of + a participant discovered less than SPDP_EVICT_MIN_AGE_MS ago; + a peer never evicted is served at once, a peer evicted before + waits SPDP_EVICT_READMIT_HOLDOFF_MS and then gets at most one + eviction per SPDP_RESEND_PERIOD_MS; each logged as a warning. + Off: a participant beyond the pool is ignored until a lease + frees a slot (the previous behaviour). config RTPS_SPDP_EVICT_MIN_AGE_MS int "SPDP_EVICT_MIN_AGE_MS: youngest participant eviction may forget, ms (0 = profile default)" @@ -337,6 +339,22 @@ menu "RTPS" selected profile's value (3 x SPDP_RESEND_PERIOD_MS: 6000 embedded, 3000 host). + config RTPS_SPDP_EVICT_READMIT_HOLDOFF_MS + int "SPDP_EVICT_READMIT_HOLDOFF_MS: no eviction for a peer evicted this recently, ms (0 = profile default)" + depends on RTPS_SPDP_EVICT_UNUSED_PARTICIPANTS + default 0 + range 0 600000 + help + A peer this participant evicted less than this long ago has + nothing evicted for it when it announces again (a free slot it + still takes at once). On a domain that stays bigger than the + pool, the peers that do not fit re-announce every period and + would otherwise take turns displacing each other ahead of a + peer never seen before - the one you may need. Longer: less + churn, but a peer you evicted and now need waits this long. 0 + keeps the selected profile's value (5 x SPDP_RESEND_PERIOD_MS: + 10000 embedded, 5000 host). + endmenu menu "Tasks (advanced)" diff --git a/components/rtps/include/rtps/config_desktop.hpp b/components/rtps/include/rtps/config_desktop.hpp index 83e46ceb33..24081505cd 100644 --- a/components/rtps/include/rtps/config_desktop.hpp +++ b/components/rtps/include/rtps/config_desktop.hpp @@ -295,6 +295,19 @@ const bool SPDP_EVICT_UNUSED_PARTICIPANTS = RTPS_CFG_SPDP_EVICT_UNUSED_PARTICIPA #define RTPS_CFG_SPDP_EVICT_MIN_AGE_MS (3 * RTPS_CFG_SPDP_RESEND_PERIOD_MS) #endif const uint32_t SPDP_EVICT_MIN_AGE_MS = RTPS_CFG_SPDP_EVICT_MIN_AGE_MS; +// A participant this one evicted is not let back in by evicting another one +// for this long after (it still takes a free slot at once). Without it, on a +// domain that stays bigger than the pool, the rejected peers re-announce every +// period and take turns displacing each other at the eviction rate, and a peer +// never seen before - the one this participant may actually need - competes +// with all of them for the one slot per period and can lose every round. Held +// off, the just-evicted go to the back of the queue; a peer never evicted is +// admitted on its first announcement (the eviction cooldown does not apply to +// it: it is new only once). menuconfig RTPS -> Discovery timing. +#ifndef RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS +#define RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS (5 * RTPS_CFG_SPDP_RESEND_PERIOD_MS) +#endif +const uint32_t SPDP_EVICT_READMIT_HOLDOFF_MS = RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS; // Transport channel pool: 2 shared multicast channels (SPDP metatraffic + // user multicast) + 2 unicast channels per participant (builtin + user), plus diff --git a/components/rtps/include/rtps/config_esp32.hpp b/components/rtps/include/rtps/config_esp32.hpp index 8edb2f2b6e..c9bae829cf 100644 --- a/components/rtps/include/rtps/config_esp32.hpp +++ b/components/rtps/include/rtps/config_esp32.hpp @@ -256,6 +256,19 @@ const bool SPDP_EVICT_UNUSED_PARTICIPANTS = RTPS_CFG_SPDP_EVICT_UNUSED_PARTICIPA #define RTPS_CFG_SPDP_EVICT_MIN_AGE_MS (3 * RTPS_CFG_SPDP_RESEND_PERIOD_MS) #endif const uint32_t SPDP_EVICT_MIN_AGE_MS = RTPS_CFG_SPDP_EVICT_MIN_AGE_MS; +// A participant this one evicted is not let back in by evicting another one +// for this long after (it still takes a free slot at once). Without it, on a +// domain that stays bigger than the pool, the rejected peers re-announce every +// period and take turns displacing each other at the eviction rate, and a peer +// never seen before - the one this participant may actually need - competes +// with all of them for the one slot per period and can lose every round. Held +// off, the just-evicted go to the back of the queue; a peer never evicted is +// admitted on its first announcement (the eviction cooldown does not apply to +// it: it is new only once). menuconfig RTPS -> Discovery timing. +#ifndef RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS +#define RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS (5 * RTPS_CFG_SPDP_RESEND_PERIOD_MS) +#endif +const uint32_t SPDP_EVICT_READMIT_HOLDOFF_MS = RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS; // Transport channel pool: 2 shared multicast channels (SPDP metatraffic + // user multicast) + 2 unicast channels per participant (builtin + user), plus diff --git a/components/rtps/include/rtps/config_host_large.hpp b/components/rtps/include/rtps/config_host_large.hpp index 8ef72a237f..89c5e03b4d 100644 --- a/components/rtps/include/rtps/config_host_large.hpp +++ b/components/rtps/include/rtps/config_host_large.hpp @@ -292,6 +292,19 @@ const bool SPDP_EVICT_UNUSED_PARTICIPANTS = RTPS_CFG_SPDP_EVICT_UNUSED_PARTICIPA #define RTPS_CFG_SPDP_EVICT_MIN_AGE_MS (3 * RTPS_CFG_SPDP_RESEND_PERIOD_MS) #endif const uint32_t SPDP_EVICT_MIN_AGE_MS = RTPS_CFG_SPDP_EVICT_MIN_AGE_MS; +// A participant this one evicted is not let back in by evicting another one +// for this long after (it still takes a free slot at once). Without it, on a +// domain that stays bigger than the pool, the rejected peers re-announce every +// period and take turns displacing each other at the eviction rate, and a peer +// never seen before - the one this participant may actually need - competes +// with all of them for the one slot per period and can lose every round. Held +// off, the just-evicted go to the back of the queue; a peer never evicted is +// admitted on its first announcement (the eviction cooldown does not apply to +// it: it is new only once). menuconfig RTPS -> Discovery timing. +#ifndef RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS +#define RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS (5 * RTPS_CFG_SPDP_RESEND_PERIOD_MS) +#endif +const uint32_t SPDP_EVICT_READMIT_HOLDOFF_MS = RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS; // Transport channel pool: 2 shared multicast channels (SPDP metatraffic + // user multicast) + 2 unicast channels per participant (builtin + user), plus diff --git a/components/rtps/include/rtps/discovery/RecentEvictions.hpp b/components/rtps/include/rtps/discovery/RecentEvictions.hpp new file mode 100644 index 0000000000..4d9f759821 --- /dev/null +++ b/components/rtps/include/rtps/discovery/RecentEvictions.hpp @@ -0,0 +1,121 @@ +/* +The MIT License +Copyright (c) 2026 ATDev +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE + +This file is part of the espp embeddedRTPS port. +*/ + +#pragma once + +#include "rtps/common/types.hpp" + +#include +#include +#include +#include + +namespace rtps { + +//! The remote participants this participant evicted lately, and the rule that +//! decides whether an announcing participant may have another one evicted for +//! it (Participant::evictUnusedRemoteParticipant). +//! +//! Why: on a domain that stays bigger than the pool, the participants that do +//! not fit re-announce every period, and with a plain "one eviction per +//! period" cooldown they take turns displacing each other at the eviction +//! rate - one is forgotten, announces again a period later, and takes the slot +//! of the next-oldest, forever. A participant never seen before (the one this +//! participant may actually need) competes with all of them for that one slot +//! per period and can lose every round (it did: a late publisher went +//! unmatched for 90 s on a domain of 28 against 20 slots). So: +//! - a participant evicted less than `holdoff` ago is HELD OFF: nothing is +//! evicted for it (it is unused, and it still gets a free slot at once); +//! - a participant this one remembers evicting, past its hold-off, waits for +//! the eviction cooldown like before; +//! - a participant never evicted (or forgotten by this ring) may have one +//! evicted for it at once, cooldown or not: it is new only once, so this +//! does not unbound the churn, and it is admitted on its first announcement. +//! A ring of N entries, oldest overwritten; no allocation. +template class RecentEvictions { +public: + using time_point = std::chrono::steady_clock::time_point; + static_assert(N > 0, "RecentEvictions needs at least one entry"); + + enum class Gate { + Proceed, //!< may evict for this participant now + HeldOff, //!< evicted lately: do not evict for it + Cooldown //!< a former evictee, but an eviction happened this period already + }; + + //! Remember that `prefix` was evicted at `now` (refreshes an existing entry, + //! else takes the ring's next slot). + void note(const GuidPrefix_t &prefix, time_point now) { + for (auto &entry : m_entries) { + if (entry.valid && entry.prefix == prefix) { + entry.at = now; + return; + } + } + auto &slot = m_entries[m_next]; + slot.prefix = prefix; + slot.at = now; + slot.valid = true; + m_next = (m_next + 1) % N; + } + + //! When `prefix` was last evicted, if the ring still remembers it. + std::optional lastEviction(const GuidPrefix_t &prefix) const { + for (const auto &entry : m_entries) { + if (entry.valid && entry.prefix == prefix) { + return entry.at; + } + } + return std::nullopt; + } + + //! Whether an eviction may be made for `newcomer` at `now`, given the time + //! of the last eviction (`lastEvictionAt`, a default time_point when none + //! happened yet), the per-period `cooldown` and the readmission `holdoff`. + Gate gate(const GuidPrefix_t &newcomer, time_point now, time_point lastEvictionAt, + std::chrono::milliseconds cooldown, std::chrono::milliseconds holdoff) const { + const auto evictedAt = lastEviction(newcomer); + if (!evictedAt) { + return Gate::Proceed; + } + if (now - *evictedAt < holdoff) { + return Gate::HeldOff; + } + if (lastEvictionAt != time_point{} && now - lastEvictionAt < cooldown) { + return Gate::Cooldown; + } + return Gate::Proceed; + } + + static constexpr std::size_t capacity() { return N; } + +private: + struct Entry { + GuidPrefix_t prefix{}; + time_point at{}; + bool valid{false}; + }; + std::array m_entries{}; + std::size_t m_next{0}; +}; + +} // namespace rtps diff --git a/components/rtps/include/rtps/entities/Participant.hpp b/components/rtps/include/rtps/entities/Participant.hpp index 698964adbf..8b1a9dcaa0 100644 --- a/components/rtps/include/rtps/entities/Participant.hpp +++ b/components/rtps/include/rtps/entities/Participant.hpp @@ -29,6 +29,7 @@ Author: i11 - Embedded Software, RWTH Aachen University #include "base_component.hpp" #include "rtps/common/types.hpp" #include "rtps/config.hpp" +#include "rtps/discovery/RecentEvictions.hpp" #include "rtps/discovery/SEDPAgent.hpp" #include "rtps/discovery/SPDPAgent.hpp" #include "rtps/entities/ReaderRef.hpp" @@ -143,13 +144,17 @@ class Participant : public espp::BaseComponent { //! the participant we have the least use for so another can be added //! (Config::SPDP_EVICT_UNUSED_PARTICIPANTS): //! an expired one first, else the oldest-discovered one none of our user - //! endpoints match, provided it is older than Config::SPDP_EVICT_MIN_AGE_MS; - //! at most one eviction per SPDP_RESEND_PERIOD_MS (counted from a successful - //! removal). Returns true and sets `evicted` when a participant was removed; - //! `reason` names the trigger in the warning. Callers hold the SPDP agent - //! mutex (the documented order: SPDP agent -> SEDP agent -> Participant) and - //! must not hold m_mutex. - bool evictUnusedRemoteParticipant(GuidPrefix_t &evicted, const char *reason); + //! endpoints match, provided it is older than Config::SPDP_EVICT_MIN_AGE_MS. + //! `newcomer` is the announcing participant the room is made for: one + //! evicted less than Config::SPDP_EVICT_READMIT_HOLDOFF_MS ago gets nothing + //! evicted for it, one evicted before that waits for the cooldown of one + //! eviction per SPDP_RESEND_PERIOD_MS (counted from a successful removal), + //! and one never evicted is served at once (see RecentEvictions). Returns + //! true and sets `evicted` when a participant was removed; `reason` names the + //! trigger in the warning. Callers hold the SPDP agent mutex (the documented + //! order: SPDP agent -> SEDP agent -> Participant) and must not hold m_mutex. + bool evictUnusedRemoteParticipant(const GuidPrefix_t &newcomer, GuidPrefix_t &evicted, + const char *reason); bool hasReaderWithMulticastLocator(const std::array &address); @@ -170,6 +175,9 @@ class Participant : public espp::BaseComponent { std::recursive_mutex m_mutex; MemoryPool m_remoteParticipants; std::chrono::steady_clock::time_point m_lastEvictionTimestamp{}; + //! The participants evicted lately (under m_mutex): one slot per pool entry + //! is enough to remember every participant that can cycle through the pool. + RecentEvictions m_recentEvictions{}; //! Whether any user (non-builtin) endpoint of ours has a proxy of this //! participant, i.e. we exchange data with it. Takes m_mutex (recursive: //! callable from the eviction path that already holds it). diff --git a/components/rtps/interop/README.md b/components/rtps/interop/README.md index 9858dcf30c..eeaa8e1f51 100644 --- a/components/rtps/interop/README.md +++ b/components/rtps/interop/README.md @@ -87,7 +87,7 @@ cd .. && ./run_qemu.sh | many_participants_late_joiner | twelve unrelated participants first, the needed one last, against the pool raised to 24 by `CONFIG_RTPS_LIMIT_SPDP_MAX_NUMBER_FOUND_PARTICIPANTS` | | ros2_pub->device_sub_frag_30k | 30 KB samples reassembled from DATA_FRAG over lwIP | | participant_pool_overflow_recovers | 28 participants against a pool of 24 (and proxy pools of 20), then all leave: discovery keeps going, every one is forgotten after the capped lease, the next publisher is received | -| pool_full_evicts_unused_for_late_joiner | the same 28 against 24, but they STAY, and the publisher the device needs joins last: it can only get in by the eviction of a participant none of the device's endpoints match (`RTPS_SPDP_EVICT_UNUSED_PARTICIPANTS`, oldest first, one per announcement period, each logged); its samples must arrive | +| pool_full_evicts_unused_for_late_joiner | the same 28 against 24, but they STAY, and the publisher the device needs joins last: it can only get in by the eviction of a participant none of the device's endpoints match (`RTPS_SPDP_EVICT_UNUSED_PARTICIPANTS`, oldest first, each logged). The crowd is complete before the publisher starts, so its rejected members keep re-announcing: a peer evicted lately gets nothing evicted for it (`SPDP_EVICT_READMIT_HOLDOFF_MS`) and a peer never evicted is served at once, else the crowd took turns displacing each other ahead of the publisher (0 samples in 90 s, 31 evictions, once); its samples must arrive | | ros2_client->device_service | the typed service server, FastDDS and CycloneDDS: the embedded build answering the inline-QoS form and the in-payload `{guid, seq}` form | | netem_loss_service_fastdds, netem_loss_service_cyclone | 15 % loss + 10 ms jitter towards the device and ~14 % loss on the way back (an ingress drop on the TAP): one `ros2 service call` per RMW, which sends a single request and waits - a lost request or reply is repaired by the reliable writers on each side, not retried by the client | | espp_host_pub->device_sub, device_pub->espp_host_sub, espp_host_frag_30k->device_sub | the host engine against the embedded one, including its DATA_FRAG path | diff --git a/components/rtps/interop/run_qemu_interop.sh b/components/rtps/interop/run_qemu_interop.sh index 7072145721..bbc888b789 100755 --- a/components/rtps/interop/run_qemu_interop.sh +++ b/components/rtps/interop/run_qemu_interop.sh @@ -313,7 +313,16 @@ for i in $(seq 1 120); do sleep 1 done echo " crowd up after ${i} s (first eviction seen: $([ "$i" -lt 120 ] && echo yes || echo no))" -sleep 10 +# The first eviction says the pool is full; the rest of the crowd follows over +# the next seconds. Let all of it arrive before the publisher starts, so the +# case meets a domain that STAYS bigger than the pool - the crowd's rejected +# members re-announce every period and would take turns displacing each other +# - and not a pool that merely filled. (A run in which the publisher started +# while the crowd was still coming up passed trivially; one in which the crowd +# was complete starved the publisher for 90 s, 31 evictions, before the +# hold-off for re-announcing evictees existed.) +sleep 20 +echo " evictions while the crowd settled: $(count_since "$m0" "forgot an unused participant")" echo " device: $(grep -o 'RTPSTEST status.*' "$LOG" | tail -1)" m=$(mark) timeout 100 ros2 topic pub -r 5 /qemu_rx std_msgs/msg/String "data: 'made room for me'" > /dev/null 2>&1 & diff --git a/components/rtps/src/discovery/SPDPAgent.cpp b/components/rtps/src/discovery/SPDPAgent.cpp index 9cda6f37ac..82e9538704 100644 --- a/components/rtps/src/discovery/SPDPAgent.cpp +++ b/components/rtps/src/discovery/SPDPAgent.cpp @@ -264,13 +264,15 @@ void SPDPAgent::processProxyData() { // see Participant::evictUnusedRemoteParticipant; lock order here is the // SPDP agent mutex, held by handleSPDPPackage, -> SEDP agent -> Participant) // and retry. When nothing can be evicted (every known participant is one - // we talk to, or one was evicted this announcement period already) the + // we talk to, this one was itself evicted lately, or one was evicted this + // announcement period already for a peer that had been evicted before) the // peer announces again (SPDP is periodic), and the liveliness sweep frees // a slot once a known peer's lease runs out, so it gets in later; nothing // to do now. (This used to spin forever in non-verbose builds, with the // agent mutex held: one participant too many on the domain froze discovery.) GuidPrefix_t evicted{}; - if (!mp_participant->evictUnusedRemoteParticipant(evicted, "Remote-participant pool full") || + if (!mp_participant->evictUnusedRemoteParticipant(m_proxyDataBuffer.m_guid.prefix, evicted, + "Remote-participant pool full") || !mp_participant->addNewRemoteParticipant(m_proxyDataBuffer)) { SPDP_LOG("Remote-participant pool full, not adding this participant"); return; @@ -294,7 +296,8 @@ void SPDPAgent::processProxyData() { // takes the SPDP mutex while holding either of the others. GuidPrefix_t evicted{}; const bool fits = mp_participant->evictUnusedRemoteParticipant( - evicted, "Builtin proxies of a new remote participant do not fit") && + m_proxyDataBuffer.m_guid.prefix, evicted, + "Builtin proxies of a new remote participant do not fit") && addProxiesForBuiltInEndpoints(); if (!fits) { SPDP_LOG("Builtin proxies for the new participant did not fit, forgetting it"); diff --git a/components/rtps/src/entities/Participant.cpp b/components/rtps/src/entities/Participant.cpp index fcfb282c86..462ef25562 100644 --- a/components/rtps/src/entities/Participant.cpp +++ b/components/rtps/src/entities/Participant.cpp @@ -663,7 +663,8 @@ bool Participant::hasUserEndpointProxyOf(const GuidPrefix_t &prefix) { return false; } -bool Participant::evictUnusedRemoteParticipant(GuidPrefix_t &evicted, const char *reason) { +bool Participant::evictUnusedRemoteParticipant(const GuidPrefix_t &newcomer, GuidPrefix_t &evicted, + const char *reason) { if (!Config::SPDP_EVICT_UNUSED_PARTICIPANTS) { return false; } @@ -684,12 +685,28 @@ bool Participant::evictUnusedRemoteParticipant(GuidPrefix_t &evicted, const char std::lock_guard lock(m_mutex); bool have = false; const auto now = std::chrono::steady_clock::now(); - if (m_lastEvictionTimestamp != std::chrono::steady_clock::time_point{} && - now - m_lastEvictionTimestamp < std::chrono::milliseconds(Config::SPDP_RESEND_PERIOD_MS)) { - // One eviction per announcement period: on a domain that stays bigger - // than the pool, the rejected peers re-announce every period, and this - // bounds how often an unused one is swapped for another unused one. + // Who is asking: a participant evicted lately is held off (it is unused, + // and letting it displace another unused one at once is how the rejected + // peers of a too-big domain took turns ahead of a newcomer); a former + // evictee past its hold-off gets one eviction per announcement period, + // which bounds how often an unused one is swapped for another unused one; + // a participant never evicted is served at once (see RecentEvictions). + using Gate = decltype(m_recentEvictions)::Gate; + switch ( + m_recentEvictions.gate(newcomer, now, m_lastEvictionTimestamp, + std::chrono::milliseconds(Config::SPDP_RESEND_PERIOD_MS), + std::chrono::milliseconds(Config::SPDP_EVICT_READMIT_HOLDOFF_MS))) { + case Gate::HeldOff: + logger_.debug("{}: not evicting for participant {:02x}{:02x}{:02x}{:02x}, itself evicted " + "less than {} ms ago", + reason != nullptr ? reason : "no room for a new remote participant", + newcomer.id[4], newcomer.id[5], newcomer.id[6], newcomer.id[7], + static_cast(Config::SPDP_EVICT_READMIT_HOLDOFF_MS)); return false; + case Gate::Cooldown: + return false; + case Gate::Proceed: + break; } for (auto &remote : m_remoteParticipants) { if (!remote.isAlive()) { @@ -733,6 +750,7 @@ bool Participant::evictUnusedRemoteParticipant(GuidPrefix_t &evicted, const char { std::lock_guard lock(m_mutex); m_lastEvictionTimestamp = std::chrono::steady_clock::now(); + m_recentEvictions.note(victim, m_lastEvictionTimestamp); inPool = static_cast(m_remoteParticipants.getNumElements()); } // The logger formats at run time (fmt::vformat): keep the placeholder count diff --git a/pc/tests/rtps_recent_evictions.cpp b/pc/tests/rtps_recent_evictions.cpp new file mode 100644 index 0000000000..5aed49e005 --- /dev/null +++ b/pc/tests/rtps_recent_evictions.cpp @@ -0,0 +1,129 @@ +// The admission rule behind Participant::evictUnusedRemoteParticipant on a +// domain that stays bigger than the remote-participant pool (RecentEvictions): +// a peer evicted lately is held off, a former evictee past its hold-off waits +// for the per-period cooldown, a peer never evicted is served at once. It +// used to be one eviction per period for anyone: the peers that did not fit +// re-announced every period and took turns displacing each other, and a late +// publisher the device needed lost every round for 90 s in the QEMU suite +// (pool_full_evicts_unused_for_late_joiner). This pins the rule and the ring. + +#include +#include + +#include "rtps/discovery/RecentEvictions.hpp" + +namespace { +using namespace std::chrono_literals; +using Ring = rtps::RecentEvictions<4>; +using Gate = Ring::Gate; +using tp = Ring::time_point; + +rtps::GuidPrefix_t prefix(uint8_t tag) { + rtps::GuidPrefix_t p{}; + p.id.fill(tag); + return p; +} + +const char *name(Gate g) { + switch (g) { + case Gate::Proceed: + return "Proceed"; + case Gate::HeldOff: + return "HeldOff"; + case Gate::Cooldown: + return "Cooldown"; + } + return "?"; +} + +bool expect(Gate got, Gate want, const char *what) { + if (got != want) { + std::printf("FAIL: %s: %s, expected %s\n", what, name(got), name(want)); + return false; + } + return true; +} +} // namespace + +int main() { + bool ok = true; + const auto t0 = tp{} + 1000s; // a default (zero) time_point means "never" + constexpr auto cooldown = 2000ms; + constexpr auto holdoff = 10000ms; + const auto never = tp{}; + Ring ring; + const auto a = prefix(0xA1); + const auto b = prefix(0xB2); + const auto c = prefix(0xC3); + + // unknown peers proceed whatever the cooldown state + ok = expect(ring.gate(a, t0, never, cooldown, holdoff), Gate::Proceed, + "unknown, no eviction yet") && + ok; + ok = expect(ring.gate(a, t0, t0 - 100ms, cooldown, holdoff), Gate::Proceed, + "unknown peer during the cooldown is still served") && + ok; + if (ring.lastEviction(a)) { + std::printf("FAIL: an unknown peer has an eviction time\n"); + ok = false; + } + + // a evicted at t0: held off for holdoff, then cooldown-bound, then free + ring.note(a, t0); + if (!ring.lastEviction(a) || *ring.lastEviction(a) != t0) { + std::printf("FAIL: the eviction time of a is not remembered\n"); + ok = false; + } + ok = expect(ring.gate(a, t0 + 1s, t0, cooldown, holdoff), Gate::HeldOff, "a one second after") && + ok; + ok = expect(ring.gate(a, t0 + holdoff - 1ms, t0, cooldown, holdoff), Gate::HeldOff, + "a just before the hold-off ends") && + ok; + ok = expect(ring.gate(a, t0 + holdoff, t0 + holdoff - 500ms, cooldown, holdoff), Gate::Cooldown, + "a past the hold-off, an eviction 500 ms ago") && + ok; + ok = expect(ring.gate(a, t0 + holdoff, t0 + holdoff - cooldown, cooldown, holdoff), Gate::Proceed, + "a past the hold-off, the cooldown just over") && + ok; + ok = expect(ring.gate(a, t0 + holdoff, never, cooldown, holdoff), Gate::Proceed, + "a past the hold-off, no eviction ever") && + ok; + // meanwhile b, never evicted, is served even right after a's eviction + ok = expect(ring.gate(b, t0 + 1ms, t0, cooldown, holdoff), Gate::Proceed, + "b right after a's eviction") && + ok; + + // a second eviction of a refreshes its entry rather than adding one + ring.note(a, t0 + 30s); + ok = expect(ring.gate(a, t0 + 31s, t0 + 30s, cooldown, holdoff), Gate::HeldOff, + "a held off again") && + ok; + ring.note(b, t0 + 31s); + ring.note(c, t0 + 32s); + // the ring (4 entries) still knows a, b, c; one more distinct peer than it + // holds overwrites the OLDEST slot (a, noted first) - not the refreshed one + // in time order, but the ring is a ring: it rolls by slot, which is what a + // bounded, allocation-free memory affords. Pin that it keeps the newest. + ring.note(prefix(0xD4), t0 + 33s); + ring.note(prefix(0xE5), t0 + 34s); + if (ring.lastEviction(a)) { + std::printf("FAIL: the oldest slot (a) was not overwritten by the fifth peer\n"); + ok = false; + } + for (uint8_t tag : {uint8_t{0xB2}, uint8_t{0xC3}, uint8_t{0xD4}, uint8_t{0xE5}}) { + if (!ring.lastEviction(prefix(tag))) { + std::printf("FAIL: peer %02x forgotten while the ring had room for it\n", tag); + ok = false; + } + } + if (Ring::capacity() != 4) { + std::printf("FAIL: capacity %zu\n", Ring::capacity()); + ok = false; + } + + if (!ok) { + return 1; + } + std::printf("PASS\n"); + return 0; +} From e57812e49c15a86334addfb09d2a5d034b6b16d3 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sat, 14 Nov 2026 13:13:13 -0600 Subject: [PATCH 2/6] style(rtps): RecentEvictions looks entries up with std::find_if, time points by const reference cppcheck (useStlAlgorithm, passedByValue) on #907. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- .../rtps/discovery/RecentEvictions.hpp | 31 +++++++++++-------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/components/rtps/include/rtps/discovery/RecentEvictions.hpp b/components/rtps/include/rtps/discovery/RecentEvictions.hpp index 4d9f759821..fabb40cd3f 100644 --- a/components/rtps/include/rtps/discovery/RecentEvictions.hpp +++ b/components/rtps/include/rtps/discovery/RecentEvictions.hpp @@ -24,6 +24,7 @@ This file is part of the espp embeddedRTPS port. #include "rtps/common/types.hpp" +#include #include #include #include @@ -64,12 +65,10 @@ template class RecentEvictions { //! Remember that `prefix` was evicted at `now` (refreshes an existing entry, //! else takes the ring's next slot). - void note(const GuidPrefix_t &prefix, time_point now) { - for (auto &entry : m_entries) { - if (entry.valid && entry.prefix == prefix) { - entry.at = now; - return; - } + void note(const GuidPrefix_t &prefix, const time_point &now) { + if (auto *entry = find(prefix); entry != nullptr) { + entry->at = now; + return; } auto &slot = m_entries[m_next]; slot.prefix = prefix; @@ -80,18 +79,14 @@ template class RecentEvictions { //! When `prefix` was last evicted, if the ring still remembers it. std::optional lastEviction(const GuidPrefix_t &prefix) const { - for (const auto &entry : m_entries) { - if (entry.valid && entry.prefix == prefix) { - return entry.at; - } - } - return std::nullopt; + const auto *entry = find(prefix); + return entry != nullptr ? std::optional{entry->at} : std::nullopt; } //! Whether an eviction may be made for `newcomer` at `now`, given the time //! of the last eviction (`lastEvictionAt`, a default time_point when none //! happened yet), the per-period `cooldown` and the readmission `holdoff`. - Gate gate(const GuidPrefix_t &newcomer, time_point now, time_point lastEvictionAt, + Gate gate(const GuidPrefix_t &newcomer, const time_point &now, const time_point &lastEvictionAt, std::chrono::milliseconds cooldown, std::chrono::milliseconds holdoff) const { const auto evictedAt = lastEviction(newcomer); if (!evictedAt) { @@ -116,6 +111,16 @@ template class RecentEvictions { }; std::array m_entries{}; std::size_t m_next{0}; + + const Entry *find(const GuidPrefix_t &prefix) const { + const auto it = std::find_if(m_entries.begin(), m_entries.end(), [&prefix](const Entry &e) { + return e.valid && e.prefix == prefix; + }); + return it != m_entries.end() ? &*it : nullptr; + } + Entry *find(const GuidPrefix_t &prefix) { + return const_cast(static_cast(*this).find(prefix)); + } }; } // namespace rtps From 685442fd30363037a2bcebb237de2d03ccb61304 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sat, 14 Nov 2026 14:20:48 -0600 Subject: [PATCH 3/6] fix(rtps): room on the receive workers' stack; the QEMU suite gates the engine tasks' stack margin The first CI run of the eviction hold-off passed the hardened late-joiner case and then crashed in the CycloneDDS pass: "A stack overflow in task rtps_worker_0", right after an eviction warning. The only addition on that path was a second formatted log (debug level, never printed) in the same frame - a few hundred bytes - so the 6144-byte worker stack had less margin than that. A receive worker runs the engine's deepest path (SPDP in -> eviction -> SEDP removal -> warning) and every reader and matched callback on top. - The held-off message is a PARTICIPANT_LOG (compiled out): nothing new is formatted on a worker. - THREAD_POOL_READER_STACKSIZE on ESP: 6144 -> 8192 in the three profiles (workers + reactor; the memory comment shows the cost against main). - The QEMU firmware's status line reports stack_min= / stack_min_task=, the smallest stack high-water mark over the engine's tasks (rtps_* and the action servers' exec_* workers) since boot (CONFIG_FREERTOS_USE_TRACE_FACILITY for uxTaskGetSystemState; the firmware's own publish timer is renamed so it does not count), and the harness gains device_stack_margin: at least 512 bytes, so a thin margin fails CI before it is a crash on a device. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/README.md | 2 +- .../rtps/include/rtps/config_desktop.hpp | 4 +- components/rtps/include/rtps/config_esp32.hpp | 2 +- .../rtps/include/rtps/config_host_large.hpp | 4 +- components/rtps/interop/README.md | 2 +- .../rtps/interop/qemu/main/rtps_qemu.cpp | 42 +++++++++++++++++-- .../rtps/interop/qemu/sdkconfig.defaults | 2 + components/rtps/interop/run_qemu_interop.sh | 8 ++++ components/rtps/src/entities/Participant.cpp | 12 +++--- 9 files changed, 63 insertions(+), 15 deletions(-) diff --git a/components/rtps/README.md b/components/rtps/README.md index 7aab6c6ff2..b06624f706 100644 --- a/components/rtps/README.md +++ b/components/rtps/README.md @@ -186,7 +186,7 @@ via `include/rtps/config.hpp`. | `RTPS_ENABLE_RPC` | on (default) | Compile in services + actions (RMI/AMI). Disable to drop that code + its threads on a pure-pub/sub device. | | `RTPS_DOMAIN_ID` | 0 | DDS domain id (the `ROS_DOMAIN_ID` equivalent, 0..232). Derives the port base `7400 + 250 * id` and GUID prefix byte 9, so every participant on a domain must use the same value. Compile-time. | | `RTPS_THREAD_POOL_READER_PRIO` | 0 = profile default (5 on ESP32) | FreeRTOS priority of the transport's worker pool and reactor tasks, which send and receive all traffic (see [Priority scheduling](#priority-scheduling-bands-dedicated-ports-dscp)). | -| `RTPS_THREAD_POOL_READER_STACKSIZE` | 0 = profile default (6144 on ESP32) | Stack of those tasks (they also run every reader and matched callback). ESP only: a host `std::thread` uses the platform default stack. | +| `RTPS_THREAD_POOL_READER_STACKSIZE` | 0 = profile default (8192 on ESP32) | Stack of those tasks (they also run every reader and matched callback). ESP only: a host `std::thread` uses the platform default stack. | | `RTPS_SPDP_WRITER_PRIO` / `RTPS_SPDP_WRITER_STACKSIZE` | 0 = profile default (5 / 4096 on ESP32) | Priority and stack of the protocol task (`rtps_protocol`: SPDP announcements, reliable-writer HEARTBEATs, liveliness checks). The stack is raised to at least 4096 before the task is created; ESP only, as above. | | (runtime) `RtpsParticipant::Config::tasks` | the above | Per-participant overrides of the same tasks - an `espp::Task::BaseConfig` (stack, priority, core id) for the receive workers (and their count), the reactor, the transport's job-retry task and the protocol task; an unset entry keeps the Kconfig default. An action server's execute workers are configured by `ActionConfig::execute_workers` / `execute_task`. | | `RTPS_SPDP_RESEND_PERIOD_MS` | 0 = profile default (2000 on ESP32) | Participant announcement period. Keep it well below the announced lease. | diff --git a/components/rtps/include/rtps/config_desktop.hpp b/components/rtps/include/rtps/config_desktop.hpp index 24081505cd..65ca21d899 100644 --- a/components/rtps/include/rtps/config_desktop.hpp +++ b/components/rtps/include/rtps/config_desktop.hpp @@ -187,11 +187,11 @@ const uint8_t MAX_TOPICNAME_LENGTH = RTPS_CFG_MAX_TOPICNAME_LENGTH; // The 1600 is a host figure that nothing applies; selected ON the target (the // Kconfig limits-profile choice puts this header on an ESP32 too) this IS the // FreeRTOS stack of every receive worker, and 1600 overflows on the first -// datagram - so on ESP it is the embedded profile's 6144, as the capacity +// datagram - so on ESP it is the embedded profile's 8192, as the capacity // profiles are about pool sizes, not task stacks. #ifndef RTPS_CFG_THREAD_POOL_READER_STACKSIZE #if defined(ESP_PLATFORM) -#define RTPS_CFG_THREAD_POOL_READER_STACKSIZE 6144 +#define RTPS_CFG_THREAD_POOL_READER_STACKSIZE 8192 #else #define RTPS_CFG_THREAD_POOL_READER_STACKSIZE 1600 #endif diff --git a/components/rtps/include/rtps/config_esp32.hpp b/components/rtps/include/rtps/config_esp32.hpp index c9bae829cf..c464c88d36 100644 --- a/components/rtps/include/rtps/config_esp32.hpp +++ b/components/rtps/include/rtps/config_esp32.hpp @@ -162,7 +162,7 @@ const uint8_t MAX_TOPICNAME_LENGTH = RTPS_CFG_MAX_TOPICNAME_LENGTH; // sets stacks through esp_pthread; a host std::thread uses the platform // default). menuconfig RTPS -> Tasks. #ifndef RTPS_CFG_THREAD_POOL_READER_STACKSIZE -#define RTPS_CFG_THREAD_POOL_READER_STACKSIZE 6144 +#define RTPS_CFG_THREAD_POOL_READER_STACKSIZE 8192 #endif const int THREAD_POOL_READER_STACKSIZE = RTPS_CFG_THREAD_POOL_READER_STACKSIZE; // byte // Stack requested for the protocol task (SPDP announcements, heartbeats, diff --git a/components/rtps/include/rtps/config_host_large.hpp b/components/rtps/include/rtps/config_host_large.hpp index 89c5e03b4d..2cc8c47afb 100644 --- a/components/rtps/include/rtps/config_host_large.hpp +++ b/components/rtps/include/rtps/config_host_large.hpp @@ -184,11 +184,11 @@ const uint8_t MAX_TOPICNAME_LENGTH = RTPS_CFG_MAX_TOPICNAME_LENGTH; // The 1600 is a host figure that nothing applies; selected ON the target (the // Kconfig limits-profile choice puts this header on an ESP32 too) this IS the // FreeRTOS stack of every receive worker, and 1600 overflows on the first -// datagram - so on ESP it is the embedded profile's 6144, as the capacity +// datagram - so on ESP it is the embedded profile's 8192, as the capacity // profiles are about pool sizes, not task stacks. #ifndef RTPS_CFG_THREAD_POOL_READER_STACKSIZE #if defined(ESP_PLATFORM) -#define RTPS_CFG_THREAD_POOL_READER_STACKSIZE 6144 +#define RTPS_CFG_THREAD_POOL_READER_STACKSIZE 8192 #else #define RTPS_CFG_THREAD_POOL_READER_STACKSIZE 1600 #endif diff --git a/components/rtps/interop/README.md b/components/rtps/interop/README.md index eeaa8e1f51..ae257935b0 100644 --- a/components/rtps/interop/README.md +++ b/components/rtps/interop/README.md @@ -97,7 +97,7 @@ cd .. && ./run_qemu.sh | netem_reorder_best_effort, netem_duplicate_best_effort | the same against the best-effort reader: samples may be lost, but none arrives twice or out of order (RTPS 2.5 8.4.12.1, `rtps_best_effort_order` on the host) | | netem_delay_discovery | 300 ms (+-50) delay from before discovery: a ROS 2 publisher is still discovered, matched and delivered over a 600 ms round trip | | netem_loss_device_pub | 15 % loss towards the device: the device's reliable writer repairs for the host subscriber against lost ACKNACKs | -| device_heap_stable, device_no_crash | free heap at the end within 96 KB of the start (two buffers grow once to the largest sample, 30 KB each); no panic / abort / assert | +| device_heap_stable, device_no_crash, device_stack_margin | free heap at the end within 96 KB of the start (two buffers grow once to the largest sample, 30 KB each); no panic / abort / assert; the smallest stack high-water mark over the engine's tasks (`stack_min=` / `stack_min_task=` in the status line: the rtps_* tasks and the action servers' exec_* workers, since boot) is at least 512 bytes - a receive worker once overflowed on the eviction path with less | The **soak** suite (`./run_qemu.sh soak`, the second CI job on the same firmware build) runs 20 cycles of churn instead: each cycle six ROS 2 diff --git a/components/rtps/interop/qemu/main/rtps_qemu.cpp b/components/rtps/interop/qemu/main/rtps_qemu.cpp index 6873f434b7..bb94ad97dc 100644 --- a/components/rtps/interop/qemu/main/rtps_qemu.cpp +++ b/components/rtps/interop/qemu/main/rtps_qemu.cpp @@ -15,6 +15,11 @@ // RTPSTEST srv += service request served // RTPSTEST status up= tx= rx= be_rx= big_rx= heap= min_heap= // int= int_min= int_largest= psram= +// stack_min= stack_min_task= +// stack_min: the smallest stack high-water mark (bytes never used) over the +// engine's tasks (rtps_* and the action servers' exec_* workers) since boot; +// the harness fails device_stack_margin below 512 (rtps_worker_0 overflowed +// once on the eviction path with a few hundred bytes of margin before). // every 2 s, for the soak and memory checks // RTPSTEST mem sizeof domain= participant= stateful_writer= stateless_writer= // stateful_reader= stateless_reader= facade= @@ -36,11 +41,14 @@ #include #include #include +#include #include #include #include #include +#include +#include #include "qemu.hpp" @@ -298,7 +306,7 @@ extern "C" void app_main(void) { // Periodic publishers: one reliable, one best-effort uint32_t counter = 0; espp::Timer publish_timer({ - .name = "rtps_pub", + .name = "qemu_pub", // not rtps_*: the stack margin below is the engine's, not this test's .period = 200ms, .callback = [&]() { @@ -315,6 +323,31 @@ extern "C" void app_main(void) { logger.info("RTPSTEST ready ip={}", interface_address); + // The engine's tasks' stack margin: the smallest high-water mark (bytes of + // stack never touched since the task started) over the rtps_* tasks (receive + // workers, reactor, job retry, protocol, reply hold) and the action servers' + // exec_* workers. Read every status period, the minimum so far is reported: + // a thin margin is a crash waiting for a slightly deeper call. + std::vector tasks; + uint32_t stack_min = UINT32_MAX; + std::string stack_min_task = "none"; + const auto sample_stacks = [&]() { + const auto count = uxTaskGetNumberOfTasks(); + tasks.resize(count + 4); + const auto n = uxTaskGetSystemState(tasks.data(), tasks.size(), nullptr); + for (UBaseType_t i = 0; i < n; ++i) { + const std::string_view name{tasks[i].pcTaskName}; + if (!name.starts_with("rtps_") && !name.starts_with("exec_")) { + continue; + } + const uint32_t margin = tasks[i].usStackHighWaterMark * sizeof(StackType_t); + if (margin < stack_min) { + stack_min = margin; + stack_min_task = std::string{name}; + } + } + }; + // Status line every 2 s: the soak and leak checks read heap and min_heap const auto t0 = std::chrono::steady_clock::now(); while (true) { @@ -322,14 +355,17 @@ extern "C" void app_main(void) { const auto up = std::chrono::duration_cast(std::chrono::steady_clock::now() - t0) .count(); + sample_stacks(); logger.info("RTPSTEST status up={} tx={} rx={} be_rx={} big_rx={} pub_matches={} " - "sub_matches={} heap={} min_heap={} int={} int_min={} int_largest={} psram={}", + "sub_matches={} heap={} min_heap={} int={} int_min={} int_largest={} psram={} " + "stack_min={} stack_min_task={}", up, tx_count.load(), rx_count.load(), be_rx_count.load(), big_rx_count.load(), pub_matches.load(), sub_matches.load(), heap_caps_get_free_size(MALLOC_CAP_DEFAULT), heap_caps_get_minimum_free_size(MALLOC_CAP_DEFAULT), heap_caps_get_free_size(MALLOC_CAP_INTERNAL), heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL), heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL), - heap_caps_get_free_size(MALLOC_CAP_SPIRAM)); + heap_caps_get_free_size(MALLOC_CAP_SPIRAM), stack_min == UINT32_MAX ? 0 : stack_min, + stack_min_task); } } diff --git a/components/rtps/interop/qemu/sdkconfig.defaults b/components/rtps/interop/qemu/sdkconfig.defaults index 5cee582cc0..a49bfea789 100644 --- a/components/rtps/interop/qemu/sdkconfig.defaults +++ b/components/rtps/interop/qemu/sdkconfig.defaults @@ -58,3 +58,5 @@ CONFIG_RTPS_ENABLE_RPC=y # against the rest; it costs a software checksum per received datagram. CONFIG_LWIP_CHECKSUM_CHECK_IP=y CONFIG_LWIP_CHECKSUM_CHECK_UDP=y +# uxTaskGetSystemState for the engine tasks' stack margin in the status line +CONFIG_FREERTOS_USE_TRACE_FACILITY=y diff --git a/components/rtps/interop/run_qemu_interop.sh b/components/rtps/interop/run_qemu_interop.sh index bbc888b789..7aca88dbf3 100755 --- a/components/rtps/interop/run_qemu_interop.sh +++ b/components/rtps/interop/run_qemu_interop.sh @@ -483,6 +483,14 @@ echo "free heap first=$FIRST_HEAP last=$LAST_HEAP" if [ "$DEVICE_STARTED" = 1 ]; then [ -n "$FIRST_HEAP" ] && [ -n "$LAST_HEAP" ] && [ "$LAST_HEAP" -ge $((FIRST_HEAP - 98304)) ]; result "device_heap_stable" $? ! grep -qE "Guru Meditation|abort\(\)|assert failed|RTPSTEST fatal" "$LOG"; result "device_no_crash" $? + # The engine tasks' stack margin (stack_min= in the status line: the smallest + # high-water mark over the rtps_* / exec_* tasks since boot, and the task). + # 512 bytes is the floor: rtps_worker_0 overflowed once on the eviction + # path with less than that, from one more formatted log in the frame. + STACK_MIN=$(grep -o " stack_min=[0-9]*" "$LOG" | tail -1 | cut -d= -f2) + STACK_MIN_TASK=$(grep -o " stack_min_task=[A-Za-z0-9_]*" "$LOG" | tail -1 | cut -d= -f2) + echo "engine tasks' smallest stack margin: ${STACK_MIN:-?} bytes (${STACK_MIN_TASK:-?})" + [ -n "$STACK_MIN" ] && [ "$STACK_MIN" -ge 512 ]; result "device_stack_margin" $? else # the memory suite on a profile that does not fit: the fatal IS the finding, # and so is a panic while the engine was being built (recorded at boot). diff --git a/components/rtps/src/entities/Participant.cpp b/components/rtps/src/entities/Participant.cpp index 462ef25562..979c9d24d9 100644 --- a/components/rtps/src/entities/Participant.cpp +++ b/components/rtps/src/entities/Participant.cpp @@ -697,11 +697,13 @@ bool Participant::evictUnusedRemoteParticipant(const GuidPrefix_t &newcomer, Gui std::chrono::milliseconds(Config::SPDP_RESEND_PERIOD_MS), std::chrono::milliseconds(Config::SPDP_EVICT_READMIT_HOLDOFF_MS))) { case Gate::HeldOff: - logger_.debug("{}: not evicting for participant {:02x}{:02x}{:02x}{:02x}, itself evicted " - "less than {} ms ago", - reason != nullptr ? reason : "no room for a new remote participant", - newcomer.id[4], newcomer.id[5], newcomer.id[6], newcomer.id[7], - static_cast(Config::SPDP_EVICT_READMIT_HOLDOFF_MS)); + // Compiled out unless PARTICIPANT_VERBOSE: this runs on a receive worker + // whose stack is sized for the engine, not for a second formatted log + // beside the eviction warning (the first build with one here overflowed + // rtps_worker_0 in the QEMU suite). + PARTICIPANT_LOG("{}: not evicting for a participant itself evicted less than {} ms ago", + reason != nullptr ? reason : "no room for a new remote participant", + static_cast(Config::SPDP_EVICT_READMIT_HOLDOFF_MS)); return false; case Gate::Cooldown: return false; From 78fa027f5f3e791bb82fc5f514b5a75ba49fefce Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sat, 14 Nov 2026 14:45:08 -0600 Subject: [PATCH 4/6] fix(rtps): eviction budgets per kind of newcomer, the ring keeps the newest evictions Review of #907 found two holes in "a never-evicted peer is served at once": the ring (one slot per pool entry, overwritten by slot order) can forget a peer still inside its hold-off once evictions run faster than one per period - which the bypass itself allows, up to N per 3 periods - and a forgotten peer passes as a first-timer, so a crowd bigger than the ring becomes a self-sustaining conveyor at that rate; and every eviction armed the one cooldown, so a stream of fresh GUIDs (ros2 CLI tools, restarting nodes) could starve a former evictee the device has since grown a reader for. Now two budgets of one eviction per period, each with its own clock: one for participants this one remembers evicting (past their hold-off), one for participants never evicted. The newcomer the device needs competes only with other first-timers, former evictees only with each other, and the churn is at most two per period. The ring overwrites the OLDEST EVICTION when full and is sized from the hold-off (2 * HOLDOFF / PERIOD + 2, capped at 64) so no peer still held off is ever forgotten. A newcomer already in the pool (the builtin-proxies call site) is never its own victim, whatever SPDP_EVICT_MIN_AGE_MS is. Stale "one per period" wording updated. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/Kconfig | 16 ++-- .../rtps/include/rtps/config_desktop.hpp | 15 ++-- components/rtps/include/rtps/config_esp32.hpp | 15 ++-- .../rtps/include/rtps/config_host_large.hpp | 15 ++-- .../rtps/discovery/RecentEvictions.hpp | 74 +++++++++------- .../include/rtps/entities/Participant.hpp | 22 +++-- components/rtps/interop/README.md | 4 +- components/rtps/src/entities/Participant.cpp | 21 +++-- pc/tests/rtps_recent_evictions.cpp | 84 +++++++++++-------- 9 files changed, 164 insertions(+), 102 deletions(-) diff --git a/components/rtps/Kconfig b/components/rtps/Kconfig index bcbb167c95..3c8c5ca531 100644 --- a/components/rtps/Kconfig +++ b/components/rtps/Kconfig @@ -320,9 +320,11 @@ menu "RTPS" (an expired one first), so a peer you need can still be discovered on a domain crowded with peers you do not. Never of a participant discovered less than SPDP_EVICT_MIN_AGE_MS ago; - a peer never evicted is served at once, a peer evicted before - waits SPDP_EVICT_READMIT_HOLDOFF_MS and then gets at most one - eviction per SPDP_RESEND_PERIOD_MS; each logged as a warning. + a peer evicted before waits SPDP_EVICT_READMIT_HOLDOFF_MS; + then one eviction per SPDP_RESEND_PERIOD_MS from the budget + of its kind (former evictees and never-evicted peers each + have their own, so neither starves the other and the churn is + at most two per period); each logged as a warning. Off: a participant beyond the pool is ignored until a lease frees a slot (the previous behaviour). @@ -350,8 +352,10 @@ menu "RTPS" still takes at once). On a domain that stays bigger than the pool, the peers that do not fit re-announce every period and would otherwise take turns displacing each other ahead of a - peer never seen before - the one you may need. Longer: less - churn, but a peer you evicted and now need waits this long. 0 + peer never seen before - the one you may need (which has its + own one-per-period eviction budget, as the former evictees have + theirs). Longer: less churn, but a peer you evicted and now + need waits this long. 0 keeps the selected profile's value (5 x SPDP_RESEND_PERIOD_MS: 10000 embedded, 5000 host). @@ -390,7 +394,7 @@ menu "RTPS" callback, and the reactor ("rtps_reactor"). Raise it when a callback needs more than the default; a value below 2048 is refused at build time. 0 keeps the selected profile's value - (6144 on the embedded profile). + (8192 on the embedded profile). config RTPS_SPDP_WRITER_PRIO int "SPDP_WRITER_PRIO: protocol task priority (0 = profile default)" diff --git a/components/rtps/include/rtps/config_desktop.hpp b/components/rtps/include/rtps/config_desktop.hpp index 65ca21d899..23bd3659af 100644 --- a/components/rtps/include/rtps/config_desktop.hpp +++ b/components/rtps/include/rtps/config_desktop.hpp @@ -284,9 +284,10 @@ const Duration_t SPDP_MAX_REMOTE_LEASE_DURATION = {RTPS_CFG_SPDP_MAX_REMOTE_LEAS // endpoints matched by any user endpoint of ours) so the newcomer gets the // slot: oldest discovered first, never one discovered less than // SPDP_EVICT_MIN_AGE_MS ago (its endpoint discovery may still be in flight), -// at most one per SPDP_RESEND_PERIOD_MS, and an expired participant before any -// live one. Each eviction is logged: a domain that keeps evicting wants a bigger -// SPDP_MAX_NUMBER_FOUND_PARTICIPANTS. menuconfig RTPS -> Discovery timing. +// at most one per SPDP_RESEND_PERIOD_MS for a peer evicted before and one for a +// peer never evicted (two budgets, see SPDP_EVICT_READMIT_HOLDOFF_MS), and an +// expired participant before any live one. Each eviction is logged: a domain that keeps evicting +// wants a bigger SPDP_MAX_NUMBER_FOUND_PARTICIPANTS. menuconfig RTPS -> Discovery timing. #ifndef RTPS_CFG_SPDP_EVICT_UNUSED_PARTICIPANTS #define RTPS_CFG_SPDP_EVICT_UNUSED_PARTICIPANTS 1 #endif @@ -301,9 +302,11 @@ const uint32_t SPDP_EVICT_MIN_AGE_MS = RTPS_CFG_SPDP_EVICT_MIN_AGE_MS; // period and take turns displacing each other at the eviction rate, and a peer // never seen before - the one this participant may actually need - competes // with all of them for the one slot per period and can lose every round. Held -// off, the just-evicted go to the back of the queue; a peer never evicted is -// admitted on its first announcement (the eviction cooldown does not apply to -// it: it is new only once). menuconfig RTPS -> Discovery timing. +// off, the just-evicted go to the back of the queue, and the one eviction per +// period is budgeted per kind - former evictees and never-evicted peers each +// have their own - so a stream of fresh GUIDs cannot starve a peer evicted +// earlier that is needed now, nor the other way round; the churn is at most +// two per period. menuconfig RTPS -> Discovery timing. #ifndef RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS #define RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS (5 * RTPS_CFG_SPDP_RESEND_PERIOD_MS) #endif diff --git a/components/rtps/include/rtps/config_esp32.hpp b/components/rtps/include/rtps/config_esp32.hpp index c464c88d36..b063c7f11e 100644 --- a/components/rtps/include/rtps/config_esp32.hpp +++ b/components/rtps/include/rtps/config_esp32.hpp @@ -245,9 +245,10 @@ const Duration_t SPDP_MAX_REMOTE_LEASE_DURATION = {RTPS_CFG_SPDP_MAX_REMOTE_LEAS // endpoints matched by any user endpoint of ours) so the newcomer gets the // slot: oldest discovered first, never one discovered less than // SPDP_EVICT_MIN_AGE_MS ago (its endpoint discovery may still be in flight), -// at most one per SPDP_RESEND_PERIOD_MS, and an expired participant before any -// live one. Each eviction is logged: a domain that keeps evicting wants a bigger -// SPDP_MAX_NUMBER_FOUND_PARTICIPANTS. menuconfig RTPS -> Discovery timing. +// at most one per SPDP_RESEND_PERIOD_MS for a peer evicted before and one for a +// peer never evicted (two budgets, see SPDP_EVICT_READMIT_HOLDOFF_MS), and an +// expired participant before any live one. Each eviction is logged: a domain that keeps evicting +// wants a bigger SPDP_MAX_NUMBER_FOUND_PARTICIPANTS. menuconfig RTPS -> Discovery timing. #ifndef RTPS_CFG_SPDP_EVICT_UNUSED_PARTICIPANTS #define RTPS_CFG_SPDP_EVICT_UNUSED_PARTICIPANTS 1 #endif @@ -262,9 +263,11 @@ const uint32_t SPDP_EVICT_MIN_AGE_MS = RTPS_CFG_SPDP_EVICT_MIN_AGE_MS; // period and take turns displacing each other at the eviction rate, and a peer // never seen before - the one this participant may actually need - competes // with all of them for the one slot per period and can lose every round. Held -// off, the just-evicted go to the back of the queue; a peer never evicted is -// admitted on its first announcement (the eviction cooldown does not apply to -// it: it is new only once). menuconfig RTPS -> Discovery timing. +// off, the just-evicted go to the back of the queue, and the one eviction per +// period is budgeted per kind - former evictees and never-evicted peers each +// have their own - so a stream of fresh GUIDs cannot starve a peer evicted +// earlier that is needed now, nor the other way round; the churn is at most +// two per period. menuconfig RTPS -> Discovery timing. #ifndef RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS #define RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS (5 * RTPS_CFG_SPDP_RESEND_PERIOD_MS) #endif diff --git a/components/rtps/include/rtps/config_host_large.hpp b/components/rtps/include/rtps/config_host_large.hpp index 2cc8c47afb..976e4c90b5 100644 --- a/components/rtps/include/rtps/config_host_large.hpp +++ b/components/rtps/include/rtps/config_host_large.hpp @@ -281,9 +281,10 @@ const Duration_t SPDP_MAX_REMOTE_LEASE_DURATION = {RTPS_CFG_SPDP_MAX_REMOTE_LEAS // endpoints matched by any user endpoint of ours) so the newcomer gets the // slot: oldest discovered first, never one discovered less than // SPDP_EVICT_MIN_AGE_MS ago (its endpoint discovery may still be in flight), -// at most one per SPDP_RESEND_PERIOD_MS, and an expired participant before any -// live one. Each eviction is logged: a domain that keeps evicting wants a bigger -// SPDP_MAX_NUMBER_FOUND_PARTICIPANTS. menuconfig RTPS -> Discovery timing. +// at most one per SPDP_RESEND_PERIOD_MS for a peer evicted before and one for a +// peer never evicted (two budgets, see SPDP_EVICT_READMIT_HOLDOFF_MS), and an +// expired participant before any live one. Each eviction is logged: a domain that keeps evicting +// wants a bigger SPDP_MAX_NUMBER_FOUND_PARTICIPANTS. menuconfig RTPS -> Discovery timing. #ifndef RTPS_CFG_SPDP_EVICT_UNUSED_PARTICIPANTS #define RTPS_CFG_SPDP_EVICT_UNUSED_PARTICIPANTS 1 #endif @@ -298,9 +299,11 @@ const uint32_t SPDP_EVICT_MIN_AGE_MS = RTPS_CFG_SPDP_EVICT_MIN_AGE_MS; // period and take turns displacing each other at the eviction rate, and a peer // never seen before - the one this participant may actually need - competes // with all of them for the one slot per period and can lose every round. Held -// off, the just-evicted go to the back of the queue; a peer never evicted is -// admitted on its first announcement (the eviction cooldown does not apply to -// it: it is new only once). menuconfig RTPS -> Discovery timing. +// off, the just-evicted go to the back of the queue, and the one eviction per +// period is budgeted per kind - former evictees and never-evicted peers each +// have their own - so a stream of fresh GUIDs cannot starve a peer evicted +// earlier that is needed now, nor the other way round; the churn is at most +// two per period. menuconfig RTPS -> Discovery timing. #ifndef RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS #define RTPS_CFG_SPDP_EVICT_READMIT_HOLDOFF_MS (5 * RTPS_CFG_SPDP_RESEND_PERIOD_MS) #endif diff --git a/components/rtps/include/rtps/discovery/RecentEvictions.hpp b/components/rtps/include/rtps/discovery/RecentEvictions.hpp index fabb40cd3f..27b5f398f0 100644 --- a/components/rtps/include/rtps/discovery/RecentEvictions.hpp +++ b/components/rtps/include/rtps/discovery/RecentEvictions.hpp @@ -37,21 +37,25 @@ namespace rtps { //! it (Participant::evictUnusedRemoteParticipant). //! //! Why: on a domain that stays bigger than the pool, the participants that do -//! not fit re-announce every period, and with a plain "one eviction per -//! period" cooldown they take turns displacing each other at the eviction -//! rate - one is forgotten, announces again a period later, and takes the slot -//! of the next-oldest, forever. A participant never seen before (the one this -//! participant may actually need) competes with all of them for that one slot -//! per period and can lose every round (it did: a late publisher went +//! not fit re-announce every period, and with one plain "one eviction per +//! period" budget for anyone they take turns displacing each other at the +//! eviction rate - one is forgotten, announces again a period later, and takes +//! the slot of the next-oldest, forever. A participant never seen before (the +//! one this participant may actually need) competes with all of them for that +//! one slot per period and can lose every round (it did: a late publisher went //! unmatched for 90 s on a domain of 28 against 20 slots). So: //! - a participant evicted less than `holdoff` ago is HELD OFF: nothing is //! evicted for it (it is unused, and it still gets a free slot at once); -//! - a participant this one remembers evicting, past its hold-off, waits for -//! the eviction cooldown like before; -//! - a participant never evicted (or forgotten by this ring) may have one -//! evicted for it at once, cooldown or not: it is new only once, so this -//! does not unbound the churn, and it is admitted on its first announcement. -//! A ring of N entries, oldest overwritten; no allocation. +//! - two eviction budgets of one per `cooldown`, each with its own clock: one +//! for the participants this one remembers evicting (past their hold-off), +//! one for participants never evicted (or no longer remembered). The +//! newcomer the device needs competes only with other first-timers, and a +//! stream of fresh GUIDs (ros2 CLI tools, restarting nodes) cannot starve a +//! former evictee the device has since grown a reader for: it has its own +//! budget. The churn stays bounded at two evictions per period. +//! A ring of N entries; when full, the oldest eviction is overwritten. Sized +//! by the caller so that the evictions one hold-off can hold (two per period) +//! all fit: a peer forgotten by the ring would look like a first-timer. template class RecentEvictions { public: using time_point = std::chrono::steady_clock::time_point; @@ -60,21 +64,29 @@ template class RecentEvictions { enum class Gate { Proceed, //!< may evict for this participant now HeldOff, //!< evicted lately: do not evict for it - Cooldown //!< a former evictee, but an eviction happened this period already + Cooldown //!< its budget (first-timer or former evictee) was spent this period }; //! Remember that `prefix` was evicted at `now` (refreshes an existing entry, - //! else takes the ring's next slot). + //! else takes a free slot, else the slot of the oldest eviction). void note(const GuidPrefix_t &prefix, const time_point &now) { if (auto *entry = find(prefix); entry != nullptr) { entry->at = now; return; } - auto &slot = m_entries[m_next]; - slot.prefix = prefix; - slot.at = now; - slot.valid = true; - m_next = (m_next + 1) % N; + auto *slot = &m_entries[0]; + for (auto &entry : m_entries) { + if (!entry.valid) { + slot = &entry; + break; + } + if (entry.at < slot->at) { + slot = &entry; + } + } + slot->prefix = prefix; + slot->at = now; + slot->valid = true; } //! When `prefix` was last evicted, if the ring still remembers it. @@ -83,22 +95,21 @@ template class RecentEvictions { return entry != nullptr ? std::optional{entry->at} : std::nullopt; } - //! Whether an eviction may be made for `newcomer` at `now`, given the time - //! of the last eviction (`lastEvictionAt`, a default time_point when none - //! happened yet), the per-period `cooldown` and the readmission `holdoff`. - Gate gate(const GuidPrefix_t &newcomer, const time_point &now, const time_point &lastEvictionAt, - std::chrono::milliseconds cooldown, std::chrono::milliseconds holdoff) const { + //! Whether an eviction may be made for `newcomer` at `now`. `lastForKnownAt` + //! and `lastForFreshAt` are when the two budgets were last spent (a default + //! time_point: never); `cooldown` is the period of each, `holdoff` the time a + //! participant stays held off after its own eviction. + Gate gate(const GuidPrefix_t &newcomer, const time_point &now, const time_point &lastForKnownAt, + const time_point &lastForFreshAt, std::chrono::milliseconds cooldown, + std::chrono::milliseconds holdoff) const { const auto evictedAt = lastEviction(newcomer); if (!evictedAt) { - return Gate::Proceed; + return spent(lastForFreshAt, now, cooldown) ? Gate::Cooldown : Gate::Proceed; } if (now - *evictedAt < holdoff) { return Gate::HeldOff; } - if (lastEvictionAt != time_point{} && now - lastEvictionAt < cooldown) { - return Gate::Cooldown; - } - return Gate::Proceed; + return spent(lastForKnownAt, now, cooldown) ? Gate::Cooldown : Gate::Proceed; } static constexpr std::size_t capacity() { return N; } @@ -110,8 +121,11 @@ template class RecentEvictions { bool valid{false}; }; std::array m_entries{}; - std::size_t m_next{0}; + static bool spent(const time_point &last, const time_point &now, + std::chrono::milliseconds cooldown) { + return last != time_point{} && now - last < cooldown; + } const Entry *find(const GuidPrefix_t &prefix) const { const auto it = std::find_if(m_entries.begin(), m_entries.end(), [&prefix](const Entry &e) { return e.valid && e.prefix == prefix; diff --git a/components/rtps/include/rtps/entities/Participant.hpp b/components/rtps/include/rtps/entities/Participant.hpp index 8b1a9dcaa0..7b2c8f2db1 100644 --- a/components/rtps/include/rtps/entities/Participant.hpp +++ b/components/rtps/include/rtps/entities/Participant.hpp @@ -35,6 +35,7 @@ Author: i11 - Embedded Software, RWTH Aachen University #include "rtps/entities/ReaderRef.hpp" #include "rtps/messages/MessageReceiver.hpp" +#include #include #include #include @@ -147,9 +148,11 @@ class Participant : public espp::BaseComponent { //! endpoints match, provided it is older than Config::SPDP_EVICT_MIN_AGE_MS. //! `newcomer` is the announcing participant the room is made for: one //! evicted less than Config::SPDP_EVICT_READMIT_HOLDOFF_MS ago gets nothing - //! evicted for it, one evicted before that waits for the cooldown of one - //! eviction per SPDP_RESEND_PERIOD_MS (counted from a successful removal), - //! and one never evicted is served at once (see RecentEvictions). Returns + //! evicted for it; otherwise one eviction per SPDP_RESEND_PERIOD_MS (counted + //! from a successful removal) from the budget of its kind - former evictees + //! and never-evicted participants each have their own, so the churn is at + //! most two per period and neither kind starves the other (see + //! RecentEvictions). Returns //! true and sets `evicted` when a participant was removed; `reason` names the //! trigger in the warning. Callers hold the SPDP agent mutex (the documented //! order: SPDP agent -> SEDP agent -> Participant) and must not hold m_mutex. @@ -174,10 +177,17 @@ class Participant : public espp::BaseComponent { std::recursive_mutex m_mutex; MemoryPool m_remoteParticipants; + //! When the two eviction budgets were last spent (under m_mutex): for a + //! participant this one remembers evicting, and for one never evicted. std::chrono::steady_clock::time_point m_lastEvictionTimestamp{}; - //! The participants evicted lately (under m_mutex): one slot per pool entry - //! is enough to remember every participant that can cycle through the pool. - RecentEvictions m_recentEvictions{}; + std::chrono::steady_clock::time_point m_lastFreshEvictionTimestamp{}; + //! The participants evicted lately (under m_mutex). Two evictions per period + //! at most, so one hold-off holds at most 2 * HOLDOFF / PERIOD of them: that + //! many slots (+2) and none still held off is ever forgotten - a forgotten one + //! would pass as a first-timer. Capped at 64 for an extreme hold-off. + static constexpr std::size_t kRecentEvictions = std::min( + 2 * (Config::SPDP_EVICT_READMIT_HOLDOFF_MS / Config::SPDP_RESEND_PERIOD_MS) + 2, 64); + RecentEvictions m_recentEvictions{}; //! Whether any user (non-builtin) endpoint of ours has a proxy of this //! participant, i.e. we exchange data with it. Takes m_mutex (recursive: //! callable from the eviction path that already holds it). diff --git a/components/rtps/interop/README.md b/components/rtps/interop/README.md index ae257935b0..5730a04a2f 100644 --- a/components/rtps/interop/README.md +++ b/components/rtps/interop/README.md @@ -45,7 +45,7 @@ touched. | ros2_pub->espp_sub | ROS 2 publisher -> espp reliable reader | | espp_be_pub->ros2_be_echo | best-effort pairing | | ros2_pub->espp_sub_liveliness, espp_pub->ros2_sub_liveliness | samples keep arriving 22 s in, i.e. past a remote participant lease (CycloneDDS: 10 s). Only samples after that point count (`rtps_interop_sub ... count_after_s`, `ros2_count_subscriber.py`), so a peer whose SPDP re-announcements were not delivered - and whose lease therefore expired, dropping every matched endpoint - fails. CycloneDDS addresses those re-announcements to readerId ENTITYID_UNKNOWN; the FastDDS pass is the control. Only the espp-publisher leg detects a dropped peer: a HEARTBEAT that reaches a matched espp reader also refreshes the sending participant's liveliness (`MessageReceiver::processHeartbeat`), so a CycloneDDS *writer* keeps its participant alive through its heartbeats even when its SPDP re-announcements are lost, while an espp writer only gets ACKNACKs back, which do not refresh it, and the peer expires | -| many_participants_late_joiner | twelve unrelated ROS 2 participants are on the domain before espp starts, then the publisher espp needs joins last and must still be matched. Guards the remote-participant pool (`SPDP_MAX_NUMBER_FOUND_PARTICIPANTS`, 32 on the host profile built here, 10 on the embedded profile - raise it via menuconfig for a domain this busy): with the pool full, a newly announcing participant evicts the oldest one none of espp's endpoints match (`RTPS_SPDP_EVICT_UNUSED_PARTICIPANTS`, on by default, one eviction per announcement period, logged); with it off a participant beyond the pool is ignored silently | +| many_participants_late_joiner | twelve unrelated ROS 2 participants are on the domain before espp starts, then the publisher espp needs joins last and must still be matched. Guards the remote-participant pool (`SPDP_MAX_NUMBER_FOUND_PARTICIPANTS`, 32 on the host profile built here, 10 on the embedded profile - raise it via menuconfig for a domain this busy): with the pool full, a newly announcing participant evicts the oldest one none of espp's endpoints match (`RTPS_SPDP_EVICT_UNUSED_PARTICIPANTS`, on by default, one eviction per announcement period per kind of newcomer, logged); with it off a participant beyond the pool is ignored silently | | ros2_pub_churn->espp_sub_unmatch | a ROS 2 node creates, uses and destroys a publisher five times in 25 s and exits (`ros2_churn_publisher.py`): the espp subscriber must see five matched->unmatched transitions, each after samples arrived, within 40 s (`rtps_interop_churn`, polling `RtpsParticipant::matched_writers()`). Only a peer's dispose can do that; a writer dropped on lease expiry alone (20 s Fast DDS, 10 s Cyclone DDS) would give at most two | | rpc_stop_race, rpc_pending_eviction, rpc_empty_reply | the service facade: a client handle used while, and after, its participant stops returns 0 / false instead of touching freed endpoints (`pc/tests/rtps_rpc_stop_race.cpp`); a client's pending table is bounded by `ServiceConfig::request_timeout` / `max_pending_requests` and stop() releases every waiter - `call()` nullopt at once, `call_future()` nullopt rather than broken_promise (`rtps_rpc_pending_eviction.cpp`); a handler returning nothing sends nothing, the client times out (`rtps_rpc_empty_reply.cpp`) | | typed_action_alignment, action_cancel_codes, action_goal_flood | the action facade: a typed Result with int64 / float64 fields is carried as one `GetResult_Response` message, byte-exact against the hand-written layout (`rtps_typed_action_alignment.cpp`); a cancel is answered with the `action_msgs/srv/CancelGoal` verdict - the goals canceling, ERROR_REJECTED / UNKNOWN_GOAL_ID / GOAL_TERMINATED, cancel-all (`rtps_action_cancel_codes.cpp`); `ActionConfig::max_goals_in_flight` caps the execute threads, duplicate ids are rejected, a finished goal is retired after `result_timeout` (`rtps_action_goal_flood.cpp`) | @@ -87,7 +87,7 @@ cd .. && ./run_qemu.sh | many_participants_late_joiner | twelve unrelated participants first, the needed one last, against the pool raised to 24 by `CONFIG_RTPS_LIMIT_SPDP_MAX_NUMBER_FOUND_PARTICIPANTS` | | ros2_pub->device_sub_frag_30k | 30 KB samples reassembled from DATA_FRAG over lwIP | | participant_pool_overflow_recovers | 28 participants against a pool of 24 (and proxy pools of 20), then all leave: discovery keeps going, every one is forgotten after the capped lease, the next publisher is received | -| pool_full_evicts_unused_for_late_joiner | the same 28 against 24, but they STAY, and the publisher the device needs joins last: it can only get in by the eviction of a participant none of the device's endpoints match (`RTPS_SPDP_EVICT_UNUSED_PARTICIPANTS`, oldest first, each logged). The crowd is complete before the publisher starts, so its rejected members keep re-announcing: a peer evicted lately gets nothing evicted for it (`SPDP_EVICT_READMIT_HOLDOFF_MS`) and a peer never evicted is served at once, else the crowd took turns displacing each other ahead of the publisher (0 samples in 90 s, 31 evictions, once); its samples must arrive | +| pool_full_evicts_unused_for_late_joiner | the same 28 against 24, but they STAY, and the publisher the device needs joins last: it can only get in by the eviction of a participant none of the device's endpoints match (`RTPS_SPDP_EVICT_UNUSED_PARTICIPANTS`, oldest first, each logged). The crowd is complete before the publisher starts, so its rejected members keep re-announcing: a peer evicted lately gets nothing evicted for it (`SPDP_EVICT_READMIT_HOLDOFF_MS`) and the one eviction per period is budgeted per kind (former evictees / never-evicted peers), else the crowd took turns displacing each other ahead of the publisher (0 samples in 90 s, 31 evictions, once); its samples must arrive | | ros2_client->device_service | the typed service server, FastDDS and CycloneDDS: the embedded build answering the inline-QoS form and the in-payload `{guid, seq}` form | | netem_loss_service_fastdds, netem_loss_service_cyclone | 15 % loss + 10 ms jitter towards the device and ~14 % loss on the way back (an ingress drop on the TAP): one `ros2 service call` per RMW, which sends a single request and waits - a lost request or reply is repaired by the reliable writers on each side, not retried by the client | | espp_host_pub->device_sub, device_pub->espp_host_sub, espp_host_frag_30k->device_sub | the host engine against the embedded one, including its DATA_FRAG path | diff --git a/components/rtps/src/entities/Participant.cpp b/components/rtps/src/entities/Participant.cpp index 979c9d24d9..75b7cc7ab7 100644 --- a/components/rtps/src/entities/Participant.cpp +++ b/components/rtps/src/entities/Participant.cpp @@ -680,6 +680,7 @@ bool Participant::evictUnusedRemoteParticipant(const GuidPrefix_t &newcomer, Gui // Phase 1 - SELECT under m_mutex. GuidPrefix_t victim{}; bool victimExpired = false; + bool known = false; // the newcomer is a former evictee (its budget) uint32_t victimAge = 0; { std::lock_guard lock(m_mutex); @@ -687,13 +688,15 @@ bool Participant::evictUnusedRemoteParticipant(const GuidPrefix_t &newcomer, Gui const auto now = std::chrono::steady_clock::now(); // Who is asking: a participant evicted lately is held off (it is unused, // and letting it displace another unused one at once is how the rejected - // peers of a too-big domain took turns ahead of a newcomer); a former - // evictee past its hold-off gets one eviction per announcement period, - // which bounds how often an unused one is swapped for another unused one; - // a participant never evicted is served at once (see RecentEvictions). + // peers of a too-big domain took turns ahead of a newcomer); otherwise one + // eviction per announcement period from the budget of its kind - former + // evictees and never-evicted participants each have their own - which + // bounds how often an unused one is swapped for another unused one without + // letting either kind starve the other (see RecentEvictions). + known = m_recentEvictions.lastEviction(newcomer).has_value(); using Gate = decltype(m_recentEvictions)::Gate; switch ( - m_recentEvictions.gate(newcomer, now, m_lastEvictionTimestamp, + m_recentEvictions.gate(newcomer, now, m_lastEvictionTimestamp, m_lastFreshEvictionTimestamp, std::chrono::milliseconds(Config::SPDP_RESEND_PERIOD_MS), std::chrono::milliseconds(Config::SPDP_EVICT_READMIT_HOLDOFF_MS))) { case Gate::HeldOff: @@ -711,6 +714,9 @@ bool Participant::evictUnusedRemoteParticipant(const GuidPrefix_t &newcomer, Gui break; } for (auto &remote : m_remoteParticipants) { + if (remote.m_guid.prefix == newcomer) { + continue; // already in the pool (its builtin proxies did not fit): never its own victim + } if (!remote.isAlive()) { // past its lease already: the liveliness sweep would forget it soon const uint32_t age = remote.getAliveSignalAgeInMilliseconds(); @@ -751,8 +757,9 @@ bool Participant::evictUnusedRemoteParticipant(const GuidPrefix_t &newcomer, Gui unsigned int inPool = 0; { std::lock_guard lock(m_mutex); - m_lastEvictionTimestamp = std::chrono::steady_clock::now(); - m_recentEvictions.note(victim, m_lastEvictionTimestamp); + const auto now = std::chrono::steady_clock::now(); + (known ? m_lastEvictionTimestamp : m_lastFreshEvictionTimestamp) = now; + m_recentEvictions.note(victim, now); inPool = static_cast(m_remoteParticipants.getNumElements()); } // The logger formats at run time (fmt::vformat): keep the placeholder count diff --git a/pc/tests/rtps_recent_evictions.cpp b/pc/tests/rtps_recent_evictions.cpp index 5aed49e005..7b8a6a2b52 100644 --- a/pc/tests/rtps_recent_evictions.cpp +++ b/pc/tests/rtps_recent_evictions.cpp @@ -1,11 +1,12 @@ // The admission rule behind Participant::evictUnusedRemoteParticipant on a // domain that stays bigger than the remote-participant pool (RecentEvictions): -// a peer evicted lately is held off, a former evictee past its hold-off waits -// for the per-period cooldown, a peer never evicted is served at once. It -// used to be one eviction per period for anyone: the peers that did not fit -// re-announced every period and took turns displacing each other, and a late -// publisher the device needed lost every round for 90 s in the QEMU suite -// (pool_full_evicts_unused_for_late_joiner). This pins the rule and the ring. +// a peer evicted lately is held off; otherwise one eviction per period from the +// budget of its kind - former evictees and never-evicted peers each have their +// own. It used to be one eviction per period for anyone: the peers that did +// not fit re-announced every period and took turns displacing each other, and +// a late publisher the device needed lost every round for 90 s in the QEMU +// suite (pool_full_evicts_unused_for_late_joiner). This pins the rule, that +// neither budget starves the other, and the ring (oldest eviction overwritten). #include #include @@ -56,63 +57,69 @@ int main() { const auto b = prefix(0xB2); const auto c = prefix(0xC3); - // unknown peers proceed whatever the cooldown state - ok = expect(ring.gate(a, t0, never, cooldown, holdoff), Gate::Proceed, - "unknown, no eviction yet") && + // a first-timer: its own budget, never the former evictees' + ok = expect(ring.gate(a, t0, never, never, cooldown, holdoff), Gate::Proceed, + "unknown, nothing spent") && ok; - ok = expect(ring.gate(a, t0, t0 - 100ms, cooldown, holdoff), Gate::Proceed, - "unknown peer during the cooldown is still served") && + ok = expect(ring.gate(a, t0, t0 - 100ms, never, cooldown, holdoff), Gate::Proceed, + "unknown: an eviction for a FORMER evictee 100 ms ago does not count against it") && + ok; + ok = expect(ring.gate(a, t0, never, t0 - 100ms, cooldown, holdoff), Gate::Cooldown, + "unknown: an eviction for another FIRST-TIMER 100 ms ago does") && + ok; + ok = expect(ring.gate(a, t0, never, t0 - cooldown, cooldown, holdoff), Gate::Proceed, + "unknown: the first-timer budget is back after one cooldown") && ok; if (ring.lastEviction(a)) { std::printf("FAIL: an unknown peer has an eviction time\n"); ok = false; } - // a evicted at t0: held off for holdoff, then cooldown-bound, then free + // a evicted at t0: held off for holdoff, then on the former evictees' budget ring.note(a, t0); if (!ring.lastEviction(a) || *ring.lastEviction(a) != t0) { std::printf("FAIL: the eviction time of a is not remembered\n"); ok = false; } - ok = expect(ring.gate(a, t0 + 1s, t0, cooldown, holdoff), Gate::HeldOff, "a one second after") && + ok = expect(ring.gate(a, t0 + 1s, never, never, cooldown, holdoff), Gate::HeldOff, + "a one second after") && ok; - ok = expect(ring.gate(a, t0 + holdoff - 1ms, t0, cooldown, holdoff), Gate::HeldOff, + ok = expect(ring.gate(a, t0 + holdoff - 1ms, never, never, cooldown, holdoff), Gate::HeldOff, "a just before the hold-off ends") && ok; - ok = expect(ring.gate(a, t0 + holdoff, t0 + holdoff - 500ms, cooldown, holdoff), Gate::Cooldown, - "a past the hold-off, an eviction 500 ms ago") && + ok = expect(ring.gate(a, t0 + holdoff, t0 + holdoff - 500ms, never, cooldown, holdoff), + Gate::Cooldown, "a past the hold-off, an eviction for a former evictee 500 ms ago") && ok; - ok = expect(ring.gate(a, t0 + holdoff, t0 + holdoff - cooldown, cooldown, holdoff), Gate::Proceed, - "a past the hold-off, the cooldown just over") && + ok = expect(ring.gate(a, t0 + holdoff, never, t0 + holdoff - 500ms, cooldown, holdoff), + Gate::Proceed, "a past the hold-off: a stream of first-timers does not starve it") && ok; - ok = expect(ring.gate(a, t0 + holdoff, never, cooldown, holdoff), Gate::Proceed, - "a past the hold-off, no eviction ever") && + ok = expect(ring.gate(a, t0 + holdoff, t0 + holdoff - cooldown, never, cooldown, holdoff), + Gate::Proceed, "a past the hold-off, its budget's cooldown just over") && ok; - // meanwhile b, never evicted, is served even right after a's eviction - ok = expect(ring.gate(b, t0 + 1ms, t0, cooldown, holdoff), Gate::Proceed, - "b right after a's eviction") && + // meanwhile b, never evicted, is served right after an eviction made for a + // former evictee: the budgets are separate + ok = expect(ring.gate(b, t0 + 1ms, t0, never, cooldown, holdoff), Gate::Proceed, + "b (first-timer) right after an eviction for a former evictee") && ok; // a second eviction of a refreshes its entry rather than adding one ring.note(a, t0 + 30s); - ok = expect(ring.gate(a, t0 + 31s, t0 + 30s, cooldown, holdoff), Gate::HeldOff, + ok = expect(ring.gate(a, t0 + 31s, never, never, cooldown, holdoff), Gate::HeldOff, "a held off again") && ok; - ring.note(b, t0 + 31s); + ring.note(b, t0 + 29s); // noted later but with an OLDER eviction time than a's refresh ring.note(c, t0 + 32s); - // the ring (4 entries) still knows a, b, c; one more distinct peer than it - // holds overwrites the OLDEST slot (a, noted first) - not the refreshed one - // in time order, but the ring is a ring: it rolls by slot, which is what a - // bounded, allocation-free memory affords. Pin that it keeps the newest. ring.note(prefix(0xD4), t0 + 33s); + // the ring (4 entries) is full: a fifth peer overwrites the OLDEST EVICTION + // (b at t0+29 s), not the oldest slot (a, refreshed to t0+30 s) ring.note(prefix(0xE5), t0 + 34s); - if (ring.lastEviction(a)) { - std::printf("FAIL: the oldest slot (a) was not overwritten by the fifth peer\n"); + if (ring.lastEviction(b)) { + std::printf("FAIL: the oldest eviction (b) was not the one overwritten\n"); ok = false; } - for (uint8_t tag : {uint8_t{0xB2}, uint8_t{0xC3}, uint8_t{0xD4}, uint8_t{0xE5}}) { + for (uint8_t tag : {uint8_t{0xA1}, uint8_t{0xC3}, uint8_t{0xD4}, uint8_t{0xE5}}) { if (!ring.lastEviction(prefix(tag))) { - std::printf("FAIL: peer %02x forgotten while the ring had room for it\n", tag); + std::printf("FAIL: peer %02x forgotten while a more recent eviction was kept\n", tag); ok = false; } } @@ -120,6 +127,17 @@ int main() { std::printf("FAIL: capacity %zu\n", Ring::capacity()); ok = false; } + // a ring of one entry still works (the Participant derives at least 2; this + // pins that N=1 is not a special case) + { + rtps::RecentEvictions<1> one; + one.note(a, t0); + one.note(b, t0 + 1s); + if (one.lastEviction(a) || !one.lastEviction(b)) { + std::printf("FAIL: a one-entry ring does not keep the newest eviction\n"); + ok = false; + } + } if (!ok) { return 1; From ebb2fafa38e38aca438c5d04a4dadd94c478eae0 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sat, 14 Nov 2026 15:50:30 -0600 Subject: [PATCH 5/6] test(rtps): the eviction case proves the crowd was complete; the workers' own stack margin; floor 1024 Review of #907: the first eviction does not prove the crowd is up (leftovers of earlier cases fill the pool too), and the eviction count during settling was printed, not asserted - a run with the publisher starting mid-crowd still passed silently. Now the case waits for at least 8 evictions since the crowd launched (28 against 20 usable slots) and records that as pool_full_crowd_complete, and requires the publisher's samples within 40 s (CI: 14 s) so a slow conveyor cannot pass. The status line adds stack_min_worker= (the receive workers alone: they run user callbacks on the engine's deepest path and are the task that overflowed) beside the global minimum, and the device_stack_margin floor is 1024 bytes: one formatted log is about 500 bytes of buffer plus frames. First measured run: 1748 bytes (rtps_reply_hold), 2108 (rtps_protocol), the workers above that at 8192 - under 60 bytes at the old 6144. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/interop/README.md | 4 +- .../rtps/interop/qemu/main/rtps_qemu.cpp | 18 +++++-- components/rtps/interop/run_qemu_interop.sh | 48 ++++++++++++------- 3 files changed, 45 insertions(+), 25 deletions(-) diff --git a/components/rtps/interop/README.md b/components/rtps/interop/README.md index 5730a04a2f..4ddd52cedf 100644 --- a/components/rtps/interop/README.md +++ b/components/rtps/interop/README.md @@ -87,7 +87,7 @@ cd .. && ./run_qemu.sh | many_participants_late_joiner | twelve unrelated participants first, the needed one last, against the pool raised to 24 by `CONFIG_RTPS_LIMIT_SPDP_MAX_NUMBER_FOUND_PARTICIPANTS` | | ros2_pub->device_sub_frag_30k | 30 KB samples reassembled from DATA_FRAG over lwIP | | participant_pool_overflow_recovers | 28 participants against a pool of 24 (and proxy pools of 20), then all leave: discovery keeps going, every one is forgotten after the capped lease, the next publisher is received | -| pool_full_evicts_unused_for_late_joiner | the same 28 against 24, but they STAY, and the publisher the device needs joins last: it can only get in by the eviction of a participant none of the device's endpoints match (`RTPS_SPDP_EVICT_UNUSED_PARTICIPANTS`, oldest first, each logged). The crowd is complete before the publisher starts, so its rejected members keep re-announcing: a peer evicted lately gets nothing evicted for it (`SPDP_EVICT_READMIT_HOLDOFF_MS`) and the one eviction per period is budgeted per kind (former evictees / never-evicted peers), else the crowd took turns displacing each other ahead of the publisher (0 samples in 90 s, 31 evictions, once); its samples must arrive | +| pool_full_evicts_unused_for_late_joiner | the same 28 against 24, but they STAY, and the publisher the device needs joins last: it can only get in by the eviction of a participant none of the device's endpoints match (`RTPS_SPDP_EVICT_UNUSED_PARTICIPANTS`, oldest first, each logged). The crowd is complete before the publisher starts (`pool_full_crowd_complete`: at least 8 evictions since its launch, else that result fails and the case is known not to have been exercised), so its rejected members keep re-announcing: a peer evicted lately gets nothing evicted for it (`SPDP_EVICT_READMIT_HOLDOFF_MS`) and the one eviction per period is budgeted per kind (former evictees / never-evicted peers), else the crowd took turns displacing each other ahead of the publisher (0 samples in 90 s, 31 evictions, once); its samples must arrive within 40 s | | ros2_client->device_service | the typed service server, FastDDS and CycloneDDS: the embedded build answering the inline-QoS form and the in-payload `{guid, seq}` form | | netem_loss_service_fastdds, netem_loss_service_cyclone | 15 % loss + 10 ms jitter towards the device and ~14 % loss on the way back (an ingress drop on the TAP): one `ros2 service call` per RMW, which sends a single request and waits - a lost request or reply is repaired by the reliable writers on each side, not retried by the client | | espp_host_pub->device_sub, device_pub->espp_host_sub, espp_host_frag_30k->device_sub | the host engine against the embedded one, including its DATA_FRAG path | @@ -97,7 +97,7 @@ cd .. && ./run_qemu.sh | netem_reorder_best_effort, netem_duplicate_best_effort | the same against the best-effort reader: samples may be lost, but none arrives twice or out of order (RTPS 2.5 8.4.12.1, `rtps_best_effort_order` on the host) | | netem_delay_discovery | 300 ms (+-50) delay from before discovery: a ROS 2 publisher is still discovered, matched and delivered over a 600 ms round trip | | netem_loss_device_pub | 15 % loss towards the device: the device's reliable writer repairs for the host subscriber against lost ACKNACKs | -| device_heap_stable, device_no_crash, device_stack_margin | free heap at the end within 96 KB of the start (two buffers grow once to the largest sample, 30 KB each); no panic / abort / assert; the smallest stack high-water mark over the engine's tasks (`stack_min=` / `stack_min_task=` in the status line: the rtps_* tasks and the action servers' exec_* workers, since boot) is at least 512 bytes - a receive worker once overflowed on the eviction path with less | +| device_heap_stable, device_no_crash, device_stack_margin | free heap at the end within 96 KB of the start (two buffers grow once to the largest sample, 30 KB each); no panic / abort / assert; the smallest stack high-water mark over the engine's tasks (`stack_min=` / `stack_min_task=` in the status line: the rtps_* tasks and the action servers' exec_* workers, since boot) is at least 1024 bytes (one formatted log is about 500 bytes of buffer plus frames); `stack_min_worker=` is the same over the receive workers alone, the tasks that run user callbacks - one overflowed on the eviction path once with a few hundred bytes of margin | The **soak** suite (`./run_qemu.sh soak`, the second CI job on the same firmware build) runs 20 cycles of churn instead: each cycle six ROS 2 diff --git a/components/rtps/interop/qemu/main/rtps_qemu.cpp b/components/rtps/interop/qemu/main/rtps_qemu.cpp index bb94ad97dc..75e3c0ddb3 100644 --- a/components/rtps/interop/qemu/main/rtps_qemu.cpp +++ b/components/rtps/interop/qemu/main/rtps_qemu.cpp @@ -16,10 +16,14 @@ // RTPSTEST status up= tx= rx= be_rx= big_rx= heap= min_heap= // int= int_min= int_largest= psram= // stack_min= stack_min_task= +// stack_min_worker= // stack_min: the smallest stack high-water mark (bytes never used) over the -// engine's tasks (rtps_* and the action servers' exec_* workers) since boot; -// the harness fails device_stack_margin below 512 (rtps_worker_0 overflowed -// once on the eviction path with a few hundred bytes of margin before). +// engine's tasks (rtps_* and the action servers' exec_* workers) since boot, +// and the task; stack_min_worker: the same over the receive workers alone +// (rtps_worker_*: they run every reader and matched callback on top of the +// engine's deepest path, and rtps_worker_0 overflowed once on the eviction +// path with a few hundred bytes of margin). The harness fails +// device_stack_margin below 1024 bytes. // every 2 s, for the soak and memory checks // RTPSTEST mem sizeof domain= participant= stateful_writer= stateless_writer= // stateful_reader= stateless_reader= facade= @@ -330,6 +334,7 @@ extern "C" void app_main(void) { // a thin margin is a crash waiting for a slightly deeper call. std::vector tasks; uint32_t stack_min = UINT32_MAX; + uint32_t stack_min_worker = UINT32_MAX; std::string stack_min_task = "none"; const auto sample_stacks = [&]() { const auto count = uxTaskGetNumberOfTasks(); @@ -345,6 +350,9 @@ extern "C" void app_main(void) { stack_min = margin; stack_min_task = std::string{name}; } + if (name.starts_with("rtps_worker") && margin < stack_min_worker) { + stack_min_worker = margin; + } } }; @@ -358,7 +366,7 @@ extern "C" void app_main(void) { sample_stacks(); logger.info("RTPSTEST status up={} tx={} rx={} be_rx={} big_rx={} pub_matches={} " "sub_matches={} heap={} min_heap={} int={} int_min={} int_largest={} psram={} " - "stack_min={} stack_min_task={}", + "stack_min={} stack_min_task={} stack_min_worker={}", up, tx_count.load(), rx_count.load(), be_rx_count.load(), big_rx_count.load(), pub_matches.load(), sub_matches.load(), heap_caps_get_free_size(MALLOC_CAP_DEFAULT), heap_caps_get_minimum_free_size(MALLOC_CAP_DEFAULT), @@ -366,6 +374,6 @@ extern "C" void app_main(void) { heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL), heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL), heap_caps_get_free_size(MALLOC_CAP_SPIRAM), stack_min == UINT32_MAX ? 0 : stack_min, - stack_min_task); + stack_min_task, stack_min_worker == UINT32_MAX ? 0 : stack_min_worker); } } diff --git a/components/rtps/interop/run_qemu_interop.sh b/components/rtps/interop/run_qemu_interop.sh index 7aca88dbf3..b0001c6ba2 100755 --- a/components/rtps/interop/run_qemu_interop.sh +++ b/components/rtps/interop/run_qemu_interop.sh @@ -308,27 +308,35 @@ for i in $(seq 1 28); do crowd+=("$!") done m0=$(mark) +# The case must meet a domain that STAYS bigger than the pool - the crowd's +# rejected members re-announce every period and would take turns displacing +# each other - not a pool that merely filled. A run in which the publisher +# started while the crowd was still coming up passed trivially; one in which +# the crowd was complete starved the publisher for 90 s (31 evictions) before +# the hold-off for re-announcing evictees existed. The first eviction alone +# does not prove the crowd is up (leftovers of the previous cases can fill the +# pool): 28 against 20 usable slots means at least 8 of the crowd had to be +# let in by an eviction, so wait for 8 evictions since the crowd was launched, +# then a few seconds more, and record whether that was reached as its own +# result - a run that could not exercise the scenario must not pass silently. for i in $(seq 1 120); do - [ "$(count_since "$m0" "forgot an unused participant")" -ge 1 ] && break + [ "$(count_since "$m0" "forgot an unused participant")" -ge 8 ] && break sleep 1 done -echo " crowd up after ${i} s (first eviction seen: $([ "$i" -lt 120 ] && echo yes || echo no))" -# The first eviction says the pool is full; the rest of the crowd follows over -# the next seconds. Let all of it arrive before the publisher starts, so the -# case meets a domain that STAYS bigger than the pool - the crowd's rejected -# members re-announce every period and would take turns displacing each other -# - and not a pool that merely filled. (A run in which the publisher started -# while the crowd was still coming up passed trivially; one in which the crowd -# was complete starved the publisher for 90 s, 31 evictions, before the -# hold-off for re-announcing evictees existed.) -sleep 20 -echo " evictions while the crowd settled: $(count_since "$m0" "forgot an unused participant")" +e0=$(count_since "$m0" "forgot an unused participant") +echo " crowd complete after ${i} s: $e0 evictions since its launch" +[ "$e0" -ge 8 ]; result "pool_full_crowd_complete" $? +sleep 5 echo " device: $(grep -o 'RTPSTEST status.*' "$LOG" | tail -1)" m=$(mark) timeout 100 ros2 topic pub -r 5 /qemu_rx std_msgs/msg/String "data: 'made room for me'" > /dev/null 2>&1 & pub=$! n=0 -for i in $(seq 1 45); do +# Within 40 s: the publisher is a first-timer and has its own eviction budget +# (one per announcement period), so it is let in on its first announcement +# after that and its samples follow in seconds (CI: 6 s). A conveyor that +# admitted it only after a minute would be a regression, not a pass. +for i in $(seq 1 20); do n=$(count_since "$m" "RTPSTEST rx made room for me") [ "$n" -ge 5 ] && break sleep 2 @@ -484,13 +492,17 @@ if [ "$DEVICE_STARTED" = 1 ]; then [ -n "$FIRST_HEAP" ] && [ -n "$LAST_HEAP" ] && [ "$LAST_HEAP" -ge $((FIRST_HEAP - 98304)) ]; result "device_heap_stable" $? ! grep -qE "Guru Meditation|abort\(\)|assert failed|RTPSTEST fatal" "$LOG"; result "device_no_crash" $? # The engine tasks' stack margin (stack_min= in the status line: the smallest - # high-water mark over the rtps_* / exec_* tasks since boot, and the task). - # 512 bytes is the floor: rtps_worker_0 overflowed once on the eviction - # path with less than that, from one more formatted log in the frame. + # high-water mark over the rtps_* / exec_* tasks since boot, and the task; + # stack_min_worker= the same over the receive workers alone). 1024 bytes is + # the floor: one formatted log costs about 500 bytes of buffer plus its + # frames, and rtps_worker_0 overflowed once on the eviction path from one + # more of those with a few hundred bytes of margin. (First measured run: + # 1748 bytes, rtps_reply_hold; the workers were above 2108 at 8192.) STACK_MIN=$(grep -o " stack_min=[0-9]*" "$LOG" | tail -1 | cut -d= -f2) STACK_MIN_TASK=$(grep -o " stack_min_task=[A-Za-z0-9_]*" "$LOG" | tail -1 | cut -d= -f2) - echo "engine tasks' smallest stack margin: ${STACK_MIN:-?} bytes (${STACK_MIN_TASK:-?})" - [ -n "$STACK_MIN" ] && [ "$STACK_MIN" -ge 512 ]; result "device_stack_margin" $? + STACK_MIN_WORKER=$(grep -o " stack_min_worker=[0-9]*" "$LOG" | tail -1 | cut -d= -f2) + echo "engine tasks' smallest stack margin: ${STACK_MIN:-?} bytes (${STACK_MIN_TASK:-?}); receive workers: ${STACK_MIN_WORKER:-?} bytes" + [ -n "$STACK_MIN" ] && [ "$STACK_MIN" -ge 1024 ]; result "device_stack_margin" $? else # the memory suite on a profile that does not fit: the fatal IS the finding, # and so is a panic while the engine was being built (recorded at boot). From 1791df0de29ad03985aadd0d3136679f2a28239e Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sat, 14 Nov 2026 16:17:00 -0600 Subject: [PATCH 6/6] test(rtps): the goal-flood test terminates a goal before counting it as done The execute callback decremented the "executing" counter and then called canceled(); the test waits for the counter to reach 0 and asks get_result, which could see CANCELING instead of CANCELED (the Jazzy interop job did, once, on a commit that changed no engine code). Terminate first. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- pc/tests/rtps_action_goal_flood.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pc/tests/rtps_action_goal_flood.cpp b/pc/tests/rtps_action_goal_flood.cpp index 79bccec5b9..5d915868a3 100644 --- a/pc/tests/rtps_action_goal_flood.cpp +++ b/pc/tests/rtps_action_goal_flood.cpp @@ -79,8 +79,11 @@ bool run() { while (!h.is_canceling()) { std::this_thread::sleep_for(5ms); } - executing.fetch_sub(1); + // terminate FIRST: the test waits for this counter to reach 0 and + // then asks get_result, which must see CANCELED, not CANCELING + // (the Jazzy interop job hit that order once). h.canceled(kEmpty); + executing.fetch_sub(1); }), "add_action_server");