Files
move_base2/test/planner_runner_test.cpp
duongtd 8bc4895a60 feat: lifecycle contract — cancel/pause must reach true quiescence before reporting done
Root cause (from a C++ host log, 2026-09-11): cancel during PLANNING only set
a discard flag on the planner thread, which ran to allocated_time before
CANCELLED could be reported; a queued next mission landed on a still-busy
planner and timed out too. Same class of bug existed for pause, recovery, and
implicitly for a legitimate ABORTED read while a component was still
unwinding. Full audit, decisions, and phased design in
docs/PLAN_LIFECYCLE_CANCEL_PAUSE_RESUME.md; old-vs-new behaviour per state in
docs/LIFECYCLE_BEHAVIOUR_MATRIX.md.

Runtime quiescence, not just "command sent":
- kPausing (new state) mirrors kCancelling: PAUSED/CANCELLED is only entered
  once planner and recovery are idle, the action reports terminal, and the
  robot is stopped per odometry (robot_stopped, stopped_measured_linear/
  angular_eps) — not merely "the command we sent was zero". settle_timeout
  bounds the wait; exceeding it still finishes but logs an ungated error
  naming which component was still busy, so a plugin that doesn't honour
  cancel/pause is visible instead of silently swallowed.
- PlannerRunner::running_planner_ (new): the instance the planner thread is
  actually inside makePlan() with, tracked separately from active_ — active_
  can already point at a different instance after swapPlanner() while the
  old attempt is still running. cancelPlan(), swapPlanner() (when a job is
  running_ or only pending_ and not yet picked up), and the destructor all
  preempt through this pointer now; the old code preempted through active_
  and could silently preempt the wrong (idle) instance after a profile swap.
- ComponentStatusBoard + per-component ComponentPhase (idle/busy/stopping/
  paused/hung), read by PlannerRunner, RecoveryRunner, ActionRunner and
  ControlLoop instead of ad hoc bools — this is what makes "did everything
  actually stop" answerable at all, and what the new Watchdog thread reads
  to flag a component busy-without-progress as hung (logged once at the
  edge) without the control loop needing to detect its own stall.
- Resume: PLANNING replans from the current pose. CONTROLLING re-issues
  setPlan() with the plan already in hand (decided: setPlan again, not a
  fresh plan) — the local planner needs nothing else since it already runs
  once per control cycle; a fresh plan on resume was considered and
  rejected as unnecessary work for a plan that's still valid.
- Command-to-zero on cancel/pause stays immediate (no deceleration ramp) —
  existing VelocityArbiter behaviour, left as is per a scoped decision.

Depends on: Test/sbpl (bd89924), pnkx_nav_core (2b0993b, robot_nav_core::
Preemptable + component_status_probe.h), Test/sbpl_lattice_planner (7456e99),
Test/recovery_core (254c7fc, onCancelRequested + ABI guard), Test/
sbpl_recovery (ea79686, worker-thread cancel), Test/action_core (669c3f7,
pause/resume + kCancelled), Test/dock_pattern_action (cc1ea74).

Verified: 13 gtest binaries / 528 tests, 0 failures. Runtime on the dev
machine (Gazebo + real ROS host + VDA5050 over MQTT), 6 scenarios — cancel
during PLANNING, pause/resume during PLANNING and CONTROLLING (incl.
submit-while-still-winding-down), pause-then-cancel during PLANNING and
CONTROLLING: no ABORTED/RECOVERING in any run, preempt lands within
hundredths of a millisecond of entering CANCELLING/PAUSING, PAUSED/CANCELLED
only reported once the robot is actually stopped per odometry. Full numbers
in the plan doc section 6.

Excluded from this commit (pre-existing, unrelated):
config/runtime/recovery_behaviors_params.yaml (allocated_time 1.0->2.0,
SBPLDetourPlanner tuning predating this work).

Not yet done (see plan doc "Trạng thái"): config tuning (phase 0, pending
per a scoping decision); runtime scenarios for cancel mid-detour and a 30 s
pause mid-action; commit to rb_ws is a separate step, not done here.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-12 22:07:34 +07:00

