From 254c7fc181702083f3c54b2340751d914c681148 Mon Sep 17 00:00:00 2001 From: duongtd Date: Sat, 12 Sep 2026 22:06:40 +0700 Subject: [PATCH] feat: onCancelRequested() sync hook + ABI version guard for RecoveryBehavior plugins MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - RecoveryBehavior::cancel() now calls a new virtual onCancelRequested() synchronously, from whichever thread calls cancel(). Documents onCancel() as effectively dead in move_base2: it only ran on the next update() tick, and CANCELLING forces tick_recovery=false, so that tick never came. Every existing behavior's onCancel() was unreachable code. Velocity-only behaviors (wait/rotate/back_up/clear_costmap) still stop correctly via the arbiter zeroing cmd_vel; this only matters for a behavior that owns a long-running operation of its own (see Test/sbpl_recovery, separate commit). - recovery_abi.h (new) + RECOVERY_CORE_EXPORT_BEHAVIOR(factory, symbol) macro: exports an extra _abi version symbol alongside the existing BOOST_DLL_ALIAS factory. recovery_registry.cpp probes it before calling the factory and refuses to load a .so whose version doesn't match (or is missing) instead of dlsym+reinterpret_cast blindly onto a vtable that just grew a virtual — the ABI hazard boost::dll plugins don't otherwise catch at load time. - All 4 in-tree behaviors switched to the export macro. - test/plugins/stale_abi_recovery.cpp (new): a plugin built against the old ABI, used to verify the registry actually refuses it. Co-Authored-By: Claude Sonnet 5 --- CMakeLists.txt | 4 ++ include/recovery_core/recovery_abi.h | 51 ++++++++++++++++++ include/recovery_core/recovery_behavior.h | 29 +++++++--- plugins/back_up_recovery.cpp | 4 +- plugins/clear_costmap_recovery.cpp | 4 +- plugins/rotate_recovery.cpp | 4 +- plugins/wait_recovery.cpp | 4 +- src/recovery_behavior.cpp | 3 ++ src/recovery_registry.cpp | 29 ++++++++++ test/config/recovery_behaviors_params.yaml | 14 +++++ test/plugins/stale_abi_recovery.cpp | 62 +++++++++++++++++++++ test/registry_test.cpp | 63 ++++++++++++++++++++++ 12 files changed, 256 insertions(+), 15 deletions(-) create mode 100644 include/recovery_core/recovery_abi.h create mode 100644 test/plugins/stale_abi_recovery.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 5ad827c..f605401 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -586,6 +586,10 @@ if(CATKIN_ENABLE_TESTING AND BUILDING_WITH_CATKIN) message(FATAL_ERROR "catkin_add_gtest NOT FOUND") endif() + # Plugin giả cho ABI guard test: build cùng test, KHÔNG nằm trong RECOVERY_CORE_PLUGIN_TARGETS + # (install đã chạy phía trên) nên không được cài. + add_recovery_core_plugin(recovery_core_test_stale_abi test/plugins/stale_abi_recovery.cpp) + set(RECOVERY_CORE_TESTS recovery_lifecycle_test output_kind_test diff --git a/include/recovery_core/recovery_abi.h b/include/recovery_core/recovery_abi.h new file mode 100644 index 0000000..8068161 --- /dev/null +++ b/include/recovery_core/recovery_abi.h @@ -0,0 +1,51 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * recovery_core — phiên bản ABI của biên plugin và macro export cho plugin .so. + * + * Author: DuongTD + *********************************************************************/ +#ifndef RECOVERY_CORE_RECOVERY_ABI_H_ +#define RECOVERY_CORE_RECOVERY_ABI_H_ + +#include + +namespace recovery_core +{ + +/** + * Phiên bản ABI của `RecoveryBehavior` (vtable + layout struct đi qua biên .so). + * + * TĂNG mỗi lần đổi chữ ký/virtual của `RecoveryBehavior`, `RecoveryResult`, `RecoveryGoal`, + * `RecoveryContext`. Plugin build với header cũ nạp vào runtime mới thì lời gọi ảo nhảy vào slot + * sai — crash lúc chạy, không có compile error nào bắt được (boost::dll = dlsym + reinterpret_cast). + * `RecoveryRegistry` tra symbol `_abi` TRƯỚC factory và từ chối nạp khi lệch. + * + * 1 — trước 2026-09-11 (không có symbol; registry coi là "không khai"). + * 2 — 2026-09-11: thêm virtual `onCancelRequested()`. + */ +constexpr int kRecoveryAbiVersion = 2; + +/// Hàm được export kèm mỗi plugin qua @ref RECOVERY_CORE_EXPORT_BEHAVIOR; trả @ref kRecoveryAbiVersion. +inline int recoveryAbiVersion() +{ + return kRecoveryAbiVersion; +} + +} // namespace recovery_core + +/** + * @brief Export một behavior cho boost::dll kèm phiên bản ABI. + * + * Thay cho `BOOST_DLL_ALIAS(Factory, Symbol)` thuần: sinh thêm symbol `_abi` trả + * @ref recovery_core::kRecoveryAbiVersion để registry kiểm trước khi gọi factory. + * + * @param factory Hàm/static member trả `RecoveryBehavior::RecoveryBehaviorPtr`. + * @param symbol Tên symbol khớp với `type` trong YAML (`{name: wait, type: WaitRecovery}`). + */ +#define RECOVERY_CORE_EXPORT_BEHAVIOR(factory, symbol) \ + BOOST_DLL_ALIAS(factory, symbol) \ + BOOST_DLL_ALIAS(recovery_core::recoveryAbiVersion, symbol##_abi) + +#endif // RECOVERY_CORE_RECOVERY_ABI_H_ diff --git a/include/recovery_core/recovery_behavior.h b/include/recovery_core/recovery_behavior.h index e8682cd..027c4f0 100644 --- a/include/recovery_core/recovery_behavior.h +++ b/include/recovery_core/recovery_behavior.h @@ -91,11 +91,13 @@ public: RecoveryResult update(const robot::Time& now); /** - * @brief Yêu cầu dừng. Tick kế tiếp trả stop output + `kCancelled`. + * @brief Yêu cầu dừng. Gọi @ref onCancelRequested NGAY (đồng bộ), rồi tick kế tiếp (nếu có) trả + * stop output + `kCancelled`. * * @note Trong `move_base2`, state machine không tick recovery sau khi cancel (state chuyển sang - * `CANCELLING`, nơi mọi nguồn vận tốc bị khoá), nên `kCancelled` thường không bao giờ đến - * tay caller. Đường này vẫn phải đúng: nó là hàng rào cho host khác và cho tương lai. + * `CANCELLING`, nơi mọi nguồn vận tốc bị khoá), nên `kCancelled`/`onCancel()` không bao + * giờ đến tay caller — chỉ @ref onCancelRequested là chắc chắn chạy. Behavior có việc chạy + * dài (worker thread, planner) phải kết thúc việc đó ngay trong hook ấy (2026-09-11). */ void cancel(); @@ -155,11 +157,24 @@ protected: virtual RecoveryResult onUpdate(const robot::Time& now, double dt) = 0; /** - * @brief Cơ hội phát lệnh giảm tốc trước khi dừng hẳn. + * @brief Gọi NGAY trong @ref cancel, trên thread gọi cancel(), trước bất kỳ tick nào. * - * Default trả stop output ngay. Plugin họ velocity đang chạy nhanh nên override để ramp về 0 thay - * vì nhảy bậc — dù `VelocityArbiter` phía ngoài có clamp gia tốc, kế hoạch dừng là việc của - * plugin, không phải của hàng rào cuối. + * Đây là hook DUY NHẤT chắc chắn chạy khi bị huỷ (xem ghi chú ở @ref cancel). Plugin có việc chạy + * dài — worker thread, một lượt makePlan — phải cắt và ĐỢI việc đó kết thúc ở đây, có trần thời + * gian; khi hàm trả về, runner coi behavior đã im (bảng trạng thái thành phần về idle). Không + * được phát vận tốc ở đây. Default no-op. (2026-09-11) + */ + virtual void onCancelRequested() + { + } + + /** + * @brief Tick kết thúc sau cancel — CHỈ chạy nếu caller còn tick thêm một lần sau @ref cancel. + * + * `move_base2` không làm vậy (CANCELLING không tick recovery), và `VelocityArbiter` phát 0 tức + * thì ở mọi state phải dừng nên có ramp ở đây cũng bị đè (quyết định 2026-09-11: lệnh lifecycle = + * 0 ngay, giảm tốc là việc của driver bánh xe). Dùng để dọn state nội bộ nếu caller khác tick; + * KHÔNG dùng để ramp. Default trả stop output. */ virtual RecoveryResult onCancel(); diff --git a/plugins/back_up_recovery.cpp b/plugins/back_up_recovery.cpp index 409d0df..967b09e 100644 --- a/plugins/back_up_recovery.cpp +++ b/plugins/back_up_recovery.cpp @@ -14,7 +14,7 @@ #include #include -#include +#include #include namespace recovery_plugins @@ -242,4 +242,4 @@ private: } // namespace recovery_plugins -BOOST_DLL_ALIAS(recovery_plugins::BackUpRecovery::create, BackUpRecovery) +RECOVERY_CORE_EXPORT_BEHAVIOR(recovery_plugins::BackUpRecovery::create, BackUpRecovery) diff --git a/plugins/clear_costmap_recovery.cpp b/plugins/clear_costmap_recovery.cpp index f024d35..5b39c14 100644 --- a/plugins/clear_costmap_recovery.cpp +++ b/plugins/clear_costmap_recovery.cpp @@ -15,7 +15,7 @@ #include #include -#include +#include #include #include #include @@ -258,4 +258,4 @@ private: } // namespace recovery_plugins -BOOST_DLL_ALIAS(recovery_plugins::ClearCostmapRecovery::create, ClearCostmapRecovery) +RECOVERY_CORE_EXPORT_BEHAVIOR(recovery_plugins::ClearCostmapRecovery::create, ClearCostmapRecovery) diff --git a/plugins/rotate_recovery.cpp b/plugins/rotate_recovery.cpp index ca8e529..e24bee5 100644 --- a/plugins/rotate_recovery.cpp +++ b/plugins/rotate_recovery.cpp @@ -14,7 +14,7 @@ #include #include -#include +#include #include namespace recovery_plugins @@ -275,4 +275,4 @@ private: } // namespace recovery_plugins -BOOST_DLL_ALIAS(recovery_plugins::RotateRecovery::create, RotateRecovery) +RECOVERY_CORE_EXPORT_BEHAVIOR(recovery_plugins::RotateRecovery::create, RotateRecovery) diff --git a/plugins/wait_recovery.cpp b/plugins/wait_recovery.cpp index b14d955..4258260 100644 --- a/plugins/wait_recovery.cpp +++ b/plugins/wait_recovery.cpp @@ -12,7 +12,7 @@ #include #include -#include +#include #include namespace recovery_plugins @@ -100,4 +100,4 @@ private: } // namespace recovery_plugins -BOOST_DLL_ALIAS(recovery_plugins::WaitRecovery::create, WaitRecovery) +RECOVERY_CORE_EXPORT_BEHAVIOR(recovery_plugins::WaitRecovery::create, WaitRecovery) diff --git a/src/recovery_behavior.cpp b/src/recovery_behavior.cpp index cfb2f5a..277d153 100644 --- a/src/recovery_behavior.cpp +++ b/src/recovery_behavior.cpp @@ -169,6 +169,9 @@ RecoveryResult RecoveryBehavior::update(const robot::Time& now) void RecoveryBehavior::cancel() { cancel_requested_ = true; + // Đồng bộ, trước mọi tick: đây là chỗ duy nhất một behavior có việc chạy dài được biết nó bị + // huỷ khi caller không tick nữa (2026-09-11). + onCancelRequested(); } RecoveryResult RecoveryBehavior::onCancel() diff --git a/src/recovery_registry.cpp b/src/recovery_registry.cpp index e2ccec5..f7dca5f 100644 --- a/src/recovery_registry.cpp +++ b/src/recovery_registry.cpp @@ -5,6 +5,8 @@ *********************************************************************/ #include +#include + #include #include @@ -68,6 +70,33 @@ bool RecoveryRegistry::loadOne(const std::string& name, const std::string& type, std::function factory; + // ABI guard (2026-09-11): plugin build với header RecoveryBehavior cũ có vtable ngắn hơn; nạp vào + // runtime mới thì lời gọi virtual mới (onCancelRequested) nhảy vào byte rác — crash đúng lúc bấm + // cancel. Tra `_abi` trước; thiếu hoặc lệch thì từ chối, log LỖI, robot chạy tiếp thiếu + // behavior này (route resolve đã biết bỏ tên thiếu). + try + { + const auto abi = boost::dll::import_alias(library_path, type + "_abi", + boost::dll::load_mode::append_decorations); + const int plugin_abi = abi(); + if (plugin_abi != kRecoveryAbiVersion) + { + robot::log_error("[recovery_core] RecoveryRegistry: '%s' from '%s' was built for ABI %d but " + "this runtime is ABI %d — refusing to load it. Rebuild the plugin against " + "the current recovery_core headers.", + type.c_str(), library_path.c_str(), plugin_abi, kRecoveryAbiVersion); + return false; + } + } + catch (const std::exception& ex) + { + robot::log_error("[recovery_core] RecoveryRegistry: '%s' from '%s' exports no '%s_abi' symbol " + "(built before 2026-09-11 or not using RECOVERY_CORE_EXPORT_BEHAVIOR) — " + "refusing to load it: %s", + type.c_str(), library_path.c_str(), type.c_str(), ex.what()); + return false; + } + try { factory = boost::dll::import_alias( diff --git a/test/config/recovery_behaviors_params.yaml b/test/config/recovery_behaviors_params.yaml index bbcf584..17cd27b 100644 --- a/test/config/recovery_behaviors_params.yaml +++ b/test/config/recovery_behaviors_params.yaml @@ -41,6 +41,16 @@ recovery_missing_library: behaviors: - {name: ghost, type: GhostRecovery} +# ABI guard (2026-09-11): plugin giả export `_abi` = 1 (lệch) và một alias không có `_abi`. +# Registry phải từ chối cả hai, log lỗi, không crash; behavior tốt cùng danh sách vẫn được giữ. +recovery_stale_abi: + behaviors: + - {name: wait, type: WaitRecovery} + - {name: stale, type: StaleAbiRecovery} + - {name: old, type: NoAbiRecovery} + wait: + wait_duration: 1.0 # [s] + # Namespace dành riêng cho test đường lỗi: một behavior tốt, một behavior hỏng — behavior tốt vẫn # phải được giữ lại. recovery_partial: @@ -54,6 +64,10 @@ recovery_partial: # lỗi "plugin build xong nhưng runtime báo không tìm thấy". WaitRecovery: library_path: librecovery_core_wait_recovery +StaleAbiRecovery: + library_path: librecovery_core_test_stale_abi +NoAbiRecovery: + library_path: librecovery_core_test_stale_abi RotateRecovery: library_path: librecovery_core_rotate_recovery diff --git a/test/plugins/stale_abi_recovery.cpp b/test/plugins/stale_abi_recovery.cpp new file mode 100644 index 0000000..0675ec3 --- /dev/null +++ b/test/plugins/stale_abi_recovery.cpp @@ -0,0 +1,62 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * recovery_core — plugin GIẢ mô phỏng một behavior build với header cũ: export `_abi` = 1 (và một + * alias không có `_abi`). Chỉ để test ABI guard của RecoveryRegistry; không cài đặt. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include + +#include + +namespace recovery_core +{ +namespace testing +{ + +class StaleAbiRecovery final : public RecoveryBehavior +{ +public: + static RecoveryBehavior::RecoveryBehaviorPtr create() + { + return std::make_shared(); + } + + RecoveryOutputType outputKind() const override + { + return RecoveryOutputType::kNone; + } + +protected: + bool onConfigure(robot::NodeHandle& /*nh*/) override + { + return true; + } + + bool onStart(const RecoveryGoal& /*goal*/) override + { + return true; + } + + RecoveryResult onUpdate(const robot::Time& /*now*/, double /*dt*/) override + { + return RecoveryResult::Succeeded(); + } +}; + +/// Phiên bản ABI "cũ" — lệch với kRecoveryAbiVersion của runtime. +int staleAbiVersion() +{ + return 1; +} + +} // namespace testing +} // namespace recovery_core + +BOOST_DLL_ALIAS(recovery_core::testing::StaleAbiRecovery::create, StaleAbiRecovery) +BOOST_DLL_ALIAS(recovery_core::testing::staleAbiVersion, StaleAbiRecovery_abi) +BOOST_DLL_ALIAS(recovery_core::testing::StaleAbiRecovery::create, NoAbiRecovery) diff --git a/test/registry_test.cpp b/test/registry_test.cpp index 1330caa..7e6fa66 100644 --- a/test/registry_test.cpp +++ b/test/registry_test.cpp @@ -91,6 +91,69 @@ TEST(Registry, OneBadBehaviorDoesNotDropTheGoodOnes) EXPECT_EQ(registry.nameAt(0), "wait"); } +TEST(Registry, RefusesPluginsBuiltForAnotherAbiVersionButKeepsTheRest) +{ + // 2026-09-11: RecoveryBehavior thêm virtual onCancelRequested(); plugin build với header cũ có + // vtable ngắn hơn và crash đúng lúc cancel. Registry tra `_abi` trước factory: lệch hoặc + // thiếu đều bị từ chối, log lỗi, behavior tốt cùng danh sách vẫn được nạp. + VelocityRig rig; + robot::NodeHandle nh; + recovery_core::RecoveryRegistry registry; + + EXPECT_FALSE(registry.loadFromConfig(nh, "recovery_stale_abi", rig.ctx)); + ASSERT_EQ(registry.size(), 1u) << "only the ABI-matching plugin may be registered"; + EXPECT_EQ(registry.nameAt(0), "wait"); +} + +TEST(RecoveryLifecycle, CancelCallsOnCancelRequestedSynchronously) +{ + // Hook đồng bộ (2026-09-11): chạy NGAY trong cancel(), không cần tick — chỗ duy nhất một behavior + // có việc chạy dài biết nó bị huỷ khi caller không tick nữa (CANCELLING không tick recovery). + class HookProbe final : public recovery_core::RecoveryBehavior + { + public: + recovery_core::RecoveryOutputType outputKind() const override + { + return recovery_core::RecoveryOutputType::kNone; + } + int hook_calls = 0; + int update_calls = 0; + + protected: + bool onConfigure(robot::NodeHandle&) override + { + return true; + } + bool onStart(const recovery_core::RecoveryGoal&) override + { + return true; + } + recovery_core::RecoveryResult onUpdate(const robot::Time&, double) override + { + ++update_calls; + return recovery_core::RecoveryResult::Running(); + } + void onCancelRequested() override + { + ++hook_calls; + } + }; + + HookProbe probe; + robot::NodeHandle nh; + recovery_core::RecoveryContext ctx; + ASSERT_TRUE(probe.configure("probe", ctx, nh)); + ASSERT_TRUE(probe.start(recovery_core::RecoveryGoal(), robot::Time(1000.0))); + ASSERT_EQ(probe.update(robot::Time(1000.05)).status, recovery_core::RecoveryStatus::kRunning); + + probe.cancel(); + EXPECT_EQ(probe.hook_calls, 1) << "onCancelRequested must run inside cancel(), before any tick"; + EXPECT_EQ(probe.update_calls, 1) << "no tick was needed for the hook"; + + probe.cancel(); + EXPECT_EQ(probe.hook_calls, 2) << "every cancel() call reaches the hook"; +} + TEST(Registry, MissingBehaviorListFails) { VelocityRig rig;