From 77caccb8c05060c9c9cb88e33c4e05b0acc769d6 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 17 Nov 2026 10:53:34 -0600 Subject: [PATCH 01/11] fix(rtps): a peer that reboots within its lease is rediscovered at once A board's GUID prefix is MAC-based, so one that reboots within its lease comes back as the participant its peers still hold, with every writer numbering from 1 again. Best-effort readers drop a sequence number below the next they expect (RTPS 2.5 8.4.12.1) - the SPDP reader included - so the restarted board's announcements and samples were ignored until the lease sweep forgot the old incarnation (5 s for an ESP peer, 100 s for a host one). #900 only covered a stale announcement after a participant's own dispose. - GUID prefix bytes 10-11 are a per-boot incarnation (Domain::guidIncarnation, esp_random once per boot) instead of a constant: a rebooted board is a new participant to every stack, as RTPS requires. - The previous boot's incarnation survives a software reset in RTC memory (Domain::previousGuidIncarnation); the SPDP agent disposes that participant as its writer's first change (inline-QoS key hash + status info, GUID in the payload), so peers that still hold it drop it at once. The receiver honours such a dispose as the participant's own when the prefixes agree in bytes 0-9 and carry this engine's vendor id (other vendors use bytes 10-11 differently: Fast DDS keeps its in-process participant id there), and remembers it as newer than anything the old incarnation can still announce. - The SPDP reader is exempt from the ordering filter; an announcement from a known participant numbered at most half of its highest is a restart (SPDPAgent::isRestart): the participant is forgotten and rediscovered from that announcement (parsed again - the parser stops at the GUID of a known one). A single reordered or duplicated announcement never qualifies. - pc/tests/rtps_participant_restart.cpp drives all of it with hand-crafted datagrams; the QEMU firmware reboots on a "RESTART" sample and logs its incarnation, the CI defaults give it a 30 s lease, and the harness gains the restart cases against the ROS 2 subscriber/publisher (both rmws) and the espp host engine. Host suite 62/62; QEMU firmware builds with the CI defaults. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/README.md | 12 + components/rtps/include/rtps/config_esp32.hpp | 8 +- .../rtps/discovery/ParticipantProxyData.hpp | 5 + .../rtps/include/rtps/discovery/SPDPAgent.hpp | 29 +- .../rtps/include/rtps/entities/Domain.hpp | 16 + .../include/rtps/entities/Participant.hpp | 10 + .../rtps/include/rtps/entities/Writer.hpp | 1 + components/rtps/interop/README.md | 2 + .../rtps/interop/qemu/main/rtps_qemu.cpp | 44 +- .../rtps/interop/qemu/sdkconfig.ci.defaults | 7 + components/rtps/interop/run_qemu_interop.sh | 91 ++++ .../src/discovery/ParticipantProxyData.cpp | 1 + components/rtps/src/discovery/SPDPAgent.cpp | 161 ++++++- components/rtps/src/entities/Domain.cpp | 80 +++- components/rtps/src/entities/Participant.cpp | 20 + .../rtps/src/entities/StatelessReader.cpp | 13 +- pc/tests/rtps_participant_restart.cpp | 416 ++++++++++++++++++ 17 files changed, 875 insertions(+), 41 deletions(-) create mode 100644 pc/tests/rtps_participant_restart.cpp diff --git a/components/rtps/README.md b/components/rtps/README.md index b06624f706..97245778ee 100644 --- a/components/rtps/README.md +++ b/components/rtps/README.md @@ -205,6 +205,18 @@ wire. The announced lease must comfortably exceed the announcement period a remote lease cap below a peer's announcement period drops that peer while it is alive. +A participant's GUID prefix on an ESP target is its MAC, the participant id, +the vendor id, the domain id and two incarnation bytes drawn once per boot +(`rtps::Domain::guidIncarnation()`), so a board that reboots is a new +participant to its peers - what RTPS requires, since every writer of the +rebooted board numbers its samples from 1 again and a peer still holding the +old incarnation would ignore them until its lease ran out. The previous +boot's incarnation survives a software reset in RTC memory and is disposed +before the first announcement, so such peers forget it at once; and a peer +that does reuse a prefix (another stack, a power-cycled board whose old +incarnation is still held) is recognised by the sequence number of its +announcements falling far below what was seen and rediscovered on the spot. + ### Per-limit capacity overrides Every capacity cap in the profile headers can be raised (or lowered) diff --git a/components/rtps/include/rtps/config_esp32.hpp b/components/rtps/include/rtps/config_esp32.hpp index b063c7f11e..233b913f31 100644 --- a/components/rtps/include/rtps/config_esp32.hpp +++ b/components/rtps/include/rtps/config_esp32.hpp @@ -60,7 +60,13 @@ const VendorId_t VENDOR_ID = {13, 37}; // Ethernet or Wi-Fi MAC (bytes 0-5) and uses this template only when neither // MAC can be read. Bytes 6-9 are always overwritten with the participant id, // VENDOR_ID and DOMAIN_ID, so two boards that both fall back share bytes 0-5 -// and 10-11 and would collide on a domain. +// and would collide on a domain. Bytes 10-11 are the boot's incarnation +// (Domain::guidIncarnation(), a nonce drawn once per boot): a board that +// reboots is a NEW participant to its peers, which is what RTPS requires - a +// peer that still held the old incarnation would otherwise ignore the +// restarted writers (their sequence numbers start at 1 again) until the lease +// ran out. The previous boot's incarnation survives a software reset in RTC +// memory and is disposed before the first announcement (SPDPAgent). const GuidPrefix_t BASE_GUID_PREFIX{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13}; // DDS domain id (the ROS_DOMAIN_ID equivalent; 0..232 with UDP). The port base diff --git a/components/rtps/include/rtps/discovery/ParticipantProxyData.hpp b/components/rtps/include/rtps/discovery/ParticipantProxyData.hpp index 50bd50969a..f98a2e111d 100644 --- a/components/rtps/include/rtps/discovery/ParticipantProxyData.hpp +++ b/components/rtps/include/rtps/discovery/ParticipantProxyData.hpp @@ -67,6 +67,11 @@ class ParticipantProxyData : public espp::BaseComponent { // When this proxy entered the remote-participant pool (eviction prefers the // oldest unused one and spares one still completing endpoint discovery). std::chrono::time_point m_discoveredTimestamp; + // The highest sequence number seen from this participant's SPDP writer. A + // later announcement numbered far below it (SPDPAgent::isRestart) means the + // peer restarted with the same GUID prefix - its writers all start again at + // 1 - and must be rediscovered, not refreshed. + SequenceNumber_t m_lastSpdpSn{0, 0}; void reset(); /// Parses the SPDP PL_CDR parameter list starting at `buffer`'s current diff --git a/components/rtps/include/rtps/discovery/SPDPAgent.hpp b/components/rtps/include/rtps/discovery/SPDPAgent.hpp index 5fc9929c3e..8dca8e5763 100644 --- a/components/rtps/include/rtps/discovery/SPDPAgent.hpp +++ b/components/rtps/include/rtps/discovery/SPDPAgent.hpp @@ -94,6 +94,9 @@ class SPDPAgent : public espp::BaseComponent { /// else GUIDPREFIX_UNKNOWN. For a dispose that carries the key in its /// payload rather than inline. static GuidPrefix_t participantPrefixInPayload(const uint8_t *data, DataSize_t size); + /// Parse the announcement in m_inputBuffer into m_proxyDataBuffer. The + /// parser stops at the GUID of a participant that is already known. + bool parseAnnouncement(); /// Participants that disposed themselves lately: the prefix, the dispose's /// sequence number and when it came. An announcement of such a prefix with /// a lower number is a delayed or duplicated copy from before the dispose @@ -112,10 +115,32 @@ class SPDPAgent : public espp::BaseComponent { size_t m_nextDisposed = 0; void rememberDispose(const GuidPrefix_t &prefix, const SequenceNumber_t &sn); bool isFromBeforeDispose(const GuidPrefix_t &prefix, const SequenceNumber_t &sn) const; - void processProxyData(); + /// `announced` is the sequence number of the announcement just received from + /// a known participant whose highest so far is `last`. A number far below + /// the highest (at most half of it) is not a reordered or duplicated + /// datagram but a peer that restarted with the same GUID prefix and numbers + /// its new SPDP writer from 1 again; such a peer is forgotten and + /// rediscovered (its SEDP and user writers restarted too). A single + /// reordered announcement (last - 1) never qualifies once a peer has + /// announced three times. + static bool isRestart(const SequenceNumber_t &announced, const SequenceNumber_t &last); + /// Whether `disposed` is an earlier incarnation of the participant whose + /// SPDP writer `writer` belongs to: same bytes 0-9 (board, participant id, + /// this engine's VENDOR_ID, domain), different incarnation bytes 10-11. + /// Such a dispose is honoured as the participant's own + /// (Domain::previousGuidIncarnation). Prefixes of other vendors never + /// qualify: their bytes 10-11 mean something else. + static bool isPreviousIncarnationOf(const GuidPrefix_t &disposed, const GuidPrefix_t &writer); + /// Dispose the participant we were in the previous boot (its prefix differs + /// from ours in the incarnation bytes only), as the first change of our + /// SPDP writer, so a peer that still holds that incarnation forgets it now + /// rather than when its lease runs out - and then discovers us. + void disposePreviousIncarnation(const GuidPrefix_t &prefix); + void processProxyData(const SequenceNumber_t &announcementSn); bool addProxiesForBuiltInEndpoints(); - void addInlineQos(CdrWriter &writer); + /// Inline QoS naming a participant instance (its key hash) + sentinel. + void addInlineQos(CdrWriter &writer, const GuidPrefix_t &prefix); void addParticipantParameters(); void endCurrentList(CdrWriter &writer); }; diff --git a/components/rtps/include/rtps/entities/Domain.hpp b/components/rtps/include/rtps/entities/Domain.hpp index 44667d86d0..b8243b668e 100644 --- a/components/rtps/include/rtps/entities/Domain.hpp +++ b/components/rtps/include/rtps/entities/Domain.hpp @@ -38,6 +38,7 @@ Author: i11 - Embedded Software, RWTH Aachen University #include "task.hpp" #include #include +#include #include namespace rtps { @@ -98,6 +99,21 @@ class Domain : public espp::BaseComponent { void stop(); Participant *createParticipant(); + + /// Bytes 10-11 of every GUID prefix generated this boot. On ESP targets a + /// nonce drawn once per boot, so a board that reboots comes back as a NEW + /// participant to every peer (RTPS requires a GUID never to be reused; a + /// peer that still holds the old incarnation would otherwise ignore the + /// restarted writers, whose sequence numbers start at 1 again, until the + /// lease ran out). Host builds return 0: their prefixes are random per + /// process already (or the configured template, for tests). + static uint16_t guidIncarnation(); + /// The previous boot's incarnation, when known: ESP targets keep it in + /// RTC memory across a software reset (not a power cycle), and the SPDP + /// agent disposes that incarnation's participant before announcing the new + /// one, so peers drop it at once. nullopt on host builds and after a + /// power-on. + static std::optional previousGuidIncarnation(); Writer *createWriter(Participant &part, const char *topicName, const char *typeName, bool reliable, bool enforceUnicast = false, const EndpointOptions &options = {}); diff --git a/components/rtps/include/rtps/entities/Participant.hpp b/components/rtps/include/rtps/entities/Participant.hpp index 7b2c8f2db1..3b838a6605 100644 --- a/components/rtps/include/rtps/entities/Participant.hpp +++ b/components/rtps/include/rtps/entities/Participant.hpp @@ -50,6 +50,13 @@ class Participant : public espp::BaseComponent { public: GuidPrefix_t m_guidPrefix; ParticipantId_t m_participantId; + /// The GUID prefix this participant had in the previous boot, when the + /// Domain could tell (ESP targets keep the prefix's incarnation bytes + /// across a software reset: Domain::generateGuidPrefix). The SPDP agent + /// disposes it before the first announcement, so peers forget the old + /// incarnation at once instead of when its lease runs out. + bool m_hasPreviousIncarnation = false; + GuidPrefix_t m_previousIncarnationPrefix{}; Ip4AddressBytes m_localIpAddress{{0, 0, 0, 0}}; /// Prefix length (CIDR bits) of the local network, used to tell which of a /// peer's announced unicast locators is reachable (see @@ -137,6 +144,9 @@ class Participant : public espp::BaseComponent { const ParticipantProxyData *findRemoteParticipant(const GuidPrefix_t &prefix); void refreshRemoteParticipantLiveliness(const GuidPrefix_t &prefix); + /// As above, and records the announcement's sequence number (the highest + /// seen is kept) for SPDPAgent's restart detection. + void refreshRemoteParticipantLiveliness(const GuidPrefix_t &prefix, const SequenceNumber_t &sn); uint32_t getRemoteParticipantCount(); MessageReceiver *getMessageReceiver(); bool checkAndResetHeartbeats(); diff --git a/components/rtps/include/rtps/entities/Writer.hpp b/components/rtps/include/rtps/entities/Writer.hpp index f0efd632bd..d9ba0bfa5d 100644 --- a/components/rtps/include/rtps/entities/Writer.hpp +++ b/components/rtps/include/rtps/entities/Writer.hpp @@ -150,6 +150,7 @@ class Writer : public espp::BaseComponent { SequenceNumber_t m_nextSequenceNumberToSend; friend class SEDPAgent; + friend class SPDPAgent; // disposePreviousIncarnation: a DATA with inline QoS virtual const CacheChange *newChange(ChangeKind_t kind, const uint8_t *data, DataSize_t size, bool inLineQoS, bool markDisposedAfterWrite, bool hasRelatedSampleIdentity = false, diff --git a/components/rtps/interop/README.md b/components/rtps/interop/README.md index 4ddd52cedf..0833e842b8 100644 --- a/components/rtps/interop/README.md +++ b/components/rtps/interop/README.md @@ -27,6 +27,7 @@ touched. | golden | wire-format bytes unchanged (see `pc/tests/rtps_golden.cpp`) | | locator_subnet | of the unicast locators a peer on several networks announces (SEDP and SPDP), the one on our subnet is kept (see `pc/tests/rtps_locator_subnet.cpp`) | | sedp_inline_qos_dispose | a peer's dispose of an endpoint (SEDP) or of its participant (SPDP) - a DATA whose inline QoS carries `PID_STATUS_INFO` + `PID_KEY_HASH`, as Fast DDS, Cyclone DDS and espp write it, in each of the three forms - unmatches the endpoint / forgets the participant at once instead of at lease expiry (see `pc/tests/rtps_sedp_inline_qos_dispose.cpp`) | +| participant_restart | a peer that restarts with the GUID prefix its peers still hold (a board rebooting within its lease; every writer numbers from 1 again) is rediscovered at once: the SPDP reader is exempt from the best-effort ordering rule, an announcement numbered far below the peer's highest (`SPDPAgent::isRestart`) forgets and rediscovers it (a single reordered or duplicated announcement does not), and a dispose from the next incarnation of the same participant (bytes 0-9 equal, incarnation bytes 10-11 differ) is honoured as its own, while one from a stranger or another participant id is still refused (see `pc/tests/rtps_participant_restart.cpp`) | | sedp_history_ring, sedp_history_overflow | the SEDP writers never overwrite a live endpoint announcement when their history is full: a sent dispose is given up first, else the announcement is refused and the endpoint creation fails loudly (the ring policy on a static ring, `pc/tests/rtps_sedp_history_ring.cpp`, a unit that links no engine object); a refused creation gives its pooled endpoint back, and an endpoint whose announcement is gone can still be deleted with its slot reused (`pc/tests/rtps_sedp_history_overflow.cpp`) | | facade_matched_counts | `RtpsParticipant::matched_writers()` / `matched_readers()` over a loopback: one remote writer counts once across two local readers on the topic, and removing the writer (which announces the SEDP dispose) brings the count to zero within a couple of seconds, not at lease expiry (`pc/tests/rtps_facade_matched_counts.cpp`) | | gap_before_data | a reliable reader applies a GAP only for sequence numbers the writer has announced (HEARTBEAT lastSN or a DATA): Fast DDS sends its SEDP readers a GAP for the next number after an endpoint deletion and then writes that number for the next announcement, which used to leave a publisher-churning peer unmatched after its first deletion (`pc/tests/rtps_gap_before_data.cpp`; the churn case is the live check) | @@ -84,6 +85,7 @@ cd .. && ./run_qemu.sh | device_boot, device_ping | the engine comes up on lwIP over the emulated OpenCores MAC | | device_pub->ros2_echo, ros2_pub->device_sub (+ best-effort pair) | delivery both ways, FastDDS and CycloneDDS | | ros2_pub->device_sub_liveliness | samples still arriving 24-34 s in, past the remote lease | +| restart_fastdds_rediscovered_by_ros2_sub, restart_cyclone_..., restart_*_device_sub_receives, restart_previous_incarnation_disposed, restart_espp_host_pub->device_sub | the device reboots (`esp_restart` on a "RESTART" sample) while a ROS 2 subscriber, a ROS 2 publisher and, in the host-engine case, an espp publisher stay up. It announces a 30 s lease for itself in `sdkconfig.ci.defaults`, so the old incarnation cannot expire during the reboot: the peers must receive the restarted publisher's first samples ("qemu 0".."qemu 9") and the rebooted device the peers' samples within seconds. The GUID prefix carries a per-boot incarnation (bytes 10-11, `Domain::guidIncarnation`); the previous one is kept in RTC memory across the reset and disposed before the first announcement (`RTPSTEST incarnation cur= prev=`), so a peer that honours the dispose drops the old participant at once rather than at lease expiry | | 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 | diff --git a/components/rtps/interop/qemu/main/rtps_qemu.cpp b/components/rtps/interop/qemu/main/rtps_qemu.cpp index 75e3c0ddb3..0ae46c04b3 100644 --- a/components/rtps/interop/qemu/main/rtps_qemu.cpp +++ b/components/rtps/interop/qemu/main/rtps_qemu.cpp @@ -7,6 +7,11 @@ // host side and asserts on the "RTPSTEST ..." lines this firmware logs: // // RTPSTEST ready ip= participant started +// RTPSTEST incarnation cur= prev= the GUID prefix incarnation of +// this boot and, after a software reset, of the +// previous one (which the engine disposes first) +// RTPSTEST restart a "RESTART" sample arrived on rt/qemu_rx: the +// device reboots (esp_restart) - the restart case // RTPSTEST pub_matched/sub_matched a writer / reader gained a remote peer // RTPSTEST tx reliable publisher sent "qemu " // RTPSTEST rx reliable subscriber received @@ -51,6 +56,7 @@ #include #include +#include #include #include @@ -205,17 +211,24 @@ extern "C" void app_main(void) { .type_name = type_name, .reliability = Reliability::RELIABLE, }); - espp::Subscriber subscriber(participant, { - .topic = "rt/qemu_rx", - .type_name = type_name, - .reliability = Reliability::RELIABLE, - .on_message = - [&](const StringMsg &msg) { - rx_count++; - logger.info("RTPSTEST rx {}", - msg.data); - }, - }); + espp::Subscriber subscriber( + participant, { + .topic = "rt/qemu_rx", + .type_name = type_name, + .reliability = Reliability::RELIABLE, + .on_message = + [&](const StringMsg &msg) { + rx_count++; + logger.info("RTPSTEST rx {}", msg.data); + if (msg.data == "RESTART") { + // the restart case: reboot + // like a board would + logger.info("RTPSTEST restart"); + std::this_thread::sleep_for(100ms); // let the log out + esp_restart(); + } + }, + }); espp::Publisher be_publisher(participant, { .topic = "rt/qemu_be_tx", .type_name = type_name, @@ -326,6 +339,15 @@ extern "C" void app_main(void) { }); logger.info("RTPSTEST ready ip={}", interface_address); + { + // The prefix incarnation (bytes 10-11 of every GUID prefix this boot) and + // the previous boot's, kept across a software reset: the engine disposed + // that incarnation before its first announcement, so peers that still held + // it (a reboot within the lease) forgot it at once. + const auto prev = rtps::Domain::previousGuidIncarnation(); + logger.info("RTPSTEST incarnation cur={:04x} prev={}", rtps::Domain::guidIncarnation(), + prev ? fmt::format("{:04x}", *prev) : std::string{"none"}); + } // 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 diff --git a/components/rtps/interop/qemu/sdkconfig.ci.defaults b/components/rtps/interop/qemu/sdkconfig.ci.defaults index 7b96fd2214..0415ef91a7 100644 --- a/components/rtps/interop/qemu/sdkconfig.ci.defaults +++ b/components/rtps/interop/qemu/sdkconfig.ci.defaults @@ -19,6 +19,13 @@ CONFIG_RTPS_LIMIT_SPDP_MAX_NUMBER_FOUND_PARTICIPANTS=24 CONFIG_RTPS_LIMIT_NUM_WRITER_PROXIES_PER_READER=20 CONFIG_RTPS_LIMIT_NUM_READER_PROXIES_PER_WRITER=20 +# The device announces a 30 s lease for itself (the embedded profile's 5 s +# would expire during the restart case's reboot and hide what it tests: that +# a peer still holding the device's previous incarnation drops it on the +# dispose the restarted device sends, and discovers the new one, well before +# the old lease runs out). +CONFIG_RTPS_SPDP_DEFAULT_REMOTE_LEASE_DURATION_S=30 + # Every ros2 CLI invocation the harness makes is a participant that announces # a 20 s lease (FastDDS) and then exits; left to the announced lease, the dead # ones pile up in the pool across cases. Cap what the device honours (the diff --git a/components/rtps/interop/run_qemu_interop.sh b/components/rtps/interop/run_qemu_interop.sh index b0001c6ba2..5ff58c650d 100755 --- a/components/rtps/interop/run_qemu_interop.sh +++ b/components/rtps/interop/run_qemu_interop.sh @@ -181,6 +181,70 @@ source "/opt/ros/${ROS_DISTRO:-jazzy}/setup.bash" export ROS_DOMAIN_ID=0 # matches the engine's Config::DOMAIN_ID run_matrix() { +# The device reboots (esp_restart on a "RESTART" sample, see rtps_qemu.cpp) +# while a ROS 2 subscriber and a ROS 2 publisher of the current rmw stay up. +# Its GUID prefix is MAC-based, so before the fix it came back as the +# participant the peers still held (and every writer numbered from 1 again): +# the peers' best-effort SPDP readers dropped its announcements, their user +# readers dropped its samples, and nothing moved until the old lease (30 s in +# sdkconfig.ci.defaults, so a reboot cannot hide behind it) ran out. Now the +# prefix carries a per-boot incarnation (bytes 10-11) and the device disposes +# the previous incarnation before announcing, so the peers forget it at once +# and discover the new one; the device's own proxies are fresh anyway. +# Results: restart__rediscovered_by_ros2_sub (the ROS 2 subscriber +# receives the restarted publisher's first samples, "qemu 0".."qemu 9", well +# inside the old lease), restart__device_sub_receives (the ROS 2 +# publisher's samples reach the rebooted device), and +# restart_previous_incarnation_disposed (the firmware found the previous +# incarnation in RTC memory and disposed it; once, FastDDS pass). +device_restart_case() { # prefix log-tag + local p="$1" t="$2" m rc=0 n i + timeout 90 ros2 topic echo /qemu_tx std_msgs/msg/String > "/tmp/${t}_restart_echo.log" 2>&1 & + local echo_pid=$! + timeout 90 ros2 topic pub -r 5 /qemu_rx std_msgs/msg/String "data: 'across restart'" > /dev/null 2>&1 & + local pub=$! + sleep 10 # both matched and flowing + m=$(mark) + local before_rx; before_rx=$(count_since "$m" "RTPSTEST rx across restart") + # published once the device's subscriber is matched (-w 1), then exits: a + # single RESTART, the rebooted device must not get it again + timeout 20 ros2 topic pub --once -w 1 /qemu_rx std_msgs/msg/String "data: 'RESTART'" > /dev/null 2>&1 + if ! wait_for_marker_since "$m" "RTPSTEST restart" 15; then + echo " the device did not take the RESTART"; rc=1 + fi + local boot; boot=$(mark) + if [ $rc -eq 0 ] && ! wait_for_marker_since "$boot" "RTPSTEST ready" 60; then + echo " the device did not come back"; rc=1 + fi + if [ $rc -eq 0 ]; then + since "$boot" | grep -o "RTPSTEST incarnation.*" | head -1 | sed 's/^/ /' + # the restarted publisher counts from 0 again: its first samples at the ROS 2 + # subscriber are the proof it was rediscovered (the old lease is 30 s) + local t0 n0=0; t0=$(date +%s) + for i in $(seq 1 25); do + n0=$(grep -c -E '^data: qemu [0-9]$' "/tmp/${t}_restart_echo.log") + [ "$n0" -ge 3 ] && break + sleep 1 + done + echo " ROS 2 subscriber got $n0 of the restarted publisher's first samples after $(( $(date +%s) - t0 )) s" + [ "$n0" -ge 3 ] || rc=1 + n=$(count_since "$boot" "RTPSTEST rx across restart"); echo " rebooted device received $n from the ROS 2 publisher" + [ "$n" -ge 5 ] || rc=1 + if [ "$p" = "" ] || [ "$t" = fastdds ]; then + since "$boot" | grep -q "RTPSTEST incarnation cur=[0-9a-f]* prev=[0-9a-f]" + result "restart_previous_incarnation_disposed" $? + fi + fi + stop_pids $echo_pid $pub + result "restart_${t}_rediscovered_by_ros2_sub" $rc + [ $rc -eq 0 ] && [ "${n:-0}" -ge 5 ]; result "restart_${t}_device_sub_receives" $? +} +wait_for_marker_since() { # mark marker timeout_s + local i + for i in $(seq 1 "$3"); do [ "$(count_since "$1" "$2")" -ge 1 ] && return 0; sleep 1; done + return 1 +} + # --- the ROS 2 cases, run once per rmw ----------------------------------------------- ros2_cases() { # prefix log-tag local p="$1" t="$2" m @@ -231,6 +295,10 @@ ros2_cases() { # prefix log-tag tail -2 "/tmp/${t}_srv.log"; result "${p}ros2_client->device_service" $rc settle + note "${p}the device restarts within its lease: the ROS 2 peers drop the old incarnation and talk to the new one" + device_restart_case "${p}" "${t}" + settle + note "${p}twelve other participants on the domain, then the publisher the device needs joins last" local crowd=() i for i in $(seq 1 12); do @@ -362,6 +430,29 @@ note "device publisher -> espp host subscriber (reliable, /qemu_tx)" rc=$?; tail -2 /tmp/hostsub.log; result "device_pub->espp_host_sub" $rc settle +note "the device restarts while the espp host publisher runs: the rebooted device receives again at once" +# The host engine keeps the device's previous incarnation until its dispose +# arrives (the espp SPDP reader lets a restarted peer through; SPDPAgent +# forgets it on the dispose or on the restart it detects); the host publisher's +# samples must reach the rebooted device within a few seconds of its boot. +m=$(mark) +"$BIN"/rtps_interop_pub rt/qemu_rx std_msgs::msg::dds_::String_ 1 400 200 $HOST_IP > /tmp/hostpub_restart.log 2>&1 & +pub=$!; sleep 10 +timeout 20 ros2 topic pub --once -w 1 /qemu_rx std_msgs/msg/String "data: 'RESTART'" > /dev/null 2>&1 +rc=0 +wait_for_marker_since "$m" "RTPSTEST restart" 15 || rc=1 +boot=$(mark) +[ $rc -eq 0 ] && { wait_for_marker_since "$boot" "RTPSTEST ready" 60 || rc=1; } +if [ $rc -eq 0 ]; then + t0=$(date +%s); n=0 + for i in $(seq 1 25); do n=$(count_since "$boot" "RTPSTEST rx espp interop"); [ "$n" -ge 5 ] && break; sleep 1; done + echo " rebooted device received $n from the espp host publisher after $(( $(date +%s) - t0 )) s" + [ "$n" -ge 5 ] || rc=1 +fi +stop_pids $pub +result "restart_espp_host_pub->device_sub" $rc +settle + note "espp host publisher -> device subscriber, 30 KB samples as DATA_FRAG (1400-byte fragments, /qemu_big)" # The ROS 2 peers send a 30 KB sample as one IP-fragmented UDP datagram (lwIP # reassembly); the host engine with a fragment size sends RTPS DATA_FRAG diff --git a/components/rtps/src/discovery/ParticipantProxyData.cpp b/components/rtps/src/discovery/ParticipantProxyData.cpp index 746fd061b1..e5fe9c1add 100644 --- a/components/rtps/src/discovery/ParticipantProxyData.cpp +++ b/components/rtps/src/discovery/ParticipantProxyData.cpp @@ -50,6 +50,7 @@ void ParticipantProxyData::reset() { m_guid = Guid_t{GUIDPREFIX_UNKNOWN, ENTITYID_UNKNOWN}; m_manualLivelinessCount = Count_t{1}; m_expectsInlineQos = false; + m_lastSpdpSn = SequenceNumber_t{0, 0}; onAliveSignal(); onDiscovered(); for (int i = 0; i < Config::SPDP_MAX_NUM_LOCATORS; ++i) { diff --git a/components/rtps/src/discovery/SPDPAgent.cpp b/components/rtps/src/discovery/SPDPAgent.cpp index 82e9538704..af99f5ff0b 100644 --- a/components/rtps/src/discovery/SPDPAgent.cpp +++ b/components/rtps/src/discovery/SPDPAgent.cpp @@ -36,6 +36,7 @@ Author: i11 - Embedded Software, RWTH Aachen University #include #include +#include #include #include @@ -52,9 +53,82 @@ void SPDPAgent::init(Participant &participant, BuiltInEndpoints &endpoints) { m_buildInEndpoints.spdpReader->registerCallback(receiveCallback, this); addParticipantParameters(); + if (participant.m_hasPreviousIncarnation) { + disposePreviousIncarnation(participant.m_previousIncarnationPrefix); + } initialized = true; } +void SPDPAgent::disposePreviousIncarnation(const GuidPrefix_t &prefix) { + // The form Fast DDS, Cyclone DDS and this engine's receiver all understand + // (handleSPDPPackage below): a DATA whose inline QoS carries the key hash of + // the disposed participant and PID_STATUS_INFO disposed|unregistered, with + // a payload that names the participant GUID for a peer that reads the key + // from the payload. Queued before the first announcement, so it goes out + // first (the stateless writer sends in sequence-number order). + std::array buffer{}; + CdrSink sink{asWritableBytes(buffer.data(), buffer.size())}; + CdrWriter writer(sink); + // inline QoS + writer.write(ParameterId::PID_KEY_HASH); + writer.write(16); + writeBytes(writer, prefix.id.data(), sizeof(GuidPrefix_t::id)); + writeBytes(writer, ENTITYID_BUILD_IN_PARTICIPANT.entityKey.data(), sizeof(EntityId_t::entityKey)); + writer.write(static_cast(ENTITYID_BUILD_IN_PARTICIPANT.entityKind)); + writer.write(ParameterId::PID_STATUS_INFO); + writer.write(4); + writer.write(0); + writer.write(0); + writer.write(0); + writer.write(3); // disposed | unregistered, as Fast DDS writes it + endCurrentList(writer); + // payload + writeBytes(writer, rtps::SMElement::SCHEME_PL_CDR_LE.data(), + rtps::SMElement::SCHEME_PL_CDR_LE.size()); + writer.write(0); // options + writer.write(ParameterId::PID_PARTICIPANT_GUID); + writer.write(16); + writeBytes(writer, prefix.id.data(), sizeof(GuidPrefix_t::id)); + writeBytes(writer, ENTITYID_BUILD_IN_PARTICIPANT.entityKey.data(), sizeof(EntityId_t::entityKey)); + writer.write(static_cast(ENTITYID_BUILD_IN_PARTICIPANT.entityKind)); + endCurrentList(writer); + + const auto *change = m_buildInEndpoints.spdpWriter->newChange( + ChangeKind_t::ALIVE, buffer.data(), static_cast(sink.size()), + /*inLineQoS=*/true, /*markDisposedAfterWrite=*/false); + if (change == nullptr) { + logger_.warn("Could not queue the dispose of the previous incarnation {:02x}{:02x}; peers " + "that still hold it forget it when its lease runs out", + prefix.id[10], prefix.id[11]); + return; + } + logger_.info("Disposing the previous incarnation {:02x}{:02x} of this participant (now " + "{:02x}{:02x}) before the first announcement", + prefix.id[10], prefix.id[11], mp_participant->m_guidPrefix.id[10], + mp_participant->m_guidPrefix.id[11]); +} + +bool SPDPAgent::isRestart(const SequenceNumber_t &announced, const SequenceNumber_t &last) { + if (!(announced < last) || announced.high < 0) { + return false; + } + const uint64_t a = + (static_cast(static_cast(announced.high)) << 32) | announced.low; + const uint64_t l = (static_cast(static_cast(last.high)) << 32) | last.low; + return a * 2 <= l; +} + +bool SPDPAgent::isPreviousIncarnationOf(const GuidPrefix_t &disposed, const GuidPrefix_t &writer) { + // Only for prefixes in this engine's layout (MAC, participant id, VENDOR_ID + // at bytes 7-8, domain, incarnation): other stacks put something else in + // bytes 10-11 - Fast DDS its participant id within a process, so two of its + // participants in one process differ only there and must not be allowed to + // dispose each other. + return !(disposed == writer) && disposed.id[7] == Config::VENDOR_ID.vendorId[0] && + disposed.id[8] == Config::VENDOR_ID.vendorId[1] && + std::equal(disposed.id.begin(), disposed.id.begin() + 10, writer.id.begin()); +} + void SPDPAgent::start() { m_running = true; } void SPDPAgent::stop() { m_running = false; } @@ -104,20 +178,9 @@ void SPDPAgent::handleSPDPPackage(const ReaderCacheChange &cacheChange) { SPDP_LOG("Announcement from before the participant's dispose, ignored"); return; } - // The payload's endianness is selected by the encapsulation identifier - // (first two bytes); endianness doesn't matter for reading those since - // they are single bytes. - const std::endian endianness = (m_inputBuffer[0] == SMElement::SCHEME_PL_CDR_LE[0] && - m_inputBuffer[1] == SMElement::SCHEME_PL_CDR_LE[1]) - ? std::endian::little - : std::endian::big; - CdrReader buffer(asBytes(m_inputBuffer.data(), m_inputBuffer.size()), endianness); - // Skip the encapsulation identifier and options (2 + 2 bytes) - skipBytes(buffer, 4); - volatile bool success = m_proxyDataBuffer.readFromBuffer(buffer, mp_participant); - if (success) { + if (parseAnnouncement()) { // TODO In case we store the history we can free the history mutex here - processProxyData(); + processProxyData(cacheChange.sn); } else { SPDP_LOG("ParticipantProxyData deserialization failed"); } @@ -126,9 +189,12 @@ void SPDPAgent::handleSPDPPackage(const ReaderCacheChange &cacheChange) { // forget it now, with every proxy of its endpoints, instead of when its // lease runs out. The instance is named by the inline-QoS key hash; a // peer that leaves the hash out carries the GUID in the payload. - // Only the peer's own SPDP writer may dispose it, and only itself: a - // DATA from another writer, or naming another participant, is malformed - // (or hostile) and must not remove anyone. + // Only the peer's own SPDP writer may dispose it, and only itself - or a + // previous incarnation of itself (the same board, participant id, vendor + // and domain with other incarnation bytes: what a restarted peer disposes + // first, see disposePreviousIncarnation). A DATA from another writer, or + // naming another participant, is malformed (or hostile) and must not + // remove anyone. if (!(cacheChange.writerGuid.entityId == ENTITYID_SPDP_BUILTIN_PARTICIPANT_WRITER)) { return; } @@ -143,14 +209,23 @@ void SPDPAgent::handleSPDPPackage(const ReaderCacheChange &cacheChange) { if (prefix == GUIDPREFIX_UNKNOWN || prefix == mp_participant->m_guidPrefix) { return; } - if (!(prefix == cacheChange.writerGuid.prefix)) { + if (!(prefix == cacheChange.writerGuid.prefix) && + !isPreviousIncarnationOf(prefix, cacheChange.writerGuid.prefix)) { logger_.warn("Participant dispose from {:02x}{:02x}{:02x}{:02x} names another participant, " "ignored", cacheChange.writerGuid.prefix.id[0], cacheChange.writerGuid.prefix.id[1], cacheChange.writerGuid.prefix.id[2], cacheChange.writerGuid.prefix.id[3]); return; } - rememberDispose(prefix, cacheChange.sn); + if (prefix == cacheChange.writerGuid.prefix) { + rememberDispose(prefix, cacheChange.sn); + } else { + // A previous incarnation is dead: whatever it still has in flight (its + // own numbering, unrelated to the new writer's) is stale, so remember + // the dispose as newer than anything it could announce. + rememberDispose(prefix, SequenceNumber_t{std::numeric_limits::max(), + std::numeric_limits::max()}); + } if (mp_participant->findRemoteParticipant(prefix) == nullptr) { return; // never known, or already gone } @@ -161,6 +236,20 @@ void SPDPAgent::handleSPDPPackage(const ReaderCacheChange &cacheChange) { } } +bool SPDPAgent::parseAnnouncement() { + // The payload's endianness is selected by the encapsulation identifier + // (first two bytes); endianness doesn't matter for reading those since + // they are single bytes. + const std::endian endianness = (m_inputBuffer[0] == SMElement::SCHEME_PL_CDR_LE[0] && + m_inputBuffer[1] == SMElement::SCHEME_PL_CDR_LE[1]) + ? std::endian::little + : std::endian::big; + CdrReader buffer(asBytes(m_inputBuffer.data(), m_inputBuffer.size()), endianness); + // Skip the encapsulation identifier and options (2 + 2 bytes) + skipBytes(buffer, 4); + return m_proxyDataBuffer.readFromBuffer(buffer, mp_participant); +} + rtps::GuidPrefix_t SPDPAgent::participantPrefixInPayload(const uint8_t *data, DataSize_t size) { // A PL_CDR parameter list behind the 4-byte encapsulation header, in the // byte order the header selects (as the ALIVE path reads it); only @@ -225,7 +314,7 @@ bool SPDPAgent::isFromBeforeDispose(const GuidPrefix_t &prefix, const SequenceNu return false; } -void SPDPAgent::processProxyData() { +void SPDPAgent::processProxyData(const SequenceNumber_t &announcementSn) { if (m_proxyDataBuffer.m_guid.prefix.id == mp_participant->m_guidPrefix.id) { return; // Our own packet } @@ -236,10 +325,34 @@ void SPDPAgent::processProxyData() { const rtps::ParticipantProxyData *remote_part; remote_part = mp_participant->findRemoteParticipant(m_proxyDataBuffer.m_guid.prefix); if (remote_part != nullptr) { - SPDP_LOG("Not adding this participant"); - mp_participant->refreshRemoteParticipantLiveliness(m_proxyDataBuffer.m_guid.prefix); - return; // Already in our list + if (!isRestart(announcementSn, remote_part->m_lastSpdpSn)) { + SPDP_LOG("Not adding this participant"); + mp_participant->refreshRemoteParticipantLiveliness(m_proxyDataBuffer.m_guid.prefix, + announcementSn); + return; // Already in our list + } + // The peer restarted with the prefix we know it by (a board back within + // its lease, see isRestart): everything we hold of it - its builtin + // proxies, its endpoints and their proxies at our readers and writers - + // belongs to the old incarnation, whose writers' sequence numbers our + // proxies expect to continue. Forget it and discover it afresh below. + // Lock order as for a dispose: this agent's mutex, then the SEDP agent's + // and the participant's inside removeRemoteParticipant. + const auto &p = m_proxyDataBuffer.m_guid.prefix; + logger_.warn("Remote participant {:02x}{:02x}{:02x}{:02x}... restarted with the same GUID " + "prefix (SPDP sequence {} after {}): rediscovering it", + p.id[0], p.id[1], p.id[2], p.id[3], announcementSn.low, + remote_part->m_lastSpdpSn.low); + mp_participant->removeRemoteParticipant(p); + // The parser stops at the GUID of a participant it already knows (nothing + // but the lease was refreshed): now that it is forgotten, parse the + // announcement in full for its locators and builtin endpoints. + if (!parseAnnouncement()) { + SPDP_LOG("ParticipantProxyData deserialization failed"); + return; + } } + m_proxyDataBuffer.m_lastSpdpSn = announcementSn; // A newcomer without a usable metatraffic unicast locator could never be // matched (addProxiesForBuiltInEndpoints() refuses it below): check that @@ -392,10 +505,10 @@ bool SPDPAgent::addProxiesForBuiltInEndpoints() { return ok; } -void SPDPAgent::addInlineQos(CdrWriter &writer) { +void SPDPAgent::addInlineQos(CdrWriter &writer, const GuidPrefix_t &prefix) { writer.write(ParameterId::PID_KEY_HASH); writer.write(16); - writeBytes(writer, mp_participant->m_guidPrefix.id.data(), sizeof(GuidPrefix_t::id)); + writeBytes(writer, prefix.id.data(), sizeof(GuidPrefix_t::id)); writeBytes(writer, ENTITYID_BUILD_IN_PARTICIPANT.entityKey.data(), sizeof(EntityId_t::entityKey)); writer.write(static_cast(ENTITYID_BUILD_IN_PARTICIPANT.entityKind)); diff --git a/components/rtps/src/entities/Domain.cpp b/components/rtps/src/entities/Domain.cpp index 6116600c42..7ff9db774f 100644 --- a/components/rtps/src/entities/Domain.cpp +++ b/components/rtps/src/entities/Domain.cpp @@ -32,7 +32,9 @@ Author: i11 - Embedded Software, RWTH Aachen University #include #if defined(ESP_PLATFORM) +#include "esp_attr.h" #include "esp_mac.h" +#include "esp_random.h" #endif #if DOMAIN_VERBOSE && RTPS_GLOBAL_VERBOSE @@ -45,6 +47,67 @@ Author: i11 - Embedded Software, RWTH Aachen University using rtps::Domain; +namespace { +#if defined(ESP_PLATFORM) +// The GUID prefix incarnation of this boot and of the previous one. The record +// lives in RTC memory, which a software reset (esp_restart, a panic reboot, +// deep sleep) preserves and a power-on leaves with arbitrary contents: the +// magic + complement check tells the two apart. Read once, lazily, on the +// first prefix generated this boot. +struct IncarnationRecord { + uint32_t magic; + uint16_t incarnation; + uint16_t check; // ~incarnation +}; +RTC_NOINIT_ATTR IncarnationRecord s_incarnationRecord; +constexpr uint32_t kIncarnationMagic = 0x52545049; // 'RTPI' + +struct IncarnationState { + uint16_t current = 0; + bool hasPrevious = false; + uint16_t previous = 0; +}; + +const IncarnationState &incarnationState() { + static const IncarnationState state = [] { + IncarnationState s; + const bool valid = + s_incarnationRecord.magic == kIncarnationMagic && + s_incarnationRecord.check == static_cast(~s_incarnationRecord.incarnation); + if (valid) { + s.hasPrevious = true; + s.previous = s_incarnationRecord.incarnation; + } + do { + s.current = static_cast(esp_random()); + } while (s.hasPrevious && s.current == s.previous); + s_incarnationRecord = + IncarnationRecord{kIncarnationMagic, s.current, static_cast(~s.current)}; + return s; + }(); + return state; +} +#endif +} // namespace + +uint16_t Domain::guidIncarnation() { +#if defined(ESP_PLATFORM) + return incarnationState().current; +#else + return 0; +#endif +} + +std::optional Domain::previousGuidIncarnation() { +#if defined(ESP_PLATFORM) + const auto &s = incarnationState(); + if (s.hasPrevious) { + return s.previous; + } +#endif + return std::nullopt; +} + Domain::Domain(const rtps::Ip4AddressBytes &localIpAddress, const DomainConfig &config) : espp::BaseComponent("RtpsDomain", espp::Logger::Verbosity::WARN) , m_defaultTransport(&Domain::datagramJumppad, this, config.transport) @@ -368,6 +431,15 @@ rtps::Participant *Domain::createParticipant() { auto &entry = m_participants[slot]; entry.reuse(generateGuidPrefix(candidate), candidate, m_localIpAddress, m_config.local_prefix_length); + if (const auto previous = previousGuidIncarnation(); previous.has_value()) { + // The same board, participant id, vendor and domain with the previous + // boot's incarnation bytes: what peers still hold if we came back within + // our lease. Disposed by the SPDP agent before the first announcement. + entry.m_previousIncarnationPrefix = entry.m_guidPrefix; + entry.m_previousIncarnationPrefix.id[10] = static_cast(*previous >> 8); + entry.m_previousIncarnationPrefix.id[11] = static_cast(*previous & 0xFF); + entry.m_hasPreviousIncarnation = true; + } if (!createBuiltinWritersAndReaders(entry)) { // Pool exhaustion (see createBuiltinWritersAndReaders): the slot was never // published, so only the probed ports need unwinding for a clean failure @@ -1015,8 +1087,12 @@ rtps::GuidPrefix_t Domain::generateGuidPrefix(ParticipantId_t id) const { prefix.id[7] = Config::VENDOR_ID.vendorId[0]; prefix.id[8] = Config::VENDOR_ID.vendorId[1]; prefix.id[9] = Config::DOMAIN_ID; - prefix.id[10] = 0xA5; - prefix.id[11] = 0x5A; + // Bytes 10-11: this boot's incarnation (see guidIncarnation()). Everything + // before it is stable across boots, which is what lets the SPDP agent + // dispose the previous incarnation and peers tell the two apart. + const uint16_t incarnation = guidIncarnation(); + prefix.id[10] = static_cast(incarnation >> 8); + prefix.id[11] = static_cast(incarnation & 0xFF); return prefix; } #endif diff --git a/components/rtps/src/entities/Participant.cpp b/components/rtps/src/entities/Participant.cpp index 75b7cc7ab7..35d2325579 100644 --- a/components/rtps/src/entities/Participant.cpp +++ b/components/rtps/src/entities/Participant.cpp @@ -56,6 +56,8 @@ Participant::~Participant() { m_spdpAgent.stop(); } void Participant::reuse(const GuidPrefix_t &guidPrefix, ParticipantId_t participantId, const Ip4AddressBytes &localIpAddress, uint8_t localPrefixLength) { + m_hasPreviousIncarnation = false; + m_previousIncarnationPrefix = GuidPrefix_t{}; m_guidPrefix = guidPrefix; m_participantId = participantId; m_localIpAddress = localIpAddress; @@ -554,6 +556,24 @@ const rtps::ParticipantProxyData *Participant::findRemoteParticipant(const GuidP return m_remoteParticipants.find(thunk, &isElementToFind); } +void Participant::refreshRemoteParticipantLiveliness(const GuidPrefix_t &prefix, + const SequenceNumber_t &sn) { + std::lock_guard lock(m_mutex); + auto isElementToFind = [&](const ParticipantProxyData &proxy) { + return proxy.m_guid.prefix == prefix; + }; + auto thunk = [](void *arg, const ParticipantProxyData &value) { + return (*static_cast(arg))(value); + }; + auto remoteParticipant = m_remoteParticipants.find(thunk, &isElementToFind); + if (remoteParticipant != nullptr) { + remoteParticipant->onAliveSignal(); + if (remoteParticipant->m_lastSpdpSn < sn) { + remoteParticipant->m_lastSpdpSn = sn; + } + } +} + void Participant::refreshRemoteParticipantLiveliness(const GuidPrefix_t &prefix) { std::lock_guard lock(m_mutex); auto isElementToFind = [&](const ParticipantProxyData &proxy) { diff --git a/components/rtps/src/entities/StatelessReader.cpp b/components/rtps/src/entities/StatelessReader.cpp index 975f2390a7..887697f3b7 100644 --- a/components/rtps/src/entities/StatelessReader.cpp +++ b/components/rtps/src/entities/StatelessReader.cpp @@ -78,6 +78,17 @@ void StatelessReader::newChange(const ReaderCacheChange &cacheChange) { // reader): participant announcements come from writers that are, by // definition, not matched yet. // + // The SPDP reader is exempt from the ordering rule as well. A peer that + // restarts with the same GUID prefix (a board rebooting within its lease: + // the prefix is MAC-based on ESP targets, and other stacks do the same) + // numbers its new SPDP writer from 1 again, below what its proxy here + // expects; dropping those announcements - and the dispose it may send first + // - would keep the stale participant, with every proxy of its endpoints, + // until the lease ran out, deaf to the restarted peer the whole time. The + // SPDP agent owns that judgement instead (SPDPAgent::isRestart, and its + // dispose memory for the duplicates); a repeated announcement only + // refreshes a lease, so nothing is lost by letting it through. + // // The claim and the callbacks are one operation under m_delivery_mutex (as // in StatefulReader::newChange()): receive workers for different sockets // can hand this reader consecutive samples at once, and with the callbacks @@ -92,7 +103,7 @@ void StatelessReader::newChange(const ReaderCacheChange &cacheChange) { }; auto it = std::find_if(m_proxies.begin(), m_proxies.end(), matches_writer); if (it != m_proxies.end()) { - if (cacheChange.sn < it->expectedSN) { + if (cacheChange.sn < it->expectedSN && !isBuiltinEndpoint()) { return; // a duplicate, or older than something already delivered } it->expectedSN = cacheChange.sn; diff --git a/pc/tests/rtps_participant_restart.cpp b/pc/tests/rtps_participant_restart.cpp new file mode 100644 index 0000000000..7103c59d03 --- /dev/null +++ b/pc/tests/rtps_participant_restart.cpp @@ -0,0 +1,416 @@ +// A peer that restarts is rediscovered at once, not when its lease runs out. +// +// The GUID prefix of an embedded participant is built from the board's MAC, +// so a board that reboots within its lease comes back with a prefix its +// peers still hold - and every one of its writers numbers its samples from 1 +// again. A best-effort reader ignores a sequence number below the next it +// expects (RTPS 2.5 8.4.12.1), and the SPDP reader is one of those: the +// restarted peer's announcements were dropped too, so nothing happened until +// the lease sweep forgot the old incarnation (5 s for an ESP peer, 100 s for a +// host one), and the peer was deaf and mute to us the whole time. Three +// mechanisms close that window; this test drives all of them with hand-crafted +// datagrams fed to a real participant, as the dispose tests do: +// +// 1. Restart detection: an announcement from a known participant numbered +// far below its highest (SPDPAgent::isRestart) forgets the participant +// and rediscovers it; its writers get fresh proxies, and a best-effort +// reader receives the restarted writer's samples from 1 again. +// 2. A reordered or duplicated announcement (last - 1) is NOT a restart: +// nothing is forgotten, a sample numbered after the ones delivered still +// arrives. +// 3. Incarnation: a peer whose prefix differs only in the incarnation bytes +// (10-11) may dispose the old incarnation - the dispose is honoured as the +// participant's own, the old one goes at once, the new one is discovered. +// A dispose naming a participant from an unrelated prefix is still +// refused, and so is one from the same board but another participant id. +// +// Exits 0 on success, 1 on the first failed check. + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rtps/entities/Domain.hpp" +#include "rtps/entities/Reader.hpp" +#include "rtps/entities/Writer.hpp" +#include "rtps/messages/MessageTypes.hpp" + +namespace { + +constexpr rtps::Ip4AddressBytes kIp{127, 0, 0, 1}; +constexpr std::array kVendor{0x01, 0x0f}; // Fast DDS, as the other dispose tests + +#define CHECK(cond, msg) \ + do { \ + if (!(cond)) { \ + std::printf("FAIL: %s (line %d)\n", msg, __LINE__); \ + return false; \ + } \ + } while (0) + +void push_u16(std::vector &p, uint16_t v) { + p.push_back(static_cast(v & 0xFF)); + p.push_back(static_cast(v >> 8)); +} + +void push_u32(std::vector &p, uint32_t v) { + for (int i = 0; i < 4; ++i) { + p.push_back(static_cast((v >> (8 * i)) & 0xFF)); + } +} + +void push_entity_id(std::vector &p, const rtps::EntityId_t &id) { + p.insert(p.end(), id.entityKey.begin(), id.entityKey.end()); + p.push_back(static_cast(id.entityKind)); +} + +void push_guid(std::vector &p, const rtps::Guid_t &guid) { + p.insert(p.end(), guid.prefix.id.begin(), guid.prefix.id.end()); + push_entity_id(p, guid.entityId); +} + +void push_param(std::vector &p, rtps::SMElement::ParameterId pid, + const std::vector &value) { + push_u16(p, static_cast(pid)); + push_u16(p, static_cast(value.size())); + p.insert(p.end(), value.begin(), value.end()); +} + +void push_sentinel(std::vector &p) { + push_param(p, rtps::SMElement::ParameterId::PID_SENTINEL, {}); +} + +std::vector guid_value(const rtps::Guid_t &guid) { + std::vector v; + push_guid(v, guid); + return v; +} + +std::vector string_value(const char *s) { + std::vector v; + const auto len = static_cast(std::strlen(s) + 1); + push_u32(v, len); + v.insert(v.end(), s, s + len); + while (v.size() % 4 != 0) { + v.push_back(0); + } + return v; +} + +std::vector locator_value(uint32_t port) { + std::vector v; + push_u32(v, static_cast(rtps::LocatorKind_t::LOCATOR_KIND_UDPv4)); + push_u32(v, port); + for (int i = 0; i < 12; ++i) { + v.push_back(0); + } + v.insert(v.end(), kIp.begin(), kIp.end()); + return v; +} + +std::vector encapsulation() { + std::vector p(rtps::SMElement::SCHEME_PL_CDR_LE.begin(), + rtps::SMElement::SCHEME_PL_CDR_LE.end()); + push_u16(p, 0); + return p; +} + +std::vector spdp_payload(const rtps::GuidPrefix_t &prefix) { + using rtps::SMElement::ParameterId; + std::vector p = encapsulation(); + push_param(p, ParameterId::PID_PROTOCOL_VERSION, + {rtps::PROTOCOLVERSION.major, rtps::PROTOCOLVERSION.minor, 0, 0}); + push_param(p, ParameterId::PID_VENDORID, {kVendor[0], kVendor[1], 0, 0}); + push_param(p, ParameterId::PID_PARTICIPANT_GUID, + guid_value(rtps::Guid_t{prefix, rtps::ENTITYID_BUILD_IN_PARTICIPANT})); + push_param(p, ParameterId::PID_METATRAFFIC_UNICAST_LOCATOR, locator_value(7410)); + push_param(p, ParameterId::PID_DEFAULT_UNICAST_LOCATOR, locator_value(7411)); + { + std::vector lease; + push_u32(lease, 100); + push_u32(lease, 0); + push_param(p, ParameterId::PID_PARTICIPANT_LEASE_DURATION, lease); + } + { + std::vector set; + push_u32(set, rtps::SMElement::DISC_BIE_PARTICIPANT_ANNOUNCER | + rtps::SMElement::DISC_BIE_PARTICIPANT_DETECTOR | + rtps::SMElement::DISC_BIE_PUBLICATION_ANNOUNCER | + rtps::SMElement::DISC_BIE_PUBLICATION_DETECTOR | + rtps::SMElement::DISC_BIE_SUBSCRIPTION_ANNOUNCER | + rtps::SMElement::DISC_BIE_SUBSCRIPTION_DETECTOR); + push_param(p, ParameterId::PID_BUILTIN_ENDPOINT_SET, set); + } + push_sentinel(p); + return p; +} + +std::vector sedp_payload(const rtps::Guid_t &endpoint, const char *topic, const char *type, + bool reliable) { + using rtps::SMElement::ParameterId; + std::vector p = encapsulation(); + push_param(p, ParameterId::PID_ENDPOINT_GUID, guid_value(endpoint)); + push_param(p, ParameterId::PID_TOPIC_NAME, string_value(topic)); + push_param(p, ParameterId::PID_TYPE_NAME, string_value(type)); + { + std::vector rel; + push_u32(rel, static_cast(reliable ? rtps::ReliabilityKind_t::RELIABLE + : rtps::ReliabilityKind_t::BEST_EFFORT)); + push_u32(rel, 0); + push_u32(rel, 0); + push_param(p, ParameterId::PID_RELIABILITY, rel); + } + push_param(p, ParameterId::PID_UNICAST_LOCATOR, locator_value(7411)); + push_sentinel(p); + return p; +} + +// A DATA submessage in one RTPS message from `prefix`, with optional inline +// QoS and payload. +std::vector data_message(const rtps::GuidPrefix_t &prefix, const rtps::EntityId_t &writer, + const rtps::EntityId_t &reader, uint32_t sn, + const std::vector &inline_qos, + const std::vector &payload) { + std::vector m{ + 'R', 'T', 'P', 'S', rtps::PROTOCOLVERSION.major, rtps::PROTOCOLVERSION.minor, + kVendor[0], kVendor[1]}; + m.insert(m.end(), prefix.id.begin(), prefix.id.end()); + uint8_t flags = rtps::FLAG_LITTLE_ENDIAN; + if (!inline_qos.empty()) { + flags |= rtps::FLAG_INLINE_QOS; + } + if (!payload.empty()) { + flags |= rtps::FLAG_DATA_PAYLOAD; + } + m.push_back(static_cast(rtps::SubmessageKind::DATA)); + m.push_back(flags); + push_u16(m, static_cast(2 + 2 + 4 + 4 + 8 + inline_qos.size() + payload.size())); + push_u16(m, 0); // extraFlags + push_u16(m, 16); // octetsToInlineQos + push_entity_id(m, reader); + push_entity_id(m, writer); + push_u32(m, 0); // SequenceNumber_t.high + push_u32(m, sn); // SequenceNumber_t.low + m.insert(m.end(), inline_qos.begin(), inline_qos.end()); + m.insert(m.end(), payload.begin(), payload.end()); + return m; +} + +// Inline QoS of a participant dispose: the key hash of the disposed +// participant and STATUS_INFO disposed|unregistered, as Fast DDS writes it and +// as this engine's SPDPAgent::disposePreviousIncarnation does. +std::vector participant_dispose_qos(const rtps::GuidPrefix_t &disposed) { + using rtps::SMElement::ParameterId; + std::vector q; + push_param(q, ParameterId::PID_KEY_HASH, + guid_value(rtps::Guid_t{disposed, rtps::ENTITYID_BUILD_IN_PARTICIPANT})); + push_param(q, ParameterId::PID_STATUS_INFO, {0, 0, 0, 3}); + push_sentinel(q); + return q; +} + +// A user sample: CDR_LE encapsulation + 4 bytes of payload. +std::vector sample_payload(uint32_t value) { + std::vector p{0x00, 0x01, 0x00, 0x00}; + push_u32(p, value); + return p; +} + +void feed(rtps::Participant *part, const std::vector &message) { + part->newMessage(message.data(), static_cast(message.size())); +} + +constexpr const char *kTopic = "restart_topic"; +constexpr const char *kType = "RestartType"; + +std::atomic g_received{0}; +std::atomic g_last_value{0}; + +void on_sample(void *, const rtps::ReaderCacheChange &change) { + uint8_t buf[8] = {0}; + if (change.copyInto(buf, sizeof(buf))) { + uint32_t v = 0; + std::memcpy(&v, buf + 4, sizeof(v)); + g_last_value = v; + } + ++g_received; +} + +// A simulated peer: its SPDP writer, its SEDP publications writer and one +// user writer, each numbering its DATAs independently - like a real stack. +struct Peer { + rtps::GuidPrefix_t prefix; + uint32_t spdp_sn = 0; + uint32_t sedp_sn = 0; + uint32_t data_sn = 0; + rtps::Guid_t writer_guid() const { + return {prefix, {{0x00, 0x00, 0x01}, rtps::EntityKind_t::USER_DEFINED_WRITER_WITHOUT_KEY}}; + } + void announce(rtps::Participant *part) { + feed(part, data_message(prefix, rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_WRITER, + rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_READER, ++spdp_sn, {}, + spdp_payload(prefix))); + } + // An announcement that repeats an earlier number (a duplicated or reordered datagram). + void announce_with(rtps::Participant *part, uint32_t sn) { + feed(part, data_message(prefix, rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_WRITER, + rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_READER, sn, {}, + spdp_payload(prefix))); + } + void announce_writer(rtps::Participant *part) { + feed(part, data_message(prefix, rtps::ENTITYID_SEDP_BUILTIN_PUBLICATIONS_WRITER, + rtps::ENTITYID_SEDP_BUILTIN_PUBLICATIONS_READER, ++sedp_sn, {}, + sedp_payload(writer_guid(), kTopic, kType, false))); + } + void publish(rtps::Participant *part, uint32_t value) { + feed(part, data_message(prefix, writer_guid().entityId, rtps::ENTITYID_UNKNOWN, ++data_sn, {}, + sample_payload(value))); + } + // Dispose `disposed` from this peer's SPDP writer (the dispose a restarted + // board sends for its previous incarnation). + void dispose(rtps::Participant *part, const rtps::GuidPrefix_t &disposed) { + feed(part, data_message(prefix, rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_WRITER, + rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_READER, ++spdp_sn, + participant_dispose_qos(disposed), {})); + } + // The peer rebooted: every writer starts at 1 again. + void reboot() { spdp_sn = sedp_sn = data_sn = 0; } +}; + +bool run_checks() { + rtps::Domain domain(kIp); + rtps::Participant *part = domain.createParticipant(); + CHECK(part != nullptr, "createParticipant"); + rtps::Reader *reader = + domain.createReader(*part, kTopic, kType, /*reliable=*/false, {0, 0, 0, 0}); + CHECK(reader != nullptr, "createReader"); + reader->registerCallback(on_sample, nullptr); + + // An ESP-style prefix: MAC, participant id, this engine's vendor id, domain, + // incarnation (the layout Domain::generateGuidPrefix produces on a board). + const auto vid = rtps::Config::VENDOR_ID.vendorId; + Peer peer{{{0x24, 0x6f, 0x28, 0xaa, 0xbb, 0xcc, 0, vid[0], vid[1], 0, 0x11, 0x22}}}; + + // --- discovered, matched, delivering ------------------------------------------------- + for (int i = 0; i < 6; ++i) { + peer.announce(part); // SPDP 1..6: a peer that has been around a while + } + CHECK(part->getRemoteParticipantCount() == 1, "peer discovered"); + peer.announce_writer(part); + CHECK(reader->getProxiesCount() == 1, "peer writer matched"); + for (uint32_t v = 1; v <= 3; ++v) { + peer.publish(part, v); // DATA 1..3 + } + CHECK(g_received == 3, "three samples delivered"); + CHECK(g_last_value == 3, "the last one is sample 3"); + + // --- 2. a duplicated / reordered announcement is not a restart -------------------------- + peer.announce_with(part, 5); // 5 after 6: one datagram late + CHECK(part->getRemoteParticipantCount() == 1, "late announcement: participant kept"); + CHECK(reader->getProxiesCount() == 1, "late announcement: writer proxy kept"); + peer.publish(part, 4); // DATA 4 continues the stream + CHECK(g_received == 4, "stream continues after a late announcement"); + peer.announce_with(part, 3); // half of 6: this one IS below the restart threshold + // ... and that is a restart by the rule (3 * 2 <= 6); the peer is rediscovered + // from this announcement, so its writer must be announced again - a real + // restarted peer does exactly that. Check the proxy went, then re-announce. + CHECK(part->getRemoteParticipantCount() == 1, "restart threshold: rediscovered participant"); + CHECK(reader->getProxiesCount() == 0, "restart threshold: the old writer proxy is gone"); + peer.sedp_sn = 0; + peer.data_sn = 0; + peer.announce_writer(part); + CHECK(reader->getProxiesCount() == 1, "restart threshold: writer matched again"); + peer.publish(part, 10); + CHECK(g_received == 5 && g_last_value == 10, "restart threshold: sample 1 of the new stream"); + // bring the peer's number up again for the next case + peer.spdp_sn = 3; + for (int i = 0; i < 6; ++i) { + peer.announce(part); // 4..9 + } + for (uint32_t v = 11; v <= 13; ++v) { + peer.publish(part, v); // DATA 2..4 + } + CHECK(g_received == 8 && g_last_value == 13, "stream continues: samples 2..4"); + + // --- 1. the peer reboots with the same prefix, no dispose --------------------------------- + peer.reboot(); + peer.announce(part); // SPDP 1 after 9 + CHECK(part->getRemoteParticipantCount() == 1, "rebooted peer: still exactly one participant"); + CHECK(reader->getProxiesCount() == 0, "rebooted peer: the old writer proxy is gone"); + peer.announce_writer(part); // SEDP 1 + CHECK(reader->getProxiesCount() == 1, "rebooted peer: its writer matched again"); + for (uint32_t v = 21; v <= 23; ++v) { + peer.publish(part, v); // DATA 1..3 again - these used to be dropped + } + CHECK(g_received == 11, "rebooted peer: its samples 1..3 delivered"); + CHECK(g_last_value == 23, "rebooted peer: the last one is sample 3 of the new stream"); + + // --- 3. a new incarnation disposes the old one -------------------------------------------- + Peer next = peer; + next.reboot(); + next.prefix.id[10] = 0x33; // the incarnation bytes change, nothing else + next.prefix.id[11] = 0x44; + // a dispose from an unrelated prefix naming the peer: refused + Peer stranger{{{0x24, 0x6f, 0x28, 0x01, 0x02, 0x03, 0, vid[0], vid[1], 0, 0x11, 0x22}}}; + // ... and from another vendor's prefix that happens to differ in bytes 10-11 + // only (Fast DDS keeps its in-process participant id there): refused + Peer foreign = next; + foreign.prefix.id[7] = kVendor[0]; + foreign.prefix.id[8] = kVendor[1]; + Peer foreign_old = peer; + foreign_old.prefix.id[7] = kVendor[0]; + foreign_old.prefix.id[8] = kVendor[1]; + foreign_old.announce(part); + CHECK(part->getRemoteParticipantCount() == 2, "a foreign-vendor participant discovered"); + foreign.dispose(part, foreign_old.prefix); + CHECK(part->getRemoteParticipantCount() == 2, + "dispose across bytes 10-11 of a foreign prefix: refused"); + foreign_old.dispose(part, foreign_old.prefix); // its own: honoured, as before + CHECK(part->getRemoteParticipantCount() == 1, "a foreign participant's own dispose: honoured"); + stranger.dispose(part, peer.prefix); + CHECK(part->getRemoteParticipantCount() == 1, "dispose from a stranger: refused"); + // from the same board, another participant id: refused too + Peer sibling = next; + sibling.prefix.id[6] = 1; + sibling.dispose(part, peer.prefix); + CHECK(part->getRemoteParticipantCount() == 1, "dispose from another participant id: refused"); + CHECK(reader->getProxiesCount() == 1, "refused disposes change nothing"); + // from the next incarnation: honoured, the old one goes at once + next.dispose(part, peer.prefix); // the new SPDP writer's first change (SN 1) + CHECK(part->getRemoteParticipantCount() == 0, "dispose from the next incarnation: honoured"); + CHECK(reader->getProxiesCount() == 0, "next incarnation: the old writer proxy is gone"); + next.announce(part); // SN 2 + CHECK(part->getRemoteParticipantCount() == 1, "next incarnation discovered"); + next.announce_writer(part); + CHECK(reader->getProxiesCount() == 1, "next incarnation: its writer matched"); + for (uint32_t v = 31; v <= 33; ++v) { + next.publish(part, v); + } + CHECK(g_received == 14 && g_last_value == 33, "next incarnation: samples delivered"); + // a stale announcement of the old incarnation still in flight (a delayed + // datagram) must not bring the dead participant back next to the new one: + // the dispose is remembered as newer than anything the old one numbered + peer.announce_with(part, 2); + CHECK(part->getRemoteParticipantCount() == 1, "stale old-incarnation announcement: ignored"); + CHECK(reader->getProxiesCount() == 1, "stale old-incarnation announcement: new proxy kept"); + next.publish(part, 34); + CHECK(g_received == 15 && g_last_value == 34, "new incarnation keeps delivering"); + + domain.stop(); + return true; +} + +} // namespace + +int main() { + if (!run_checks()) { + return 1; + } + std::printf("PASS\n"); + return 0; +} From 66e9669e929976bc1fc548a5a523f71acb3d96d7 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 17 Nov 2026 11:08:41 -0600 Subject: [PATCH 02/11] test(rtps): mark the restart test's repeat-announcement helper const (cppcheck) Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- pc/tests/rtps_participant_restart.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pc/tests/rtps_participant_restart.cpp b/pc/tests/rtps_participant_restart.cpp index 7103c59d03..c64437c94c 100644 --- a/pc/tests/rtps_participant_restart.cpp +++ b/pc/tests/rtps_participant_restart.cpp @@ -257,7 +257,7 @@ struct Peer { spdp_payload(prefix))); } // An announcement that repeats an earlier number (a duplicated or reordered datagram). - void announce_with(rtps::Participant *part, uint32_t sn) { + void announce_with(rtps::Participant *part, uint32_t sn) const { feed(part, data_message(prefix, rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_WRITER, rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_READER, sn, {}, spdp_payload(prefix))); From 98d2c8089f7d9878a11f9909e6c9fe288b978db4 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 17 Nov 2026 12:05:50 -0600 Subject: [PATCH 03/11] fix(rtps): dispose the previous incarnation as that incarnation; per-Domain incarnation; review fixes Review of the first revision: - The previous-incarnation dispose was sent from the NEW prefix naming the old participant. Cyclone DDS refuses an SPDP dispose whose source prefix is not the participant it names, and Fast DDS drops a non-ALIVE change from a writer it has not matched yet, so only espp peers honoured it. It is now a raw RTPS message AS the old incarnation (its prefix in the header, its SPDP writer, its participant GUID as key hash and payload, a sequence number above anything it sent), multicast on the first three announce cycles (SPDPAgent::sendPreviousIncarnationDispose). Every stack takes a participant's own dispose, so the receive-side relaxation for same-board prefixes, the SN-max dispose memory and the Writer friend declaration go. - The SPDP reader never holds writer proxies, so its exemption from the ordering filter was dead code; reverted, prose corrected everywhere. - The incarnation is drawn per Domain (constructor), not once per process: an application that recreates its Domain is a new participant too, and the QEMU firmware can restart its participant without rebooting the chip - QEMU's emulated chip panics inside ESP-IDF's startup (esp_timer interrupt allocation) after esp_restart, which took the first CI run's device down for the rest of the matrix. - The restart verdict is decided and recorded under the participant mutex (Participant::noteRemoteParticipantAnnouncement); isRestart rejects sequence number 0 and peers seen fewer than three times. - RTC_NOINIT_ATTR falls back to .noinit DRAM on chips without RTC memory. - Harness: RESTART is published for 6 s (a one-shot publisher raced the device's matching and never got through) and the new participant ignores it for its first 20 s; the ROS 2 daemon's publisher count on the device's topic now proves the old incarnation was dropped (restart__old_incarnation_dropped); results no longer share a flag; the RTC check is named for what it checks. - Docs: the power-cycle case expires with its lease (nothing to dispose); the fallback-prefix collision note; README rows. Host suite 60/60; QEMU firmware builds with the CI defaults. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/README.md | 24 ++- components/rtps/include/rtps/config_esp32.hpp | 5 +- .../rtps/include/rtps/discovery/SPDPAgent.hpp | 53 +++-- .../rtps/include/rtps/entities/Domain.hpp | 28 ++- .../include/rtps/entities/Participant.hpp | 15 +- .../include/rtps/entities/StatelessWriter.hpp | 7 + .../rtps/include/rtps/entities/Writer.hpp | 1 - components/rtps/interop/README.md | 4 +- .../rtps/interop/qemu/main/rtps_qemu.cpp | 58 +++-- components/rtps/interop/run_qemu_interop.sh | 71 ++++--- components/rtps/src/discovery/SPDPAgent.cpp | 200 +++++++++--------- components/rtps/src/entities/Domain.cpp | 87 ++++---- components/rtps/src/entities/Participant.cpp | 20 +- .../rtps/src/entities/StatelessReader.cpp | 18 +- pc/tests/rtps_participant_restart.cpp | 92 ++++---- 15 files changed, 384 insertions(+), 299 deletions(-) diff --git a/components/rtps/README.md b/components/rtps/README.md index 97245778ee..4a387a3185 100644 --- a/components/rtps/README.md +++ b/components/rtps/README.md @@ -206,16 +206,20 @@ a remote lease cap below a peer's announcement period drops that peer while it is alive. A participant's GUID prefix on an ESP target is its MAC, the participant id, -the vendor id, the domain id and two incarnation bytes drawn once per boot -(`rtps::Domain::guidIncarnation()`), so a board that reboots is a new -participant to its peers - what RTPS requires, since every writer of the -rebooted board numbers its samples from 1 again and a peer still holding the -old incarnation would ignore them until its lease ran out. The previous -boot's incarnation survives a software reset in RTC memory and is disposed -before the first announcement, so such peers forget it at once; and a peer -that does reuse a prefix (another stack, a power-cycled board whose old -incarnation is still held) is recognised by the sequence number of its -announcements falling far below what was seen and rediscovered on the spot. +the vendor id, the domain id and two incarnation bytes drawn when the Domain +is constructed (`rtps::Domain::guidIncarnation()`), so a board that reboots - +or an application that recreates its Domain - is a new participant to its +peers: what RTPS requires, since every writer of the restarted board numbers +its samples from 1 again and a peer still holding the old incarnation would +ignore them until its lease ran out. The previous incarnation is kept in RTC +memory (`.noinit` RAM on chips without it), which survives a software reset, +and is disposed, as that incarnation, on the first announce cycles, so such +peers forget it at once (after a power-on there is nothing to dispose; the +old incarnation then expires with its lease). A peer +that does reuse a prefix across a restart - this engine's boards never do, but +a stack that derives its prefix from stable hardware identifiers would - is +recognised by the sequence number of its announcements falling far below what +it had reached, and rediscovered on the spot. ### Per-limit capacity overrides diff --git a/components/rtps/include/rtps/config_esp32.hpp b/components/rtps/include/rtps/config_esp32.hpp index 233b913f31..a1eeca37da 100644 --- a/components/rtps/include/rtps/config_esp32.hpp +++ b/components/rtps/include/rtps/config_esp32.hpp @@ -59,8 +59,9 @@ const VendorId_t VENDOR_ID = {13, 37}; // Fallback only: Domain::generateGuidPrefix() builds the prefix from the // Ethernet or Wi-Fi MAC (bytes 0-5) and uses this template only when neither // MAC can be read. Bytes 6-9 are always overwritten with the participant id, -// VENDOR_ID and DOMAIN_ID, so two boards that both fall back share bytes 0-5 -// and would collide on a domain. Bytes 10-11 are the boot's incarnation +// VENDOR_ID and DOMAIN_ID, so two boards that both fall back share bytes 0-9 +// and collide on a domain unless their incarnations differ (2^-16 odds of +// matching). Bytes 10-11 are the boot's incarnation // (Domain::guidIncarnation(), a nonce drawn once per boot): a board that // reboots is a NEW participant to its peers, which is what RTPS requires - a // peer that still held the old incarnation would otherwise ignore the diff --git a/components/rtps/include/rtps/discovery/SPDPAgent.hpp b/components/rtps/include/rtps/discovery/SPDPAgent.hpp index 8dca8e5763..f1a916737d 100644 --- a/components/rtps/include/rtps/discovery/SPDPAgent.hpp +++ b/components/rtps/include/rtps/discovery/SPDPAgent.hpp @@ -69,6 +69,24 @@ class SPDPAgent : public espp::BaseComponent { /// scheduler at SPDP_RESEND_PERIOD_MS cadence instead of a dedicated /// broadcast thread. void announce(); + /// `announced` is the sequence number of the announcement just received from + /// a known participant whose highest so far is `last`. A number far below + /// the highest (at most half of it, once the peer has announced at least + /// three times) is not a reordered or duplicated datagram but a peer that + /// restarted with the same GUID prefix and numbers its new SPDP writer from + /// 1 again; such a peer is forgotten and rediscovered (its SEDP and user + /// writers restarted too, and the stateful readers' proxies would keep + /// waiting for the old numbers). Edges: a peer seen fewer than three times + /// is never judged (a reordered second announcement must not tear down a + /// participant just discovered); a restarted peer whose first + /// announcements were lost is caught as long as its number is still at most + /// half of what was seen before, else its lease decides; number 0 never + /// qualifies (not a valid RTPS sequence number). This engine's own boards + /// never reuse a prefix (Domain::guidIncarnation), so this guards against + /// stacks that do. Security: a spoofed low-numbered announcement can tear + /// down and re-add a healthy peer - no more than a spoofed dispose, which + /// the protocol has always allowed from any multicast sender. + static bool isRestart(const SequenceNumber_t &announced, const SequenceNumber_t &last); std::recursive_mutex m_mutex; private: @@ -115,32 +133,21 @@ class SPDPAgent : public espp::BaseComponent { size_t m_nextDisposed = 0; void rememberDispose(const GuidPrefix_t &prefix, const SequenceNumber_t &sn); bool isFromBeforeDispose(const GuidPrefix_t &prefix, const SequenceNumber_t &sn) const; - /// `announced` is the sequence number of the announcement just received from - /// a known participant whose highest so far is `last`. A number far below - /// the highest (at most half of it) is not a reordered or duplicated - /// datagram but a peer that restarted with the same GUID prefix and numbers - /// its new SPDP writer from 1 again; such a peer is forgotten and - /// rediscovered (its SEDP and user writers restarted too). A single - /// reordered announcement (last - 1) never qualifies once a peer has - /// announced three times. - static bool isRestart(const SequenceNumber_t &announced, const SequenceNumber_t &last); - /// Whether `disposed` is an earlier incarnation of the participant whose - /// SPDP writer `writer` belongs to: same bytes 0-9 (board, participant id, - /// this engine's VENDOR_ID, domain), different incarnation bytes 10-11. - /// Such a dispose is honoured as the participant's own - /// (Domain::previousGuidIncarnation). Prefixes of other vendors never - /// qualify: their bytes 10-11 mean something else. - static bool isPreviousIncarnationOf(const GuidPrefix_t &disposed, const GuidPrefix_t &writer); - /// Dispose the participant we were in the previous boot (its prefix differs - /// from ours in the incarnation bytes only), as the first change of our - /// SPDP writer, so a peer that still holds that incarnation forgets it now - /// rather than when its lease runs out - and then discovers us. - void disposePreviousIncarnation(const GuidPrefix_t &prefix); + /// Send the dispose of the participant we were in the previous boot, AS that + /// participant: an RTPS message whose header prefix and SPDP writer are the + /// old incarnation's, with its participant GUID as key hash + payload and + /// a sequence number above anything it could have sent (every stack's SPDP + /// reader takes a participant's own dispose; one from another writer + /// naming it is refused by Cyclone DDS, Fast DDS and this engine alike). + /// Sent on the first PREVIOUS_INCARNATION_DISPOSES announce cycles - best + /// effort, multicast, a lost datagram costs a peer one lease. + void sendPreviousIncarnationDispose(); + static constexpr uint8_t PREVIOUS_INCARNATION_DISPOSES = 3; + uint8_t m_previousIncarnationDisposesLeft = 0; void processProxyData(const SequenceNumber_t &announcementSn); bool addProxiesForBuiltInEndpoints(); - /// Inline QoS naming a participant instance (its key hash) + sentinel. - void addInlineQos(CdrWriter &writer, const GuidPrefix_t &prefix); + void addInlineQos(CdrWriter &writer); void addParticipantParameters(); void endCurrentList(CdrWriter &writer); }; diff --git a/components/rtps/include/rtps/entities/Domain.hpp b/components/rtps/include/rtps/entities/Domain.hpp index b8243b668e..0a85d3167c 100644 --- a/components/rtps/include/rtps/entities/Domain.hpp +++ b/components/rtps/include/rtps/entities/Domain.hpp @@ -100,20 +100,25 @@ class Domain : public espp::BaseComponent { Participant *createParticipant(); - /// Bytes 10-11 of every GUID prefix generated this boot. On ESP targets a - /// nonce drawn once per boot, so a board that reboots comes back as a NEW + /// Bytes 10-11 of every GUID prefix this Domain generates. On ESP targets + /// a nonce drawn when the Domain is constructed, so a board that reboots - + /// or an application that recreates its Domain - comes back as a NEW /// participant to every peer (RTPS requires a GUID never to be reused; a /// peer that still holds the old incarnation would otherwise ignore the /// restarted writers, whose sequence numbers start at 1 again, until the /// lease ran out). Host builds return 0: their prefixes are random per - /// process already (or the configured template, for tests). - static uint16_t guidIncarnation(); - /// The previous boot's incarnation, when known: ESP targets keep it in - /// RTC memory across a software reset (not a power cycle), and the SPDP - /// agent disposes that incarnation's participant before announcing the new - /// one, so peers drop it at once. nullopt on host builds and after a - /// power-on. - static std::optional previousGuidIncarnation(); + /// process already (or the configured template, for tests). The static + /// form reports the most recently constructed Domain's value. + uint16_t guidIncarnation() const { return m_incarnation; } + static uint16_t currentGuidIncarnation(); + /// The incarnation before this Domain's, when known: ESP targets keep the + /// last one in RTC memory across a software reset (not a power cycle), so + /// it is the previous boot's after a reboot and the previous Domain's after + /// a recreation. The SPDP agent disposes that incarnation's participant on + /// its first announce cycles, so peers drop it at once. nullopt on host + /// builds and after a power-on. + std::optional previousGuidIncarnation() const { return m_previousIncarnation; } + static std::optional currentPreviousGuidIncarnation(); Writer *createWriter(Participant &part, const char *topicName, const char *typeName, bool reliable, bool enforceUnicast = false, const EndpointOptions &options = {}); @@ -251,6 +256,9 @@ class Domain : public espp::BaseComponent { bool m_initComplete = false; bool m_transportSetupOk = true; + uint16_t m_incarnation = 0; + std::optional m_previousIncarnation{}; + void drawGuidIncarnation(); std::recursive_mutex m_mutex; void receiveCallback(const PacketInfo &packet); diff --git a/components/rtps/include/rtps/entities/Participant.hpp b/components/rtps/include/rtps/entities/Participant.hpp index 3b838a6605..45bb7476d8 100644 --- a/components/rtps/include/rtps/entities/Participant.hpp +++ b/components/rtps/include/rtps/entities/Participant.hpp @@ -144,9 +144,18 @@ class Participant : public espp::BaseComponent { const ParticipantProxyData *findRemoteParticipant(const GuidPrefix_t &prefix); void refreshRemoteParticipantLiveliness(const GuidPrefix_t &prefix); - /// As above, and records the announcement's sequence number (the highest - /// seen is kept) for SPDPAgent's restart detection. - void refreshRemoteParticipantLiveliness(const GuidPrefix_t &prefix, const SequenceNumber_t &sn); + /// What an SPDP announcement from `prefix`, numbered `sn`, means for the + /// remote participant we may know by that prefix - decided and recorded in + /// one step under the participant mutex (the lease sweep removes entries + /// concurrently). + enum class AnnouncementVerdict : uint8_t { + Unknown, ///< no such participant: discover it + Known, ///< a known participant; its lease and highest SPDP number were refreshed + Restart, ///< a known participant restarted with this prefix (SPDPAgent::isRestart): + ///< forget it and discover it afresh; nothing was refreshed + }; + AnnouncementVerdict noteRemoteParticipantAnnouncement(const GuidPrefix_t &prefix, + const SequenceNumber_t &sn); uint32_t getRemoteParticipantCount(); MessageReceiver *getMessageReceiver(); bool checkAndResetHeartbeats(); diff --git a/components/rtps/include/rtps/entities/StatelessWriter.hpp b/components/rtps/include/rtps/entities/StatelessWriter.hpp index 2ad8f58c1a..f56dd765c3 100644 --- a/components/rtps/include/rtps/entities/StatelessWriter.hpp +++ b/components/rtps/include/rtps/entities/StatelessWriter.hpp @@ -65,6 +65,13 @@ class StatelessWriter : public Writer { EsppTransport *m_transport; +public: + /// The transport this writer sends on and the source port it sends from + /// (SPDPAgent sends the previous incarnation's dispose through them). + EsppTransport *getTransport() const { return m_transport; } + Ip4Port_t getSourcePort() const { return m_srcPort; } + +private: SimpleHistoryCache m_history; }; diff --git a/components/rtps/include/rtps/entities/Writer.hpp b/components/rtps/include/rtps/entities/Writer.hpp index d9ba0bfa5d..f0efd632bd 100644 --- a/components/rtps/include/rtps/entities/Writer.hpp +++ b/components/rtps/include/rtps/entities/Writer.hpp @@ -150,7 +150,6 @@ class Writer : public espp::BaseComponent { SequenceNumber_t m_nextSequenceNumberToSend; friend class SEDPAgent; - friend class SPDPAgent; // disposePreviousIncarnation: a DATA with inline QoS virtual const CacheChange *newChange(ChangeKind_t kind, const uint8_t *data, DataSize_t size, bool inLineQoS, bool markDisposedAfterWrite, bool hasRelatedSampleIdentity = false, diff --git a/components/rtps/interop/README.md b/components/rtps/interop/README.md index 0833e842b8..436b94bc30 100644 --- a/components/rtps/interop/README.md +++ b/components/rtps/interop/README.md @@ -27,7 +27,7 @@ touched. | golden | wire-format bytes unchanged (see `pc/tests/rtps_golden.cpp`) | | locator_subnet | of the unicast locators a peer on several networks announces (SEDP and SPDP), the one on our subnet is kept (see `pc/tests/rtps_locator_subnet.cpp`) | | sedp_inline_qos_dispose | a peer's dispose of an endpoint (SEDP) or of its participant (SPDP) - a DATA whose inline QoS carries `PID_STATUS_INFO` + `PID_KEY_HASH`, as Fast DDS, Cyclone DDS and espp write it, in each of the three forms - unmatches the endpoint / forgets the participant at once instead of at lease expiry (see `pc/tests/rtps_sedp_inline_qos_dispose.cpp`) | -| participant_restart | a peer that restarts with the GUID prefix its peers still hold (a board rebooting within its lease; every writer numbers from 1 again) is rediscovered at once: the SPDP reader is exempt from the best-effort ordering rule, an announcement numbered far below the peer's highest (`SPDPAgent::isRestart`) forgets and rediscovers it (a single reordered or duplicated announcement does not), and a dispose from the next incarnation of the same participant (bytes 0-9 equal, incarnation bytes 10-11 differ) is honoured as its own, while one from a stranger or another participant id is still refused (see `pc/tests/rtps_participant_restart.cpp`) | +| participant_restart | a peer that restarts with the GUID prefix its peers still hold (every writer numbers from 1 again) is rediscovered at once: an announcement numbered far below the peer's highest (`SPDPAgent::isRestart`) forgets and rediscovers it (a single reordered or duplicated announcement does not); a rebooted board of this engine instead comes back with new incarnation bytes and first disposes its previous incarnation as that incarnation (old prefix, its SPDP writer, a number above anything it sent), which every stack honours as the participant's own dispose - the old one goes at once, a stale announcement of it is ignored, a dispose naming a participant from any other prefix is still refused (see `pc/tests/rtps_participant_restart.cpp`) | | sedp_history_ring, sedp_history_overflow | the SEDP writers never overwrite a live endpoint announcement when their history is full: a sent dispose is given up first, else the announcement is refused and the endpoint creation fails loudly (the ring policy on a static ring, `pc/tests/rtps_sedp_history_ring.cpp`, a unit that links no engine object); a refused creation gives its pooled endpoint back, and an endpoint whose announcement is gone can still be deleted with its slot reused (`pc/tests/rtps_sedp_history_overflow.cpp`) | | facade_matched_counts | `RtpsParticipant::matched_writers()` / `matched_readers()` over a loopback: one remote writer counts once across two local readers on the topic, and removing the writer (which announces the SEDP dispose) brings the count to zero within a couple of seconds, not at lease expiry (`pc/tests/rtps_facade_matched_counts.cpp`) | | gap_before_data | a reliable reader applies a GAP only for sequence numbers the writer has announced (HEARTBEAT lastSN or a DATA): Fast DDS sends its SEDP readers a GAP for the next number after an endpoint deletion and then writes that number for the next announcement, which used to leave a publisher-churning peer unmatched after its first deletion (`pc/tests/rtps_gap_before_data.cpp`; the churn case is the live check) | @@ -85,7 +85,7 @@ cd .. && ./run_qemu.sh | device_boot, device_ping | the engine comes up on lwIP over the emulated OpenCores MAC | | device_pub->ros2_echo, ros2_pub->device_sub (+ best-effort pair) | delivery both ways, FastDDS and CycloneDDS | | ros2_pub->device_sub_liveliness | samples still arriving 24-34 s in, past the remote lease | -| restart_fastdds_rediscovered_by_ros2_sub, restart_cyclone_..., restart_*_device_sub_receives, restart_previous_incarnation_disposed, restart_espp_host_pub->device_sub | the device reboots (`esp_restart` on a "RESTART" sample) while a ROS 2 subscriber, a ROS 2 publisher and, in the host-engine case, an espp publisher stay up. It announces a 30 s lease for itself in `sdkconfig.ci.defaults`, so the old incarnation cannot expire during the reboot: the peers must receive the restarted publisher's first samples ("qemu 0".."qemu 9") and the rebooted device the peers' samples within seconds. The GUID prefix carries a per-boot incarnation (bytes 10-11, `Domain::guidIncarnation`); the previous one is kept in RTC memory across the reset and disposed before the first announcement (`RTPSTEST incarnation cur= prev=`), so a peer that honours the dispose drops the old participant at once rather than at lease expiry | +| restart__rediscovered_by_ros2_sub, restart__device_sub_receives, restart__old_incarnation_dropped, restart_previous_incarnation_remembered, restart_espp_host_pub->device_sub | the device restarts its participant on a "RESTART" sample (it recreates its Domain - what a board's reboot looks like to its peers; a software reset of QEMU's emulated chip panics inside ESP-IDF's startup, so the chip is not rebooted) while a ROS 2 subscriber, a ROS 2 publisher and, in the host-engine case, an espp publisher stay up. It announces a 30 s lease for itself in `sdkconfig.ci.defaults`, so the old incarnation cannot expire during the restart: the ROS 2 subscriber must receive the restarted publisher's first samples ("qemu 0".."qemu 9") and the restarted device the ROS 2 publisher's samples within seconds. The GUID prefix carries a per-Domain incarnation (bytes 10-11, `Domain::guidIncarnation`); the previous one is kept in RTC memory (`RTPSTEST incarnation cur= prev=`, `restart_previous_incarnation_remembered`) and disposed as that participant on the first announce cycles, so the ROS 2 daemon's count of publishers on the device's topic drops back to one within seconds instead of after the 30 s lease (`restart__old_incarnation_dropped`) | | 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 | diff --git a/components/rtps/interop/qemu/main/rtps_qemu.cpp b/components/rtps/interop/qemu/main/rtps_qemu.cpp index 0ae46c04b3..a6469299f7 100644 --- a/components/rtps/interop/qemu/main/rtps_qemu.cpp +++ b/components/rtps/interop/qemu/main/rtps_qemu.cpp @@ -11,7 +11,14 @@ // this boot and, after a software reset, of the // previous one (which the engine disposes first) // RTPSTEST restart a "RESTART" sample arrived on rt/qemu_rx: the -// device reboots (esp_restart) - the restart case +// firmware tears its participant down and creates a +// new one (a new GUID incarnation, which first disposes +// the previous one) - the restart case. Not esp_restart: +// QEMU's emulated chip panics in ESP-IDF's startup +// after a software reset (esp_timer interrupt +// allocation), so the participant restarts, as an +// application recreating its Domain would. Ignored, +// with a marker, in the first 20 s of a participant. // RTPSTEST pub_matched/sub_matched a writer / reader gained a remote peer // RTPSTEST tx reliable publisher sent "qemu " // RTPSTEST rx reliable subscriber received @@ -56,7 +63,6 @@ #include #include -#include #include #include @@ -129,6 +135,12 @@ static std::string ip4_to_string(esp_ip4_addr_t ip) { return buf; } +// One participant lifetime: endpoints, timers, the status loop. Returns when a +// RESTART sample asks for a new participant (the restart case); everything it +// owns is destroyed on the way out, and app_main builds the next one. +static void run_participant(espp::Logger &logger, const std::string &interface_address, + const std::string &interface_netmask); + extern "C" void app_main(void) { espp::Logger logger({.tag = "rtps_qemu", .level = espp::Logger::Verbosity::INFO}); logger.info("Starting the RTPS QEMU interop firmware"); @@ -172,6 +184,16 @@ extern "C" void app_main(void) { esp_netif_get_ip_info(esp_netif_get_handle_from_ifkey("ETH_DEF"), &ip_info); const std::string interface_netmask = ip4_to_string(ip_info.netmask); + while (true) { + run_participant(logger, interface_address, interface_netmask); + logger.info("RTPSTEST participant torn down, starting a new one"); + } +} + +static void run_participant(espp::Logger &logger, const std::string &interface_address, + const std::string &interface_netmask) { + const auto boot_time = std::chrono::steady_clock::now(); + std::atomic restart_requested{false}; // Counters for the status line (the callbacks run on the engine's threads) std::atomic tx_count{0}; std::atomic rx_count{0}; @@ -221,11 +243,20 @@ extern "C" void app_main(void) { rx_count++; logger.info("RTPSTEST rx {}", msg.data); if (msg.data == "RESTART") { - // the restart case: reboot - // like a board would - logger.info("RTPSTEST restart"); - std::this_thread::sleep_for(100ms); // let the log out - esp_restart(); + // the restart case (see the header comment). The + // harness repeats the sample for a few seconds so a + // just-matched writer gets it through; copies that + // reach the NEW participant are ignored for its + // first 20 s. + const auto up_s = std::chrono::duration_cast( + std::chrono::steady_clock::now() - boot_time) + .count(); + if (up_s < 20) { + logger.info("RTPSTEST restart ignored (participant {} s old)", + up_s); + } else if (!restart_requested.exchange(true)) { + logger.info("RTPSTEST restart"); + } } }, }); @@ -341,11 +372,12 @@ extern "C" void app_main(void) { logger.info("RTPSTEST ready ip={}", interface_address); { // The prefix incarnation (bytes 10-11 of every GUID prefix this boot) and - // the previous boot's, kept across a software reset: the engine disposed - // that incarnation before its first announcement, so peers that still held - // it (a reboot within the lease) forgot it at once. - const auto prev = rtps::Domain::previousGuidIncarnation(); - logger.info("RTPSTEST incarnation cur={:04x} prev={}", rtps::Domain::guidIncarnation(), + // the previous one (the previous boot's, kept across a software reset, or + // the previous participant's after a RESTART): the engine disposes that + // incarnation on its first announce cycles, so peers that still held it + // forget it at once. + const auto prev = rtps::Domain::currentPreviousGuidIncarnation(); + logger.info("RTPSTEST incarnation cur={:04x} prev={}", rtps::Domain::currentGuidIncarnation(), prev ? fmt::format("{:04x}", *prev) : std::string{"none"}); } @@ -380,7 +412,7 @@ extern "C" void app_main(void) { // 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) { + while (!restart_requested) { std::this_thread::sleep_for(2s); const auto up = std::chrono::duration_cast(std::chrono::steady_clock::now() - t0) diff --git a/components/rtps/interop/run_qemu_interop.sh b/components/rtps/interop/run_qemu_interop.sh index 5ff58c650d..d870d98a8d 100755 --- a/components/rtps/interop/run_qemu_interop.sh +++ b/components/rtps/interop/run_qemu_interop.sh @@ -181,31 +181,36 @@ source "/opt/ros/${ROS_DISTRO:-jazzy}/setup.bash" export ROS_DOMAIN_ID=0 # matches the engine's Config::DOMAIN_ID run_matrix() { -# The device reboots (esp_restart on a "RESTART" sample, see rtps_qemu.cpp) -# while a ROS 2 subscriber and a ROS 2 publisher of the current rmw stay up. -# Its GUID prefix is MAC-based, so before the fix it came back as the -# participant the peers still held (and every writer numbered from 1 again): -# the peers' best-effort SPDP readers dropped its announcements, their user -# readers dropped its samples, and nothing moved until the old lease (30 s in -# sdkconfig.ci.defaults, so a reboot cannot hide behind it) ran out. Now the -# prefix carries a per-boot incarnation (bytes 10-11) and the device disposes -# the previous incarnation before announcing, so the peers forget it at once -# and discover the new one; the device's own proxies are fresh anyway. +# The device restarts its participant (on a "RESTART" sample, see +# rtps_qemu.cpp; a software reset of the emulated chip trips a QEMU startup +# bug, so the firmware recreates its Domain instead, which is what a board's +# reboot does to its peers) while a ROS 2 subscriber and a ROS 2 publisher of +# the current rmw stay up. Its GUID prefix is MAC-based, so before the fix it +# came back as the participant the peers still held, with every writer +# numbered from 1 again: the peers' readers rejected those numbers and nothing +# moved until the old lease (30 s in sdkconfig.ci.defaults, so a restart cannot +# hide behind it) ran out. Now the prefix carries a per-Domain incarnation +# (bytes 10-11), so the restarted device is a new participant, and it disposes +# the previous incarnation - as that incarnation - on its first announce +# cycles, so the peers drop the old one at once instead of holding it for the +# lease. # Results: restart__rediscovered_by_ros2_sub (the ROS 2 subscriber # receives the restarted publisher's first samples, "qemu 0".."qemu 9", well # inside the old lease), restart__device_sub_receives (the ROS 2 -# publisher's samples reach the rebooted device), and -# restart_previous_incarnation_disposed (the firmware found the previous -# incarnation in RTC memory and disposed it; once, FastDDS pass). +# publisher's samples reach the rebooted device), +# restart__old_incarnation_dropped (the ROS 2 daemon, a participant that +# was up throughout, counts ONE publisher on the device's topic again within +# 15 s of the restart - without the dispose it holds both for 30 s), and +# restart_previous_incarnation_remembered (the new Domain found the previous +# incarnation in the RTC record; once, on the FastDDS pass). device_restart_case() { # prefix log-tag - local p="$1" t="$2" m rc=0 n i + local p="$1" t="$2" m rc=0 n=0 n0=0 i timeout 90 ros2 topic echo /qemu_tx std_msgs/msg/String > "/tmp/${t}_restart_echo.log" 2>&1 & local echo_pid=$! timeout 90 ros2 topic pub -r 5 /qemu_rx std_msgs/msg/String "data: 'across restart'" > /dev/null 2>&1 & local pub=$! - sleep 10 # both matched and flowing + sleep 10 # both matched and flowing, and the daemon knows the device m=$(mark) - local before_rx; before_rx=$(count_since "$m" "RTPSTEST rx across restart") # published once the device's subscriber is matched (-w 1), then exits: a # single RESTART, the rebooted device must not get it again timeout 20 ros2 topic pub --once -w 1 /qemu_rx std_msgs/msg/String "data: 'RESTART'" > /dev/null 2>&1 @@ -214,30 +219,38 @@ device_restart_case() { # prefix log-tag fi local boot; boot=$(mark) if [ $rc -eq 0 ] && ! wait_for_marker_since "$boot" "RTPSTEST ready" 60; then - echo " the device did not come back"; rc=1 + echo " the device's new participant did not come up"; rc=1 fi + local pubs=2 t0 if [ $rc -eq 0 ]; then - since "$boot" | grep -o "RTPSTEST incarnation.*" | head -1 | sed 's/^/ /' # the restarted publisher counts from 0 again: its first samples at the ROS 2 # subscriber are the proof it was rediscovered (the old lease is 30 s) - local t0 n0=0; t0=$(date +%s) + t0=$(date +%s) for i in $(seq 1 25); do n0=$(grep -c -E '^data: qemu [0-9]$' "/tmp/${t}_restart_echo.log") [ "$n0" -ge 3 ] && break sleep 1 done echo " ROS 2 subscriber got $n0 of the restarted publisher's first samples after $(( $(date +%s) - t0 )) s" - [ "$n0" -ge 3 ] || rc=1 n=$(count_since "$boot" "RTPSTEST rx across restart"); echo " rebooted device received $n from the ROS 2 publisher" - [ "$n" -ge 5 ] || rc=1 - if [ "$p" = "" ] || [ "$t" = fastdds ]; then + # the daemon's view: publishers of /qemu_tx; two while it still holds the + # old incarnation, one once the dispose (or the lease, 30 s) took it + for i in $(seq 1 15); do + pubs=$(timeout 10 ros2 topic info -v /qemu_tx 2>/dev/null | grep -c 'Endpoint type: PUBLISHER') + [ "${pubs:-2}" -le 1 ] && break + sleep 1 + done + echo " daemon counts ${pubs:-?} publisher(s) on /qemu_tx $(( $(date +%s) - t0 )) s after the reboot" + since "$boot" | grep -o "RTPSTEST incarnation.*" | head -1 | sed 's/^/ /' + if [ "$t" = fastdds ]; then since "$boot" | grep -q "RTPSTEST incarnation cur=[0-9a-f]* prev=[0-9a-f]" - result "restart_previous_incarnation_disposed" $? + result "restart_previous_incarnation_remembered" $? fi fi stop_pids $echo_pid $pub - result "restart_${t}_rediscovered_by_ros2_sub" $rc - [ $rc -eq 0 ] && [ "${n:-0}" -ge 5 ]; result "restart_${t}_device_sub_receives" $? + [ $rc -eq 0 ] && [ "$n0" -ge 3 ]; result "restart_${t}_rediscovered_by_ros2_sub" $? + [ $rc -eq 0 ] && [ "$n" -ge 5 ]; result "restart_${t}_device_sub_receives" $? + [ $rc -eq 0 ] && [ "${pubs:-2}" -le 1 ]; result "restart_${t}_old_incarnation_dropped" $? } wait_for_marker_since() { # mark marker timeout_s local i @@ -431,10 +444,10 @@ rc=$?; tail -2 /tmp/hostsub.log; result "device_pub->espp_host_sub" $rc settle note "the device restarts while the espp host publisher runs: the rebooted device receives again at once" -# The host engine keeps the device's previous incarnation until its dispose -# arrives (the espp SPDP reader lets a restarted peer through; SPDPAgent -# forgets it on the dispose or on the restart it detects); the host publisher's -# samples must reach the rebooted device within a few seconds of its boot. +# The host engine holds the device's previous incarnation until its dispose +# arrives (sent as that incarnation on the device's first announce cycles) and +# discovers the new one; the host publisher's samples must reach the rebooted +# device within a few seconds of its boot. m=$(mark) "$BIN"/rtps_interop_pub rt/qemu_rx std_msgs::msg::dds_::String_ 1 400 200 $HOST_IP > /tmp/hostpub_restart.log 2>&1 & pub=$!; sleep 10 diff --git a/components/rtps/src/discovery/SPDPAgent.cpp b/components/rtps/src/discovery/SPDPAgent.cpp index af99f5ff0b..dc32c848f6 100644 --- a/components/rtps/src/discovery/SPDPAgent.cpp +++ b/components/rtps/src/discovery/SPDPAgent.cpp @@ -25,11 +25,15 @@ Author: i11 - Embedded Software, RWTH Aachen University #include "rtps/discovery/SPDPAgent.hpp" +#include "rtps/communication/EsppTransport.hpp" #include "rtps/discovery/ParticipantProxyData.hpp" #include "rtps/entities/Participant.hpp" #include "rtps/entities/Reader.hpp" +#include "rtps/entities/StatelessWriter.hpp" #include "rtps/entities/Writer.hpp" +#include "rtps/messages/MessageFactory.hpp" #include "rtps/messages/MessageTypes.hpp" +#include "rtps/storages/PayloadBuffer.hpp" #include "rtps/utils/Log.hpp" #include "rtps/utils/udpUtils.hpp" #include @@ -54,81 +58,93 @@ void SPDPAgent::init(Participant &participant, BuiltInEndpoints &endpoints) { addParticipantParameters(); if (participant.m_hasPreviousIncarnation) { - disposePreviousIncarnation(participant.m_previousIncarnationPrefix); + m_previousIncarnationDisposesLeft = PREVIOUS_INCARNATION_DISPOSES; } initialized = true; } -void SPDPAgent::disposePreviousIncarnation(const GuidPrefix_t &prefix) { - // The form Fast DDS, Cyclone DDS and this engine's receiver all understand - // (handleSPDPPackage below): a DATA whose inline QoS carries the key hash of - // the disposed participant and PID_STATUS_INFO disposed|unregistered, with - // a payload that names the participant GUID for a peer that reads the key - // from the payload. Queued before the first announcement, so it goes out - // first (the stateless writer sends in sequence-number order). - std::array buffer{}; - CdrSink sink{asWritableBytes(buffer.data(), buffer.size())}; - CdrWriter writer(sink); - // inline QoS - writer.write(ParameterId::PID_KEY_HASH); - writer.write(16); - writeBytes(writer, prefix.id.data(), sizeof(GuidPrefix_t::id)); - writeBytes(writer, ENTITYID_BUILD_IN_PARTICIPANT.entityKey.data(), sizeof(EntityId_t::entityKey)); - writer.write(static_cast(ENTITYID_BUILD_IN_PARTICIPANT.entityKind)); - writer.write(ParameterId::PID_STATUS_INFO); - writer.write(4); - writer.write(0); - writer.write(0); - writer.write(0); - writer.write(3); // disposed | unregistered, as Fast DDS writes it - endCurrentList(writer); - // payload - writeBytes(writer, rtps::SMElement::SCHEME_PL_CDR_LE.data(), - rtps::SMElement::SCHEME_PL_CDR_LE.size()); - writer.write(0); // options - writer.write(ParameterId::PID_PARTICIPANT_GUID); - writer.write(16); - writeBytes(writer, prefix.id.data(), sizeof(GuidPrefix_t::id)); - writeBytes(writer, ENTITYID_BUILD_IN_PARTICIPANT.entityKey.data(), sizeof(EntityId_t::entityKey)); - writer.write(static_cast(ENTITYID_BUILD_IN_PARTICIPANT.entityKind)); - endCurrentList(writer); - - const auto *change = m_buildInEndpoints.spdpWriter->newChange( - ChangeKind_t::ALIVE, buffer.data(), static_cast(sink.size()), - /*inLineQoS=*/true, /*markDisposedAfterWrite=*/false); - if (change == nullptr) { - logger_.warn("Could not queue the dispose of the previous incarnation {:02x}{:02x}; peers " - "that still hold it forget it when its lease runs out", - prefix.id[10], prefix.id[11]); +void SPDPAgent::sendPreviousIncarnationDispose() { + if (mp_participant == nullptr || !mp_participant->m_hasPreviousIncarnation) { return; } - logger_.info("Disposing the previous incarnation {:02x}{:02x} of this participant (now " - "{:02x}{:02x}) before the first announcement", - prefix.id[10], prefix.id[11], mp_participant->m_guidPrefix.id[10], + auto *writer = static_cast(m_buildInEndpoints.spdpWriter); + EsppTransport *transport = writer ? writer->getTransport() : nullptr; + if (transport == nullptr) { + return; + } + const GuidPrefix_t &old = mp_participant->m_previousIncarnationPrefix; + + // The change: inline QoS (the old participant's key hash, STATUS_INFO + // disposed|unregistered as Fast DDS writes it) and a PL_CDR payload naming + // the same GUID, for a peer that reads the key from the payload. + PayloadBuffer change; + { + std::array buffer{}; + CdrSink sink{asWritableBytes(buffer.data(), buffer.size())}; + CdrWriter cdr(sink); + cdr.write(ParameterId::PID_KEY_HASH); + cdr.write(16); + writeBytes(cdr, old.id.data(), sizeof(GuidPrefix_t::id)); + writeBytes(cdr, ENTITYID_BUILD_IN_PARTICIPANT.entityKey.data(), sizeof(EntityId_t::entityKey)); + cdr.write(static_cast(ENTITYID_BUILD_IN_PARTICIPANT.entityKind)); + cdr.write(ParameterId::PID_STATUS_INFO); + cdr.write(4); + cdr.write(0); + cdr.write(0); + cdr.write(0); + cdr.write(3); + endCurrentList(cdr); + writeBytes(cdr, rtps::SMElement::SCHEME_PL_CDR_LE.data(), + rtps::SMElement::SCHEME_PL_CDR_LE.size()); + cdr.write(0); // options + cdr.write(ParameterId::PID_PARTICIPANT_GUID); + cdr.write(16); + writeBytes(cdr, old.id.data(), sizeof(GuidPrefix_t::id)); + writeBytes(cdr, ENTITYID_BUILD_IN_PARTICIPANT.entityKey.data(), sizeof(EntityId_t::entityKey)); + cdr.write(static_cast(ENTITYID_BUILD_IN_PARTICIPANT.entityKind)); + endCurrentList(cdr); + change.append(buffer.data(), static_cast(sink.size())); + } + + // The message, as the old incarnation: its prefix in the header, its SPDP + // writer as the source, a number its writer cannot have reached (a + // best-effort reader rejects a number at or below the last it took from + // that writer), to the SPDP multicast locator every peer listens on. + PayloadBuffer message; + MessageFactory::addHeader(message, old); + MessageFactory::addSubMessageTimeStamp(message); + const SequenceNumber_t sn{std::numeric_limits::max(), + std::numeric_limits::max()}; + MessageFactory::addSubMessageData(message, change, /*containsInlineQos=*/true, sn, + ENTITYID_SPDP_BUILTIN_PARTICIPANT_WRITER, + ENTITYID_SPDP_BUILTIN_PARTICIPANT_READER); + + const LocatorIPv4 multicast(getBuiltInMulticastLocator()); + PacketInfo info; + info.srcPort = writer->getSourcePort(); + info.destAddr = multicast.getIp4AddressBytes(); + info.destPort = static_cast(multicast.port); + info.payload = std::move(message.bytes); + transport->sendPacket(info); + logger_.info("Disposed the previous incarnation {:02x}{:02x} of this participant (now " + "{:02x}{:02x}), as that participant", + old.id[10], old.id[11], mp_participant->m_guidPrefix.id[10], mp_participant->m_guidPrefix.id[11]); } bool SPDPAgent::isRestart(const SequenceNumber_t &announced, const SequenceNumber_t &last) { - if (!(announced < last) || announced.high < 0) { + if (!(announced < last) || announced.high < 0 || last.high < 0) { return false; } const uint64_t a = (static_cast(static_cast(announced.high)) << 32) | announced.low; const uint64_t l = (static_cast(static_cast(last.high)) << 32) | last.low; + if (a == 0 || l < 3) { + return false; // 0 is not a sequence number; too few announcements to judge + } return a * 2 <= l; } -bool SPDPAgent::isPreviousIncarnationOf(const GuidPrefix_t &disposed, const GuidPrefix_t &writer) { - // Only for prefixes in this engine's layout (MAC, participant id, VENDOR_ID - // at bytes 7-8, domain, incarnation): other stacks put something else in - // bytes 10-11 - Fast DDS its participant id within a process, so two of its - // participants in one process differ only there and must not be allowed to - // dispose each other. - return !(disposed == writer) && disposed.id[7] == Config::VENDOR_ID.vendorId[0] && - disposed.id[8] == Config::VENDOR_ID.vendorId[1] && - std::equal(disposed.id.begin(), disposed.id.begin() + 10, writer.id.begin()); -} - void SPDPAgent::start() { m_running = true; } void SPDPAgent::stop() { m_running = false; } @@ -139,6 +155,12 @@ void SPDPAgent::announce() { // here when this was a dedicated thread body). const DataSize_t size = static_cast(m_outputSize); const uint8_t *payload = m_outputBuffer.data(); + if (m_previousIncarnationDisposesLeft > 0) { + // before our own announcement, so a peer that still holds the previous + // incarnation drops it first and discovers us as new + --m_previousIncarnationDisposesLeft; + sendPreviousIncarnationDispose(); + } // StatelessWriter drops already-sent history; enqueue a fresh SPDP sample // for each announce cycle. m_buildInEndpoints.spdpWriter->newChange(ChangeKind_t::ALIVE, payload, size); @@ -189,12 +211,11 @@ void SPDPAgent::handleSPDPPackage(const ReaderCacheChange &cacheChange) { // forget it now, with every proxy of its endpoints, instead of when its // lease runs out. The instance is named by the inline-QoS key hash; a // peer that leaves the hash out carries the GUID in the payload. - // Only the peer's own SPDP writer may dispose it, and only itself - or a - // previous incarnation of itself (the same board, participant id, vendor - // and domain with other incarnation bytes: what a restarted peer disposes - // first, see disposePreviousIncarnation). A DATA from another writer, or - // naming another participant, is malformed (or hostile) and must not - // remove anyone. + // Only the peer's own SPDP writer may dispose it, and only itself: a + // DATA from another writer, or naming another participant, is malformed + // (or hostile) and must not remove anyone. (A restarted board disposes + // its previous incarnation AS that incarnation - sendPreviousIncarnationDispose + // - so it passes this rule like any participant's own dispose.) if (!(cacheChange.writerGuid.entityId == ENTITYID_SPDP_BUILTIN_PARTICIPANT_WRITER)) { return; } @@ -209,23 +230,14 @@ void SPDPAgent::handleSPDPPackage(const ReaderCacheChange &cacheChange) { if (prefix == GUIDPREFIX_UNKNOWN || prefix == mp_participant->m_guidPrefix) { return; } - if (!(prefix == cacheChange.writerGuid.prefix) && - !isPreviousIncarnationOf(prefix, cacheChange.writerGuid.prefix)) { + if (!(prefix == cacheChange.writerGuid.prefix)) { logger_.warn("Participant dispose from {:02x}{:02x}{:02x}{:02x} names another participant, " "ignored", cacheChange.writerGuid.prefix.id[0], cacheChange.writerGuid.prefix.id[1], cacheChange.writerGuid.prefix.id[2], cacheChange.writerGuid.prefix.id[3]); return; } - if (prefix == cacheChange.writerGuid.prefix) { - rememberDispose(prefix, cacheChange.sn); - } else { - // A previous incarnation is dead: whatever it still has in flight (its - // own numbering, unrelated to the new writer's) is stale, so remember - // the dispose as newer than anything it could announce. - rememberDispose(prefix, SequenceNumber_t{std::numeric_limits::max(), - std::numeric_limits::max()}); - } + rememberDispose(prefix, cacheChange.sn); if (mp_participant->findRemoteParticipant(prefix) == nullptr) { return; // never known, or already gone } @@ -322,27 +334,25 @@ void SPDPAgent::processProxyData(const SequenceNumber_t &announcementSn) { SPDP_LOG("Message from GUID = {} {} {} {}", m_proxyDataBuffer.m_guid.prefix.id[4], m_proxyDataBuffer.m_guid.prefix.id[5], m_proxyDataBuffer.m_guid.prefix.id[6], m_proxyDataBuffer.m_guid.prefix.id[7]); - const rtps::ParticipantProxyData *remote_part; - remote_part = mp_participant->findRemoteParticipant(m_proxyDataBuffer.m_guid.prefix); - if (remote_part != nullptr) { - if (!isRestart(announcementSn, remote_part->m_lastSpdpSn)) { - SPDP_LOG("Not adding this participant"); - mp_participant->refreshRemoteParticipantLiveliness(m_proxyDataBuffer.m_guid.prefix, - announcementSn); - return; // Already in our list - } - // The peer restarted with the prefix we know it by (a board back within - // its lease, see isRestart): everything we hold of it - its builtin - // proxies, its endpoints and their proxies at our readers and writers - - // belongs to the old incarnation, whose writers' sequence numbers our - // proxies expect to continue. Forget it and discover it afresh below. - // Lock order as for a dispose: this agent's mutex, then the SEDP agent's - // and the participant's inside removeRemoteParticipant. + using Verdict = Participant::AnnouncementVerdict; + const Verdict verdict = mp_participant->noteRemoteParticipantAnnouncement( + m_proxyDataBuffer.m_guid.prefix, announcementSn); + if (verdict == Verdict::Known) { + SPDP_LOG("Not adding this participant"); + return; // Already in our list, lease refreshed + } + if (verdict == Verdict::Restart) { + // The peer restarted with the prefix we know it by (see isRestart): + // everything we hold of it - its builtin proxies, its endpoints and their + // proxies at our readers and writers - belongs to the old incarnation, + // whose writers' sequence numbers our stateful proxies expect to continue. + // Forget it and discover it afresh below. Lock order as for a dispose: + // this agent's mutex, then the SEDP agent's and the participant's inside + // removeRemoteParticipant. const auto &p = m_proxyDataBuffer.m_guid.prefix; logger_.warn("Remote participant {:02x}{:02x}{:02x}{:02x}... restarted with the same GUID " - "prefix (SPDP sequence {} after {}): rediscovering it", - p.id[0], p.id[1], p.id[2], p.id[3], announcementSn.low, - remote_part->m_lastSpdpSn.low); + "prefix (SPDP sequence {} far below what it had reached): rediscovering it", + p.id[0], p.id[1], p.id[2], p.id[3], announcementSn.low); mp_participant->removeRemoteParticipant(p); // The parser stops at the GUID of a participant it already knows (nothing // but the lease was refreshed): now that it is forgotten, parse the @@ -505,10 +515,10 @@ bool SPDPAgent::addProxiesForBuiltInEndpoints() { return ok; } -void SPDPAgent::addInlineQos(CdrWriter &writer, const GuidPrefix_t &prefix) { +void SPDPAgent::addInlineQos(CdrWriter &writer) { writer.write(ParameterId::PID_KEY_HASH); writer.write(16); - writeBytes(writer, prefix.id.data(), sizeof(GuidPrefix_t::id)); + writeBytes(writer, mp_participant->m_guidPrefix.id.data(), sizeof(GuidPrefix_t::id)); writeBytes(writer, ENTITYID_BUILD_IN_PARTICIPANT.entityKey.data(), sizeof(EntityId_t::entityKey)); writer.write(static_cast(ENTITYID_BUILD_IN_PARTICIPANT.entityKind)); diff --git a/components/rtps/src/entities/Domain.cpp b/components/rtps/src/entities/Domain.cpp index 7ff9db774f..1e027ef324 100644 --- a/components/rtps/src/entities/Domain.cpp +++ b/components/rtps/src/entities/Domain.cpp @@ -27,6 +27,7 @@ Author: i11 - Embedded Software, RWTH Aachen University #include "rtps/utils/Log.hpp" #include "rtps/utils/udpUtils.hpp" #include +#include #include #include #include @@ -35,6 +36,7 @@ Author: i11 - Embedded Software, RWTH Aachen University #include "esp_attr.h" #include "esp_mac.h" #include "esp_random.h" +#include "soc/soc_caps.h" #endif #if DOMAIN_VERBOSE && RTPS_GLOBAL_VERBOSE @@ -49,60 +51,64 @@ using rtps::Domain; namespace { #if defined(ESP_PLATFORM) -// The GUID prefix incarnation of this boot and of the previous one. The record -// lives in RTC memory, which a software reset (esp_restart, a panic reboot, -// deep sleep) preserves and a power-on leaves with arbitrary contents: the -// magic + complement check tells the two apart. Read once, lazily, on the -// first prefix generated this boot. +// The last GUID prefix incarnation drawn (by this boot's Domains or the +// previous boot's). The record lives in RTC memory (where the chip has it), +// which a software reset (esp_restart, a panic reboot, deep sleep) preserves +// and a power-on leaves with arbitrary contents: the magic + complement check +// tells the two apart. Each Domain draws its incarnation from esp_random and +// records it here (Domain::drawGuidIncarnation). struct IncarnationRecord { uint32_t magic; uint16_t incarnation; uint16_t check; // ~incarnation }; +#if SOC_RTC_FAST_MEM_SUPPORTED || SOC_RTC_SLOW_MEM_SUPPORTED RTC_NOINIT_ATTR IncarnationRecord s_incarnationRecord; +#else +// No RTC memory on this chip: .noinit DRAM also survives a software reset +// (esp_restart, a panic reboot), just not deep sleep. +__NOINIT_ATTR IncarnationRecord s_incarnationRecord; +#endif constexpr uint32_t kIncarnationMagic = 0x52545049; // 'RTPI' -struct IncarnationState { - uint16_t current = 0; - bool hasPrevious = false; - uint16_t previous = 0; -}; - -const IncarnationState &incarnationState() { - static const IncarnationState state = [] { - IncarnationState s; - const bool valid = - s_incarnationRecord.magic == kIncarnationMagic && - s_incarnationRecord.check == static_cast(~s_incarnationRecord.incarnation); - if (valid) { - s.hasPrevious = true; - s.previous = s_incarnationRecord.incarnation; - } - do { - s.current = static_cast(esp_random()); - } while (s.hasPrevious && s.current == s.previous); - s_incarnationRecord = - IncarnationRecord{kIncarnationMagic, s.current, static_cast(~s.current)}; - return s; - }(); - return state; -} +// The most recently constructed Domain's incarnation and its predecessor, for +// the static accessors (a firmware logs them without holding the Domain). +std::atomic s_currentIncarnation{0}; +std::atomic s_currentPrevious{-1}; // -1: none #endif } // namespace -uint16_t Domain::guidIncarnation() { +void Domain::drawGuidIncarnation() { +#if defined(ESP_PLATFORM) + const bool valid = + s_incarnationRecord.magic == kIncarnationMagic && + s_incarnationRecord.check == static_cast(~s_incarnationRecord.incarnation); + if (valid) { + m_previousIncarnation = s_incarnationRecord.incarnation; + } + do { + m_incarnation = static_cast(esp_random()); + } while (m_previousIncarnation && m_incarnation == *m_previousIncarnation); + s_incarnationRecord = + IncarnationRecord{kIncarnationMagic, m_incarnation, static_cast(~m_incarnation)}; + s_currentIncarnation = m_incarnation; + s_currentPrevious = m_previousIncarnation ? static_cast(*m_previousIncarnation) : -1; +#endif +} + +uint16_t Domain::currentGuidIncarnation() { #if defined(ESP_PLATFORM) - return incarnationState().current; + return s_currentIncarnation.load(); #else return 0; #endif } -std::optional Domain::previousGuidIncarnation() { +std::optional Domain::currentPreviousGuidIncarnation() { #if defined(ESP_PLATFORM) - const auto &s = incarnationState(); - if (s.hasPrevious) { - return s.previous; + const int32_t p = s_currentPrevious.load(); + if (p >= 0) { + return static_cast(p); } #endif return std::nullopt; @@ -114,6 +120,7 @@ Domain::Domain(const rtps::Ip4AddressBytes &localIpAddress, const DomainConfig & , m_transport(&m_defaultTransport) , m_localIpAddress(localIpAddress) , m_config(config) { + drawGuidIncarnation(); m_transportSetupOk = initializeTransport(); } @@ -124,6 +131,7 @@ Domain::Domain(rtps::EsppTransport &transport, const rtps::Ip4AddressBytes &loca , m_transport(&transport) , m_localIpAddress(localIpAddress) , m_config(config) { + drawGuidIncarnation(); m_transportSetupOk = initializeTransport(); } @@ -431,7 +439,7 @@ rtps::Participant *Domain::createParticipant() { auto &entry = m_participants[slot]; entry.reuse(generateGuidPrefix(candidate), candidate, m_localIpAddress, m_config.local_prefix_length); - if (const auto previous = previousGuidIncarnation(); previous.has_value()) { + if (const auto previous = m_previousIncarnation; previous.has_value()) { // The same board, participant id, vendor and domain with the previous // boot's incarnation bytes: what peers still hold if we came back within // our lease. Disposed by the SPDP agent before the first announcement. @@ -1090,9 +1098,8 @@ rtps::GuidPrefix_t Domain::generateGuidPrefix(ParticipantId_t id) const { // Bytes 10-11: this boot's incarnation (see guidIncarnation()). Everything // before it is stable across boots, which is what lets the SPDP agent // dispose the previous incarnation and peers tell the two apart. - const uint16_t incarnation = guidIncarnation(); - prefix.id[10] = static_cast(incarnation >> 8); - prefix.id[11] = static_cast(incarnation & 0xFF); + prefix.id[10] = static_cast(m_incarnation >> 8); + prefix.id[11] = static_cast(m_incarnation & 0xFF); return prefix; } #endif diff --git a/components/rtps/src/entities/Participant.cpp b/components/rtps/src/entities/Participant.cpp index 35d2325579..4470c100ab 100644 --- a/components/rtps/src/entities/Participant.cpp +++ b/components/rtps/src/entities/Participant.cpp @@ -556,8 +556,9 @@ const rtps::ParticipantProxyData *Participant::findRemoteParticipant(const GuidP return m_remoteParticipants.find(thunk, &isElementToFind); } -void Participant::refreshRemoteParticipantLiveliness(const GuidPrefix_t &prefix, - const SequenceNumber_t &sn) { +Participant::AnnouncementVerdict +Participant::noteRemoteParticipantAnnouncement(const GuidPrefix_t &prefix, + const SequenceNumber_t &sn) { std::lock_guard lock(m_mutex); auto isElementToFind = [&](const ParticipantProxyData &proxy) { return proxy.m_guid.prefix == prefix; @@ -566,12 +567,17 @@ void Participant::refreshRemoteParticipantLiveliness(const GuidPrefix_t &prefix, return (*static_cast(arg))(value); }; auto remoteParticipant = m_remoteParticipants.find(thunk, &isElementToFind); - if (remoteParticipant != nullptr) { - remoteParticipant->onAliveSignal(); - if (remoteParticipant->m_lastSpdpSn < sn) { - remoteParticipant->m_lastSpdpSn = sn; - } + if (remoteParticipant == nullptr) { + return AnnouncementVerdict::Unknown; + } + if (SPDPAgent::isRestart(sn, remoteParticipant->m_lastSpdpSn)) { + return AnnouncementVerdict::Restart; + } + remoteParticipant->onAliveSignal(); + if (remoteParticipant->m_lastSpdpSn < sn) { + remoteParticipant->m_lastSpdpSn = sn; } + return AnnouncementVerdict::Known; } void Participant::refreshRemoteParticipantLiveliness(const GuidPrefix_t &prefix) { diff --git a/components/rtps/src/entities/StatelessReader.cpp b/components/rtps/src/entities/StatelessReader.cpp index 887697f3b7..77971b9c13 100644 --- a/components/rtps/src/entities/StatelessReader.cpp +++ b/components/rtps/src/entities/StatelessReader.cpp @@ -76,18 +76,10 @@ void StatelessReader::newChange(const ReaderCacheChange &cacheChange) { // match are lost either way; the matched ones that follow arrive in order. // The builtin readers are exempt (the only stateless one is the SPDP // reader): participant announcements come from writers that are, by - // definition, not matched yet. - // - // The SPDP reader is exempt from the ordering rule as well. A peer that - // restarts with the same GUID prefix (a board rebooting within its lease: - // the prefix is MAC-based on ESP targets, and other stacks do the same) - // numbers its new SPDP writer from 1 again, below what its proxy here - // expects; dropping those announcements - and the dispose it may send first - // - would keep the stale participant, with every proxy of its endpoints, - // until the lease ran out, deaf to the restarted peer the whole time. The - // SPDP agent owns that judgement instead (SPDPAgent::isRestart, and its - // dispose memory for the duplicates); a repeated announcement only - // refreshes a lease, so nothing is lost by letting it through. + // definition, not matched yet. (The SPDP reader never holds a writer proxy, + // so the ordering rule never applies to announcements; a peer that restarts + // with the prefix we know it by is caught by the SPDP agent instead - + // SPDPAgent::isRestart.) // // The claim and the callbacks are one operation under m_delivery_mutex (as // in StatefulReader::newChange()): receive workers for different sockets @@ -103,7 +95,7 @@ void StatelessReader::newChange(const ReaderCacheChange &cacheChange) { }; auto it = std::find_if(m_proxies.begin(), m_proxies.end(), matches_writer); if (it != m_proxies.end()) { - if (cacheChange.sn < it->expectedSN && !isBuiltinEndpoint()) { + if (cacheChange.sn < it->expectedSN) { return; // a duplicate, or older than something already delivered } it->expectedSN = cacheChange.sn; diff --git a/pc/tests/rtps_participant_restart.cpp b/pc/tests/rtps_participant_restart.cpp index c64437c94c..336c9048f8 100644 --- a/pc/tests/rtps_participant_restart.cpp +++ b/pc/tests/rtps_participant_restart.cpp @@ -1,15 +1,15 @@ // A peer that restarts is rediscovered at once, not when its lease runs out. // // The GUID prefix of an embedded participant is built from the board's MAC, -// so a board that reboots within its lease comes back with a prefix its -// peers still hold - and every one of its writers numbers its samples from 1 -// again. A best-effort reader ignores a sequence number below the next it -// expects (RTPS 2.5 8.4.12.1), and the SPDP reader is one of those: the -// restarted peer's announcements were dropped too, so nothing happened until -// the lease sweep forgot the old incarnation (5 s for an ESP peer, 100 s for a -// host one), and the peer was deaf and mute to us the whole time. Three -// mechanisms close that window; this test drives all of them with hand-crafted -// datagrams fed to a real participant, as the dispose tests do: +// so a board that rebooted within its lease used to come back with the prefix +// its peers still held - and every one of its writers numbering its samples +// from 1 again. Its announcements only refreshed the known participant's +// lease, the stateful readers kept waiting for the old numbers and a +// best-effort reader ignored the restarted writer (RTPS 2.5 8.4.12.1), so +// nothing moved until the lease sweep forgot the old incarnation (5 s for an +// ESP peer, 100 s for a host one). This test drives the receiving side of the +// fix with hand-crafted datagrams fed to a real participant, as the dispose +// tests do: // // 1. Restart detection: an announcement from a known participant numbered // far below its highest (SPDPAgent::isRestart) forgets the participant @@ -18,11 +18,13 @@ // 2. A reordered or duplicated announcement (last - 1) is NOT a restart: // nothing is forgotten, a sample numbered after the ones delivered still // arrives. -// 3. Incarnation: a peer whose prefix differs only in the incarnation bytes -// (10-11) may dispose the old incarnation - the dispose is honoured as the -// participant's own, the old one goes at once, the new one is discovered. -// A dispose naming a participant from an unrelated prefix is still -// refused, and so is one from the same board but another participant id. +// 3. Incarnation: a rebooted board of this engine comes back with new +// incarnation bytes (10-11) and first disposes its previous incarnation +// AS that incarnation (old prefix, its SPDP writer, a sequence number +// above anything it sent): the old participant goes at once, the new one +// is discovered, and a stale announcement of the old one still in flight +// is ignored. A dispose naming a participant from any other prefix is +// refused, as before. // // Exits 0 on success, 1 on the first failed check. @@ -32,6 +34,7 @@ #include #include #include +#include #include #include @@ -43,7 +46,7 @@ namespace { constexpr rtps::Ip4AddressBytes kIp{127, 0, 0, 1}; -constexpr std::array kVendor{0x01, 0x0f}; // Fast DDS, as the other dispose tests +const std::array kVendor = rtps::Config::VENDOR_ID.vendorId; // an espp-shaped peer #define CHECK(cond, msg) \ do { \ @@ -203,7 +206,7 @@ std::vector data_message(const rtps::GuidPrefix_t &prefix, const rtps:: // Inline QoS of a participant dispose: the key hash of the disposed // participant and STATUS_INFO disposed|unregistered, as Fast DDS writes it and -// as this engine's SPDPAgent::disposePreviousIncarnation does. +// as this engine's SPDPAgent::sendPreviousIncarnationDispose does. std::vector participant_dispose_qos(const rtps::GuidPrefix_t &disposed) { using rtps::SMElement::ParameterId; std::vector q; @@ -271,11 +274,10 @@ struct Peer { feed(part, data_message(prefix, writer_guid().entityId, rtps::ENTITYID_UNKNOWN, ++data_sn, {}, sample_payload(value))); } - // Dispose `disposed` from this peer's SPDP writer (the dispose a restarted - // board sends for its previous incarnation). - void dispose(rtps::Participant *part, const rtps::GuidPrefix_t &disposed) { + // Dispose `disposed` from this peer's SPDP writer, numbered `sn`. + void dispose(rtps::Participant *part, const rtps::GuidPrefix_t &disposed, uint32_t sn) { feed(part, data_message(prefix, rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_WRITER, - rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_READER, ++spdp_sn, + rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_READER, sn, participant_dispose_qos(disposed), {})); } // The peer rebooted: every writer starts at 1 again. @@ -350,41 +352,29 @@ bool run_checks() { CHECK(g_received == 11, "rebooted peer: its samples 1..3 delivered"); CHECK(g_last_value == 23, "rebooted peer: the last one is sample 3 of the new stream"); - // --- 3. a new incarnation disposes the old one -------------------------------------------- + // --- 3. the board reboots into a new incarnation and disposes the old one ----------------- + // What a rebooted board of this engine sends first (SPDPAgent:: + // sendPreviousIncarnationDispose): a dispose of the OLD participant, as the + // old participant - its prefix, its SPDP writer - with a sequence number + // above anything that writer reached. Then the new incarnation announces. Peer next = peer; next.reboot(); next.prefix.id[10] = 0x33; // the incarnation bytes change, nothing else next.prefix.id[11] = 0x44; - // a dispose from an unrelated prefix naming the peer: refused + // a dispose from an unrelated prefix naming the peer: refused, as always Peer stranger{{{0x24, 0x6f, 0x28, 0x01, 0x02, 0x03, 0, vid[0], vid[1], 0, 0x11, 0x22}}}; - // ... and from another vendor's prefix that happens to differ in bytes 10-11 - // only (Fast DDS keeps its in-process participant id there): refused - Peer foreign = next; - foreign.prefix.id[7] = kVendor[0]; - foreign.prefix.id[8] = kVendor[1]; - Peer foreign_old = peer; - foreign_old.prefix.id[7] = kVendor[0]; - foreign_old.prefix.id[8] = kVendor[1]; - foreign_old.announce(part); - CHECK(part->getRemoteParticipantCount() == 2, "a foreign-vendor participant discovered"); - foreign.dispose(part, foreign_old.prefix); - CHECK(part->getRemoteParticipantCount() == 2, - "dispose across bytes 10-11 of a foreign prefix: refused"); - foreign_old.dispose(part, foreign_old.prefix); // its own: honoured, as before - CHECK(part->getRemoteParticipantCount() == 1, "a foreign participant's own dispose: honoured"); - stranger.dispose(part, peer.prefix); + stranger.dispose(part, peer.prefix, 1); CHECK(part->getRemoteParticipantCount() == 1, "dispose from a stranger: refused"); - // from the same board, another participant id: refused too - Peer sibling = next; - sibling.prefix.id[6] = 1; - sibling.dispose(part, peer.prefix); - CHECK(part->getRemoteParticipantCount() == 1, "dispose from another participant id: refused"); + // ... and from the next incarnation's own writer naming the old one: another + // prefix is another participant, refused too (the engine does not send that) + next.dispose(part, peer.prefix, 1); + CHECK(part->getRemoteParticipantCount() == 1, "dispose from another prefix: refused"); CHECK(reader->getProxiesCount() == 1, "refused disposes change nothing"); - // from the next incarnation: honoured, the old one goes at once - next.dispose(part, peer.prefix); // the new SPDP writer's first change (SN 1) - CHECK(part->getRemoteParticipantCount() == 0, "dispose from the next incarnation: honoured"); - CHECK(reader->getProxiesCount() == 0, "next incarnation: the old writer proxy is gone"); - next.announce(part); // SN 2 + // the old incarnation's own dispose, numbered beyond its last announcement + peer.dispose(part, peer.prefix, std::numeric_limits::max()); + CHECK(part->getRemoteParticipantCount() == 0, "the previous incarnation's dispose: honoured"); + CHECK(reader->getProxiesCount() == 0, "previous incarnation: the old writer proxy is gone"); + next.announce(part); CHECK(part->getRemoteParticipantCount() == 1, "next incarnation discovered"); next.announce_writer(part); CHECK(reader->getProxiesCount() == 1, "next incarnation: its writer matched"); @@ -393,9 +383,9 @@ bool run_checks() { } CHECK(g_received == 14 && g_last_value == 33, "next incarnation: samples delivered"); // a stale announcement of the old incarnation still in flight (a delayed - // datagram) must not bring the dead participant back next to the new one: - // the dispose is remembered as newer than anything the old one numbered - peer.announce_with(part, 2); + // datagram, numbered below the dispose) must not bring the dead participant + // back next to the new one + peer.announce_with(part, 9); CHECK(part->getRemoteParticipantCount() == 1, "stale old-incarnation announcement: ignored"); CHECK(reader->getProxiesCount() == 1, "stale old-incarnation announcement: new proxy kept"); next.publish(part, 34); From c475d434826f3c612e2cfbaa2a60484bf4d54140 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 17 Nov 2026 12:24:16 -0600 Subject: [PATCH 04/11] test(rtps): the restart test's dispose helper is const (cppcheck) Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- pc/tests/rtps_participant_restart.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pc/tests/rtps_participant_restart.cpp b/pc/tests/rtps_participant_restart.cpp index 336c9048f8..5e707dc943 100644 --- a/pc/tests/rtps_participant_restart.cpp +++ b/pc/tests/rtps_participant_restart.cpp @@ -275,7 +275,7 @@ struct Peer { sample_payload(value))); } // Dispose `disposed` from this peer's SPDP writer, numbered `sn`. - void dispose(rtps::Participant *part, const rtps::GuidPrefix_t &disposed, uint32_t sn) { + void dispose(rtps::Participant *part, const rtps::GuidPrefix_t &disposed, uint32_t sn) const { feed(part, data_message(prefix, rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_WRITER, rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_READER, sn, participant_dispose_qos(disposed), {})); From 4eb0bd7fe99aea5348e8b947ad2881d9b0a8a9ec Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 17 Nov 2026 13:14:36 -0600 Subject: [PATCH 05/11] test(rtps): deliver the QEMU RESTART reliably; shorten the ignore-guard to 5 s The first CI run of the restart cases showed the engine fix working on the cyclone pass (incarnation cur/prev, the daemon drops to one publisher at once) but the fastdds and espp-host cases failed at "the device did not take the RESTART": `ros2 topic pub --once -w 1` publishes a single reliable sample right after the match and does not reliably reach the device, and the firmware's 20 s ignore-guard was longer than the spacing between cases, so a just-restarted participant swallowed the next case's RESTART too. Publish RESTART at 2 Hz after the subscriber matches (`-w 1 -r 2`) and stop it the moment the device takes the restart, so the new participant gets no copy; the firmware ignore-guard drops to 5 s as a backstop for an in-flight duplicate. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/interop/qemu/main/rtps_qemu.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/components/rtps/interop/qemu/main/rtps_qemu.cpp b/components/rtps/interop/qemu/main/rtps_qemu.cpp index a6469299f7..21ec700ad5 100644 --- a/components/rtps/interop/qemu/main/rtps_qemu.cpp +++ b/components/rtps/interop/qemu/main/rtps_qemu.cpp @@ -18,7 +18,7 @@ // after a software reset (esp_timer interrupt // allocation), so the participant restarts, as an // application recreating its Domain would. Ignored, -// with a marker, in the first 20 s of a participant. +// with a marker, in the first 5 s of a participant. // RTPSTEST pub_matched/sub_matched a writer / reader gained a remote peer // RTPSTEST tx reliable publisher sent "qemu " // RTPSTEST rx reliable subscriber received @@ -247,11 +247,11 @@ static void run_participant(espp::Logger &logger, const std::string &interface_a // harness repeats the sample for a few seconds so a // just-matched writer gets it through; copies that // reach the NEW participant are ignored for its - // first 20 s. + // first 5 s. const auto up_s = std::chrono::duration_cast( std::chrono::steady_clock::now() - boot_time) .count(); - if (up_s < 20) { + if (up_s < 5) { logger.info("RTPSTEST restart ignored (participant {} s old)", up_s); } else if (!restart_requested.exchange(true)) { From 791f136e0d5272e51eec6bce90751fac2da41029 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 17 Nov 2026 14:09:49 -0600 Subject: [PATCH 06/11] test(rtps): trigger the QEMU restart through the service, not a topic sample The topic-based RESTART trigger was never reliably delivered on the fastdds pass (a single reliable sample to a freshly-matched reader, and even -r 2 to a new publisher participant, did not reach the device, while the cyclone pass won the timing). The restart now rides the already-matched /qemu_add_two_ints request/reply channel, which both RMWs proved reliable (the service case passes): a magic request (a=424242, b=0) restarts the participant after the reply goes out. The topic callback no longer carries the trigger. (The earlier -w1/-r2 harness change in this branch did not actually land - a multi-edit threw before writing - which is why the previous CI run repeated the failure.) Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- .../rtps/interop/qemu/main/rtps_qemu.cpp | 110 +++++++----------- components/rtps/interop/run_qemu_interop.sh | 26 +++-- 2 files changed, 55 insertions(+), 81 deletions(-) diff --git a/components/rtps/interop/qemu/main/rtps_qemu.cpp b/components/rtps/interop/qemu/main/rtps_qemu.cpp index 21ec700ad5..5fb2c06606 100644 --- a/components/rtps/interop/qemu/main/rtps_qemu.cpp +++ b/components/rtps/interop/qemu/main/rtps_qemu.cpp @@ -10,48 +10,13 @@ // RTPSTEST incarnation cur= prev= the GUID prefix incarnation of // this boot and, after a software reset, of the // previous one (which the engine disposes first) -// RTPSTEST restart a "RESTART" sample arrived on rt/qemu_rx: the -// firmware tears its participant down and creates a -// new one (a new GUID incarnation, which first disposes -// the previous one) - the restart case. Not esp_restart: -// QEMU's emulated chip panics in ESP-IDF's startup -// after a software reset (esp_timer interrupt -// allocation), so the participant restarts, as an -// application recreating its Domain would. Ignored, -// with a marker, in the first 5 s of a participant. -// RTPSTEST pub_matched/sub_matched a writer / reader gained a remote peer -// RTPSTEST tx reliable publisher sent "qemu " -// RTPSTEST rx reliable subscriber received -// RTPSTEST be_rx best-effort subscriber received -// RTPSTEST big_rx len= fragmented-sample subscriber received n bytes -// 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= -// the engine's compile-time-sized objects (bytes) -// RTPSTEST mem heap internal= internal_min= internal_largest= psram= psram_largest= -// at boot, started, endpoints: the memory suite's deltas -// -// Topics (ROS 2 names: "rt/" prefix stripped, std_msgs/msg/String): -// rt/qemu_tx reliable, device publishes "qemu " every 200 ms -// rt/qemu_rx reliable, device subscribes -// rt/qemu_be_tx best-effort, device publishes "qemu_be " every 200 ms -// rt/qemu_be_rx best-effort, device subscribes -// rt/qemu_big reliable, device subscribes (fragmented samples) -// /qemu_add_two_ints example_interfaces/srv/AddTwoInts service the device serves -// /qemu_fibonacci example_interfaces/action/Fibonacci action the device serves -// (one execute worker: the memory suite reads its cost) +// RTPSTEST restart the restart case called /qemu_add_two_ints with a +// magic request: the firmware tears its participant +// down and creates a new one (a new GUID incarnation, +// which first disposes the previous one). Not +// esp_restart: QEMU's emulated chip panics in +// ESP-IDF startup after a software reset. Ignored in +// the first 5 s of a participant. #include #include @@ -193,6 +158,10 @@ extern "C" void app_main(void) { static void run_participant(espp::Logger &logger, const std::string &interface_address, const std::string &interface_netmask) { const auto boot_time = std::chrono::steady_clock::now(); + // The restart case calls /qemu_add_two_ints with this magic pair to ask the + // device to recreate its participant (see the service handler below). + constexpr int64_t kRestartMagicA = 424242; + constexpr int64_t kRestartMagicB = 0; std::atomic restart_requested{false}; // Counters for the status line (the callbacks run on the engine's threads) std::atomic tx_count{0}; @@ -233,33 +202,17 @@ static void run_participant(espp::Logger &logger, const std::string &interface_a .type_name = type_name, .reliability = Reliability::RELIABLE, }); - espp::Subscriber subscriber( - participant, { - .topic = "rt/qemu_rx", - .type_name = type_name, - .reliability = Reliability::RELIABLE, - .on_message = - [&](const StringMsg &msg) { - rx_count++; - logger.info("RTPSTEST rx {}", msg.data); - if (msg.data == "RESTART") { - // the restart case (see the header comment). The - // harness repeats the sample for a few seconds so a - // just-matched writer gets it through; copies that - // reach the NEW participant are ignored for its - // first 5 s. - const auto up_s = std::chrono::duration_cast( - std::chrono::steady_clock::now() - boot_time) - .count(); - if (up_s < 5) { - logger.info("RTPSTEST restart ignored (participant {} s old)", - up_s); - } else if (!restart_requested.exchange(true)) { - logger.info("RTPSTEST restart"); - } - } - }, - }); + espp::Subscriber subscriber(participant, { + .topic = "rt/qemu_rx", + .type_name = type_name, + .reliability = Reliability::RELIABLE, + .on_message = + [&](const StringMsg &msg) { + rx_count++; + logger.info("RTPSTEST rx {}", + msg.data); + }, + }); espp::Publisher be_publisher(participant, { .topic = "rt/qemu_be_tx", .type_name = type_name, @@ -303,6 +256,25 @@ static void run_participant(espp::Logger &logger, const std::string &interface_a .handler = [&](const AddReq &r) { logger.info("RTPSTEST srv {}+{}={}", r.a, r.b, r.a + r.b); + // The restart case triggers through this reliable, + // already-matched request/reply channel (a topic + // sample to a freshly-matched reliable reader is + // not reliably delivered on every RMW). The magic + // request restarts the participant AFTER the reply + // goes out (the status loop tears down ~2 s later); + // ignored in the participant's first 5 s so an + // in-flight retry does not restart the new one. + if (r.a == kRestartMagicA && r.b == kRestartMagicB) { + const auto up_s = std::chrono::duration_cast( + std::chrono::steady_clock::now() - boot_time) + .count(); + if (up_s < 5) { + logger.info("RTPSTEST restart ignored (participant {} s old)", + up_s); + } else if (!restart_requested.exchange(true)) { + logger.info("RTPSTEST restart"); + } + } return AddResp{r.a + r.b}; }, }); diff --git a/components/rtps/interop/run_qemu_interop.sh b/components/rtps/interop/run_qemu_interop.sh index d870d98a8d..bdfdfe19c3 100755 --- a/components/rtps/interop/run_qemu_interop.sh +++ b/components/rtps/interop/run_qemu_interop.sh @@ -181,11 +181,11 @@ source "/opt/ros/${ROS_DISTRO:-jazzy}/setup.bash" export ROS_DOMAIN_ID=0 # matches the engine's Config::DOMAIN_ID run_matrix() { -# The device restarts its participant (on a "RESTART" sample, see -# rtps_qemu.cpp; a software reset of the emulated chip trips a QEMU startup -# bug, so the firmware recreates its Domain instead, which is what a board's -# reboot does to its peers) while a ROS 2 subscriber and a ROS 2 publisher of -# the current rmw stay up. Its GUID prefix is MAC-based, so before the fix it +# The device restarts its participant (triggered through its /qemu_add_two_ints +# service with a magic request, see rtps_qemu.cpp; a software reset of the +# emulated chip trips a QEMU startup bug, so the firmware recreates its Domain +# instead, which is what a board's reboot does to its peers) while a ROS 2 +# subscriber and a ROS 2 publisher of the current rmw stay up. Its GUID prefix is MAC-based, so before the fix it # came back as the participant the peers still held, with every writer # numbered from 1 again: the peers' readers rejected those numbers and nothing # moved until the old lease (30 s in sdkconfig.ci.defaults, so a restart cannot @@ -211,11 +211,13 @@ device_restart_case() { # prefix log-tag local pub=$! sleep 10 # both matched and flowing, and the daemon knows the device m=$(mark) - # published once the device's subscriber is matched (-w 1), then exits: a - # single RESTART, the rebooted device must not get it again - timeout 20 ros2 topic pub --once -w 1 /qemu_rx std_msgs/msg/String "data: 'RESTART'" > /dev/null 2>&1 - if ! wait_for_marker_since "$m" "RTPSTEST restart" 15; then - echo " the device did not take the RESTART"; rc=1 + # Trigger the restart through the already-matched service (a topic sample to + # a freshly-matched reliable reader is not reliably delivered on every RMW); + # the magic request restarts the device after it replies (rtps_qemu.cpp). + timeout 20 ros2 service call /qemu_add_two_ints example_interfaces/srv/AddTwoInts \ + "{a: 424242, b: 0}" > /dev/null 2>&1 + if ! wait_for_marker_since "$m" "RTPSTEST restart" 20; then + echo " the device did not take the restart"; rc=1 fi local boot; boot=$(mark) if [ $rc -eq 0 ] && ! wait_for_marker_since "$boot" "RTPSTEST ready" 60; then @@ -451,9 +453,9 @@ note "the device restarts while the espp host publisher runs: the rebooted devic m=$(mark) "$BIN"/rtps_interop_pub rt/qemu_rx std_msgs::msg::dds_::String_ 1 400 200 $HOST_IP > /tmp/hostpub_restart.log 2>&1 & pub=$!; sleep 10 -timeout 20 ros2 topic pub --once -w 1 /qemu_rx std_msgs/msg/String "data: 'RESTART'" > /dev/null 2>&1 +timeout 20 ros2 service call /qemu_add_two_ints example_interfaces/srv/AddTwoInts "{a: 424242, b: 0}" > /dev/null 2>&1 rc=0 -wait_for_marker_since "$m" "RTPSTEST restart" 15 || rc=1 +wait_for_marker_since "$m" "RTPSTEST restart" 20 || rc=1 boot=$(mark) [ $rc -eq 0 ] && { wait_for_marker_since "$boot" "RTPSTEST ready" 60 || rc=1; } if [ $rc -eq 0 ]; then From 26238aed63510b98323c45bbccdf657821fc753c Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 17 Nov 2026 15:00:12 -0600 Subject: [PATCH 07/11] test(rtps): move the QEMU restart-magic constants to file scope (cppcheck) cppcheck flagged the function-local kRestartMagicA/B as unread - it does not connect their use inside the nested service-handler lambda. At namespace scope the use is plain. No behaviour change. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/interop/qemu/main/rtps_qemu.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/components/rtps/interop/qemu/main/rtps_qemu.cpp b/components/rtps/interop/qemu/main/rtps_qemu.cpp index 5fb2c06606..d3e712d11c 100644 --- a/components/rtps/interop/qemu/main/rtps_qemu.cpp +++ b/components/rtps/interop/qemu/main/rtps_qemu.cpp @@ -65,6 +65,10 @@ void log_mem_heap(espp::Logger &logger, const char *stage) { heap_caps_get_free_size(MALLOC_CAP_SPIRAM), heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM)); } +// The restart case calls /qemu_add_two_ints with this magic request to ask the +// device to recreate its participant (see the service handler in run_participant). +constexpr int64_t kRestartMagicA = 424242; +constexpr int64_t kRestartMagicB = 0; } // namespace using namespace std::chrono_literals; @@ -158,10 +162,6 @@ extern "C" void app_main(void) { static void run_participant(espp::Logger &logger, const std::string &interface_address, const std::string &interface_netmask) { const auto boot_time = std::chrono::steady_clock::now(); - // The restart case calls /qemu_add_two_ints with this magic pair to ask the - // device to recreate its participant (see the service handler below). - constexpr int64_t kRestartMagicA = 424242; - constexpr int64_t kRestartMagicB = 0; std::atomic restart_requested{false}; // Counters for the status line (the callbacks run on the engine's threads) std::atomic tx_count{0}; From cdbb6933831ee80da0ed5861c3e5b35236f4759b Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 17 Nov 2026 15:50:09 -0600 Subject: [PATCH 08/11] test(rtps): restart the QEMU device once per boot (FastDDS); repeated recreate is fragile With the service-triggered restart delivering reliably, the FastDDS restart cases pass (incarnation rotates, the ROS 2 daemon drops the old participant at once, the previous incarnation is remembered and disposed) and so does the espp-host one. But the device "reboots" by recreating its espp participant in-process (a chip reset trips a QEMU startup bug), and doing that several times in one boot is not yet robust: after a couple of cycles the engine's teardown leaves a task that fires into freed state, the device panics, and QEMU cannot survive the reboot. That is a separate teardown-robustness follow-up, not the discovery fix under test. So the matrix restarts the device once, on the FastDDS pass - enough to prove a real DDS stack honours the standard participant dispose the device sends. The receive side for every peer (and the espp host engine) is covered by pc/tests/rtps_participant_restart.cpp. The per-rmw and espp-host restart cases are dropped. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/interop/README.md | 2 +- components/rtps/interop/run_qemu_interop.sh | 47 +++++++++------------ 2 files changed, 22 insertions(+), 27 deletions(-) diff --git a/components/rtps/interop/README.md b/components/rtps/interop/README.md index 436b94bc30..46e4d434f5 100644 --- a/components/rtps/interop/README.md +++ b/components/rtps/interop/README.md @@ -85,7 +85,7 @@ cd .. && ./run_qemu.sh | device_boot, device_ping | the engine comes up on lwIP over the emulated OpenCores MAC | | device_pub->ros2_echo, ros2_pub->device_sub (+ best-effort pair) | delivery both ways, FastDDS and CycloneDDS | | ros2_pub->device_sub_liveliness | samples still arriving 24-34 s in, past the remote lease | -| restart__rediscovered_by_ros2_sub, restart__device_sub_receives, restart__old_incarnation_dropped, restart_previous_incarnation_remembered, restart_espp_host_pub->device_sub | the device restarts its participant on a "RESTART" sample (it recreates its Domain - what a board's reboot looks like to its peers; a software reset of QEMU's emulated chip panics inside ESP-IDF's startup, so the chip is not rebooted) while a ROS 2 subscriber, a ROS 2 publisher and, in the host-engine case, an espp publisher stay up. It announces a 30 s lease for itself in `sdkconfig.ci.defaults`, so the old incarnation cannot expire during the restart: the ROS 2 subscriber must receive the restarted publisher's first samples ("qemu 0".."qemu 9") and the restarted device the ROS 2 publisher's samples within seconds. The GUID prefix carries a per-Domain incarnation (bytes 10-11, `Domain::guidIncarnation`); the previous one is kept in RTC memory (`RTPSTEST incarnation cur= prev=`, `restart_previous_incarnation_remembered`) and disposed as that participant on the first announce cycles, so the ROS 2 daemon's count of publishers on the device's topic drops back to one within seconds instead of after the 30 s lease (`restart__old_incarnation_dropped`) | +| restart_fastdds_rediscovered_by_ros2_sub, restart_fastdds_device_sub_receives, restart_fastdds_old_incarnation_dropped, restart_previous_incarnation_remembered | the device restarts its participant on a "RESTART" sample (it recreates its Domain - what a board's reboot looks like to its peers; a software reset of QEMU's emulated chip panics inside ESP-IDF's startup, so the chip is not rebooted) (once per boot, on the FastDDS pass: recreating the espp participant in-process repeatedly in one QEMU boot is not yet robust, a separate follow-up; the receive side for every peer, and the espp host engine, are covered by `pc/tests/rtps_participant_restart.cpp`) while a ROS 2 subscriber and a ROS 2 publisher stay up. It announces a 30 s lease for itself in `sdkconfig.ci.defaults`, so the old incarnation cannot expire during the restart: the ROS 2 subscriber must receive the restarted publisher's first samples ("qemu 0".."qemu 9") and the restarted device the ROS 2 publisher's samples within seconds. The GUID prefix carries a per-Domain incarnation (bytes 10-11, `Domain::guidIncarnation`); the previous one is kept in RTC memory (`RTPSTEST incarnation cur= prev=`, `restart_previous_incarnation_remembered`) and disposed as that participant on the first announce cycles, so the ROS 2 daemon's count of publishers on the device's topic drops back to one within seconds instead of after the 30 s lease (`restart__old_incarnation_dropped`) | | 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 | diff --git a/components/rtps/interop/run_qemu_interop.sh b/components/rtps/interop/run_qemu_interop.sh index bdfdfe19c3..f095a159ce 100755 --- a/components/rtps/interop/run_qemu_interop.sh +++ b/components/rtps/interop/run_qemu_interop.sh @@ -185,7 +185,9 @@ run_matrix() { # service with a magic request, see rtps_qemu.cpp; a software reset of the # emulated chip trips a QEMU startup bug, so the firmware recreates its Domain # instead, which is what a board's reboot does to its peers) while a ROS 2 -# subscriber and a ROS 2 publisher of the current rmw stay up. Its GUID prefix is MAC-based, so before the fix it +# subscriber and a ROS 2 publisher stay up. Called once per boot (FastDDS); a +# real DDS stack honouring the standard participant dispose the device sends is +# what this proves, and the host test covers the receive side for every peer. Its GUID prefix is MAC-based, so before the fix it # came back as the participant the peers still held, with every writer # numbered from 1 again: the peers' readers rejected those numbers and nothing # moved until the old lease (30 s in sdkconfig.ci.defaults, so a restart cannot @@ -310,9 +312,20 @@ ros2_cases() { # prefix log-tag tail -2 "/tmp/${t}_srv.log"; result "${p}ros2_client->device_service" $rc settle - note "${p}the device restarts within its lease: the ROS 2 peers drop the old incarnation and talk to the new one" - device_restart_case "${p}" "${t}" - settle + # Restart the device's participant once per firmware boot, on the FastDDS + # pass. Recreating the espp participant in-process is how the device + # "reboots" here (a chip reset trips a QEMU startup bug - see + # device_restart_case); doing it repeatedly in one boot is not yet robust + # (the engine's teardown leaves a task that can fire into freed state after a + # few cycles - a separate follow-up), so the matrix exercises it once. The + # host test (pc/tests/rtps_participant_restart.cpp) covers the receive side + # for any peer; the dispose the device sends is the standard participant + # dispose every DDS honours, so one real-stack pass is enough to prove interop. + if [ "${t}" = fastdds ]; then + note "${p}the device restarts within its lease: the ROS 2 peers drop the old incarnation and talk to the new one" + device_restart_case "${p}" "${t}" + settle + fi note "${p}twelve other participants on the domain, then the publisher the device needs joins last" local crowd=() i @@ -445,28 +458,10 @@ note "device publisher -> espp host subscriber (reliable, /qemu_tx)" rc=$?; tail -2 /tmp/hostsub.log; result "device_pub->espp_host_sub" $rc settle -note "the device restarts while the espp host publisher runs: the rebooted device receives again at once" -# The host engine holds the device's previous incarnation until its dispose -# arrives (sent as that incarnation on the device's first announce cycles) and -# discovers the new one; the host publisher's samples must reach the rebooted -# device within a few seconds of its boot. -m=$(mark) -"$BIN"/rtps_interop_pub rt/qemu_rx std_msgs::msg::dds_::String_ 1 400 200 $HOST_IP > /tmp/hostpub_restart.log 2>&1 & -pub=$!; sleep 10 -timeout 20 ros2 service call /qemu_add_two_ints example_interfaces/srv/AddTwoInts "{a: 424242, b: 0}" > /dev/null 2>&1 -rc=0 -wait_for_marker_since "$m" "RTPSTEST restart" 20 || rc=1 -boot=$(mark) -[ $rc -eq 0 ] && { wait_for_marker_since "$boot" "RTPSTEST ready" 60 || rc=1; } -if [ $rc -eq 0 ]; then - t0=$(date +%s); n=0 - for i in $(seq 1 25); do n=$(count_since "$boot" "RTPSTEST rx espp interop"); [ "$n" -ge 5 ] && break; sleep 1; done - echo " rebooted device received $n from the espp host publisher after $(( $(date +%s) - t0 )) s" - [ "$n" -ge 5 ] || rc=1 -fi -stop_pids $pub -result "restart_espp_host_pub->device_sub" $rc -settle +# NOTE: the device restarts its participant once per boot, on the FastDDS pass +# above (recreating it repeatedly in one QEMU boot is not yet robust - see +# device_restart_case). The espp host engine's handling of a restarted peer is +# covered by pc/tests/rtps_participant_restart.cpp. note "espp host publisher -> device subscriber, 30 KB samples as DATA_FRAG (1400-byte fragments, /qemu_big)" # The ROS 2 peers send a 30 KB sample as one IP-fragmented UDP datagram (lwIP From 5c75c6d03ad07466abd8725c57cd9b6b603b8a4b Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 17 Nov 2026 15:58:55 -0600 Subject: [PATCH 09/11] test(rtps): restart the QEMU device on both rmw passes (FastDDS and CycloneDDS) The engine fix must be proven against CycloneDDS too, not only FastDDS. The last run showed two in-process participant recreates in one boot are stable (the FastDDS and espp-host restarts both passed); only a third crashed, from internal-RAM fragmentation as each recreate reallocates the engine's task stacks. So restart once on each rmw pass - FastDDS and CycloneDDS get a real peer to honour the device's dispose - and drop the redundant espp-host restart (the host test covers that side). The repeated-recreate fragmentation stays a separate teardown follow-up. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/interop/README.md | 2 +- components/rtps/interop/run_qemu_interop.sh | 28 ++++++++++----------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/components/rtps/interop/README.md b/components/rtps/interop/README.md index 46e4d434f5..e650a47bab 100644 --- a/components/rtps/interop/README.md +++ b/components/rtps/interop/README.md @@ -85,7 +85,7 @@ cd .. && ./run_qemu.sh | device_boot, device_ping | the engine comes up on lwIP over the emulated OpenCores MAC | | device_pub->ros2_echo, ros2_pub->device_sub (+ best-effort pair) | delivery both ways, FastDDS and CycloneDDS | | ros2_pub->device_sub_liveliness | samples still arriving 24-34 s in, past the remote lease | -| restart_fastdds_rediscovered_by_ros2_sub, restart_fastdds_device_sub_receives, restart_fastdds_old_incarnation_dropped, restart_previous_incarnation_remembered | the device restarts its participant on a "RESTART" sample (it recreates its Domain - what a board's reboot looks like to its peers; a software reset of QEMU's emulated chip panics inside ESP-IDF's startup, so the chip is not rebooted) (once per boot, on the FastDDS pass: recreating the espp participant in-process repeatedly in one QEMU boot is not yet robust, a separate follow-up; the receive side for every peer, and the espp host engine, are covered by `pc/tests/rtps_participant_restart.cpp`) while a ROS 2 subscriber and a ROS 2 publisher stay up. It announces a 30 s lease for itself in `sdkconfig.ci.defaults`, so the old incarnation cannot expire during the restart: the ROS 2 subscriber must receive the restarted publisher's first samples ("qemu 0".."qemu 9") and the restarted device the ROS 2 publisher's samples within seconds. The GUID prefix carries a per-Domain incarnation (bytes 10-11, `Domain::guidIncarnation`); the previous one is kept in RTC memory (`RTPSTEST incarnation cur= prev=`, `restart_previous_incarnation_remembered`) and disposed as that participant on the first announce cycles, so the ROS 2 daemon's count of publishers on the device's topic drops back to one within seconds instead of after the 30 s lease (`restart__old_incarnation_dropped`) | +| restart__rediscovered_by_ros2_sub, restart__device_sub_receives, restart__old_incarnation_dropped, restart_previous_incarnation_remembered | the device restarts its participant on a "RESTART" sample (it recreates its Domain - what a board's reboot looks like to its peers; a software reset of QEMU's emulated chip panics inside ESP-IDF's startup, so the chip is not rebooted) (once on each rmw pass, FastDDS and CycloneDDS, so a real peer of each stack honours the dispose the restarted device sends; the espp participant is recreated in-process to "reboot" - a chip reset trips a QEMU startup bug - and that fragments internal RAM, so two recreates per boot is the ceiling and no third is done, a teardown/fragmentation follow-up; the espp host engine's side is covered by `pc/tests/rtps_participant_restart.cpp`) while a ROS 2 subscriber and a ROS 2 publisher stay up. It announces a 30 s lease for itself in `sdkconfig.ci.defaults`, so the old incarnation cannot expire during the restart: the ROS 2 subscriber must receive the restarted publisher's first samples ("qemu 0".."qemu 9") and the restarted device the ROS 2 publisher's samples within seconds. The GUID prefix carries a per-Domain incarnation (bytes 10-11, `Domain::guidIncarnation`); the previous one is kept in RTC memory (`RTPSTEST incarnation cur= prev=`, `restart_previous_incarnation_remembered`) and disposed as that participant on the first announce cycles, so the ROS 2 daemon's count of publishers on the device's topic drops back to one within seconds instead of after the 30 s lease (`restart__old_incarnation_dropped`) | | 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 | diff --git a/components/rtps/interop/run_qemu_interop.sh b/components/rtps/interop/run_qemu_interop.sh index f095a159ce..aa4b24f83e 100755 --- a/components/rtps/interop/run_qemu_interop.sh +++ b/components/rtps/interop/run_qemu_interop.sh @@ -312,20 +312,20 @@ ros2_cases() { # prefix log-tag tail -2 "/tmp/${t}_srv.log"; result "${p}ros2_client->device_service" $rc settle - # Restart the device's participant once per firmware boot, on the FastDDS - # pass. Recreating the espp participant in-process is how the device - # "reboots" here (a chip reset trips a QEMU startup bug - see - # device_restart_case); doing it repeatedly in one boot is not yet robust - # (the engine's teardown leaves a task that can fire into freed state after a - # few cycles - a separate follow-up), so the matrix exercises it once. The - # host test (pc/tests/rtps_participant_restart.cpp) covers the receive side - # for any peer; the dispose the device sends is the standard participant - # dispose every DDS honours, so one real-stack pass is enough to prove interop. - if [ "${t}" = fastdds ]; then - note "${p}the device restarts within its lease: the ROS 2 peers drop the old incarnation and talk to the new one" - device_restart_case "${p}" "${t}" - settle - fi + # Restart the device's participant once on EACH rmw pass (FastDDS and + # CycloneDDS), so a real peer of each stack is proven to honour the dispose + # the restarted device sends. Recreating the espp participant in-process is + # how the device "reboots" here (a chip reset trips a QEMU startup bug - see + # device_restart_case). That recreate frees and reallocates the engine's + # FreeRTOS task stacks in internal RAM, which fragments it; two recreates in + # one boot are stable, but more are not yet (a stack allocation eventually + # fails and the device aborts - a separate teardown/fragmentation follow-up). + # So the two rmw passes get one restart each and no third is done (the + # espp-host engine's handling of a restarted peer is covered by + # pc/tests/rtps_participant_restart.cpp). + note "${p}the device restarts within its lease: the ROS 2 peers drop the old incarnation and talk to the new one" + device_restart_case "${p}" "${t}" + settle note "${p}twelve other participants on the domain, then the publisher the device needs joins last" local crowd=() i From d56b767ed2365760a39f90f7927abeefe33f9354 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 17 Nov 2026 17:36:22 -0600 Subject: [PATCH 10/11] test(rtps): restart the QEMU device once, watched by both RMW stacks The device "reboots" in QEMU by recreating its espp participant in-process (a chip reset trips a QEMU startup bug). That recreate frees and reallocates the engine's FreeRTOS task stacks in internal RAM and fragments it: the first recreate is reliable, but a second one eventually fails a stack allocation and the device aborts. Restarting once per rmw pass therefore crashed the device on the second (CycloneDDS) recreate, so the CycloneDDS dispose was never actually verified and device_no_crash failed. Do the restart exactly once for the whole run, on the FastDDS pass, with BOTH a FastDDS and a CycloneDDS peer watching that single restart. Each stack's own subscriber proves the new incarnation is accepted at once (its echo receives the restarted publisher's "qemu 0".. samples, daemon-independent), and each stack's ROS 2 daemon proves the dispose is honoured (publisher count on the device topic drops back to one within seconds instead of after the 30 s lease). The dispose checks also require the daemon to have seen the live publisher before the restart, so a daemon that never discovered cannot read as a trivial pass. Results are now restart_fastdds_rediscovered_by_ros2_sub, restart_cyclone_rediscovered_by_ros2_sub, restart_device_sub_receives, restart_fastdds_old_incarnation_dropped, restart_cyclone_old_incarnation_dropped and restart_previous_incarnation_remembered. The espp host engine's own handling of a restarted peer stays covered by pc/tests/rtps_participant_restart.cpp. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/interop/README.md | 2 +- components/rtps/interop/run_qemu_interop.sh | 128 ++++++++++++-------- 2 files changed, 80 insertions(+), 50 deletions(-) diff --git a/components/rtps/interop/README.md b/components/rtps/interop/README.md index e650a47bab..6308f68266 100644 --- a/components/rtps/interop/README.md +++ b/components/rtps/interop/README.md @@ -85,7 +85,7 @@ cd .. && ./run_qemu.sh | device_boot, device_ping | the engine comes up on lwIP over the emulated OpenCores MAC | | device_pub->ros2_echo, ros2_pub->device_sub (+ best-effort pair) | delivery both ways, FastDDS and CycloneDDS | | ros2_pub->device_sub_liveliness | samples still arriving 24-34 s in, past the remote lease | -| restart__rediscovered_by_ros2_sub, restart__device_sub_receives, restart__old_incarnation_dropped, restart_previous_incarnation_remembered | the device restarts its participant on a "RESTART" sample (it recreates its Domain - what a board's reboot looks like to its peers; a software reset of QEMU's emulated chip panics inside ESP-IDF's startup, so the chip is not rebooted) (once on each rmw pass, FastDDS and CycloneDDS, so a real peer of each stack honours the dispose the restarted device sends; the espp participant is recreated in-process to "reboot" - a chip reset trips a QEMU startup bug - and that fragments internal RAM, so two recreates per boot is the ceiling and no third is done, a teardown/fragmentation follow-up; the espp host engine's side is covered by `pc/tests/rtps_participant_restart.cpp`) while a ROS 2 subscriber and a ROS 2 publisher stay up. It announces a 30 s lease for itself in `sdkconfig.ci.defaults`, so the old incarnation cannot expire during the restart: the ROS 2 subscriber must receive the restarted publisher's first samples ("qemu 0".."qemu 9") and the restarted device the ROS 2 publisher's samples within seconds. The GUID prefix carries a per-Domain incarnation (bytes 10-11, `Domain::guidIncarnation`); the previous one is kept in RTC memory (`RTPSTEST incarnation cur= prev=`, `restart_previous_incarnation_remembered`) and disposed as that participant on the first announce cycles, so the ROS 2 daemon's count of publishers on the device's topic drops back to one within seconds instead of after the 30 s lease (`restart__old_incarnation_dropped`) | +| restart_fastdds_rediscovered_by_ros2_sub, restart_cyclone_rediscovered_by_ros2_sub, restart_device_sub_receives, restart_fastdds_old_incarnation_dropped, restart_cyclone_old_incarnation_dropped, restart_previous_incarnation_remembered | the device restarts its participant on one "RESTART" trigger (it recreates its Domain - what a board's reboot looks like to its peers; a software reset of QEMU's emulated chip panics inside ESP-IDF's startup, so the chip is not rebooted). The restart is done ONCE for the whole run, with BOTH a FastDDS peer and a CycloneDDS peer watching that single restart, so each stack is proven to honour the dispose without a second recreate: the espp participant is recreated in-process to "reboot", which fragments internal RAM, so the first recreate is reliable and a second is not yet (a teardown/fragmentation follow-up); the espp host engine's own side is covered by `pc/tests/rtps_participant_restart.cpp`. Both a ROS 2 subscriber per stack and a ROS 2 publisher stay up. The device announces a 30 s lease for itself in `sdkconfig.ci.defaults`, so the old incarnation cannot expire during the restart: each stack's subscriber must receive the restarted publisher's first samples ("qemu 0".."qemu 9") and the rebooted device the ROS 2 publisher's samples within seconds. The GUID prefix carries a per-Domain incarnation (bytes 10-11, `Domain::guidIncarnation`); the previous one is kept in RTC memory (`RTPSTEST incarnation cur= prev=`, `restart_previous_incarnation_remembered`) and disposed as that participant on the first announce cycles, so each RMW daemon's count of publishers on the device's topic drops back to one within seconds instead of after the 30 s lease (`restart_fastdds_old_incarnation_dropped`, `restart_cyclone_old_incarnation_dropped`) | | 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 | diff --git a/components/rtps/interop/run_qemu_interop.sh b/components/rtps/interop/run_qemu_interop.sh index aa4b24f83e..73aff1fb21 100755 --- a/components/rtps/interop/run_qemu_interop.sh +++ b/components/rtps/interop/run_qemu_interop.sh @@ -196,22 +196,45 @@ run_matrix() { # the previous incarnation - as that incarnation - on its first announce # cycles, so the peers drop the old one at once instead of holding it for the # lease. -# Results: restart__rediscovered_by_ros2_sub (the ROS 2 subscriber +# This runs ONCE, with BOTH a FastDDS and a CycloneDDS peer watching the single +# restart, so each stack is proven to honour the dispose without a second device +# reboot. Recreating the espp participant in-process is how the device "reboots" +# here (a chip reset trips a QEMU startup bug); that recreate frees and +# reallocates the engine's FreeRTOS task stacks in internal RAM, which fragments +# it - the FIRST recreate is reliable, a SECOND one eventually fails a stack +# allocation and the device aborts (a teardown/fragmentation follow-up). So the +# restart is done exactly once and both RMW stacks observe it together. +# Results: restart__rediscovered_by_ros2_sub (that stack's subscriber # receives the restarted publisher's first samples, "qemu 0".."qemu 9", well -# inside the old lease), restart__device_sub_receives (the ROS 2 -# publisher's samples reach the rebooted device), -# restart__old_incarnation_dropped (the ROS 2 daemon, a participant that -# was up throughout, counts ONE publisher on the device's topic again within -# 15 s of the restart - without the dispose it holds both for 30 s), and -# restart_previous_incarnation_remembered (the new Domain found the previous -# incarnation in the RTC record; once, on the FastDDS pass). -device_restart_case() { # prefix log-tag - local p="$1" t="$2" m rc=0 n=0 n0=0 i - timeout 90 ros2 topic echo /qemu_tx std_msgs/msg/String > "/tmp/${t}_restart_echo.log" 2>&1 & - local echo_pid=$! - timeout 90 ros2 topic pub -r 5 /qemu_rx std_msgs/msg/String "data: 'across restart'" > /dev/null 2>&1 & +# inside the old 30 s lease - daemon-independent proof the new incarnation is +# accepted at once), restart__old_incarnation_dropped (that stack's ROS 2 +# daemon, up throughout, counts ONE publisher on the device's topic again +# within ~15 s - without the dispose it would hold two for the full lease), +# restart_device_sub_receives (the ROS 2 publisher's samples reach the rebooted +# device), restart_previous_incarnation_remembered (the new Domain found the +# previous incarnation in the RTC record). +device_restart_case() { # (args unused; runs once, watching both stacks) + local m rc=0 n=0 i t0 + # CycloneDDS peers get the same discovery config the cyclone pass uses, and + # its daemon is warmed so its topic-info view of /qemu_tx is populated (the + # FastDDS daemon is already warm from this pass). Both echoes run across the + # restart; the cyclone echo discovers the device directly, independent of its + # daemon, so the rediscovery proof does not depend on the daemon at all. + local cyc='60' + RMW_IMPLEMENTATION=rmw_cyclonedds_cpp CYCLONEDDS_URI="$cyc" ros2 daemon start > /dev/null 2>&1 + timeout 150 ros2 topic echo /qemu_tx std_msgs/msg/String > "/tmp/fastdds_restart_echo.log" 2>&1 & + local echo_fd=$! + RMW_IMPLEMENTATION=rmw_cyclonedds_cpp CYCLONEDDS_URI="$cyc" \ + timeout 150 ros2 topic echo /qemu_tx std_msgs/msg/String > "/tmp/cyclone_restart_echo.log" 2>&1 & + local echo_cy=$! + timeout 150 ros2 topic pub -r 5 /qemu_rx std_msgs/msg/String "data: 'across restart'" > /dev/null 2>&1 & local pub=$! - sleep 10 # both matched and flowing, and the daemon knows the device + sleep 15 # both stacks matched and flowing, and both daemons know the device + local fd_pre cy_pre + fd_pre=$(timeout 10 ros2 topic info -v /qemu_tx 2>/dev/null | grep -c 'Endpoint type: PUBLISHER') + cy_pre=$(RMW_IMPLEMENTATION=rmw_cyclonedds_cpp CYCLONEDDS_URI="$cyc" \ + timeout 10 ros2 topic info -v /qemu_tx 2>/dev/null | grep -c 'Endpoint type: PUBLISHER') + echo " before the restart: FastDDS daemon sees ${fd_pre:-?} publisher(s), CycloneDDS daemon sees ${cy_pre:-?}" m=$(mark) # Trigger the restart through the already-matched service (a topic sample to # a freshly-matched reliable reader is not reliably delivered on every RMW); @@ -225,36 +248,44 @@ device_restart_case() { # prefix log-tag if [ $rc -eq 0 ] && ! wait_for_marker_since "$boot" "RTPSTEST ready" 60; then echo " the device's new participant did not come up"; rc=1 fi - local pubs=2 t0 + local n_fd=0 n_cy=0 pubs_fd=2 pubs_cy=2 if [ $rc -eq 0 ]; then - # the restarted publisher counts from 0 again: its first samples at the ROS 2 + # the restarted publisher counts from 0 again: its first samples at each # subscriber are the proof it was rediscovered (the old lease is 30 s) t0=$(date +%s) - for i in $(seq 1 25); do - n0=$(grep -c -E '^data: qemu [0-9]$' "/tmp/${t}_restart_echo.log") - [ "$n0" -ge 3 ] && break + for i in $(seq 1 30); do + n_fd=$(grep -c -E '^data: qemu [0-9]$' "/tmp/fastdds_restart_echo.log") + n_cy=$(grep -c -E '^data: qemu [0-9]$' "/tmp/cyclone_restart_echo.log") + [ "$n_fd" -ge 3 ] && [ "$n_cy" -ge 3 ] && break sleep 1 done - echo " ROS 2 subscriber got $n0 of the restarted publisher's first samples after $(( $(date +%s) - t0 )) s" + echo " $(( $(date +%s) - t0 )) s after the restart, first samples reached: FastDDS sub $n_fd, CycloneDDS sub $n_cy" n=$(count_since "$boot" "RTPSTEST rx across restart"); echo " rebooted device received $n from the ROS 2 publisher" - # the daemon's view: publishers of /qemu_tx; two while it still holds the - # old incarnation, one once the dispose (or the lease, 30 s) took it - for i in $(seq 1 15); do - pubs=$(timeout 10 ros2 topic info -v /qemu_tx 2>/dev/null | grep -c 'Endpoint type: PUBLISHER') - [ "${pubs:-2}" -le 1 ] && break + since "$boot" | grep -o "RTPSTEST incarnation.*" | head -1 | sed 's/^/ /' + since "$boot" | grep -q "RTPSTEST incarnation cur=[0-9a-f]* prev=[0-9a-f]" + result "restart_previous_incarnation_remembered" $? + # each daemon's view of /qemu_tx: two publishers while it still holds the old + # incarnation, one once the dispose took it. Kept well under the 30 s lease + # (short query timeouts, <=12 rounds) so a lingering old one still reads two. + for i in $(seq 1 12); do + pubs_fd=$(timeout 6 ros2 topic info -v /qemu_tx 2>/dev/null | grep -c 'Endpoint type: PUBLISHER') + pubs_cy=$(RMW_IMPLEMENTATION=rmw_cyclonedds_cpp CYCLONEDDS_URI="$cyc" \ + timeout 6 ros2 topic info -v /qemu_tx 2>/dev/null | grep -c 'Endpoint type: PUBLISHER') + [ "${pubs_fd:-2}" -le 1 ] && [ "${pubs_cy:-2}" -le 1 ] && break sleep 1 done - echo " daemon counts ${pubs:-?} publisher(s) on /qemu_tx $(( $(date +%s) - t0 )) s after the reboot" - since "$boot" | grep -o "RTPSTEST incarnation.*" | head -1 | sed 's/^/ /' - if [ "$t" = fastdds ]; then - since "$boot" | grep -q "RTPSTEST incarnation cur=[0-9a-f]* prev=[0-9a-f]" - result "restart_previous_incarnation_remembered" $? - fi + echo " $(( $(date +%s) - t0 )) s after the restart: FastDDS daemon counts ${pubs_fd:-?} publisher(s), CycloneDDS daemon ${pubs_cy:-?}" fi - stop_pids $echo_pid $pub - [ $rc -eq 0 ] && [ "$n0" -ge 3 ]; result "restart_${t}_rediscovered_by_ros2_sub" $? - [ $rc -eq 0 ] && [ "$n" -ge 5 ]; result "restart_${t}_device_sub_receives" $? - [ $rc -eq 0 ] && [ "${pubs:-2}" -le 1 ]; result "restart_${t}_old_incarnation_dropped" $? + stop_pids $echo_fd $echo_cy $pub + RMW_IMPLEMENTATION=rmw_cyclonedds_cpp CYCLONEDDS_URI="$cyc" ros2 daemon stop > /dev/null 2>&1 + [ $rc -eq 0 ] && [ "$n_fd" -ge 3 ]; result "restart_fastdds_rediscovered_by_ros2_sub" $? + [ $rc -eq 0 ] && [ "$n_cy" -ge 3 ]; result "restart_cyclone_rediscovered_by_ros2_sub" $? + [ $rc -eq 0 ] && [ "$n" -ge 5 ]; result "restart_device_sub_receives" $? + # the dispose proof needs the daemon to have had a baseline (it saw the live + # publisher before the restart); require that too so a daemon that never + # discovered cannot read as a trivial pass. + [ $rc -eq 0 ] && [ "${fd_pre:-0}" -ge 1 ] && [ "${pubs_fd:-2}" -le 1 ]; result "restart_fastdds_old_incarnation_dropped" $? + [ $rc -eq 0 ] && [ "${cy_pre:-0}" -ge 1 ] && [ "${pubs_cy:-2}" -le 1 ]; result "restart_cyclone_old_incarnation_dropped" $? } wait_for_marker_since() { # mark marker timeout_s local i @@ -312,20 +343,19 @@ ros2_cases() { # prefix log-tag tail -2 "/tmp/${t}_srv.log"; result "${p}ros2_client->device_service" $rc settle - # Restart the device's participant once on EACH rmw pass (FastDDS and - # CycloneDDS), so a real peer of each stack is proven to honour the dispose - # the restarted device sends. Recreating the espp participant in-process is - # how the device "reboots" here (a chip reset trips a QEMU startup bug - see - # device_restart_case). That recreate frees and reallocates the engine's - # FreeRTOS task stacks in internal RAM, which fragments it; two recreates in - # one boot are stable, but more are not yet (a stack allocation eventually - # fails and the device aborts - a separate teardown/fragmentation follow-up). - # So the two rmw passes get one restart each and no third is done (the - # espp-host engine's handling of a restarted peer is covered by - # pc/tests/rtps_participant_restart.cpp). - note "${p}the device restarts within its lease: the ROS 2 peers drop the old incarnation and talk to the new one" - device_restart_case "${p}" "${t}" - settle + # Restart the device's participant ONCE for the whole run, on the FastDDS + # pass, with BOTH a FastDDS and a CycloneDDS peer watching that single restart + # (device_restart_case), so each stack is proven to honour the dispose without + # a second in-process recreate - which is not yet reliable, because recreating + # the espp participant fragments internal RAM and a later stack allocation + # eventually fails (a teardown/fragmentation follow-up). The espp-host engine's + # own handling of a restarted peer is covered by + # pc/tests/rtps_participant_restart.cpp. + if [ "$t" = fastdds ]; then + note "${p}the device restarts within its lease: both the FastDDS and the CycloneDDS peer drop the old incarnation and talk to the new one" + device_restart_case + settle + fi note "${p}twelve other participants on the domain, then the publisher the device needs joins last" local crowd=() i From 273d5efde9f129433c84f7a9686b99911371f9d3 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Tue, 17 Nov 2026 18:21:09 -0600 Subject: [PATCH 11/11] test(rtps): poll for the rebooted device's receive after the restart The single restart now passes everything but restart_device_sub_receives: with both stacks watching, the device's own publisher is rediscovered instantly, so the rediscovery loop broke at 0 s and the reverse direction (the rebooted device receiving the across-restart ROS 2 publisher) was sampled before its new incarnation had re-matched that writer. Poll for it instead - the publisher stays up at 5 Hz, so the new reader fills in within seconds of re-match. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/interop/run_qemu_interop.sh | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/components/rtps/interop/run_qemu_interop.sh b/components/rtps/interop/run_qemu_interop.sh index 73aff1fb21..0c7ee3b81f 100755 --- a/components/rtps/interop/run_qemu_interop.sh +++ b/components/rtps/interop/run_qemu_interop.sh @@ -260,7 +260,16 @@ device_restart_case() { # (args unused; runs once, watching both stacks) sleep 1 done echo " $(( $(date +%s) - t0 )) s after the restart, first samples reached: FastDDS sub $n_fd, CycloneDDS sub $n_cy" - n=$(count_since "$boot" "RTPSTEST rx across restart"); echo " rebooted device received $n from the ROS 2 publisher" + # The reverse direction re-matches a beat later than the device's own + # publisher (whose samples above arrive at once), so poll for it rather than + # sampling once: the across-restart publisher stays up and keeps sending at + # 5 Hz, so the new incarnation's reader fills in within seconds of re-match. + for i in $(seq 1 25); do + n=$(count_since "$boot" "RTPSTEST rx across restart") + [ "$n" -ge 5 ] && break + sleep 1 + done + echo " rebooted device received $n from the ROS 2 publisher $(( $(date +%s) - t0 )) s after the restart" since "$boot" | grep -o "RTPSTEST incarnation.*" | head -1 | sed 's/^/ /' since "$boot" | grep -q "RTPSTEST incarnation cur=[0-9a-f]* prev=[0-9a-f]" result "restart_previous_incarnation_remembered" $?