761 lines
30 KiB
C++

/*********************************************************************
*
* Software License Agreement (BSD License)
*
* move_base2 — test PlannerRunner: nạp plugin thật qua Boost.DLL, và mọi đường lỗi phải trả false
* chứ không được để dữ liệu hỏng đi tiếp.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <chrono>
#include <cstddef>
#include <cstdlib>
#include <cstdint>
#include <limits>
#include <string>
#include <thread>
#include <vector>
#include <boost/dll/import.hpp>
#include <yaml-cpp/yaml.h>
#include <robot/node_handle.h>
#include <move_base2/runners/planner_runner.h>
namespace
{
using move_base2::PlannerRunner;
/**
* @brief Con trỏ costmap giả.
*
* `PlannerRunner::configure` từ chối costmap null — đúng, vì mọi plugin thật đều dùng nó. Nhưng
* `Costmap2DROBOT` không dựng được trong unit test (cần `tf3::BufferCore` thật và cây config đầy
* đủ), nên test dùng một địa chỉ hợp lệ nhưng không phải costmap.
*
* An toàn ở đây vì `test_global_planner.cpp` **không alias nào chạm vào con trỏ này** — nó chỉ được
* chuyển tiếp qua `initialize()` rồi bị bỏ qua. Đường có costmap thật thuộc test tích hợp (Phase 5).
*/
robot_costmap_2d::Costmap2DROBOT* dummyCostmap()
{
static std::uintptr_t placeholder = 0;
return reinterpret_cast<robot_costmap_2d::Costmap2DROBOT*>(&placeholder);
}
/// @brief Chạy trọn một lượt lập plan đồng bộ hoá lại cho test: kick, chờ thread, lấy kết quả.
bool runOnePlan(move_base2::PlannerRunner& runner, const robot_geometry_msgs::PoseStamped& start,
const robot_geometry_msgs::PoseStamped& goal,
const robot_protocol_msgs::Order* order, move_base2::PlanResult& result)
{
if (!runner.startPlan(start, goal, order, /*tag=*/1))
{
return false;
}
// Thread planner là thread thật; test phải chờ nó. Vòng quay ngắn thay vì sleep cố định để test
// không phụ thuộc vào tốc độ máy.
for (int i = 0; i < 10000 && runner.isPlanning(); ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return runner.pollPlan(result);
}
robot_geometry_msgs::PoseStamped makePose(double x, double y)
{
robot_geometry_msgs::PoseStamped pose;
pose.header.frame_id = "map";
pose.pose.position.x = x; // [m]
pose.pose.position.y = y; // [m]
pose.pose.orientation.w = 1.0;
return pose;
}
/// @brief Runner đã configure với planner @p name; ASSERT nếu không nạp được.
class Fixture
{
public:
explicit Fixture(const std::string& name = "TestPlannerOk")
{
robot::NodeHandle nh;
std::string error;
runner_.disableCostmapLockForTesting(); // costmap placeholder
ok_ = runner_.configure(nh, dummyCostmap(), name, error);
error_ = error;
}
bool ok() const
{
return ok_;
}
const std::string& error() const
{
return error_;
}
PlannerRunner runner_;
private:
bool ok_ = false;
std::string error_;
};
} // namespace
// ================================================================================================
// Cấu hình
// ================================================================================================
TEST(PlannerRunner, RefusesNullCostmap)
{
// Plugin thật nào cũng dùng costmap. Nhận null rồi chuyển tiếp xuống `initialize()` là đẩy quyết
// định "sập hay không" cho từng plugin tự lo.
robot::NodeHandle nh;
PlannerRunner runner;
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
std::string error;
EXPECT_FALSE(runner.configure(nh, nullptr, "TestPlannerOk", error));
EXPECT_FALSE(error.empty());
EXPECT_FALSE(runner.configured());
}
TEST(PlannerRunner, ConfiguresWithoutAnInitialPlanner)
{
robot::NodeHandle nh;
PlannerRunner runner;
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
std::string error;
ASSERT_TRUE(runner.configure(nh, dummyCostmap(), "", error)) << error;
EXPECT_TRUE(runner.configured());
EXPECT_TRUE(runner.activePlanner().empty());
EXPECT_EQ(runner.loadedCount(), 0U);
}
TEST(PlannerRunner, RefusesSecondConfigure)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
robot::NodeHandle nh;
std::string error;
EXPECT_FALSE(fixture.runner_.configure(nh, dummyCostmap(), "TestPlannerOk", error));
}
TEST(PlannerRunner, ConfigureFailsWhenTheInitialPlannerCannotBeLoaded)
{
robot::NodeHandle nh;
PlannerRunner runner;
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
std::string error;
EXPECT_FALSE(runner.configure(nh, dummyCostmap(), "TestPlannerMissingLibrary", error));
EXPECT_FALSE(error.empty());
EXPECT_FALSE(runner.configured()) << "configure failed but the object still reports itself as "
"configured";
}
// ================================================================================================
// Nạp plugin qua Boost.DLL
// ================================================================================================
TEST(PlannerRunner, LoadsTheInitialPlannerAndReportsItAsActive)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
EXPECT_EQ(fixture.runner_.activePlanner(), "TestPlannerOk");
EXPECT_EQ(fixture.runner_.loadedCount(), 1U);
}
TEST(PlannerRunner, SwapsBetweenPlannersAndReusesLoadedLibraries)
{
// swapPlanner chạy ở CỬA VÀO mỗi yêu cầu. Đổi qua lại giữa hai profile không được dlopen lại.
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerEmptyPlan"));
EXPECT_EQ(fixture.runner_.activePlanner(), "TestPlannerEmptyPlan");
EXPECT_EQ(fixture.runner_.loadedCount(), 2U);
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(fixture.runner_.activePlanner(), "TestPlannerOk");
EXPECT_EQ(fixture.runner_.loadedCount(), 2U) << "switched back to the previous planner yet "
"reloaded the library";
}
TEST(PlannerRunner, FailedSwapKeepsThePreviousPlannerActive)
{
// Bên gọi từ chối yêu cầu dựa trên giá trị trả về. Chuyển sang trạng thái "không có planner" sẽ
// giết luôn yêu cầu đang chạy dở, dù nó chẳng liên quan gì tới planner vừa nạp hỏng.
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
EXPECT_FALSE(fixture.runner_.swapPlanner("TestPlannerMissingLibrary"));
EXPECT_EQ(fixture.runner_.activePlanner(), "TestPlannerOk");
move_base2::PlanResult result;
ASSERT_TRUE(runOnePlan(fixture.runner_, makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, result));
EXPECT_TRUE(result.succeeded);
}
TEST(PlannerRunner, PlannerReportingInitializeFailureIsRejected)
{
// Bản cũ chỉ log rồi đi tiếp với planner chưa khởi tạo xong.
robot::NodeHandle nh;
PlannerRunner runner;
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
std::string error;
EXPECT_FALSE(runner.configure(nh, dummyCostmap(), "TestPlannerInitFails", error));
}
TEST(PlannerRunner, PlannerThatFailedToInitializeIsNotCached)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
EXPECT_FALSE(fixture.runner_.swapPlanner("TestPlannerInitFails"));
EXPECT_EQ(fixture.runner_.loadedCount(), 1U)
<< "a broken instance was cached — every later attempt would get that same broken one back";
}
TEST(PlannerRunner, RefusesEmptyPlannerName)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
EXPECT_FALSE(fixture.runner_.swapPlanner(""));
EXPECT_EQ(fixture.runner_.activePlanner(), "TestPlannerOk");
}
TEST(PlannerRunner, SwapBeforeConfigureIsRefused)
{
PlannerRunner runner;
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
EXPECT_FALSE(runner.swapPlanner("TestPlannerOk"));
}
// ================================================================================================
// Một lượt lập plan — mọi đường lỗi phải báo thất bại, plan phải rỗng
// ================================================================================================
TEST(PlannerRunner, ProducesANonEmptyPlanOnTheHappyPath)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
move_base2::PlanResult result;
ASSERT_TRUE(runOnePlan(fixture.runner_, makePose(0.0, 0.0), makePose(2.0, 1.0), nullptr, result));
ASSERT_TRUE(result.succeeded);
ASSERT_FALSE(result.plan.empty());
EXPECT_EQ(result.tag, 1U);
EXPECT_DOUBLE_EQ(result.plan.back().pose.position.x, 2.0);
EXPECT_DOUBLE_EQ(result.plan.back().pose.position.y, 1.0);
}
TEST(PlannerRunner, OrderIsForwardedToTheOrderAwareOverload)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
const robot_protocol_msgs::Order order;
move_base2::PlanResult result;
ASSERT_TRUE(runOnePlan(fixture.runner_, makePose(0.0, 0.0), makePose(2.0, 0.0), &order, result));
EXPECT_TRUE(result.succeeded);
EXPECT_FALSE(result.plan.empty());
}
TEST(PlannerRunner, OrderIsCopiedSoItMayDieBeforeThePlanFinishes)
{
// Con trỏ Order chỉ hợp lệ trong lời gọi startPlan, nhưng lượt lập plan sống lâu hơn thế. Không
// sao chép là thread planner đọc bộ nhớ đã chết.
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
{
const robot_protocol_msgs::Order order;
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), &order, 7));
} // order chết ở đây
for (int i = 0; i < 10000 && fixture.runner_.isPlanning(); ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
move_base2::PlanResult result;
ASSERT_TRUE(fixture.runner_.pollPlan(result));
EXPECT_TRUE(result.succeeded);
EXPECT_EQ(result.tag, 7U);
}
TEST(PlannerRunner, PlannerReturningTrueWithAnEmptyPlanIsTreatedAsFailure)
{
// Contract của PlannerPort: thành công nghĩa là plan KHÔNG rỗng. Lọt qua thì tầng trên gọi
// front()/back() trên vector rỗng.
Fixture fixture("TestPlannerEmptyPlan");
ASSERT_TRUE(fixture.ok()) << fixture.error();
move_base2::PlanResult result;
ASSERT_TRUE(runOnePlan(fixture.runner_, makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, result));
EXPECT_FALSE(result.succeeded);
EXPECT_TRUE(result.plan.empty());
}
TEST(PlannerRunner, ExceptionFromThePluginIsContained)
{
// Plugin là code bên thứ ba nạp lúc chạy. Exception thoát khỏi thân thread là std::terminate —
// mất cả tiến trình navigation vì một lượt lập plan hỏng.
Fixture fixture("TestPlannerThrowing");
ASSERT_TRUE(fixture.ok()) << fixture.error();
move_base2::PlanResult result;
ASSERT_TRUE(runOnePlan(fixture.runner_, makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, result));
EXPECT_FALSE(result.succeeded);
EXPECT_TRUE(result.plan.empty());
}
TEST(PlannerRunner, NonFiniteStartOrGoalIsRejectedBeforeStartingTheThread)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
const double nan = std::numeric_limits<double>::quiet_NaN();
const double inf = std::numeric_limits<double>::infinity();
EXPECT_FALSE(fixture.runner_.startPlan(makePose(nan, 0.0), makePose(2.0, 0.0), nullptr, 1));
EXPECT_FALSE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(inf, 0.0), nullptr, 1));
EXPECT_FALSE(fixture.runner_.isPlanning());
}
TEST(PlannerRunner, StartPlanWithoutAnActivePlannerFails)
{
robot::NodeHandle nh;
PlannerRunner runner;
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
std::string error;
ASSERT_TRUE(runner.configure(nh, dummyCostmap(), "", error)) << error;
EXPECT_FALSE(runner.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
}
TEST(PlannerRunner, SecondStartWhileOneIsInFlightIsRefused)
{
// Một lượt tại một thời điểm. Nhận thêm sẽ đè lên yêu cầu đang chạy và làm mất công đã bỏ ra.
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
const bool refused = !fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(3.0, 0.0), nullptr, 2);
for (int i = 0; i < 10000 && fixture.runner_.isPlanning(); ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
// Lượt đầu có thể đã xong trước lời gọi thứ hai (planner giả rất nhanh), nên chỉ khẳng định điều
// luôn đúng: không bao giờ có hai lượt cùng chạy, và kết quả thu về là của MỘT lượt.
move_base2::PlanResult result;
ASSERT_TRUE(fixture.runner_.pollPlan(result));
EXPECT_TRUE(result.tag == 1U || (!refused && result.tag == 2U));
EXPECT_FALSE(fixture.runner_.pollPlan(result)) << "a second result is still sitting in the "
"mailbox";
}
TEST(PlannerRunner, CancelledPlanProducesNoResult)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
fixture.runner_.cancelPlan();
for (int i = 0; i < 10000 && fixture.runner_.isPlanning(); ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
move_base2::PlanResult result;
EXPECT_FALSE(fixture.runner_.pollPlan(result))
<< "a cancelled attempt still returned a result — the caller would follow a plan to a goal "
"nobody asks for anymore";
}
TEST(PlannerRunner, CancelPreemptsAPreemptablePlannerWithinMilliseconds)
{
// 2026-09-11: plugin implement robot_nav_core::Preemptable thì cancelPlan() cắt lượt đang chạy —
// thread rảnh trong vài ms thay vì 2 s. Đây là thứ làm CANCELLED/PAUSED nói thật mà không phải chờ.
Fixture fixture("TestPlannerSlowPreemptable");
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
ASSERT_TRUE(fixture.runner_.isPlanning());
const auto before = std::chrono::steady_clock::now();
fixture.runner_.cancelPlan();
int waited_ms = 0;
while (fixture.runner_.isPlanning() && waited_ms < 1000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
++waited_ms;
}
const double elapsed_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
EXPECT_FALSE(fixture.runner_.isPlanning());
EXPECT_LT(elapsed_ms, 200.0) << "preempt did not reach the planner; the thread ran to the end";
move_base2::PlanResult result;
EXPECT_FALSE(fixture.runner_.pollPlan(result)) << "a preempted attempt must not deliver a plan";
// Lượt kế phải khởi động được ngay và chạy bình thường (cờ preempt không dính sang lượt sau).
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(1.0, 0.0), nullptr, 2));
EXPECT_TRUE(fixture.runner_.isPlanning());
fixture.runner_.cancelPlan();
for (int i = 0; i < 1000 && fixture.runner_.isPlanning(); ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
EXPECT_FALSE(fixture.runner_.isPlanning());
}
TEST(PlannerRunner, SwapWhileAPreemptablePlannerIsRunningCutsTheOldAttempt)
{
// Đổi profile (mission kế dùng planner khác) trong lúc lượt cũ chưa về: swapPlanner phải cắt
// instance ĐANG chạy, không chỉ đánh dấu vứt. Không cắt thì yêu cầu kế đứng ở kBusy tới hết
// allocated_time của lượt cũ (2 s ở đây, 10-30 s với SBPL thật).
Fixture fixture("TestPlannerSlowPreemptable");
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
ASSERT_TRUE(fixture.runner_.isPlanning());
const auto before = std::chrono::steady_clock::now();
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
for (int i = 0; i < 1000 && fixture.runner_.isPlanning(); ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
const double elapsed_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
EXPECT_FALSE(fixture.runner_.isPlanning());
EXPECT_LT(elapsed_ms, 200.0) << "swapPlanner did not preempt the running instance";
move_base2::PlanResult result;
EXPECT_FALSE(fixture.runner_.pollPlan(result)) << "the old planner's attempt must be discarded";
EXPECT_EQ(fixture.runner_.activePlanner(), "TestPlannerOk");
// Planner mới chạy bình thường ngay sau đó.
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(1.0, 0.0), nullptr, 2));
for (int i = 0; i < 10000 && fixture.runner_.isPlanning(); ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
ASSERT_TRUE(fixture.runner_.pollPlan(result));
EXPECT_TRUE(result.succeeded);
EXPECT_EQ(result.tag, 2U);
}
TEST(PlannerRunner, CancelAfterSwapPreemptsTheInstanceThatIsActuallyRunning)
{
// Thứ tự thật trong log 2026-09-11 (mission 2 đổi profile TRƯỚC khi accept_request gọi
// cancelPlan): active_ đã trỏ sang planner mới, nhưng thread vẫn ở trong makePlan của planner cũ.
// cancelPlan phải cắt đúng instance đang chạy, không phải active_.
Fixture fixture("TestPlannerSlowPreemptable");
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
ASSERT_TRUE(fixture.runner_.isPlanning());
// Đổi sang planner "ngoan" (stubborn — không Preemptable) để chứng minh cancel không nhìn active_:
// nếu cancel dynamic_cast trên active_ thì ra null và lượt Preemptable đang chạy KHÔNG bị cắt.
// Lưu ý: swapPlanner nay cũng preempt; để tách bạch, test này chỉ khẳng định tổng thể thread rảnh
// trong vài ms sau cặp swap+cancel, đúng như ControlLoop làm khi nhận goal mới.
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerSlowStubborn"));
fixture.runner_.cancelPlan();
int waited_ms = 0;
while (fixture.runner_.isPlanning() && waited_ms < 1000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
++waited_ms;
}
EXPECT_FALSE(fixture.runner_.isPlanning());
EXPECT_LT(waited_ms, 200) << "the running Preemptable instance was not the one preempted";
move_base2::PlanResult result;
EXPECT_FALSE(fixture.runner_.pollPlan(result));
}
TEST(PlannerRunner, SwapWhileTheJobIsQueuedButNotStartedDropsIt)
{
// Yêu cầu vừa được đặt, thread chưa kịp nhận: đổi planner phải rút yêu cầu đó ra, không để thread
// chạy yêu cầu của planner cũ trên instance mới rồi vứt.
Fixture fixture("TestPlannerSlowPreemptable");
ASSERT_TRUE(fixture.ok()) << fixture.error();
bool dropped_before_start = false;
for (int attempt = 0; attempt < 50 && !dropped_before_start; ++attempt)
{
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
// Cả hai nhánh (rút trước khi thread nhận / cắt sau khi nó nhận) đều phải rảnh trong vài ms.
int waited_ms = 0;
while (fixture.runner_.isPlanning() && waited_ms < 1000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
++waited_ms;
}
EXPECT_FALSE(fixture.runner_.isPlanning());
EXPECT_LT(waited_ms, 200);
move_base2::PlanResult result;
EXPECT_FALSE(fixture.runner_.pollPlan(result));
dropped_before_start = (waited_ms == 0);
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerSlowPreemptable"));
}
// Không ép nhánh "rút trước khi nhận" phải xảy ra (phụ thuộc scheduler), chỉ cần cả hai nhánh
// đều đúng.
SUCCEED();
}
TEST(PlannerRunner, DestructorPreemptsARunningPreemptablePlanner)
{
// Shutdown giữa một lượt search dài: destructor phải cắt lượt đó thay vì chờ hết allocated_time.
const auto before = std::chrono::steady_clock::now();
{
Fixture fixture("TestPlannerSlowPreemptable");
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
ASSERT_TRUE(fixture.runner_.isPlanning());
}
const double elapsed_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - before).count();
EXPECT_LT(elapsed_ms, 500.0) << "destructor waited for the whole 2 s search";
}
TEST(PlannerRunner, CancelOnAStubbornPlannerFallsBackToDiscardingTheResult)
{
// Plugin cũ (không Preemptable): hành vi trước 2026-09-11 giữ nguyên — thread bận tới hết lượt,
// kết quả về bị vứt. isPlanning() phải nói thật suốt quãng đó.
Fixture fixture("TestPlannerSlowStubborn");
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
std::this_thread::sleep_for(std::chrono::milliseconds(50));
fixture.runner_.cancelPlan();
EXPECT_TRUE(fixture.runner_.isPlanning()) << "a stubborn planner cannot be cut short";
for (int i = 0; i < 2000 && fixture.runner_.isPlanning(); ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
EXPECT_FALSE(fixture.runner_.isPlanning());
move_base2::PlanResult result;
EXPECT_FALSE(fixture.runner_.pollPlan(result));
}
TEST(PlannerRunner, ResultCarriesBackTheTagItWasStartedWith)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 42));
for (int i = 0; i < 10000 && fixture.runner_.isPlanning(); ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
move_base2::PlanResult result;
ASSERT_TRUE(fixture.runner_.pollPlan(result));
EXPECT_EQ(result.tag, 42U);
}
TEST(PlannerRunner, PollOnAnIdleRunnerReturnsNothing)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
move_base2::PlanResult result;
EXPECT_FALSE(fixture.runner_.pollPlan(result));
EXPECT_FALSE(fixture.runner_.isPlanning());
}
TEST(PlannerRunner, DestructorJoinsWhileAPlanIsInFlight)
{
// Detach thay vì join sẽ để thread chạm vào buffer đã bị huỷ. Test này chạy sạch dưới sanitizer
// là bằng chứng; ở đây nó ít nhất khẳng định destructor không treo.
robot::NodeHandle nh;
std::string error;
{
PlannerRunner runner;
runner.disableCostmapLockForTesting(); // costmap của test là placeholder, không dereference được
ASSERT_TRUE(runner.configure(nh, dummyCostmap(), "TestPlannerOk", error)) << error;
EXPECT_TRUE(runner.startPlan(makePose(0.0, 0.0), makePose(2.0, 0.0), nullptr, 1));
}
SUCCEED();
}
// ================================================================================================
// Nối tham số marker docking vào namespace của global planner
// ================================================================================================
namespace
{
/// @brief Đọc cửa sổ quan sát trong thư viện plugin test (xem test_global_planner.cpp).
std::size_t pluginInitializeCount()
{
return boost::dll::import_alias<std::size_t()>(
"libmove_base2_test_global_planner", "TestPlannerInitializeCount",
boost::dll::load_mode::append_decorations | boost::dll::load_mode::search_system_folders)();
}
std::string pluginLastFootprintDock()
{
return boost::dll::import_alias<std::string()>(
"libmove_base2_test_global_planner", "TestPlannerLastFootprintDock",
boost::dll::load_mode::append_decorations | boost::dll::load_mode::search_system_folders)();
}
} // namespace
TEST(PlannerRunnerDockingMarker, CopiesTheMarkerFootprintIntoThePlannerNamespace)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_a", "TestPlannerOk"));
// Đích là namespace của PLANNER, không phải của marker: plugin chỉ đọc namespace mang tên chính
// nó, nên chép sai chỗ là khoá nằm im mãi mãi mà không có lỗi nào.
robot::NodeHandle nh;
YAML::Node copied;
ASSERT_TRUE(nh.getParam("TestPlannerOk/footprint_dock", copied));
ASSERT_TRUE(copied.IsSequence());
ASSERT_EQ(copied.size(), 4U);
EXPECT_DOUBLE_EQ(copied[0][0].as<double>(), 0.5);
EXPECT_DOUBLE_EQ(copied[0][1].as<double>(), -0.4);
// Allow-list đóng: profile của marker còn mang `global_planner`/`local_planner`, chép cả cụm sang
// sẽ tạo ra khoá vô nghĩa trong namespace planner và có thể đè lên khoá cùng tên.
std::string leaked;
EXPECT_FALSE(nh.getParam("TestPlannerOk/global_planner", leaked, std::string()));
}
TEST(PlannerRunnerDockingMarker, TargetsWhateverPlannerTheProfileNamesNotJustDockPlanner)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
// Tên planner đến từ profile, không hard-code. Planner này còn chưa có block config nào —
// `setParam` phải tự tạo, nếu không thì mọi planner mới thêm đều lặng lẽ không nhận được param.
ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_b", "SomeOtherGlobalPlanner"));
robot::NodeHandle nh;
YAML::Node copied;
ASSERT_TRUE(nh.getParam("SomeOtherGlobalPlanner/footprint_dock", copied));
ASSERT_TRUE(copied.IsSequence());
EXPECT_DOUBLE_EQ(copied[0][0].as<double>(), 0.2);
}
TEST(PlannerRunnerDockingMarker, RebuildsTheInstanceSoTheNewMarkerFootprintIsActuallyRead)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
const std::size_t after_configure = pluginInitializeCount();
ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_a", "TestPlannerOk"));
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), after_configure + 1)
<< "instance phải được dựng lại thì initialize() mới đọc được footprint mới";
const std::string dock_a = pluginLastFootprintDock();
EXPECT_NE(dock_a.find("0.5"), std::string::npos) << dock_a;
// Marker khác, CÙNG planner: đường tắt "đã đúng planner" trong swapPlanner không được nuốt lần
// dựng lại này — nuốt là dock vào trạm thứ hai bằng kích thước của trạm thứ nhất.
ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_b", "TestPlannerOk"));
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), after_configure + 2);
const std::string dock_b = pluginLastFootprintDock();
EXPECT_NE(dock_b.find("0.2"), std::string::npos) << dock_b;
// Thư viện chỉ được dlopen một lần: dựng lại là gọi lại factory sẵn có, không nạp lại .so.
EXPECT_EQ(fixture.runner_.loadedCount(), 1U);
}
TEST(PlannerRunnerDockingMarker, DockingTheSameMarkerTwiceDoesNotReinitialiseThePlanner)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_a", "TestPlannerOk"));
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
const std::size_t after_first = pluginInitializeCount();
ASSERT_TRUE(fixture.runner_.bindDockingMarker("dock_a", "TestPlannerOk"));
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), after_first)
<< "param không đổi thì initialize() lại chỉ tốn thời gian ngay lúc robot đang chờ lệnh";
}
TEST(PlannerRunnerDockingMarker, MarkerWithoutAProfileIsAcceptedAndChangesNothing)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
const std::size_t before = pluginInitializeCount();
// `maker_sources` mới là allow-list; bảng profile chỉ là override. Marker hợp lệ nhưng không có
// entry riêng phải chạy tiếp bằng cặp planner mặc định, không bị từ chối.
EXPECT_TRUE(fixture.runner_.bindDockingMarker("marker_without_profile", "TestPlannerOk"));
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), before);
}
TEST(PlannerRunnerDockingMarker, ProfileWithoutFootprintDockIsAcceptedAndChangesNothing)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
const std::size_t before = pluginInitializeCount();
EXPECT_TRUE(fixture.runner_.bindDockingMarker("dock_no_footprint", "TestPlannerOk"));
ASSERT_TRUE(fixture.runner_.swapPlanner("TestPlannerOk"));
EXPECT_EQ(pluginInitializeCount(), before);
}
TEST(PlannerRunnerDockingMarker, EmptyMarkerOrPlannerNameIsANoOp)
{
Fixture fixture;
ASSERT_TRUE(fixture.ok()) << fixture.error();
// Chặng không phải docking, hoặc profile không khai global planner riêng — cả hai đều hợp lệ.
EXPECT_TRUE(fixture.runner_.bindDockingMarker("", "TestPlannerOk"));
EXPECT_TRUE(fixture.runner_.bindDockingMarker("dock_a", ""));
}
TEST(PlannerRunnerDockingMarker, RefusesBeforeConfigure)
{
PlannerRunner runner;
EXPECT_FALSE(runner.bindDockingMarker("dock_a", "TestPlannerOk"));
}
int main(int argc, char** argv)
{
// ctest không mang theo biến môi trường của shell; binary tự trỏ vào cây config và thư viện của
// gói, đúng cách recovery_runner_test và action_runner_test đang làm.
setenv("PNKX_NAV_CORE_CONFIG_DIR", MOVE_BASE2_TEST_CONFIG_DIR, 0);
setenv("PNKX_NAV_CORE_LIBRARY_PATH", MOVE_BASE2_TEST_LIBRARY_DIR, 0);
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}