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..3c8c5ca531 100644 --- a/components/rtps/Kconfig +++ b/components/rtps/Kconfig @@ -318,11 +318,15 @@ 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 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). config RTPS_SPDP_EVICT_MIN_AGE_MS int "SPDP_EVICT_MIN_AGE_MS: youngest participant eviction may forget, ms (0 = profile default)" @@ -337,6 +341,24 @@ 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 (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). + endmenu menu "Tasks (advanced)" @@ -372,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/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 83e46ceb33..23bd3659af 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 @@ -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 @@ -295,6 +296,21 @@ 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, 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 +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..b063c7f11e 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, @@ -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 @@ -256,6 +257,21 @@ 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, 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 +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..976e4c90b5 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 @@ -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 @@ -292,6 +293,21 @@ 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, 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 +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..27b5f398f0 --- /dev/null +++ b/components/rtps/include/rtps/discovery/RecentEvictions.hpp @@ -0,0 +1,140 @@ +/* +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 +#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 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); +//! - 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; + 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 //!< its budget (first-timer or former evictee) was spent this period + }; + + //! Remember that `prefix` was evicted at `now` (refreshes an existing entry, + //! 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[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. + std::optional lastEviction(const GuidPrefix_t &prefix) const { + const auto *entry = find(prefix); + return entry != nullptr ? std::optional{entry->at} : std::nullopt; + } + + //! 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 spent(lastForFreshAt, now, cooldown) ? Gate::Cooldown : Gate::Proceed; + } + if (now - *evictedAt < holdoff) { + return Gate::HeldOff; + } + return spent(lastForKnownAt, now, cooldown) ? Gate::Cooldown : 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{}; + + 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; + }); + return it != m_entries.end() ? &*it : nullptr; + } + Entry *find(const GuidPrefix_t &prefix) { + return const_cast(static_cast(*this).find(prefix)); + } +}; + +} // namespace rtps diff --git a/components/rtps/include/rtps/entities/Participant.hpp b/components/rtps/include/rtps/entities/Participant.hpp index 698964adbf..7b2c8f2db1 100644 --- a/components/rtps/include/rtps/entities/Participant.hpp +++ b/components/rtps/include/rtps/entities/Participant.hpp @@ -29,11 +29,13 @@ 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" #include "rtps/messages/MessageReceiver.hpp" +#include #include #include #include @@ -143,13 +145,19 @@ 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; 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. + bool evictUnusedRemoteParticipant(const GuidPrefix_t &newcomer, GuidPrefix_t &evicted, + const char *reason); bool hasReaderWithMulticastLocator(const std::array &address); @@ -169,7 +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{}; + 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 9858dcf30c..4ddd52cedf 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, 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 (`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 | 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 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 6873f434b7..75e3c0ddb3 100644 --- a/components/rtps/interop/qemu/main/rtps_qemu.cpp +++ b/components/rtps/interop/qemu/main/rtps_qemu.cpp @@ -15,6 +15,15 @@ // 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_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, +// 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= @@ -36,11 +45,14 @@ #include #include #include +#include #include #include #include #include +#include +#include #include "qemu.hpp" @@ -298,7 +310,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 +327,35 @@ 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; + uint32_t stack_min_worker = 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}; + } + if (name.starts_with("rtps_worker") && margin < stack_min_worker) { + stack_min_worker = margin; + } + } + }; + // 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 +363,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={} 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), 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, stack_min_worker == UINT32_MAX ? 0 : stack_min_worker); } } 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 7072145721..b0001c6ba2 100755 --- a/components/rtps/interop/run_qemu_interop.sh +++ b/components/rtps/interop/run_qemu_interop.sh @@ -308,18 +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))" -sleep 10 +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 @@ -474,6 +491,18 @@ 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; + # 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) + 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). 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..75b7cc7ab7 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; } @@ -679,19 +680,43 @@ bool Participant::evictUnusedRemoteParticipant(GuidPrefix_t &evicted, const char // 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); 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); 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_lastFreshEvictionTimestamp, + std::chrono::milliseconds(Config::SPDP_RESEND_PERIOD_MS), + std::chrono::milliseconds(Config::SPDP_EVICT_READMIT_HOLDOFF_MS))) { + case Gate::HeldOff: + // 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; + case Gate::Proceed: + 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(); @@ -732,7 +757,9 @@ bool Participant::evictUnusedRemoteParticipant(GuidPrefix_t &evicted, const char unsigned int inPool = 0; { std::lock_guard lock(m_mutex); - m_lastEvictionTimestamp = std::chrono::steady_clock::now(); + 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_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"); diff --git a/pc/tests/rtps_recent_evictions.cpp b/pc/tests/rtps_recent_evictions.cpp new file mode 100644 index 0000000000..7b8a6a2b52 --- /dev/null +++ b/pc/tests/rtps_recent_evictions.cpp @@ -0,0 +1,147 @@ +// 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; 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 + +#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); + + // 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, 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 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, never, never, cooldown, holdoff), Gate::HeldOff, + "a one second after") && + ok; + 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, 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, 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, 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 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, never, never, cooldown, holdoff), Gate::HeldOff, + "a held off again") && + ok; + ring.note(b, t0 + 29s); // noted later but with an OLDER eviction time than a's refresh + ring.note(c, t0 + 32s); + 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(b)) { + std::printf("FAIL: the oldest eviction (b) was not the one overwritten\n"); + ok = false; + } + 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 a more recent eviction was kept\n", tag); + ok = false; + } + } + if (Ring::capacity() != 4) { + 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; + } + std::printf("PASS\n"); + return 0; +}